content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.ComponentModel; using Syncfusion.XForms.Border; using Syncfusion.XForms.Cards; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace EssentialUIKit.Helpers { /// <summary> /// This class is used to set margin or padding based on flow direction (LTR or RTL). /// </summary> [Preserve(AllMembers = true)] public static class RTLHelper { #region Bindable Properties /// <summary> /// Gets or sets the MarginProperty. /// </summary> public static readonly BindableProperty MarginProperty = BindableProperty.CreateAttached("Margin", typeof(Thickness), typeof(RTLHelper), ZeroThickness, propertyChanged: OnMarginPropertyChanged); /// <summary> /// Gets or sets the PaddingProperty. /// </summary> public static readonly BindableProperty PaddingProperty = BindableProperty.CreateAttached("Padding", typeof(Thickness), typeof(RTLHelper), ZeroThickness, propertyChanged: OnPaddingPropertyChanged); /// <summary> /// Gets or sets the CornerRadiusProperty. /// </summary> public static readonly BindableProperty CornerRadiusProperty = BindableProperty.CreateAttached("CornerRadius", typeof(Thickness), typeof(RTLHelper), ZeroThickness, propertyChanged: OnCornerRadiusPropertyChanged); #endregion #region Private Fields /// <summary> /// Field to hold the zero thickness. /// </summary> private static readonly Thickness ZeroThickness = new Thickness(); #endregion #region Methods /// <summary> /// Gets the value of margin. /// </summary> /// <param name="bindable">The view</param> /// <returns>Returns the margin</returns> public static Thickness GetMargin(BindableObject bindable) { return (Thickness) bindable.GetValue(MarginProperty); } /// <summary> /// Gets the value of padding. /// </summary> /// <param name="bindable">The layout</param> /// <returns>Returns the padding.</returns> public static Thickness GetPadding(BindableObject bindable) { return (Thickness)bindable.GetValue(PaddingProperty); } /// <summary> /// Gets the value of corner radius. /// </summary> /// <param name="bindable">The view</param> /// <returns>Returns the corner radius.</returns> public static Thickness GetCornerRadius(BindableObject bindable) { return (Thickness)bindable.GetValue(CornerRadiusProperty); } /// <summary> /// Sets the value of margin. /// </summary> /// <param name="bindable">The view</param> /// <param name="value">The margin</param> public static void SetMargin(BindableObject bindable, Thickness value) { if (value != ZeroThickness) { bindable.SetValue(MarginProperty, value); } else { bindable.ClearValue(MarginProperty); } } /// <summary> /// Sets the value of padding. /// </summary> /// <param name="bindable">The layout</param> /// <param name="value">The padding</param> public static void SetPadding(BindableObject bindable, Thickness value) { if (value != ZeroThickness) { bindable.SetValue(PaddingProperty, value); } else { bindable.ClearValue(PaddingProperty); } } /// <summary> /// Sets the value of corner radius. /// </summary> /// <param name="bindable">The view</param> /// <param name="value">The corner radius</param> public static void SetCornerRadius(BindableObject bindable, Thickness value) { if (value != ZeroThickness) { bindable.SetValue(CornerRadiusProperty, value); } else { bindable.ClearValue(CornerRadiusProperty); } } /// <summary> /// Invoked when the value of margin property is changed. /// </summary> /// <param name="bindable">The view</param> /// <param name="oldValue">The old value</param> /// <param name="newValue">the new value</param> private static void OnMarginPropertyChanged(BindableObject bindable, object oldValue, object newValue) { if (!(bindable is View view)) return; var previousMargin = (Thickness) oldValue; var currentMargin = (Thickness) newValue; UpdateMargin(view); if (currentMargin != ZeroThickness) { if (previousMargin == ZeroThickness) { OnElementAttached(view); } } else { OnElementDetached(view); } } /// <summary> /// Invoked when the value of padding property is changed. /// </summary> /// <param name="bindable">The layout</param> /// <param name="oldValue">The old value</param> /// <param name="newValue">the new value</param> private static void OnPaddingPropertyChanged(BindableObject bindable, object oldValue, object newValue) { if (!(bindable is Layout layout)) return; var previousPadding = (Thickness)oldValue; var currentPadding = (Thickness)newValue; UpdatePadding(layout); if (currentPadding != ZeroThickness) { if (previousPadding == ZeroThickness) { OnElementAttached(layout); } } else { OnElementDetached(layout); } } /// <summary> /// Invoked when the value of corner radius property is changed. /// </summary> /// <param name="bindable">The view</param> /// <param name="oldValue">The old value</param> /// <param name="newValue">the new value</param> private static void OnCornerRadiusPropertyChanged(BindableObject bindable, object oldValue, object newValue) { if (!(bindable is View view)) return; var previousCornerRadius = (Thickness)oldValue; var currentCornerRadius = (Thickness)newValue; UpdateCornerRadius(view); if (currentCornerRadius != ZeroThickness) { if (previousCornerRadius == ZeroThickness) { OnElementAttached(view); } } else { OnElementDetached(view); } } /// <summary> /// Updates the margin value when the flow direction is changed. /// </summary> /// <param name="view">The view</param> private static void UpdateMargin(VisualElement view) { var controller = (IVisualElementController) view; var margin = GetMargin(view); if (margin != ZeroThickness) { if (controller.EffectiveFlowDirection == EffectiveFlowDirection.RightToLeft) { margin = new Thickness(margin.Right, margin.Top, margin.Left, margin.Bottom); } view.SetValue(View.MarginProperty, margin); } else { view.ClearValue(View.MarginProperty); } } /// <summary> /// Updates padding when the the flow direction is changed. /// </summary> /// <param name="layout">The layout</param> private static void UpdatePadding(View layout) { var controller = (IVisualElementController)layout; var padding = GetPadding(layout); if (padding != ZeroThickness) { if (controller.EffectiveFlowDirection == EffectiveFlowDirection.RightToLeft) { padding = new Thickness(padding.Right, padding.Top, padding.Left, padding.Bottom); } layout.SetValue(Layout.PaddingProperty, padding); } else { layout.ClearValue(Layout.PaddingProperty); } } /// <summary> /// Updates the value of the corner radius when flow direction is changed. /// </summary> /// <param name="view">The view</param> private static void UpdateCornerRadius(View view) { var controller = (IVisualElementController)view; var cornerRadius = GetCornerRadius(view); if (cornerRadius != ZeroThickness) { if (controller.EffectiveFlowDirection == EffectiveFlowDirection.RightToLeft) { cornerRadius = new Thickness(cornerRadius.Top, cornerRadius.Left, cornerRadius.Bottom, cornerRadius.Right); } if (view is SfCardView) { view.SetValue(SfCardView.CornerRadiusProperty, cornerRadius); } else if (view is SfBorder) { view.SetValue(SfBorder.CornerRadiusProperty, cornerRadius); } } else { if (view is SfCardView) { view.ClearValue(SfCardView.CornerRadiusProperty); } else if (view is SfBorder) { view.ClearValue(SfBorder.CornerRadiusProperty); } } } /// <summary> /// Updates the margin when flow direction is changed . /// </summary> /// <param name="sender">The view</param> /// <param name="e">Property changed event args</param> private static void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (sender is View view) { if (e.PropertyName == VisualElement.FlowDirectionProperty.PropertyName) { UpdateMargin(view); UpdatePadding(view); UpdateCornerRadius(view); } } } /// <summary> /// Invoked when the view is added to the main view. /// </summary> /// <param name="element">The view</param> private static void OnElementAttached(View element) { element.PropertyChanged += OnElementPropertyChanged; } /// <summary> /// Invoked when detach from the view. /// </summary> /// <param name="element">The view</param> private static void OnElementDetached(View element) { element.PropertyChanged -= OnElementPropertyChanged; } #endregion } }
33.264706
118
0.538373
[ "MIT" ]
DarryStonem/essential-ui-kit-for-xamarin.forms
EssentialUIKit/Helpers/RTLHelper.cs
11,312
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("EdgeSerialPort")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EdgeSerialPort")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("ab183e5a-bb9d-4258-b2bf-ea0b07fe8fa5")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.324324
57
0.745622
[ "MIT" ]
s-nlf-fh/PocketSocket
Software/Electron/app/dll/EdgeSerialPort/EdgeSerialPort/Properties/AssemblyInfo.cs
1,654
C#
using System; using System.Linq; using System.IO; using System.Threading; using System.Threading.Tasks; using NAudio.Wave; using NAudio.CoreAudioApi; namespace BisoProject { class AudioIO { MMDevice InputDevice; public bool ShortRecordStop = false; public delegate void VoiceRecorded(byte[] streamByte, VoiceCaptureType captuertype); public event VoiceRecorded OnShortVoiceRecorded; public void InitCaptureSound() { MMDeviceEnumerator enumerator = new MMDeviceEnumerator(); var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active); MMDevice[] devicesList = devices.ToArray(); Console.WriteLine("사용하실 마이크 디바이스를 선택해주세요"); Console.WriteLine(""); for (int i = 0; i < devicesList.Length; i++) { Console.WriteLine(i.ToString() + ". " + devicesList[i]); } Console.WriteLine(""); selectInput: string devicenum = Console.ReadLine(); try { Convert.ToInt16(devicenum); } catch { Console.WriteLine(devicenum + "은(는) 정수가 아닙니다"); goto selectInput; } if (Convert.ToInt16(devicenum) > devicesList.Length - 1 || 0 > Convert.ToInt16(devicenum)) { Console.WriteLine(devicenum + "은(는) 범위 바깥의 값입니다"); goto selectInput; } InputDevice = devicesList[Convert.ToInt16(devicenum)]; Console.WriteLine(""); Console.WriteLine("마이크 트리거를 사용할까요? (Y/N)"); Console.WriteLine(""); SetInputTriggerBool: string InputTriggerUse = Console.ReadLine(); if(InputTriggerUse == "Y" || InputTriggerUse == "y") { ConsoleKeyInfo keys; while (true) { if (ShortRecordStop == false) CaptureShortSound(); if (Console.KeyAvailable) { keys = Console.ReadKey(true); if (keys.Key == ConsoleKey.Spacebar) Program.StartVoiceCapture(VoiceCaptureType.DefaultCapture); } } } else if (InputTriggerUse == "N" || InputTriggerUse == "n") { ConsoleKeyInfo keys; while (true) { if (Console.KeyAvailable) { keys = Console.ReadKey(true); if (keys.Key == ConsoleKey.Spacebar) Program.StartVoiceCapture(VoiceCaptureType.DefaultCapture); } } } else { Console.WriteLine("유효한 값을 적어주세요"); goto SetInputTriggerBool; } } private void CaptureShortSound() { WasapiCapture capture = new WasapiCapture(InputDevice); MemoryStream memoryStream = new MemoryStream(); WaveFileWriter writer = new WaveFileWriter(memoryStream, capture.WaveFormat); long voiceTime = 0; long stopPos = 0; int stopcount = 0; capture.DataAvailable += (s, a) => { writer.Write(a.Buffer, 0, a.BytesRecorded); int soundValue = ((int)Math.Round(InputDevice.AudioMeterInformation.MasterPeakValue * 100)); //Console.WriteLine(soundValue); if (soundValue > 20)//장치 소리값이 20보다 크다면 { if (voiceTime == 0)//보이스타임 없을떄 { voiceTime = Convert.ToInt64(writer.Position - writer.WaveFormat.AverageBytesPerSecond * 1.5f);//현재 녹음파일의 스트림 위치의 1.5초뒤부터 자름 } } else if (soundValue < 15)//말이 없다면 { if (voiceTime != 0)//소리를 받는중이라면 { if (stopcount >= 5) { if (stopPos == 0) stopPos = (long)(writer.Position + writer.WaveFormat.AverageBytesPerSecond * 0.3f);//0.3초후 중지 예약 } stopcount++; } } if (voiceTime != 0)//소리를 받는중이라면 { if (writer.Position > voiceTime + capture.WaveFormat.AverageBytesPerSecond * 4f)//1.5(4-2.5)초뒤에 녹음 중지 { capture.StopRecording(); } if (stopPos != 0) { if (writer.Position > stopPos)//말이 없는지 0.3초후 { capture.StopRecording(); } } } if(ShortRecordStop == true) { capture.StopRecording(); } }; capture.RecordingStopped += (s, a) => { if (ShortRecordStop == true) { writer.Dispose(); capture.Dispose(); memoryStream.Dispose(); } else { writer.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); WaveFileReader WaveFileWriterTrimRead = new WaveFileReader(memoryStream);//자를 파일 MemoryStream memoryStreamTrim = new MemoryStream(); WaveFileWriter WaveFileWriterTrim = new WaveFileWriter(memoryStreamTrim, capture.WaveFormat);//자르고 받을파일 double BytesPerMillisecond = WaveFileWriterTrimRead.WaveFormat.AverageBytesPerSecond / 1000.0;//----------------------------------스타트랑 앤드 int start = (int)(WaveFileWriterTrimRead.Position * BytesPerMillisecond) + (int)voiceTime;//말시작한 1초앞은 자르기 start -= start % WaveFileWriterTrimRead.WaveFormat.BlockAlign; int end = (int)((WaveFileWriterTrimRead.Position + WaveFileWriterTrimRead.TotalTime.Seconds * 1000f) * BytesPerMillisecond); end -= end % WaveFileWriterTrimRead.WaveFormat.BlockAlign; //---------------------------------- TrimWavFile(WaveFileWriterTrimRead, WaveFileWriterTrim, start, end); //이거슨 싹둑싹둑 메소드 WaveFileWriterTrimRead.Dispose();//해제 WaveFileWriterTrim.Flush(); memoryStreamTrim.Seek(0, SeekOrigin.Begin); MemoryStream ConvertedMemory = WaveFormatConversion(memoryStreamTrim, capture.WaveFormat); byte[] fileData = new byte[ConvertedMemory.Length]; ConvertedMemory.Read(fileData, 0, fileData.Length); //ConvertedMemory.Seek(0, SeekOrigin.Begin); //PlaySound(ConvertedMemory);//메모리 스트림으로 읽기 OnShortVoiceRecorded?.Invoke(fileData, VoiceCaptureType.ShortTriggerCapture); ConvertedMemory.Dispose(); writer.Dispose(); capture.Dispose(); memoryStream.Dispose(); memoryStream = null; } }; try { capture.StartRecording(); } catch { writer.Dispose(); capture.Dispose(); memoryStream.Dispose(); } while (capture.CaptureState != NAudio.CoreAudioApi.CaptureState.Stopped) { Thread.Sleep(5000); } } private AudIOData CaptureSound() { WasapiCapture capture = new WasapiCapture(InputDevice); MemoryStream memoryStream = new MemoryStream(); WaveFileWriter writer = new WaveFileWriter(memoryStream, capture.WaveFormat); long stopPos = 0; int stopcount = 0; capture.DataAvailable += (s, a) => { writer.Write(a.Buffer, 0, a.BytesRecorded); int soundValue = ((int)Math.Round(InputDevice.AudioMeterInformation.MasterPeakValue * 100)); Console.WriteLine("================" + soundValue); if (soundValue > 20)//장치 소리값이 20보다 크다면 { stopcount = 0; } else if (soundValue < 15 && writer.Position > capture.WaveFormat.AverageBytesPerSecond * 2f)//말이 없다면 { if (stopcount >= 2)//말 없음 2프레임 지속 { if (stopPos == 0) stopPos = (long)(writer.Position + writer.WaveFormat.AverageBytesPerSecond * 0f);//0초후 중지 예약 } stopcount++; } if (writer.Position > capture.WaveFormat.AverageBytesPerSecond * 6f)//6초뒤에 녹음 중지 { capture.StopRecording(); } if (stopPos != 0) { if (writer.Position > stopPos)//말이 없는지 0.3초후 녹음 중지 { capture.StopRecording(); } } }; byte[] fileData = null;//오디오 바이트 capture.RecordingStopped += (s, a) => { writer.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); MemoryStream ConvertedMemory = WaveFormatConversion(memoryStream, capture.WaveFormat); fileData = new byte[ConvertedMemory.Length];//오다오 바이트 할당 ConvertedMemory.Read(fileData, 0, fileData.Length); //ConvertedMemory.Seek(0, SeekOrigin.Begin); //PlaySound(ConvertedMemory); ConvertedMemory.Dispose(); capture.Dispose(); memoryStream.Dispose(); memoryStream = null; }; try { capture.StartRecording(); } catch { writer.Dispose(); capture.Dispose(); memoryStream.Dispose(); return new AudIOData(true); } while (capture.CaptureState != NAudio.CoreAudioApi.CaptureState.Stopped) { Thread.Sleep(500); } return new AudIOData(fileData);//이벤트에서 받은 오디오 반환 } public void PlaySound(MemoryStream memoryStream) { using (var audioFile = new WaveFileReader(memoryStream)) using (var outputDevice = new WaveOutEvent()) { outputDevice.Init(audioFile); outputDevice.Play(); while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } memoryStream.Dispose(); } } public void PlayMp3Sound(MemoryStream memoryStream) { using (var audioFile = new Mp3FileReader(memoryStream)) using (var outputDevice = new WaveOutEvent()) { outputDevice.Init(audioFile); outputDevice.Play(); while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } memoryStream.Dispose(); } } public void PlayMp3Sound(string FileDir) { using (var audioFile = new Mp3FileReader(FileDir)) using (var outputDevice = new WaveOutEvent()) { outputDevice.Init(audioFile); outputDevice.Play(); while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } } } public AudIOData PlayMp3SoundAndRecordSound(string filedir) { bool Timeronce = false; using (var audioFile = new Mp3FileReader(filedir)) using (var outputDevice = new WaveOutEvent()) { outputDevice.Init(audioFile); outputDevice.Play(); while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(50); if (Timeronce == false && audioFile.CurrentTime.Milliseconds > 200) { Timeronce = true; return CaptureSound(); } } } return new AudIOData(true); } private void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos) { endPos = endPos > reader.Length ? (int)reader.Length : endPos; startPos = startPos > 0 ? startPos : 0; reader.Position = startPos; byte[] buffer = new byte[reader.WaveFormat.BlockAlign * 100]; while (reader.Position < endPos) { int bytesRequired = (int)(endPos - reader.Position); if (bytesRequired > 0) { int bytesToRead = Math.Min(bytesRequired, buffer.Length); int bytesRead = reader.Read(buffer, 0, bytesToRead); if (bytesRead > 0) { writer.Write(buffer, 0, bytesRead); } } } } private MemoryStream WaveFormatConversion(MemoryStream memoryStream, WaveFormat waveFormat) { using (var reader = new WaveFileReader(memoryStream)) { var newFormat = new WaveFormat(16000, 16, 1); using (var resampler = new MediaFoundationResampler(reader, newFormat)) { MemoryStream ConvertStream = new MemoryStream(); WaveFileWriter.WriteWavFileToStream(ConvertStream, resampler); return ConvertStream; } } } public void ShortCaptureCtrol(bool toggle) { ShortRecordStop = toggle; } } public struct AudIOData { public readonly byte[] AudioStreamByte; public readonly bool error; public AudIOData(byte[] AudioStreamByte) { this.AudioStreamByte = AudioStreamByte; this.error = false; } public AudIOData(bool error) { this.AudioStreamByte = null; this.error = error; } } }
36.026128
157
0.476759
[ "MIT" ]
noname0310/BisoProject
BisoProject/BisoProject/AudioIO.cs
15,697
C#
//////////////////////////////////////////////////////////////////////////////// using UnityEngine; namespace WeChatWASM.MDV { public class Layout { Context mContext; BlockContainer mDocument; public Layout( Context context, BlockContainer doc ) { mContext = context; mDocument = doc; } public float Height { get { return mDocument.Rect.height; } } public Block Find( string id ) { return mDocument.Find( id ); } public void Arrange( float maxWidth ) { mContext.Reset(); mDocument.Arrange( mContext, Vector2.zero, maxWidth ); } public void Draw() { mContext.Reset(); mDocument.Draw( mContext ); } } }
21.384615
81
0.46283
[ "MIT" ]
AlanSean/UnityGame3D
Assets/WX-WASM-SDK/UnityMarkdownViewer/Editor/Scripts/Layout/Layout.cs
836
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:2.4.0.0 // SpecFlow Generator Version:2.4.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Microsoft.Dynamics365.UIAutomation.BDD.Features { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "2.4.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute()] public partial class LoginFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; private Microsoft.VisualStudio.TestTools.UnitTesting.TestContext _testContext; #line 1 "Login.feature" #line hidden public virtual Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext { get { return this._testContext; } set { this._testContext = value; } } [Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute()] public static void FeatureSetup(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext testContext) { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(null, 0); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Login", "\tIn order to avoid silly mistakes\r\n\tAs a math idiot\r\n\tI want to be told the sum o" + "f two numbers", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute()] public static void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute()] public virtual void TestInitialize() { if (((testRunner.FeatureContext != null) && (testRunner.FeatureContext.FeatureInfo.Title != "Login"))) { global::Microsoft.Dynamics365.UIAutomation.BDD.Features.LoginFeature.FeatureSetup(null); } } [Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<Microsoft.VisualStudio.TestTools.UnitTesting.TestContext>(_testContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()] [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Login to CRM")] [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Login")] [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mytag")] public virtual void LoginToCRM() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Login to CRM", null, new string[] { "mytag"}); #line 7 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 8 testRunner.Given("I login to CRM", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 9 testRunner.When("I navigate to Sales and select Accounts", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 10 testRunner.Then("I click on New command", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
41.130435
239
0.608879
[ "MIT" ]
ismail4u/Dynamics365.BDD
Microsoft.Dynamics365.UIAutomation.BDD/Features/Login.feature.cs
4,732
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.OData; using System.Web.Http.OData.Builder; using System.Web.Http.OData.Query; using Moq; using NuGet.Services.Entities; using NuGetGallery.Configuration; using NuGetGallery.Framework; using NuGetGallery.OData; using NuGetGallery.WebApi; namespace NuGetGallery.Controllers { public abstract class ODataFeedControllerFactsBase<TController> where TController : NuGetODataController { protected const string _siteRoot = "https://nuget.localtest.me"; protected const string TestPackageId = "Some.Awesome.Package"; protected readonly IReadOnlyCollection<Package> AvailablePackages; protected readonly IReadOnlyCollection<Package> UnavailablePackages; protected readonly IReadOnlyCollection<Package> NonSemVer2Packages; protected readonly IReadOnlyCollection<Package> SemVer2Packages; protected readonly IReadOnlyEntityRepository<Package> PackagesRepository; protected readonly IQueryable<Package> AllPackages; protected ODataFeedControllerFactsBase() { // Arrange AllPackages = CreatePackagesQueryable(); AvailablePackages = AllPackages.Where(p => p.PackageStatusKey == PackageStatus.Available).ToList(); UnavailablePackages = AllPackages.Where(p => p.PackageStatusKey != PackageStatus.Available).ToList(); NonSemVer2Packages = AvailablePackages.Where(p => p.SemVerLevelKey == SemVerLevelKey.Unknown).ToList(); SemVer2Packages = AvailablePackages.Where(p => p.SemVerLevelKey == SemVerLevelKey.SemVer2).ToList(); var packagesRepositoryMock = new Mock<IReadOnlyEntityRepository<Package>>(MockBehavior.Strict); packagesRepositoryMock.Setup(m => m.GetAll()).Returns(AllPackages).Verifiable(); PackagesRepository = packagesRepositoryMock.Object; } protected abstract TController CreateController( IReadOnlyEntityRepository<Package> packagesRepository, IEntityRepository<Package> readWritePackagesRepository, IGalleryConfigurationService configurationService, ISearchService searchService, ITelemetryService telemetryService, IFeatureFlagService featureFlagService); protected TController CreateTestableODataFeedController( HttpRequestMessage request, Mock<IFeatureFlagService> featureFlagService) { var searchService = new Mock<ISearchService>().Object; var configurationService = new TestGalleryConfigurationService(); configurationService.Current.SiteRoot = _siteRoot; var telemetryService = new Mock<ITelemetryService>(); if (featureFlagService == null) { featureFlagService = new Mock<IFeatureFlagService>(); featureFlagService.SetReturnsDefault(true); } var readWritePackagesRepositoryMock = new Mock<IEntityRepository<Package>>(); var controller = CreateController( PackagesRepository, readWritePackagesRepositoryMock.Object, configurationService, searchService, telemetryService.Object, featureFlagService.Object); AddRequestToController(request, controller); return controller; } protected static void AddRequestToController(HttpRequestMessage request, TController controller) { var httpRequest = new HttpRequest(string.Empty, request.RequestUri.AbsoluteUri, request.RequestUri.Query); var httpResponse = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(httpRequest, httpResponse); request.Properties.Add("MS_HttpContext", httpContext); controller.Request = request; HttpContext.Current = httpContext; controller.ControllerContext.Controller = controller; controller.ControllerContext.Configuration = new HttpConfiguration(); } protected async Task<IReadOnlyCollection<TFeedPackage>> GetCollection<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, IHttpActionResult> controllerAction, string requestPath) where TFeedPackage : class { var queryResult = (QueryResult<TFeedPackage>)GetActionResult(controllerAction, requestPath); return await GetValueFromQueryResult(queryResult); } protected async Task<IReadOnlyCollection<TFeedPackage>> GetCollection<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, Task<IHttpActionResult>> asyncControllerAction, string requestPath) where TFeedPackage : class { var queryResult = (QueryResult<TFeedPackage>)await GetActionResultAsync(asyncControllerAction, requestPath); return await GetValueFromQueryResult(queryResult); } protected async Task<int> GetInt<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, IHttpActionResult> controllerAction, string requestPath) where TFeedPackage : class { var queryResult = (QueryResult<TFeedPackage>)GetActionResult(controllerAction, requestPath); return int.Parse(await GetValueFromQueryResult(queryResult)); } protected async Task<int> GetInt<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, Task<IHttpActionResult>> asyncControllerAction, string requestPath) where TFeedPackage : class { var queryResult = (QueryResult<TFeedPackage>)await GetActionResultAsync(asyncControllerAction, requestPath); return int.Parse(await GetValueFromQueryResult(queryResult)); } protected static ODataQueryContext CreateODataQueryContext<TFeedPackage>() where TFeedPackage : class { var oDataModelBuilder = new ODataConventionModelBuilder(); oDataModelBuilder.EntitySet<TFeedPackage>("Packages"); return new ODataQueryContext(oDataModelBuilder.GetEdmModel(), typeof(TFeedPackage)); } protected IHttpActionResult GetActionResult<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, IHttpActionResult> controllerAction, string requestPath, Mock<IFeatureFlagService> featureFlagService = null) where TFeedPackage : class { var request = new HttpRequestMessage(HttpMethod.Get, $"{_siteRoot}{requestPath}"); var controller = CreateTestableODataFeedController(request, featureFlagService); return controllerAction(controller, new ODataQueryOptions<TFeedPackage>(CreateODataQueryContext<TFeedPackage>(), request)); } protected async Task<IHttpActionResult> GetActionResultAsync<TFeedPackage>( Func<TController, ODataQueryOptions<TFeedPackage>, Task<IHttpActionResult>> asyncControllerAction, string requestPath, Mock<IFeatureFlagService> featureFlagService = null) where TFeedPackage : class { var request = new HttpRequestMessage(HttpMethod.Get, $"{_siteRoot}{requestPath}"); var controller = CreateTestableODataFeedController(request, featureFlagService); return await asyncControllerAction(controller, new ODataQueryOptions<TFeedPackage>(CreateODataQueryContext<TFeedPackage>(), request)); } private static IQueryable<Package> CreatePackagesQueryable() { var packageRegistration = new PackageRegistration { Id = TestPackageId }; var list = new List<Package> { new Package { PackageRegistration = packageRegistration, Version = "0.9.0.0", NormalizedVersion = "0.9.0", SemVerLevelKey = SemVerLevelKey.Unknown, PackageStatusKey = PackageStatus.Deleted, }, new Package { PackageRegistration = packageRegistration, Version = "0.8.0.0", NormalizedVersion = "0.8.0", SemVerLevelKey = SemVerLevelKey.Unknown, PackageStatusKey = PackageStatus.Validating, }, new Package { PackageRegistration = packageRegistration, Version = "0.7.0.0", NormalizedVersion = "0.7.0", SemVerLevelKey = SemVerLevelKey.Unknown, PackageStatusKey = PackageStatus.FailedValidation, }, new Package { PackageRegistration = packageRegistration, Version = "1.0.0.0", NormalizedVersion = "1.0.0", SemVerLevelKey = SemVerLevelKey.Unknown }, new Package { PackageRegistration = packageRegistration, Version = "1.0.0.0-alpha", NormalizedVersion = "1.0.0-alpha", IsPrerelease = true, SemVerLevelKey = SemVerLevelKey.Unknown }, new Package { PackageRegistration = packageRegistration, Version = "2.0.0", NormalizedVersion = "2.0.0", SemVerLevelKey = SemVerLevelKey.Unknown, IsLatestStable = true }, new Package { PackageRegistration = packageRegistration, Version = "2.0.0-alpha", NormalizedVersion = "2.0.0-alpha", IsPrerelease = true, SemVerLevelKey = SemVerLevelKey.Unknown, IsLatest = true }, new Package { PackageRegistration = packageRegistration, Version = "2.0.0-alpha.1", NormalizedVersion = "2.0.0-alpha.1", IsPrerelease = true, SemVerLevelKey = SemVerLevelKey.SemVer2 }, new Package { PackageRegistration = packageRegistration, Version = "2.0.0+metadata", NormalizedVersion = "2.0.0", SemVerLevelKey = SemVerLevelKey.SemVer2, IsLatestStableSemVer2 = true }, new Package { PackageRegistration = packageRegistration, Version = "2.0.1-alpha.1", NormalizedVersion = "2.0.1-alpha.1", IsPrerelease = true, SemVerLevelKey = SemVerLevelKey.SemVer2, IsLatestSemVer2 = true } }; return list.AsQueryable(); } private static async Task<dynamic> GetValueFromQueryResult<TEntity>(QueryResult<TEntity> queryResult) { var httpResponseMessage = await queryResult.ExecuteAsync(CancellationToken.None); if (queryResult.FormatAsCountResult) { var stringContent = (StringContent)httpResponseMessage.Content; return await stringContent.ReadAsStringAsync(); } else if (queryResult.FormatAsSingleResult) { var objectContent = (ObjectContent<TEntity>)httpResponseMessage.Content; return (TEntity)objectContent.Value; } else { var objectContent = (ObjectContent<IQueryable<TEntity>>)httpResponseMessage.Content; return ((IQueryable<TEntity>)objectContent.Value).ToList(); } } } }
43.403448
135
0.614205
[ "Apache-2.0" ]
snyk123/NuGetGallery
tests/NuGetGallery.Facts/Controllers/ODataFeedControllerFactsBase.cs
12,587
C#
using System.Collections.Generic; using Binance.Net.Enums; using CryptoExchange.Net.Converters; namespace Binance.Net.Converters { internal class MarginLevelStatusConverter : BaseConverter<MarginLevelStatus> { public MarginLevelStatusConverter() : this(true) { } public MarginLevelStatusConverter(bool quotes) : base(quotes) { } protected override List<KeyValuePair<MarginLevelStatus, string>> Mapping => new List<KeyValuePair<MarginLevelStatus, string>> { new KeyValuePair<MarginLevelStatus, string>(MarginLevelStatus.Excessive, "EXCESSIVE"), new KeyValuePair<MarginLevelStatus, string>(MarginLevelStatus.Normal, "NORMAL"), new KeyValuePair<MarginLevelStatus, string>(MarginLevelStatus.MarginCall, "MARGIN_CALL"), new KeyValuePair<MarginLevelStatus, string>(MarginLevelStatus.PreLiquidation, "PRE_LIQUIDATION"), new KeyValuePair<MarginLevelStatus, string>(MarginLevelStatus.ForceLiquidation, "FORCE_LIQUIDATION") }; } }
47.090909
133
0.737452
[ "MIT" ]
Andres-MMG/Binance.Net
Binance.Net/Converters/MarginLevelStatusConverter.cs
1,038
C#
#region Copyright (c) 2017 Leoxia Ltd // -------------------------------------------------------------------------------------------------------------------- // <copyright file="IShallowCloneable.cs" company="Leoxia Ltd"> // Copyright (c) 2017 Leoxia Ltd // </copyright> // // .NET Software Development // https://www.leoxia.com // Build. Tomorrow. Together // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Leoxia.Abstractions { /// <summary> /// Interface for Clone method that only clone properties. /// </summary> /// <typeparam name="T">Type of cloned object</typeparam> public interface IShallowCloneable<T> { /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> T Clone(); } /// <summary> /// Interface for Clone method that only clone properties. /// </summary> public interface IShallowCloneable { /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> object Clone(); } }
38.311475
121
0.588789
[ "MIT" ]
leoxialtd/Leoxia.Abstractions
src/Leoxia.Abstractions/IShallowCloneable.cs
2,339
C#
//----------------------------------------------------------------- // All Rights Reserved. Copyright (C) 2021, DotNet. //----------------------------------------------------------------- using DotNet.Util; namespace DotNet.Business { /// <summary> /// BaseManager /// 通用基类部分 /// /// 修改纪录 /// /// 2018.01.09 版本:Troy.Cui进行扩展。 /// /// <author> /// <name>Troy.Cui</name> /// <date>2018.01.09</date> /// </author> /// </summary> public partial class BaseManager : IBaseManager { #region 获取上一个下一个 /// <summary> /// 获取上一个下一个编号 /// </summary> /// <param name="currentId">当前编号</param> /// <param name="tableName">表名</param> /// <param name="orderTypeId">订单类型编号</param> /// <param name="previousId">上一个编号</param> /// <param name="nextId">下一个编号</param> /// <returns></returns> public virtual bool GetPreviousAndNextId(int currentId, string tableName, string orderTypeId, out int previousId, out int nextId) { if (string.IsNullOrEmpty(tableName)) { tableName = CurrentTableName; } previousId = currentId; nextId = currentId; var result = false; var sb = Pool.StringBuilder.Get(); sb.Append("WITH T1 AS( "); sb.Append("SELECT TOP 1 Id AS PreviousId, " + currentId + " AS CurrentId FROM " + tableName + " WHERE 1 = 1 "); if (!string.IsNullOrEmpty(orderTypeId)) { sb.Append(" AND OrderTypeId = " + orderTypeId + ""); } sb.Append(" AND Id < " + currentId + " ORDER BY Id DESC "); sb.Append(") "); sb.Append(",T2 AS ( "); sb.Append("SELECT TOP 1 Id AS NextId, " + currentId + " AS CurrentId FROM " + tableName + " WHERE 1 = 1 "); if (!string.IsNullOrEmpty(orderTypeId)) { sb.Append(" AND OrderTypeId = " + orderTypeId + ""); } sb.Append(" AND Id > " + currentId + " ORDER BY Id ASC "); sb.Append(") "); sb.Append("SELECT ISNULL(T1.PreviousId," + currentId + ") AS PreviousId,ISNULL(T1.CurrentId,T2.CurrentId) AS CurrentId,ISNULL(T2.NextId," + currentId + ") AS NextId FROM T1 FULL JOIN T2 ON T1.CurrentId = T2.CurrentId "); var dt = DbHelper.Fill(sb.Put()); if (dt != null && dt.Rows.Count == 0) { previousId = currentId; nextId = currentId; result = false; } else if (dt != null && (int.Parse(dt.Rows[0]["PreviousId"].ToString()) != currentId || int.Parse(dt.Rows[0]["NextId"].ToString()) != currentId)) { previousId = int.Parse(dt.Rows[0]["PreviousId"].ToString()); nextId = int.Parse(dt.Rows[0]["NextId"].ToString()); result = true; } return result; } #endregion } }
37.753086
232
0.482341
[ "MIT" ]
cuiwenyuan/DotNet.Util
src/DotNet.Business/Util/Extend/BaseManager.GetPreviousAndNextId.cs
3,176
C#
namespace Animals.Animals { using System; public class Dog : Animal, IAnimal { public Dog(string name, int age) : base(age) { this.Name = name; } //public string Name { get; private set; } => removed because of Animal.cs public override string Speak() { return string.Format(base.Speak() + " Bau!", this.Name); } public string CatchBone() { return string.Format(base.Speak() + " I catch the bone!", this.Name); } public override string ToString() { return "I'm a dog."; } } }
22.166667
85
0.496241
[ "MIT" ]
petyakostova/Telerik-Academy
C#/_Demos C# OOP/05. OOP Principles - Part 2/Animals/Animals/Dog.cs
667
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opensearch-2021-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpenSearchService.Model { /// <summary> /// Container for the parameters to the UpdateDomainConfig operation. /// Modifies the cluster configuration of the specified domain, such as setting the instance /// type and the number of instances. /// </summary> public partial class UpdateDomainConfigRequest : AmazonOpenSearchServiceRequest { private string _accessPolicies; private Dictionary<string, string> _advancedOptions = new Dictionary<string, string>(); private AdvancedSecurityOptionsInput _advancedSecurityOptions; private AutoTuneOptions _autoTuneOptions; private ClusterConfig _clusterConfig; private CognitoOptions _cognitoOptions; private DomainEndpointOptions _domainEndpointOptions; private string _domainName; private EBSOptions _ebsOptions; private EncryptionAtRestOptions _encryptionAtRestOptions; private Dictionary<string, LogPublishingOption> _logPublishingOptions = new Dictionary<string, LogPublishingOption>(); private NodeToNodeEncryptionOptions _nodeToNodeEncryptionOptions; private SnapshotOptions _snapshotOptions; private VPCOptions _vpcOptions; /// <summary> /// Gets and sets the property AccessPolicies. /// <para> /// IAM access policy as a JSON-formatted string. /// </para> /// </summary> [AWSProperty(Min=0, Max=102400)] public string AccessPolicies { get { return this._accessPolicies; } set { this._accessPolicies = value; } } // Check to see if AccessPolicies property is set internal bool IsSetAccessPolicies() { return this._accessPolicies != null; } /// <summary> /// Gets and sets the property AdvancedOptions. /// <para> /// Modifies the advanced option to allow references to indices in an HTTP request body. /// Must be <code>false</code> when configuring access to individual sub-resources. By /// default, the value is <code>true</code>. See <a href="http://docs.aws.amazon.com/opensearch-service/latest/developerguide/createupdatedomains.html#createdomain-configure-advanced-options" /// target="_blank">Advanced options </a> for more information. /// </para> /// </summary> public Dictionary<string, string> AdvancedOptions { get { return this._advancedOptions; } set { this._advancedOptions = value; } } // Check to see if AdvancedOptions property is set internal bool IsSetAdvancedOptions() { return this._advancedOptions != null && this._advancedOptions.Count > 0; } /// <summary> /// Gets and sets the property AdvancedSecurityOptions. /// <para> /// Specifies advanced security options. /// </para> /// </summary> public AdvancedSecurityOptionsInput AdvancedSecurityOptions { get { return this._advancedSecurityOptions; } set { this._advancedSecurityOptions = value; } } // Check to see if AdvancedSecurityOptions property is set internal bool IsSetAdvancedSecurityOptions() { return this._advancedSecurityOptions != null; } /// <summary> /// Gets and sets the property AutoTuneOptions. /// <para> /// Specifies Auto-Tune options. /// </para> /// </summary> public AutoTuneOptions AutoTuneOptions { get { return this._autoTuneOptions; } set { this._autoTuneOptions = value; } } // Check to see if AutoTuneOptions property is set internal bool IsSetAutoTuneOptions() { return this._autoTuneOptions != null; } /// <summary> /// Gets and sets the property ClusterConfig. /// <para> /// The type and number of instances to instantiate for the domain cluster. /// </para> /// </summary> public ClusterConfig ClusterConfig { get { return this._clusterConfig; } set { this._clusterConfig = value; } } // Check to see if ClusterConfig property is set internal bool IsSetClusterConfig() { return this._clusterConfig != null; } /// <summary> /// Gets and sets the property CognitoOptions. /// <para> /// Options to specify the Cognito user and identity pools for OpenSearch Dashboards authentication. /// For more information, see <a href="http://docs.aws.amazon.com/opensearch-service/latest/developerguide/cognito-auth.html" /// target="_blank">Configuring Amazon Cognito authentication for OpenSearch Dashboards</a>. /// /// </para> /// </summary> public CognitoOptions CognitoOptions { get { return this._cognitoOptions; } set { this._cognitoOptions = value; } } // Check to see if CognitoOptions property is set internal bool IsSetCognitoOptions() { return this._cognitoOptions != null; } /// <summary> /// Gets and sets the property DomainEndpointOptions. /// <para> /// Options to specify configuration that will be applied to the domain endpoint. /// </para> /// </summary> public DomainEndpointOptions DomainEndpointOptions { get { return this._domainEndpointOptions; } set { this._domainEndpointOptions = value; } } // Check to see if DomainEndpointOptions property is set internal bool IsSetDomainEndpointOptions() { return this._domainEndpointOptions != null; } /// <summary> /// Gets and sets the property DomainName. /// <para> /// The name of the domain you're updating. /// </para> /// </summary> [AWSProperty(Required=true, Min=3, Max=28)] public string DomainName { get { return this._domainName; } set { this._domainName = value; } } // Check to see if DomainName property is set internal bool IsSetDomainName() { return this._domainName != null; } /// <summary> /// Gets and sets the property EBSOptions. /// <para> /// Specify the type and size of the EBS volume to use. /// </para> /// </summary> public EBSOptions EBSOptions { get { return this._ebsOptions; } set { this._ebsOptions = value; } } // Check to see if EBSOptions property is set internal bool IsSetEBSOptions() { return this._ebsOptions != null; } /// <summary> /// Gets and sets the property EncryptionAtRestOptions. /// <para> /// Specifies encryption of data at rest options. /// </para> /// </summary> public EncryptionAtRestOptions EncryptionAtRestOptions { get { return this._encryptionAtRestOptions; } set { this._encryptionAtRestOptions = value; } } // Check to see if EncryptionAtRestOptions property is set internal bool IsSetEncryptionAtRestOptions() { return this._encryptionAtRestOptions != null; } /// <summary> /// Gets and sets the property LogPublishingOptions. /// <para> /// Map of <code>LogType</code> and <code>LogPublishingOption</code>, each containing /// options to publish a given type of OpenSearch log. /// </para> /// </summary> public Dictionary<string, LogPublishingOption> LogPublishingOptions { get { return this._logPublishingOptions; } set { this._logPublishingOptions = value; } } // Check to see if LogPublishingOptions property is set internal bool IsSetLogPublishingOptions() { return this._logPublishingOptions != null && this._logPublishingOptions.Count > 0; } /// <summary> /// Gets and sets the property NodeToNodeEncryptionOptions. /// <para> /// Specifies node-to-node encryption options. /// </para> /// </summary> public NodeToNodeEncryptionOptions NodeToNodeEncryptionOptions { get { return this._nodeToNodeEncryptionOptions; } set { this._nodeToNodeEncryptionOptions = value; } } // Check to see if NodeToNodeEncryptionOptions property is set internal bool IsSetNodeToNodeEncryptionOptions() { return this._nodeToNodeEncryptionOptions != null; } /// <summary> /// Gets and sets the property SnapshotOptions. /// <para> /// Option to set the time, in UTC format, for the daily automated snapshot. Default value /// is <code>0</code> hours. /// </para> /// </summary> public SnapshotOptions SnapshotOptions { get { return this._snapshotOptions; } set { this._snapshotOptions = value; } } // Check to see if SnapshotOptions property is set internal bool IsSetSnapshotOptions() { return this._snapshotOptions != null; } /// <summary> /// Gets and sets the property VPCOptions. /// <para> /// Options to specify the subnets and security groups for the VPC endpoint. For more /// information, see <a href="http://docs.aws.amazon.com/opensearch-service/latest/developerguide/vpc.html" /// target="_blank">Launching your Amazon OpenSearch Service domains using a VPC </a>. /// /// </para> /// </summary> public VPCOptions VPCOptions { get { return this._vpcOptions; } set { this._vpcOptions = value; } } // Check to see if VPCOptions property is set internal bool IsSetVPCOptions() { return this._vpcOptions != null; } } }
35.266458
199
0.603822
[ "Apache-2.0" ]
MDanialSaleem/aws-sdk-net
sdk/src/Services/OpenSearchService/Generated/Model/UpdateDomainConfigRequest.cs
11,250
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Econom.Data.Static { public static class FoodDictionary { public static List<string> AdjectiveSuffixes = new List<string> { "ed", "ful", "ing", "ly", "ious", "ness", "less", "ment" }; public static IList<string> Noise = new List<string> { "strength", "health", "all", "fitnes", "extra", "multi", "ultimate", "all", "cento", "nature","organic", "original", "dairy", "firm", "house", "plus", "food", "foods", "slice", "twin", "real", "instant", "skin", "style", "pack", "man", "woman", "baby", "pure", "value", "guarantee", "simply", "glory", "chef", "express" }; public static List<string> Adjectives = new List<string>() { "light", "acerbic", "acid", "acidic", "acrid", "aftertaste", "aged", "ambrosial", "ample", "appealing", "appetizing", "aromatic", "astringent", "baked", "beautiful", "bite-size", "bitter", "bland", "blazed", "blended", "blunt", "boiled", "brackish", "briny", "brown", "browned", "burnt", "buttered", "caked", "calorie", "candied", "caramelized", "caustic", "center cut", "char-broiled", "cheesy", "chilled", "chocolate", "chocolate flavored", "choice", "cholesterol free", "chunked", "cinnamon", "classic", "classy", "clove coated", "cold", "cool", "copious", "country", "crafted", "creamed", "creamy", "crisp", "crunchy", "cured", "cutting", "dazzling", "deep-fried", "delectable", "delectable", "delicious", "delight", "delightful", "distinctive", "doughy", "dressed", "dripping", "drizzle", "drizzled", "dry", "dulcified", "dull", "edible", "elastic", "encrusted", "epicurean taste", "ethnic", "extraordinary", "famous", "fantastic", "fetid", "fiery", "filet", "fizzy", "flaky", "flat", "flavored", "flavorful", "flavorless", "flavorsome", "fleshy", "fluffy", "fragile", "free", "free – range", "fresh", "fried", "frosty", "frozen", "fruity", "full", "full-bodied", "furry", "famy", "garlic", "garlicky", "generous", "generous portion", "gingery", "glazed", "golden", "gorgeous", "gourmet", "greasy", "grilled", "gritty", "gustatory", "half", "harsh", "heady", "heaping", "heart healthy", "heart smart", "hearty", "heavenly", "homemade", "", "honeyed", "honey-glazed", "hot", "ice-cold", "icy", "incisive", "indulgent", "infused", "insipid", "intense", "intriguing", "juicy", "jumbo", "kosher", "large", "lavish", "layered", "lean", "leathery", "lemon", "less", "light / lite", "lightly salted", "lightly-breaded", "lip smacking", "lively", "low", "low sodium", "low-fat", "lukewarm", "luscious", "lush", "marinated", "mashed", "mellow", "mild", "minty", "mixed", "mixture of", "moist", "moist", "mouth-watering", "nationally famous", "natural", "nectarous", "non-fat", "nutmeg", "nutty", "oily", "open face", "organic", "overpowering", "palatable indicates", "penetrating", "peppery", "perfection", "petite", "pickled", "piquant", "plain", "pleasant", "plump", "poached", "popular", "pounded", "prepared", "prickly", "pulpy", "pungent", "pureed", "rancid", "rank", "reduced", "refresh", "rich", "ripe", "roasted", "robust", "rotten", "rubbery", "saccharine", "saline", "salty", "savory", "Sapid", "saporific", "saporous", "satin", "satiny", "sauteed", "savorless", "savory", "scrumptious", "sea salt", "seared", "seasoned", "served in", "served with", "sharp", "sharp-tasting", "silky", "simmered", "sizzling", "skillfully", "small", "smelly", "smoked", "smoky", "smooth", "smothered", "soothing", "sour", "style", "special", "spiced", "spicy", "spiral-cut", "spongy", "sprinkled", "stale", "steamed", "steamy", "sticky", "stinging", "flavored", "strong", "stuffed", "succulent", "sugar coated", "sugar ", "free", "sugared", "sugarless", "sugary", "superb", "sweet", "sweet-and-sour", "sweetened", "syrupy", "tangy", "tantalizing", "tart", "tasteful", "tasteless", "tasty", "tender", "tepid", "terrific", "thick", "thin", "toasted", "toothsome", "topped", "tossed", "tough", "traditional", "treacly", "treat", "unflavored", "unsavory", "unseasoned", "vanilla", "vanilla flavored", "velvety", "vinegary", "warm", "waxy", "weak", "whipped", "whole", "wonderful", "yucky", "yummy", "zesty", "zingy" }; } }
19.005666
116
0.394247
[ "MIT" ]
MariyaSteffanova/EcoMaster
Econom/Data/Common/Econom.Data.Static/FoodDictionary.cs
6,713
C#
/* See License.md in the solution root for license information. * File: TestUtmGrid.cs */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Geodesy; namespace UnitTestGeodesy { [TestClass] public class TestUtmGrid { UtmProjection utm = new UtmProjection(); private void validateCorners(UtmGrid g) { Assert.AreEqual(g.ToString(),new UtmGrid(utm,g.LowerRightCorner).ToString()); Assert.AreEqual(g.ToString(), new UtmGrid(utm, g.UpperLeftCorner).ToString()); Assert.AreEqual(g.ToString(), new UtmGrid(utm, g.UpperRightCorner).ToString()); } [TestMethod] public void TestConstructor1() { var g = new UtmGrid(utm, 1, 'C'); Assert.AreEqual(g.LowerLeftCorner.Longitude,-180); Assert.AreEqual(g.LowerLeftCorner.Latitude,utm.MinLatitude); Assert.AreEqual(g.Width,6.0); validateCorners(g); } [TestMethod] public void TestConstructor2() { var g = new UtmGrid(utm, 1, 'X'); Assert.AreEqual(g.LowerLeftCorner.Longitude, -180); Assert.AreEqual(g.LowerLeftCorner.Latitude, utm.MaxLatitude - g.Height); Assert.AreEqual(g.Height,12.0); Assert.AreEqual(g.Width,6.0); validateCorners(g); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor3() { var loc = new GlobalCoordinates(utm.MaxLatitude + 1.0, 0); var g = new UtmGrid(utm, loc); } [TestMethod] public void TestConstructor4() { var loc = new GlobalCoordinates(utm.MaxLatitude, 0); var g = new UtmGrid(utm, loc); Assert.IsTrue(true); validateCorners(g); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor5() { var g = new UtmGrid(utm, 0, 'C'); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor6() { var g = new UtmGrid(utm, 1, 'A'); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestConstructor7() { var g = new UtmGrid(null, 1, 'C'); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor8() { var g = new UtmGrid(utm, UtmGrid.NumberOfGrids + 1); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor_32X() { var g = new UtmGrid(utm, 32, 'X'); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor_34X() { var g = new UtmGrid(utm, 34, 'X'); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestConstructor_36X() { var g = new UtmGrid(utm, 36, 'X'); } [TestMethod] public void TestConstructor_32V() { var g = new UtmGrid(utm, 32, 'V'); Assert.AreEqual(g.Width,9.0); validateCorners(g); } [TestMethod] public void TestConstructor_31V() { var g = new UtmGrid(utm, 31, 'V'); Assert.AreEqual(g.Width, 3.0); var l = g.LowerLeftCorner; // 4 degrees east of lower left is normally in the same grid // but not so in 31V l.Longitude += 4.0; var g2 = new UtmGrid(utm, l); Assert.AreEqual(g2.ToString(),"32V"); validateCorners(g); validateCorners(g2); } [TestMethod] public void TestConstructor_31X() { var g = new UtmGrid(utm, 31, 'X'); Assert.AreEqual(g.Width, 9.0); var l = g.LowerLeftCorner; // Going a little more than width should bring us // into the next zone 32, but not in this band l.Longitude += g.Width + 1.0; var g2 = new UtmGrid(utm, l); Assert.AreEqual(g2.ToString(),"33X"); validateCorners(g); validateCorners(g2); } [TestMethod] public void TestConstructor_37X() { var g = new UtmGrid(utm, 37, 'X'); Assert.AreEqual(g.Width, 9.0); validateCorners(g); } [TestMethod] public void TestConstructor_33X() { var g = new UtmGrid(utm, 33, 'X'); Assert.AreEqual(g.Width, 12.0); var l = g.LowerRightCorner; l.Longitude += 1.0; var g2 = new UtmGrid(utm, l); Assert.AreEqual(g2.ToString(),"35X"); validateCorners(g); validateCorners(g2); } [TestMethod] public void TestConstructor_35X() { var g = new UtmGrid(utm, 35, 'X'); Assert.AreEqual(g.Width, 12.0); var l = g.LowerRightCorner; l.Longitude += 1.0; var g2 = new UtmGrid(utm, l); Assert.AreEqual(g2.ToString(), "37X"); validateCorners(g); validateCorners(g2); } [TestMethod] public void TestCorners() { var g = new UtmGrid(utm, 32, 'U'); var glrc = new UtmGrid(utm, g.LowerRightCorner); Assert.AreEqual(glrc.ToString(),"32U"); var gulc = new UtmGrid(utm, g.UpperLeftCorner); Assert.AreEqual(gulc.ToString(), "32U"); var gurc = new UtmGrid(utm, g.UpperRightCorner); Assert.AreEqual(gurc.ToString(), "32U"); validateCorners(g); } [TestMethod] public void TestOrdinal() { var g = new UtmGrid(utm, 32, 'U'); int ord = g.Ordinal; var g2 = new UtmGrid(utm, ord); Assert.AreEqual(g,g2); validateCorners(g); validateCorners(g2); } [TestMethod] public void TestOrdinal2() { for (int ord = 0; ord < 1200; ord++) { if (UtmGrid.IsValidOrdinal(ord)) { var g = new UtmGrid(utm, ord); Assert.AreEqual(g.Ordinal, ord); } } } [TestMethod] public void TestBandSetter() { var g0 = new UtmGrid(utm, 32, 'U'); var g = new UtmGrid(utm, 32, 'U'); g.Band = 'V'; Assert.AreEqual(g.ToString(),"32V"); Assert.AreEqual(g.LowerLeftCorner.Latitude - g0.LowerLeftCorner.Latitude,g0.Height); validateCorners(g); } [TestMethod] public void TestZoneSetter() { var g0 = new UtmGrid(utm, 32, 'U'); var g = new UtmGrid(utm, 32, 'U'); g.Zone = 33; Assert.AreEqual(g.ToString(), "33U"); Assert.AreEqual(g.LowerLeftCorner.Longitude - g0.LowerLeftCorner.Longitude, g0.Width); validateCorners(g); } [TestMethod] public void TestOriginCompute() { var g = new UtmGrid(utm, 32, 'U'); var o = g.Origin; Assert.AreEqual(o.Projection,utm); Assert.AreEqual(o.Grid.ToString(),"32U"); Assert.IsTrue(Math.Abs(o.ScaleFactor - 1.0) < 0.001); validateCorners(g); } [TestMethod] public void ValidateAllGridsCorners() { double maxHeight = double.MinValue; double maxWidth = double.MinValue; double minWidth = double.MaxValue; double minHeight = double.MaxValue; UtmGrid G = new UtmGrid(utm,1,'C'); for (int zone = 1; zone <= UtmGrid.NumberOfZones; zone++) { for (int band = 0; band < UtmGrid.NumberOfBands; band++) { bool valid = true; try { G = new UtmGrid(utm, zone, band); } catch (Exception) { valid = false; } if (valid) { validateCorners(G); minWidth = Math.Min(minWidth, G.MapWidth); maxWidth = Math.Max(maxWidth, G.MapWidth); minHeight = Math.Min(minHeight, G.MapHeight); maxHeight = Math.Max(maxHeight, G.MapHeight); } } } Assert.IsTrue(maxHeight >= minHeight && minHeight > 0.0); Assert.IsTrue(maxWidth >= minWidth && minWidth > 0.0); } [TestMethod] public void TestEquals1() { string s = "123"; var g = new UtmGrid(utm, 1, 'C'); Assert.IsFalse(g.Equals(s)); } [TestMethod] public void TestEquals2() { var g1 = new UtmGrid(utm, 1, 'C'); var g2 = new UtmGrid(utm, 1, 'D'); g2.Band = 'C'; Assert.IsTrue(g1.Equals(g2)); } [TestMethod] public void TestEquality() { var g1 = new UtmGrid(utm, 1, 'C'); var g2 = new UtmGrid(utm, 1, 'D'); g2.Band = 'C'; Assert.IsTrue(g1==g2); } [TestMethod] public void TestInEquality() { var g1 = new UtmGrid(utm, 1, 'C'); var g2 = new UtmGrid(utm, 1, 'D'); Assert.IsTrue(g1 != g2); } [TestMethod] public void TestNeighbors() { var g = new UtmGrid(utm,Constants.MyHome); Assert.IsTrue(g.Band=='U' && g.Zone==32); var n = g.North; Assert.IsTrue(n.Band == 'V' && n.Zone == 32); var s = g.South; Assert.IsTrue(s.Band == 'T' && s.Zone == 32); var w = g.West; Assert.IsTrue(w.Band == 'U' && w.Zone == 31); var e = g.East; Assert.IsTrue(e.Band == 'U' && e.Zone == 33); } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestNorth1() { var g = new UtmGrid(utm,31,'U'); var n = g.North; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestNorth2() { var g = new UtmGrid(utm, 32, 'W'); var n = g.North; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestNorth3() { var g = new UtmGrid(utm, 34, 'W'); var n = g.North; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestNorth4() { var g = new UtmGrid(utm, 36, 'W'); var n = g.North; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestNorth5() { var g = new UtmGrid(utm, 1, 'X'); var n = g.North; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth1() { var g = new UtmGrid(utm, 31, 'W'); var n = g.South; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth2() { var g = new UtmGrid(utm, 31, 'X'); var n = g.South; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth3() { var g = new UtmGrid(utm, 33, 'X'); var n = g.South; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth4() { var g = new UtmGrid(utm, 35, 'X'); var n = g.South; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth5() { var g = new UtmGrid(utm, 37, 'X'); var n = g.South; } [TestMethod] [ExpectedException(typeof(GeodesyException))] public void TestSouth6() { var g = new UtmGrid(utm, 37, 'C'); var n = g.South; } } }
30.148936
98
0.495178
[ "Apache-2.0" ]
juergenpf/Geodesy
UnitTestGeodesy/TestUtmGrid.cs
12,755
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Syntax; using Microsoft.CodeAnalysis.Razor; using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.VisualStudio.Test; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Xunit; using SystemDebugger = System.Diagnostics.Debugger; namespace Microsoft.VisualStudio.Editor.Razor { public class DefaultVisualStudioRazorParserIntegrationTest : ProjectSnapshotManagerDispatcherTestBase { private const string TestLinePragmaFileName = "C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml"; private const string TestProjectPath = "C:\\This\\Path\\Is\\Just\\For\\Project.csproj"; public DefaultVisualStudioRazorParserIntegrationTest() { Workspace = CodeAnalysis.TestWorkspace.Create(); ProjectSnapshot = new EphemeralProjectSnapshot(Workspace.Services, TestProjectPath); } private ProjectSnapshot ProjectSnapshot { get; } private CodeAnalysis.Workspace Workspace { get; } [UIFact] public async Task NoDocumentSnapshotParsesComponentFileCorrectly() { // Arrange var snapshot = new StringTextSnapshot("@code { }"); var testBuffer = new TestTextBuffer(snapshot); var documentTracker = CreateDocumentTracker(testBuffer, filePath: "C:\\This\\Path\\Is\\Just\\For\\component.razor"); using (var manager = CreateParserManager(documentTracker)) { // Act await manager.InitializeWithDocumentAsync(snapshot); // Assert Assert.Equal(1, manager._parseCount); var codeDocument = await manager.InnerParser.GetLatestCodeDocumentAsync(snapshot); Assert.Equal(FileKinds.Component, codeDocument.GetFileKind()); // @code is only applicable in component files so we're verifying that `@code` was treated as a directive. var directiveNodes = manager.CurrentSyntaxTree.Root.DescendantNodes().Where(child => child.Kind == SyntaxKind.RazorDirective); Assert.Single(directiveNodes); } } [UIFact] public async Task BufferChangeStartsFullReparseIfChangeOverlapsMultipleSpans() { // Arrange var original = new StringTextSnapshot("Foo @bar Baz"); using (var manager = CreateParserManager(original)) { var changed = new StringTextSnapshot("Foo @bap Daz"); var edit = new TestEdit(7, 3, original, changed, "p D"); await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // Act - 1 await manager.ApplyEditAndWaitForParseAsync(edit); // Assert - 1 Assert.Equal(2, manager._parseCount); // Act - 2 await manager.ApplyEditAndWaitForParseAsync(edit); // Assert - 2 Assert.Equal(3, manager._parseCount); } } [UIFact] public async Task AwaitPeriodInsertionAcceptedProvisionally() { // Arrange var original = new StringTextSnapshot("foo @await Html baz"); using (var manager = CreateParserManager(original)) { var changed = new StringTextSnapshot("foo @await Html. baz"); var edit = new TestEdit(15, 0, original, changed, "."); await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // Act await manager.ApplyEditAndWaitForReparseAsync(edit); // Assert Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } [UIFact] public async Task ImpExprAcceptsDCIInStmtBlkAfterIdentifiers() { // ImplicitExpressionAcceptsDotlessCommitInsertionsInStatementBlockAfterIdentifiers var changed = new StringTextSnapshot("@{" + Environment.NewLine + " @DateTime." + Environment.NewLine + "}"); var original = new StringTextSnapshot("@{" + Environment.NewLine + " @DateTime" + Environment.NewLine + "}"); var edit = new TestEdit(15 + Environment.NewLine.Length, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. ApplyAndVerifyPartialChange(edit, "DateTime."); original = changed; changed = new StringTextSnapshot("@{" + Environment.NewLine + " @DateTime.." + Environment.NewLine + "}"); edit = new TestEdit(16 + Environment.NewLine.Length, 0, original, changed, "."); ApplyAndVerifyPartialChange(edit, "DateTime.."); original = changed; changed = new StringTextSnapshot("@{" + Environment.NewLine + " @DateTime.Now." + Environment.NewLine + "}"); edit = new TestEdit(16 + Environment.NewLine.Length, 0, original, changed, "Now"); ApplyAndVerifyPartialChange(edit, "DateTime.Now."); } } [UIFact] public async Task ImpExprAcceptsDCIInStatementBlock() { // ImpExprAcceptsDotlessCommitInsertionsInStatementBlock var changed = new StringTextSnapshot("@{" + Environment.NewLine + " @DateT." + Environment.NewLine + "}"); var original = new StringTextSnapshot("@{" + Environment.NewLine + " @DateT" + Environment.NewLine + "}"); var edit = new TestEdit(12 + Environment.NewLine.Length, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. ApplyAndVerifyPartialChange(edit, "DateT."); original = changed; changed = new StringTextSnapshot("@{" + Environment.NewLine + " @DateTime." + Environment.NewLine + "}"); edit = new TestEdit(12 + Environment.NewLine.Length, 0, original, changed, "ime"); ApplyAndVerifyPartialChange(edit, "DateTime."); } } [UIFact] public async Task ImpExprProvisionallyAcceptsDCI() { // ImpExprProvisionallyAcceptsDotlessCommitInsertions var changed = new StringTextSnapshot("foo @DateT. baz"); var original = new StringTextSnapshot("foo @DateT baz"); var edit = new TestEdit(10, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. ApplyAndVerifyPartialChange(edit, "DateT."); original = changed; changed = new StringTextSnapshot("foo @DateTime. baz"); edit = new TestEdit(10, 0, original, changed, "ime"); ApplyAndVerifyPartialChange(edit, "DateTime."); // Verify the reparse finally comes await manager.WaitForReparseAsync(); Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } [UIFact(Skip = "https://github.com/dotnet/aspnetcore/issues/17234")] public async Task ImpExprProvisionallyAcceptsDCIAfterIdentifiers_CompletesSyntaxTreeRequest() { var original = new StringTextSnapshot("foo @DateTime baz", versionNumber: 0); var changed = new StringTextSnapshot("foo @DateTime. baz", versionNumber: 1); var edit = new TestEdit(13, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); var codeDocumentTask = manager.InnerParser.GetLatestCodeDocumentAsync(changed); Assert.False(codeDocumentTask.IsCompleted); // Perform a partially parsed accepted change ApplyAndVerifyPartialChange(edit, "DateTime."); Assert.True(codeDocumentTask.IsCompleted); } } [UIFact] public async Task ImpExprProvisionallyAcceptsDCIAfterIdentifiers() { // ImplicitExpressionProvisionallyAcceptsDotlessCommitInsertionsAfterIdentifiers var changed = new StringTextSnapshot("foo @DateTime. baz"); var original = new StringTextSnapshot("foo @DateTime baz"); var edit = new TestEdit(13, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. ApplyAndVerifyPartialChange(edit, "DateTime."); original = changed; changed = new StringTextSnapshot("foo @DateTime.. baz"); edit = new TestEdit(14, 0, original, changed, "."); ApplyAndVerifyPartialChange(edit, "DateTime.."); original = changed; changed = new StringTextSnapshot("foo @DateTime.Now. baz"); edit = new TestEdit(14, 0, original, changed, "Now"); ApplyAndVerifyPartialChange(edit, "DateTime.Now."); // Verify the reparse eventually happens await manager.WaitForReparseAsync(); Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } [UIFact] public async Task ImpExprProvisionallyAccCaseInsensitiveDCI_NewRoslynIntegration() { // ImplicitExpressionProvisionallyAcceptsCaseInsensitiveDotlessCommitInsertions_NewRoslynIntegration var original = new StringTextSnapshot("foo @date baz"); var changed = new StringTextSnapshot("foo @date. baz"); var edit = new TestEdit(9, 0, original, changed, "."); using (var manager = CreateParserManager(original)) { void ApplyAndVerifyPartialChange(Action applyEdit, string expectedCode) { applyEdit(); Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. // @date => @date. ApplyAndVerifyPartialChange(() => manager.ApplyEdit(edit), "date."); original = changed; changed = new StringTextSnapshot("foo @date baz"); edit = new TestEdit(9, 1, original, changed, ""); // @date. => @date ApplyAndVerifyPartialChange(() => manager.ApplyEdit(edit), "date"); original = changed; changed = new StringTextSnapshot("foo @DateTime baz"); edit = new TestEdit(5, 4, original, changed, "DateTime"); // @date => @DateTime ApplyAndVerifyPartialChange(() => manager.ApplyEdit(edit), "DateTime"); original = changed; changed = new StringTextSnapshot("foo @DateTime. baz"); edit = new TestEdit(13, 0, original, changed, "."); // @DateTime => @DateTime. ApplyAndVerifyPartialChange(() => manager.ApplyEdit(edit), "DateTime."); // Verify the reparse eventually happens await manager.WaitForReparseAsync(); Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } [UIFact] public async Task ImpExprRejectsAcceptableChangeIfPrevWasProvisionallyAccepted() { // ImplicitExpressionRejectsChangeWhichWouldHaveBeenAcceptedIfLastChangeWasProvisionallyAcceptedOnDifferentSpan // Arrange var dotTyped = new TestEdit(8, 0, new StringTextSnapshot("foo @foo @bar"), new StringTextSnapshot("foo @foo. @bar"), "."); var charTyped = new TestEdit(14, 0, new StringTextSnapshot("foo @foo. @bar"), new StringTextSnapshot("foo @foo. @barb"), "b"); using (var manager = CreateParserManager(dotTyped.OldSnapshot)) { await manager.InitializeWithDocumentAsync(dotTyped.OldSnapshot); // Apply the dot change await manager.ApplyEditAndWaitForReparseAsync(dotTyped); // Act (apply the identifier start char change) await manager.ApplyEditAndWaitForParseAsync(charTyped); // Assert Assert.Equal(2, manager._parseCount); VerifyPartialParseTree(manager, charTyped.NewSnapshot.GetText()); } } [UIFact] public async Task ImpExprAcceptsIdentifierTypedAfterDotIfLastChangeProvisional() { // ImplicitExpressionAcceptsIdentifierTypedAfterDotIfLastChangeWasProvisionalAcceptanceOfDot // Arrange var dotTyped = new TestEdit(8, 0, new StringTextSnapshot("foo @foo bar"), new StringTextSnapshot("foo @foo. bar"), "."); var charTyped = new TestEdit(9, 0, new StringTextSnapshot("foo @foo. bar"), new StringTextSnapshot("foo @foo.b bar"), "b"); using (var manager = CreateParserManager(dotTyped.OldSnapshot)) { await manager.InitializeWithDocumentAsync(dotTyped.OldSnapshot); // Apply the dot change manager.ApplyEdit(dotTyped); // Act (apply the identifier start char change) manager.ApplyEdit(charTyped); // Assert Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, charTyped.NewSnapshot.GetText()); } } [UIFact] public async Task ImpExpr_AcceptsParenthesisAtEnd_SingleEdit() { // Arrange var edit = new TestEdit(8, 0, new StringTextSnapshot("foo @foo bar"), new StringTextSnapshot("foo @foo() bar"), "()"); using (var manager = CreateParserManager(edit.OldSnapshot)) { await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // Apply the () edit manager.ApplyEdit(edit); // Assert Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, edit.NewSnapshot.GetText()); } } [UIFact] public async Task ImpExpr_AcceptsParenthesisAtEnd_TwoEdits() { // Arrange var edit1 = new TestEdit(8, 0, new StringTextSnapshot("foo @foo bar"), new StringTextSnapshot("foo @foo( bar"), "("); var edit2 = new TestEdit(9, 0, new StringTextSnapshot("foo @foo( bar"), new StringTextSnapshot("foo @foo() bar"), ")"); using (var manager = CreateParserManager(edit1.OldSnapshot)) { await manager.InitializeWithDocumentAsync(edit1.OldSnapshot); // Apply the ( edit manager.ApplyEdit(edit1); // Apply the ) edit manager.ApplyEdit(edit2); // Assert Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, edit2.NewSnapshot.GetText()); } } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfIfKeywordTyped() { await RunTypeKeywordTestAsync("if"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfDoKeywordTyped() { await RunTypeKeywordTestAsync("do"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfTryKeywordTyped() { await RunTypeKeywordTestAsync("try"); } [UIFact] public async Task ImplicitExpressionCorrectlyTriggersReparseIfForKeywordTyped() { await RunTypeKeywordTestAsync("for"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfForEachKeywordTyped() { await RunTypeKeywordTestAsync("foreach"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfWhileKeywordTyped() { await RunTypeKeywordTestAsync("while"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfSwitchKeywordTyped() { await RunTypeKeywordTestAsync("switch"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfLockKeywordTyped() { await RunTypeKeywordTestAsync("lock"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfUsingKeywordTyped() { await RunTypeKeywordTestAsync("using"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfSectionKeywordTyped() { await RunTypeKeywordTestAsync("section"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfInheritsKeywordTyped() { await RunTypeKeywordTestAsync("inherits"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfFunctionsKeywordTyped() { await RunTypeKeywordTestAsync("functions"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfNamespaceKeywordTyped() { await RunTypeKeywordTestAsync("namespace"); } [UIFact] public async Task ImpExprCorrectlyTriggersReparseIfClassKeywordTyped() { await RunTypeKeywordTestAsync("class"); } private void VerifyPartialParseTree(TestParserManager manager, string content, string expectedCode = null) { if (expectedCode != null) { // Verify if the syntax tree represents the expected input. var syntaxTreeContent = manager.PartialParsingSyntaxTreeRoot.ToFullString(); Assert.Contains(expectedCode, syntaxTreeContent, StringComparison.Ordinal); } var sourceDocument = TestRazorSourceDocument.Create(content); var syntaxTree = RazorSyntaxTree.Create(manager.PartialParsingSyntaxTreeRoot, sourceDocument, manager.CurrentSyntaxTree.Diagnostics, manager.CurrentSyntaxTree.Options); BaselineTest(syntaxTree); } private void VerifyCurrentSyntaxTree(TestParserManager manager) { BaselineTest(manager.CurrentSyntaxTree); } private TestParserManager CreateParserManager(VisualStudioDocumentTracker documentTracker) { var templateEngineFactory = CreateProjectEngineFactory(); var parser = new DefaultVisualStudioRazorParser( JoinableTaskFactory.Context, documentTracker, templateEngineFactory, new DefaultErrorReporter(), new TestCompletionBroker()) { // We block idle work with the below reset events. Therefore, make tests fast and have the idle timer fire as soon as possible. _idleDelay = TimeSpan.FromMilliseconds(1), NotifyUIIdleStart = new ManualResetEventSlim(), BlockBackgroundIdleWork = new ManualResetEventSlim(), }; parser.StartParser(); return new TestParserManager(parser); } private TestParserManager CreateParserManager(ITextSnapshot originalSnapshot) { var textBuffer = new TestTextBuffer(originalSnapshot); var documentTracker = CreateDocumentTracker(textBuffer); return CreateParserManager(documentTracker); } private static ProjectSnapshotProjectEngineFactory CreateProjectEngineFactory(IEnumerable<TagHelperDescriptor> tagHelpers = null) { var fileSystem = new TestRazorProjectFileSystem(); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { RazorExtensions.Register(builder); builder.AddDefaultImports("@addTagHelper *, Test"); if (tagHelpers != null) { builder.AddTagHelpers(tagHelpers); } }); return new TestProjectSnapshotProjectEngineFactory() { Engine = projectEngine, }; } private async Task RunTypeKeywordTestAsync(string keyword) { // Arrange var before = "@" + keyword.Substring(0, keyword.Length - 1); var after = "@" + keyword; var changed = new StringTextSnapshot(after); var old = new StringTextSnapshot(before); var change = new SourceChange(keyword.Length, 0, keyword[keyword.Length - 1].ToString()); var edit = new TestEdit(change, old, changed); using (var manager = CreateParserManager(old)) { await manager.InitializeWithDocumentAsync(edit.OldSnapshot); // Act await manager.ApplyEditAndWaitForParseAsync(edit); // Assert Assert.Equal(2, manager._parseCount); } } private static void DoWithTimeoutIfNotDebugging(Func<int, bool> withTimeout) { #if DEBUG if (SystemDebugger.IsAttached) { withTimeout(Timeout.Infinite); } else { #endif Assert.True(withTimeout((int)TimeSpan.FromSeconds(5).TotalMilliseconds), "Timeout expired!"); #if DEBUG } #endif } private VisualStudioDocumentTracker CreateDocumentTracker(Text.ITextBuffer textBuffer, string filePath = TestLinePragmaFileName) { var focusedTextView = Mock.Of<ITextView>(textView => textView.HasAggregateFocus == true, MockBehavior.Strict); var documentTracker = Mock.Of<VisualStudioDocumentTracker>(tracker => tracker.TextBuffer == textBuffer && tracker.TextViews == new[] { focusedTextView } && tracker.FilePath == filePath && tracker.ProjectPath == TestProjectPath && tracker.ProjectSnapshot == ProjectSnapshot && tracker.IsSupportedProject == true, MockBehavior.Strict); textBuffer.Properties.AddProperty(typeof(VisualStudioDocumentTracker), documentTracker); return documentTracker; } private class TestParserManager : IDisposable { public int _parseCount; private readonly ManualResetEventSlim _parserComplete; private readonly ManualResetEventSlim _reparseComplete; private readonly TestTextBuffer _testBuffer; private readonly DefaultVisualStudioRazorParser _parser; public TestParserManager(DefaultVisualStudioRazorParser parser) { _parserComplete = new ManualResetEventSlim(); _reparseComplete = new ManualResetEventSlim(); _testBuffer = (TestTextBuffer)parser.TextBuffer; _parseCount = 0; _parser = parser; parser.DocumentStructureChanged += (sender, args) => { CurrentSyntaxTree = args.CodeDocument.GetSyntaxTree(); Interlocked.Increment(ref _parseCount); if (args.SourceChange is null) { // Reparse occurred _reparseComplete.Set(); } _parserComplete.Set(); }; } public RazorSyntaxTree CurrentSyntaxTree { get; private set; } public SyntaxNode PartialParsingSyntaxTreeRoot => _parser._partialParser.ModifiedSyntaxTreeRoot; public VisualStudioRazorParser InnerParser => _parser; public async Task InitializeWithDocumentAsync(ITextSnapshot snapshot) { var old = new StringTextSnapshot(string.Empty); var initialChange = new SourceChange(0, 0, snapshot.GetText()); var edit = new TestEdit(initialChange, old, snapshot); await ApplyEditAndWaitForParseAsync(edit); } public void ApplyEdit(TestEdit edit) { _testBuffer.ApplyEdit(edit); } public async Task ApplyEditAndWaitForParseAsync(TestEdit edit) { ApplyEdit(edit); await WaitForParseAsync(); } public async Task ApplyEditAndWaitForReparseAsync(TestEdit edit) { ApplyEdit(edit); await WaitForReparseAsync(); } public async Task WaitForParseAsync() { // Get off of the UI thread so we can wait for the document structure changed event to fire await Task.Run(() => DoWithTimeoutIfNotDebugging(_parserComplete.Wait)); _parserComplete.Reset(); } public async Task WaitForReparseAsync() { Assert.True(_parser._idleTimer != null); // Allow background idle work to continue _parser.BlockBackgroundIdleWork.Set(); // Get off of the UI thread so we can wait for the idle timer to fire await Task.Run(() => DoWithTimeoutIfNotDebugging(_parser.NotifyUIIdleStart.Wait)); Assert.Null(_parser._idleTimer); // Get off of the UI thread so we can wait for the document structure changed event to fire for reparse await Task.Run(() => DoWithTimeoutIfNotDebugging(_reparseComplete.Wait)); _reparseComplete.Reset(); _parser.BlockBackgroundIdleWork.Reset(); _parser.NotifyUIIdleStart.Reset(); } public void Dispose() { _parser.Dispose(); _parserComplete.Dispose(); _reparseComplete.Dispose(); } } private class TestCompletionBroker : VisualStudioCompletionBroker { public override bool IsCompletionActive(ITextView textView) => false; } } }
40.299065
180
0.584316
[ "MIT" ]
50Wliu/razor-tooling
src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserIntegrationTest.cs
30,186
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Player : MonoBehaviour { Animator an; [Range(0,5)] public int velocidade = 2; public static int ponto; public GameObject portal; void Start () { an = GetComponent<Animator>(); } void Update () { //an.SetFloat("Blend", 1); transform.Translate(Vector3.forward*Time.deltaTime*Input.GetAxis("Vertical")*velocidade); an.SetFloat("Blend", Input.GetAxis("Vertical")); if (Input.GetKey(KeyCode.LeftShift)) { an.speed = 2; velocidade = 4; } else { an.speed = 1; velocidade = 2; } transform.Rotate(0, Input.GetAxis("Horizontal")*velocidade, 0, Space.Self); if (ponto>=4) { portal.gameObject.SetActive(true); } } void OnTriggerEnter(Collider c) { if (c.tag == "Portal") { SceneManager.LoadScene("Final"); } } }
19.781818
97
0.556066
[ "MIT" ]
DavidGomes8/Exercicio_BlendTree
Assets/Script/Player.cs
1,090
C#
/* Copyright (C) 2009-2012 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Text; using System.Diagnostics; using IKVM.Reflection.Reader; using IKVM.Reflection.Emit; namespace IKVM.Reflection { public sealed class ResolveEventArgs : EventArgs { private readonly string name; private readonly Assembly requestingAssembly; public ResolveEventArgs(string name) : this(name, null) { } public ResolveEventArgs(string name, Assembly requestingAssembly) { this.name = name; this.requestingAssembly = requestingAssembly; } public string Name { get { return name; } } public Assembly RequestingAssembly { get { return requestingAssembly; } } } public enum AssemblyComparisonResult { Unknown = 0, EquivalentFullMatch = 1, EquivalentWeakNamed = 2, EquivalentFXUnified = 3, EquivalentUnified = 4, NonEquivalentVersion = 5, NonEquivalent = 6, EquivalentPartialMatch = 7, EquivalentPartialWeakNamed = 8, EquivalentPartialUnified = 9, EquivalentPartialFXUnified = 10, NonEquivalentPartialVersion = 11, } public delegate Assembly ResolveEventHandler(object sender, ResolveEventArgs args); [Flags] public enum UniverseOptions { None = 0, EnableFunctionPointers = 1, DisableFusion = 2, DisablePseudoCustomAttributeRetrieval = 4, } public sealed class Universe : IDisposable { internal static readonly bool MonoRuntime = System.Type.GetType("Mono.Runtime") != null; private readonly Dictionary<Type, Type> canonicalizedTypes = new Dictionary<Type, Type>(); private readonly List<AssemblyReader> assemblies = new List<AssemblyReader>(); private readonly List<AssemblyBuilder> dynamicAssemblies = new List<AssemblyBuilder>(); private readonly Dictionary<string, Assembly> assembliesByName = new Dictionary<string, Assembly>(); private readonly Dictionary<System.Type, Type> importedTypes = new Dictionary<System.Type, Type>(); private Dictionary<ScopedTypeName, Type> missingTypes; private bool resolveMissingMembers; private readonly bool enableFunctionPointers; private readonly bool useNativeFusion; private readonly bool returnPseudoCustomAttributes; private Type typeof_System_Object; private Type typeof_System_ValueType; private Type typeof_System_Enum; private Type typeof_System_Void; private Type typeof_System_Boolean; private Type typeof_System_Char; private Type typeof_System_SByte; private Type typeof_System_Byte; private Type typeof_System_Int16; private Type typeof_System_UInt16; private Type typeof_System_Int32; private Type typeof_System_UInt32; private Type typeof_System_Int64; private Type typeof_System_UInt64; private Type typeof_System_Single; private Type typeof_System_Double; private Type typeof_System_String; private Type typeof_System_IntPtr; private Type typeof_System_UIntPtr; private Type typeof_System_TypedReference; private Type typeof_System_Type; private Type typeof_System_Array; private Type typeof_System_DateTime; private Type typeof_System_DBNull; private Type typeof_System_Decimal; private Type typeof_System_NonSerializedAttribute; private Type typeof_System_SerializableAttribute; private Type typeof_System_AttributeUsageAttribute; private Type typeof_System_Runtime_InteropServices_DllImportAttribute; private Type typeof_System_Runtime_InteropServices_FieldOffsetAttribute; private Type typeof_System_Runtime_InteropServices_InAttribute; private Type typeof_System_Runtime_InteropServices_MarshalAsAttribute; private Type typeof_System_Runtime_InteropServices_UnmanagedType; private Type typeof_System_Runtime_InteropServices_VarEnum; private Type typeof_System_Runtime_InteropServices_OutAttribute; private Type typeof_System_Runtime_InteropServices_StructLayoutAttribute; private Type typeof_System_Runtime_InteropServices_OptionalAttribute; private Type typeof_System_Runtime_InteropServices_PreserveSigAttribute; private Type typeof_System_Runtime_InteropServices_CallingConvention; private Type typeof_System_Runtime_InteropServices_CharSet; private Type typeof_System_Runtime_InteropServices_ComImportAttribute; private Type typeof_System_Runtime_CompilerServices_DecimalConstantAttribute; private Type typeof_System_Runtime_CompilerServices_SpecialNameAttribute; private Type typeof_System_Runtime_CompilerServices_MethodImplAttribute; private Type typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute; private Type typeof_System_Reflection_AssemblyCopyrightAttribute; private Type typeof_System_Reflection_AssemblyTrademarkAttribute; private Type typeof_System_Reflection_AssemblyProductAttribute; private Type typeof_System_Reflection_AssemblyCompanyAttribute; private Type typeof_System_Reflection_AssemblyDescriptionAttribute; private Type typeof_System_Reflection_AssemblyTitleAttribute; private Type typeof_System_Reflection_AssemblyInformationalVersionAttribute; private Type typeof_System_Reflection_AssemblyFileVersionAttribute; private Type typeof_System_Security_Permissions_CodeAccessSecurityAttribute; private Type typeof_System_Security_Permissions_PermissionSetAttribute; private Type typeof_System_Security_Permissions_SecurityAction; private List<ResolveEventHandler> resolvers = new List<ResolveEventHandler>(); private Predicate<Type> missingTypeIsValueType; public Universe() : this(UniverseOptions.None) { } public Universe(UniverseOptions options) { enableFunctionPointers = (options & UniverseOptions.EnableFunctionPointers) != 0; useNativeFusion = (options & UniverseOptions.DisableFusion) == 0 && GetUseNativeFusion(); returnPseudoCustomAttributes = (options & UniverseOptions.DisablePseudoCustomAttributeRetrieval) == 0; } private static bool GetUseNativeFusion() { try { return Environment.OSVersion.Platform == PlatformID.Win32NT && !MonoRuntime && Environment.GetEnvironmentVariable("IKVM_DISABLE_FUSION") == null; } catch (System.Security.SecurityException) { return false; } } internal Assembly Mscorlib { get { return Load("mscorlib"); } } private Type ImportMscorlibType(System.Type type) { if (Mscorlib.__IsMissing) { return Mscorlib.ResolveType(new TypeName(type.Namespace, type.Name)); } // We use FindType instead of ResolveType here, because on some versions of mscorlib some of // the special types we use/support are missing and the type properties are defined to // return null in that case. // Note that we don't have to unescape type.Name here, because none of the names contain special characters. return Mscorlib.FindType(new TypeName(type.Namespace, type.Name)); } private Type ResolvePrimitive(string name) { // Primitive here means that these types have a special metadata encoding, which means that // there can be references to them without referring to them by name explicitly. // We want these types to be usable even when they don't exist in mscorlib or there is no mscorlib loaded. return Mscorlib.FindType(new TypeName("System", name)) ?? GetMissingType(Mscorlib.ManifestModule, null, new TypeName("System", name)); } internal Type System_Object { get { return typeof_System_Object ?? (typeof_System_Object = ResolvePrimitive("Object")); } } internal Type System_ValueType { // System.ValueType is not a primitive, but generic type parameters can have a ValueType constraint // (we also don't want to return null here) get { return typeof_System_ValueType ?? (typeof_System_ValueType = ResolvePrimitive("ValueType")); } } internal Type System_Enum { // System.Enum is not a primitive, but we don't want to return null get { return typeof_System_Enum ?? (typeof_System_Enum = ResolvePrimitive("Enum")); } } internal Type System_Void { get { return typeof_System_Void ?? (typeof_System_Void = ResolvePrimitive("Void")); } } internal Type System_Boolean { get { return typeof_System_Boolean ?? (typeof_System_Boolean = ResolvePrimitive("Boolean")); } } internal Type System_Char { get { return typeof_System_Char ?? (typeof_System_Char = ResolvePrimitive("Char")); } } internal Type System_SByte { get { return typeof_System_SByte ?? (typeof_System_SByte = ResolvePrimitive("SByte")); } } internal Type System_Byte { get { return typeof_System_Byte ?? (typeof_System_Byte = ResolvePrimitive("Byte")); } } internal Type System_Int16 { get { return typeof_System_Int16 ?? (typeof_System_Int16 = ResolvePrimitive("Int16")); } } internal Type System_UInt16 { get { return typeof_System_UInt16 ?? (typeof_System_UInt16 = ResolvePrimitive("UInt16")); } } internal Type System_Int32 { get { return typeof_System_Int32 ?? (typeof_System_Int32 = ResolvePrimitive("Int32")); } } internal Type System_UInt32 { get { return typeof_System_UInt32 ?? (typeof_System_UInt32 = ResolvePrimitive("UInt32")); } } internal Type System_Int64 { get { return typeof_System_Int64 ?? (typeof_System_Int64 = ResolvePrimitive("Int64")); } } internal Type System_UInt64 { get { return typeof_System_UInt64 ?? (typeof_System_UInt64 = ResolvePrimitive("UInt64")); } } internal Type System_Single { get { return typeof_System_Single ?? (typeof_System_Single = ResolvePrimitive("Single")); } } internal Type System_Double { get { return typeof_System_Double ?? (typeof_System_Double = ResolvePrimitive("Double")); } } internal Type System_String { get { return typeof_System_String ?? (typeof_System_String = ResolvePrimitive("String")); } } internal Type System_IntPtr { get { return typeof_System_IntPtr ?? (typeof_System_IntPtr = ResolvePrimitive("IntPtr")); } } internal Type System_UIntPtr { get { return typeof_System_UIntPtr ?? (typeof_System_UIntPtr = ResolvePrimitive("UIntPtr")); } } internal Type System_TypedReference { get { return typeof_System_TypedReference ?? (typeof_System_TypedReference = ResolvePrimitive("TypedReference")); } } internal Type System_Type { // System.Type is not a primitive, but it does have a special encoding in custom attributes get { return typeof_System_Type ?? (typeof_System_Type = ResolvePrimitive("Type")); } } internal Type System_Array { // System.Array is not a primitive, but it used as a base type for array types (that are primitives) get { return typeof_System_Array ?? (typeof_System_Array = ResolvePrimitive("Array")); } } internal Type System_DateTime { get { return typeof_System_DateTime ?? (typeof_System_DateTime = ImportMscorlibType(typeof(System.DateTime))); } } internal Type System_DBNull { get { return typeof_System_DBNull ?? (typeof_System_DBNull = ImportMscorlibType(typeof(System.DBNull))); } } internal Type System_Decimal { get { return typeof_System_Decimal ?? (typeof_System_Decimal = ImportMscorlibType(typeof(System.Decimal))); } } internal Type System_NonSerializedAttribute { get { return typeof_System_NonSerializedAttribute ?? (typeof_System_NonSerializedAttribute = ImportMscorlibType(typeof(System.NonSerializedAttribute))); } } internal Type System_SerializableAttribute { get { return typeof_System_SerializableAttribute ?? (typeof_System_SerializableAttribute = ImportMscorlibType(typeof(System.SerializableAttribute))); } } internal Type System_AttributeUsageAttribute { get { return typeof_System_AttributeUsageAttribute ?? (typeof_System_AttributeUsageAttribute = ImportMscorlibType(typeof(System.AttributeUsageAttribute))); } } internal Type System_Runtime_InteropServices_DllImportAttribute { get { return typeof_System_Runtime_InteropServices_DllImportAttribute ?? (typeof_System_Runtime_InteropServices_DllImportAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.DllImportAttribute))); } } internal Type System_Runtime_InteropServices_FieldOffsetAttribute { get { return typeof_System_Runtime_InteropServices_FieldOffsetAttribute ?? (typeof_System_Runtime_InteropServices_FieldOffsetAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.FieldOffsetAttribute))); } } internal Type System_Runtime_InteropServices_InAttribute { get { return typeof_System_Runtime_InteropServices_InAttribute ?? (typeof_System_Runtime_InteropServices_InAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.InAttribute))); } } internal Type System_Runtime_InteropServices_MarshalAsAttribute { get { return typeof_System_Runtime_InteropServices_MarshalAsAttribute ?? (typeof_System_Runtime_InteropServices_MarshalAsAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.MarshalAsAttribute))); } } internal Type System_Runtime_InteropServices_UnmanagedType { get { return typeof_System_Runtime_InteropServices_UnmanagedType ?? (typeof_System_Runtime_InteropServices_UnmanagedType = ImportMscorlibType(typeof(System.Runtime.InteropServices.UnmanagedType))); } } internal Type System_Runtime_InteropServices_VarEnum { get { return typeof_System_Runtime_InteropServices_VarEnum ?? (typeof_System_Runtime_InteropServices_VarEnum = ImportMscorlibType(typeof(System.Runtime.InteropServices.VarEnum))); } } internal Type System_Runtime_InteropServices_OutAttribute { get { return typeof_System_Runtime_InteropServices_OutAttribute ?? (typeof_System_Runtime_InteropServices_OutAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.OutAttribute))); } } internal Type System_Runtime_InteropServices_StructLayoutAttribute { get { return typeof_System_Runtime_InteropServices_StructLayoutAttribute ?? (typeof_System_Runtime_InteropServices_StructLayoutAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.StructLayoutAttribute))); } } internal Type System_Runtime_InteropServices_OptionalAttribute { get { return typeof_System_Runtime_InteropServices_OptionalAttribute ?? (typeof_System_Runtime_InteropServices_OptionalAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.OptionalAttribute))); } } internal Type System_Runtime_InteropServices_PreserveSigAttribute { get { return typeof_System_Runtime_InteropServices_PreserveSigAttribute ?? (typeof_System_Runtime_InteropServices_PreserveSigAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.PreserveSigAttribute))); } } internal Type System_Runtime_InteropServices_CallingConvention { get { return typeof_System_Runtime_InteropServices_CallingConvention ?? (typeof_System_Runtime_InteropServices_CallingConvention = ImportMscorlibType(typeof(System.Runtime.InteropServices.CallingConvention))); } } internal Type System_Runtime_InteropServices_CharSet { get { return typeof_System_Runtime_InteropServices_CharSet ?? (typeof_System_Runtime_InteropServices_CharSet = ImportMscorlibType(typeof(System.Runtime.InteropServices.CharSet))); } } internal Type System_Runtime_InteropServices_ComImportAttribute { get { return typeof_System_Runtime_InteropServices_ComImportAttribute ?? (typeof_System_Runtime_InteropServices_ComImportAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.ComImportAttribute))); } } internal Type System_Runtime_CompilerServices_DecimalConstantAttribute { get { return typeof_System_Runtime_CompilerServices_DecimalConstantAttribute ?? (typeof_System_Runtime_CompilerServices_DecimalConstantAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.DecimalConstantAttribute))); } } internal Type System_Runtime_CompilerServices_SpecialNameAttribute { get { return typeof_System_Runtime_CompilerServices_SpecialNameAttribute ?? (typeof_System_Runtime_CompilerServices_SpecialNameAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.SpecialNameAttribute))); } } internal Type System_Runtime_CompilerServices_MethodImplAttribute { get { return typeof_System_Runtime_CompilerServices_MethodImplAttribute ?? (typeof_System_Runtime_CompilerServices_MethodImplAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.MethodImplAttribute))); } } internal Type System_Security_SuppressUnmanagedCodeSecurityAttribute { get { return typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute ?? (typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute = ImportMscorlibType(typeof(System.Security.SuppressUnmanagedCodeSecurityAttribute))); } } internal Type System_Reflection_AssemblyCopyrightAttribute { get { return typeof_System_Reflection_AssemblyCopyrightAttribute ?? (typeof_System_Reflection_AssemblyCopyrightAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyCopyrightAttribute))); } } internal Type System_Reflection_AssemblyTrademarkAttribute { get { return typeof_System_Reflection_AssemblyTrademarkAttribute ?? (typeof_System_Reflection_AssemblyTrademarkAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyTrademarkAttribute))); } } internal Type System_Reflection_AssemblyProductAttribute { get { return typeof_System_Reflection_AssemblyProductAttribute ?? (typeof_System_Reflection_AssemblyProductAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyProductAttribute))); } } internal Type System_Reflection_AssemblyCompanyAttribute { get { return typeof_System_Reflection_AssemblyCompanyAttribute ?? (typeof_System_Reflection_AssemblyCompanyAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyCompanyAttribute))); } } internal Type System_Reflection_AssemblyDescriptionAttribute { get { return typeof_System_Reflection_AssemblyDescriptionAttribute ?? (typeof_System_Reflection_AssemblyDescriptionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyDescriptionAttribute))); } } internal Type System_Reflection_AssemblyTitleAttribute { get { return typeof_System_Reflection_AssemblyTitleAttribute ?? (typeof_System_Reflection_AssemblyTitleAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyTitleAttribute))); } } internal Type System_Reflection_AssemblyInformationalVersionAttribute { get { return typeof_System_Reflection_AssemblyInformationalVersionAttribute ?? (typeof_System_Reflection_AssemblyInformationalVersionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyInformationalVersionAttribute))); } } internal Type System_Reflection_AssemblyFileVersionAttribute { get { return typeof_System_Reflection_AssemblyFileVersionAttribute ?? (typeof_System_Reflection_AssemblyFileVersionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyFileVersionAttribute))); } } internal Type System_Security_Permissions_CodeAccessSecurityAttribute { get { return typeof_System_Security_Permissions_CodeAccessSecurityAttribute ?? (typeof_System_Security_Permissions_CodeAccessSecurityAttribute = ImportMscorlibType(typeof(System.Security.Permissions.CodeAccessSecurityAttribute))); } } internal Type System_Security_Permissions_PermissionSetAttribute { get { return typeof_System_Security_Permissions_PermissionSetAttribute ?? (typeof_System_Security_Permissions_PermissionSetAttribute = ImportMscorlibType(typeof(System.Security.Permissions.PermissionSetAttribute))); } } internal Type System_Security_Permissions_SecurityAction { get { return typeof_System_Security_Permissions_SecurityAction ?? (typeof_System_Security_Permissions_SecurityAction = ImportMscorlibType(typeof(System.Security.Permissions.SecurityAction))); } } internal bool HasMscorlib { get { return GetLoadedAssembly("mscorlib") != null; } } public event ResolveEventHandler AssemblyResolve { add { resolvers.Add(value); } remove { resolvers.Remove(value); } } public Type Import(System.Type type) { Type imported; if (!importedTypes.TryGetValue(type, out imported)) { imported = ImportImpl(type); if (imported != null) { importedTypes.Add(type, imported); } } return imported; } private Type ImportImpl(System.Type type) { if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly) { throw new ArgumentException("Did you really want to import " + type.FullName + "?"); } if (type.HasElementType) { if (type.IsArray) { if (type.Name.EndsWith("[]")) { return Import(type.GetElementType()).MakeArrayType(); } else { return Import(type.GetElementType()).MakeArrayType(type.GetArrayRank()); } } else if (type.IsByRef) { return Import(type.GetElementType()).MakeByRefType(); } else if (type.IsPointer) { return Import(type.GetElementType()).MakePointerType(); } else { throw new InvalidOperationException(); } } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null) { throw new NotImplementedException(); } else { return Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition]; } } else if (type.IsGenericType && !type.IsGenericTypeDefinition) { System.Type[] args = type.GetGenericArguments(); Type[] importedArgs = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { importedArgs[i] = Import(args[i]); } return Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs); } else if (type.IsNested) { // note that we can't pass in the namespace here, because .NET's Type.Namespace implementation is broken for nested types // (it returns the namespace of the declaring type) return Import(type.DeclaringType).ResolveNestedType(new TypeName(null, type.Name)); } else if (type.Assembly == typeof(object).Assembly) { // make sure mscorlib types always end up in our mscorlib return Mscorlib.ResolveType(new TypeName(type.Namespace, type.Name)); } else { return Import(type.Assembly).ResolveType(new TypeName(type.Namespace, type.Name)); } } private Assembly Import(System.Reflection.Assembly asm) { return Load(asm.FullName); } public RawModule OpenRawModule(string path) { path = Path.GetFullPath(path); return OpenRawModule(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), path); } public RawModule OpenRawModule(Stream stream, string location) { if (!stream.CanRead || !stream.CanSeek || stream.Position != 0) { throw new ArgumentException("Stream must support read/seek and current position must be zero.", "stream"); } return new RawModule(new ModuleReader(null, this, stream, location)); } public Assembly LoadAssembly(RawModule module) { string refname = module.GetAssemblyName().FullName; Assembly asm = GetLoadedAssembly(refname); if (asm == null) { AssemblyReader asm1 = module.ToAssembly(); assemblies.Add(asm1); asm = asm1; } return asm; } public Assembly LoadFile(string path) { try { using (RawModule module = OpenRawModule(path)) { return LoadAssembly(module); } } catch (IOException x) { throw new FileNotFoundException(x.Message, x); } catch (UnauthorizedAccessException x) { throw new FileNotFoundException(x.Message, x); } } private static string GetSimpleAssemblyName(string refname) { int pos; string name; if (Fusion.ParseAssemblySimpleName(refname, out pos, out name) != ParseAssemblyResult.OK) { throw new ArgumentException(); } return name; } private Assembly GetLoadedAssembly(string refname) { Assembly asm; if (!assembliesByName.TryGetValue(refname, out asm)) { string simpleName = GetSimpleAssemblyName(refname); for (int i = 0; i < assemblies.Count; i++) { AssemblyComparisonResult result; if (simpleName.Equals(assemblies[i].Name, StringComparison.InvariantCultureIgnoreCase) && CompareAssemblyIdentity(refname, false, assemblies[i].FullName, false, out result)) { asm = assemblies[i]; assembliesByName.Add(refname, asm); break; } } } return asm; } private Assembly GetDynamicAssembly(string refname) { string simpleName = GetSimpleAssemblyName(refname); foreach (AssemblyBuilder asm in dynamicAssemblies) { AssemblyComparisonResult result; if (simpleName.Equals(asm.Name, StringComparison.InvariantCultureIgnoreCase) && CompareAssemblyIdentity(refname, false, asm.FullName, false, out result)) { return asm; } } return null; } public Assembly Load(string refname) { return Load(refname, null, true); } internal Assembly Load(string refname, Assembly requestingAssembly, bool throwOnError) { Assembly asm = GetLoadedAssembly(refname); if (asm != null) { return asm; } if (resolvers.Count == 0) { asm = DefaultResolver(refname, throwOnError); } else { ResolveEventArgs args = new ResolveEventArgs(refname, requestingAssembly); foreach (ResolveEventHandler evt in resolvers) { asm = evt(this, args); if (asm != null) { break; } } if (asm == null) { asm = GetDynamicAssembly(refname); } } if (asm != null) { string defname = asm.FullName; if (refname != defname) { assembliesByName.Add(refname, asm); } return asm; } if (throwOnError) { throw new FileNotFoundException(refname); } return null; } private Assembly DefaultResolver(string refname, bool throwOnError) { Assembly asm = GetDynamicAssembly(refname); if (asm != null) { return asm; } string fileName; if (throwOnError) { try { fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location; } catch (System.BadImageFormatException x) { throw new BadImageFormatException(x.Message, x); } } else { try { fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location; } catch (System.BadImageFormatException x) { throw new BadImageFormatException(x.Message, x); } catch (FileNotFoundException) { // we intentionally only swallow the FileNotFoundException, if the file exists but isn't a valid assembly, // we should throw an exception return null; } } return LoadFile(fileName); } public Type GetType(string assemblyQualifiedTypeName) { // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(), // import that assembly and pass it as the context, but implicitly importing is considered evil return GetType(null, assemblyQualifiedTypeName, false, false); } public Type GetType(string assemblyQualifiedTypeName, bool throwOnError) { // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(), // import that assembly and pass it as the context, but implicitly importing is considered evil return GetType(null, assemblyQualifiedTypeName, throwOnError, false); } public Type GetType(string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase) { // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(), // import that assembly and pass it as the context, but implicitly importing is considered evil return GetType(null, assemblyQualifiedTypeName, throwOnError, ignoreCase); } // note that context is slightly different from the calling assembly (System.Type.GetType), // because context is passed to the AssemblyResolve event as the RequestingAssembly public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError) { return GetType(context, assemblyQualifiedTypeName, throwOnError, false); } // note that context is slightly different from the calling assembly (System.Type.GetType), // because context is passed to the AssemblyResolve event as the RequestingAssembly public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase) { TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, throwOnError); if (parser.Error) { return null; } return parser.GetType(this, context, throwOnError, assemblyQualifiedTypeName, false, ignoreCase); } // this is similar to GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError), // but instead it assumes that the type must exist (i.e. if EnableMissingMemberResolution is enabled // it will create a missing type) public Type ResolveType(Assembly context, string assemblyQualifiedTypeName) { TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, false); if (parser.Error) { return null; } return parser.GetType(this, context, false, assemblyQualifiedTypeName, true, false); } public Assembly[] GetAssemblies() { Assembly[] array = new Assembly[assemblies.Count + dynamicAssemblies.Count]; for (int i = 0; i < assemblies.Count; i++) { array[i] = assemblies[i]; } for (int i = 0, j = assemblies.Count; j < array.Length; i++, j++) { array[j] = dynamicAssemblies[i]; } return array; } // this is equivalent to the Fusion CompareAssemblyIdentity API public bool CompareAssemblyIdentity(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result) { return useNativeFusion ? Fusion.CompareAssemblyIdentityNative(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result) : Fusion.CompareAssemblyIdentityPure(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result); } public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { return DefineDynamicAssemblyImpl(name, access, null, null, null, null); } public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir) { return DefineDynamicAssemblyImpl(name, access, dir, null, null, null); } #if NET_4_0 [Obsolete] #endif public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) { return DefineDynamicAssemblyImpl(name, access, dir, requiredPermissions, optionalPermissions, refusedPermissions); } private AssemblyBuilder DefineDynamicAssemblyImpl(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) { AssemblyBuilder asm = new AssemblyBuilder(this, name, dir, requiredPermissions, optionalPermissions, refusedPermissions); dynamicAssemblies.Add(asm); return asm; } internal void RenameAssembly(Assembly assembly, AssemblyName oldName) { List<string> remove = new List<string>(); foreach (KeyValuePair<string, Assembly> kv in assembliesByName) { if (kv.Value == assembly) { remove.Add(kv.Key); } } foreach (string key in remove) { assembliesByName.Remove(key); } } public void Dispose() { foreach (Assembly asm in assemblies) { foreach (Module mod in asm.GetLoadedModules()) { mod.Dispose(); } } foreach (AssemblyBuilder asm in dynamicAssemblies) { foreach (Module mod in asm.GetLoadedModules()) { mod.Dispose(); } } } public Assembly CreateMissingAssembly(string assemblyName) { Assembly asm = new MissingAssembly(this, assemblyName); string name = asm.FullName; if (!assembliesByName.ContainsKey(name)) { assembliesByName.Add(name, asm); } return asm; } public void EnableMissingMemberResolution() { resolveMissingMembers = true; } internal bool MissingMemberResolution { get { return resolveMissingMembers; } } internal bool EnableFunctionPointers { get { return enableFunctionPointers; } } private struct ScopedTypeName : IEquatable<ScopedTypeName> { private readonly object scope; private readonly TypeName name; internal ScopedTypeName(object scope, TypeName name) { this.scope = scope; this.name = name; } public override bool Equals(object obj) { ScopedTypeName? other = obj as ScopedTypeName?; return other != null && ((IEquatable<ScopedTypeName>)other.Value).Equals(this); } public override int GetHashCode() { return scope.GetHashCode() * 7 + name.GetHashCode(); } bool IEquatable<ScopedTypeName>.Equals(ScopedTypeName other) { return other.scope == scope && other.name == name; } } private Type GetMissingType(Module module, Type declaringType, TypeName typeName) { if (missingTypes == null) { missingTypes = new Dictionary<ScopedTypeName, Type>(); } ScopedTypeName stn = new ScopedTypeName(declaringType ?? (object)module, typeName); Type type; if (!missingTypes.TryGetValue(stn, out type)) { type = new MissingType(module, declaringType, typeName.Namespace, typeName.Name); missingTypes.Add(stn, type); } return type; } internal Type GetMissingTypeOrThrow(Module module, Type declaringType, TypeName typeName) { if (resolveMissingMembers || module.Assembly.__IsMissing) { return GetMissingType(module, declaringType, typeName); } string fullName = TypeNameParser.Escape(typeName.ToString()); if (declaringType != null) { fullName = declaringType.FullName + "+" + fullName; } throw new TypeLoadException(String.Format("Type '{0}' not found in assembly '{1}'", fullName, module.Assembly.FullName)); } internal MethodBase GetMissingMethodOrThrow(Type declaringType, string name, MethodSignature signature) { if (resolveMissingMembers) { MethodInfo method = new MissingMethod(declaringType, name, signature); if (name == ".ctor") { return new ConstructorInfoImpl(method); } return method; } throw new MissingMethodException(declaringType.ToString(), name); } internal FieldInfo GetMissingFieldOrThrow(Type declaringType, string name, FieldSignature signature) { if (resolveMissingMembers) { return new MissingField(declaringType, name, signature); } throw new MissingFieldException(declaringType.ToString(), name); } internal PropertyInfo GetMissingPropertyOrThrow(Type declaringType, string name, PropertySignature propertySignature) { // HACK we need to check __IsMissing here, because Type doesn't have a FindProperty API // since properties are never resolved, except by custom attributes if (resolveMissingMembers || declaringType.__IsMissing) { return new MissingProperty(declaringType, name, propertySignature); } throw new System.MissingMemberException(declaringType.ToString(), name); } internal Type CanonicalizeType(Type type) { Type canon; if (!canonicalizedTypes.TryGetValue(type, out canon)) { canon = type; canonicalizedTypes.Add(canon, canon); } return canon; } public Type MakeFunctionPointer(__StandAloneMethodSig sig) { return FunctionPointerType.Make(this, sig); } public __StandAloneMethodSig MakeStandAloneMethodSig(System.Runtime.InteropServices.CallingConvention callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers) { return new __StandAloneMethodSig(true, callingConvention, 0, returnType ?? this.System_Void, Util.Copy(parameterTypes), Type.EmptyTypes, PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes))); } public __StandAloneMethodSig MakeStandAloneMethodSig(CallingConventions callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, Type[] optionalParameterTypes, CustomModifiers[] parameterTypeCustomModifiers) { return new __StandAloneMethodSig(false, 0, callingConvention, returnType ?? this.System_Void, Util.Copy(parameterTypes), Util.Copy(optionalParameterTypes), PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes) + Util.NullSafeLength(optionalParameterTypes))); } public event Predicate<Type> MissingTypeIsValueType { add { if (missingTypeIsValueType != null) { throw new InvalidOperationException("Only a single MissingTypeIsValueType handler can be registered."); } missingTypeIsValueType = value; } remove { if (value.Equals(missingTypeIsValueType)) { missingTypeIsValueType = null; } } } internal bool ResolveMissingTypeIsValueType(MissingType missingType) { if (missingTypeIsValueType != null) { return missingTypeIsValueType(missingType); } throw new MissingMemberException(missingType); } internal bool ReturnPseudoCustomAttributes { get { return returnPseudoCustomAttributes; } } } }
34.939616
254
0.765456
[ "Apache-2.0" ]
asegeda-softheme/mono
mcs/class/IKVM.Reflection/Universe.cs
38,189
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CognitoIdentityProvider.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations { /// <summary> /// GetGroup Request Marshaller /// </summary> public class GetGroupRequestMarshaller : IMarshaller<IRequest, GetGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetGroupRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetGroupRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CognitoIdentityProvider"); string target = "AWSCognitoIdentityProviderService.GetGroup"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-04-18"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetGroupName()) { context.Writer.WritePropertyName("GroupName"); context.Writer.Write(publicRequest.GroupName); } if(publicRequest.IsSetUserPoolId()) { context.Writer.WritePropertyName("UserPoolId"); context.Writer.Write(publicRequest.UserPoolId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetGroupRequestMarshaller _instance = new GetGroupRequestMarshaller(); internal static GetGroupRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetGroupRequestMarshaller Instance { get { return _instance; } } } }
35.153153
131
0.620707
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/Internal/MarshallTransformations/GetGroupRequestMarshaller.cs
3,902
C#
namespace SaaSOvation.Collaboration.Domain.Model.Forums { public interface IPostRepository { Post Get(Tenants.Tenant tenantId, PostId postId); PostId GetNextIdentity(); void Save(Post post); } }
19.5
57
0.67094
[ "Apache-2.0" ]
GermanKuber-zz/IDDD_Samples_NET
iddd_collaboration/Domain.Model/Forums/IPostRepository.cs
236
C#
using DarkUI.Controls; using System.Windows.Forms; namespace Grimoire.UI { partial class Set { public static Set Instance = new Set(); /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.btnSave = new DarkUI.Controls.DarkButton(); this.listBox1 = new DarkUI.Controls.DarkListBox(this.components); this.comboBox1 = new DarkUI.Controls.DarkComboBox(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.btnAdd = new DarkUI.Controls.DarkButton(); this.btnRefresh = new DarkUI.Controls.DarkButton(); this.btnLoad = new DarkUI.Controls.DarkButton(); this.btnClear = new DarkUI.Controls.DarkButton(); this.SuspendLayout(); // // btnSave // this.btnSave.Checked = false; this.btnSave.Location = new System.Drawing.Point(10, 355); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(112, 23); this.btnSave.TabIndex = 0; this.btnSave.Text = "Save"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // listBox1 // this.listBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(51)))), ((int)(((byte)(66))))); this.listBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.listBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220))))); this.listBox1.FormattingEnabled = true; this.listBox1.ItemHeight = 18; this.listBox1.Location = new System.Drawing.Point(10, 65); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(352, 110); this.listBox1.TabIndex = 1; // // comboBox1 // this.comboBox1.DisplayMember = "Name"; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(58, 13); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(206, 21); this.comboBox1.TabIndex = 3; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // openFileDialog1 // this.openFileDialog1.FileName = "openFileDialog1"; // // btnAdd // this.btnAdd.Checked = false; this.btnAdd.Location = new System.Drawing.Point(270, 11); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(98, 23); this.btnAdd.TabIndex = 5; this.btnAdd.Text = "Add"; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnRefresh // this.btnRefresh.Checked = false; this.btnRefresh.Location = new System.Drawing.Point(12, 12); this.btnRefresh.Name = "btnRefresh"; this.btnRefresh.Size = new System.Drawing.Size(40, 23); this.btnRefresh.TabIndex = 6; this.btnRefresh.Text = "R"; this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click); // // btnLoad // this.btnLoad.Checked = false; this.btnLoad.Location = new System.Drawing.Point(250, 355); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(112, 23); this.btnLoad.TabIndex = 0; this.btnLoad.Text = "Load"; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // btnClear // this.btnClear.Checked = false; this.btnClear.Location = new System.Drawing.Point(270, 36); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(98, 23); this.btnClear.TabIndex = 5; this.btnClear.Text = "Clear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // Set // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(32)))), ((int)(((byte)(40))))); this.ClientSize = new System.Drawing.Size(374, 387); this.Controls.Add(this.btnRefresh); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnAdd); this.Controls.Add(this.comboBox1); this.Controls.Add(this.listBox1); this.Controls.Add(this.btnLoad); this.Controls.Add(this.btnSave); this.Icon = global::Properties.Resources.GrimoireIcon; this.Name = "Set"; this.Text = "Set"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Set_FormClosing); this.Load += new System.EventHandler(this.Set_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.OpenFileDialog openFileDialog1; private DarkButton btnSave; private DarkListBox listBox1; private DarkComboBox comboBox1; private DarkButton btnAdd; private DarkButton btnRefresh; private DarkButton btnLoad; private DarkButton btnClear; } }
43.18239
140
0.573405
[ "CC0-1.0" ]
GentleGanku/GrimliteRev
Source Code/Grimlite Rev (Bordered)/Grimoire.UI/Set.Designer.cs
6,868
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Query; namespace Microsoft.EntityFrameworkCore { /// <summary> /// Static methods that are useful in application code where there is not an EF type for the method to be accessed from. For example, /// referencing a shadow state property in a LINQ query. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-database-functions">Database functions</see> and /// <see href="https://aka.ms/efcore-docs-efproperty">Using EF.Property in EF Core queries</see> for more information. /// </remarks> // ReSharper disable once InconsistentNaming public static partial class EF { internal static readonly MethodInfo PropertyMethod = typeof(EF).GetRequiredDeclaredMethod(nameof(Property)); /// <summary> /// <para> /// References a given property or navigation on an entity instance. This is useful for shadow state properties, for /// which no CLR property exists. Currently this method can only be used in LINQ queries and can not be used to /// access the value assigned to a property in other scenarios. /// </para> /// <para> /// Note that this is a static method accessed through the top-level <see cref="EF" /> static type. /// </para> /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-efproperty">Using EF.Property in EF Core queries</see> for more information. /// </remarks> /// <example> /// <para> /// The following code performs a filter using the a LastUpdated shadow state property. /// </para> /// <code> /// var blogs = context.Blogs /// .Where(b =&gt; EF.Property&lt;DateTime&gt;(b, "LastUpdated") > DateTime.Now.AddDays(-5)); /// </code> /// </example> /// <typeparam name="TProperty"> The type of the property being referenced. </typeparam> /// <param name="entity"> The entity to access the property on. </param> /// <param name="propertyName"> The name of the property. </param> /// <returns> The value assigned to the property. </returns> public static TProperty Property<TProperty>( object entity, [NotParameterized] string propertyName) => throw new InvalidOperationException(CoreStrings.PropertyMethodInvoked); /// <summary> /// <para> /// Provides CLR methods that get translated to database functions when used in LINQ to Entities queries. /// Calling these methods in other contexts (e.g. LINQ to Objects) will throw a <see cref="NotSupportedException" />. /// </para> /// <para> /// Note that this is a static property accessed through the top-level <see cref="EF" /> static type. /// </para> /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-database-functions">Database functions</see> for more information. /// </remarks> public static DbFunctions Functions => DbFunctions.Instance; } }
48.916667
141
0.608177
[ "MIT" ]
CameronAavik/efcore
src/EFCore/EF.cs
3,522
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.OSConfig.V1.Inputs { /// <summary> /// VM inventory details. /// </summary> public sealed class OSPolicyAssignmentInstanceFilterInventoryArgs : Pulumi.ResourceArgs { /// <summary> /// The OS short name /// </summary> [Input("osShortName", required: true)] public Input<string> OsShortName { get; set; } = null!; /// <summary> /// The OS version Prefix matches are supported if asterisk(*) is provided as the last character. For example, to match all versions with a major version of `7`, specify the following value for this field `7.*` An empty string matches all OS versions. /// </summary> [Input("osVersion")] public Input<string>? OsVersion { get; set; } public OSPolicyAssignmentInstanceFilterInventoryArgs() { } } }
33.8
259
0.65765
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/OSConfig/V1/Inputs/OSPolicyAssignmentInstanceFilterInventoryArgs.cs
1,183
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace Altinn.Platform.Storage.Interface.Models { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] public class TextResource { /// <summary> /// Gets or sets the unique id of the text resource, format {org}-{app}-{language} e.g. ttd-demoapp-nb /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the org, used as a partition key /// </summary> [JsonProperty(PropertyName = "org")] public string Org {get; set;} /// <summary> /// Gets or sets the language. Should be a two letter ISO name. /// </summary> /// <value></value> [JsonProperty(PropertyName= "language")] public string Language {get; set;} /// <summary> /// Gets or sets a list of text resource elements /// </summary> [JsonProperty(PropertyName = "resources")] public List<TextResourceElement> Resources { get; set; } } public class TextResourceElement { /// <summary> /// Gets or sets the id /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// gets or sets the value /// </summary> [JsonProperty(PropertyName = "value")] public string Value { get; set; } /// <summary> /// gets or sets the variables /// </summary> [JsonProperty(PropertyName = "variables")] public List<TextResourceVariable> Variables { get; set; } } public class TextResourceVariable { /// <summary> /// gets or sets the key /// </summary> [JsonProperty(PropertyName = "key")] public string Key { get; set; } /// <summary> /// gets or sets the dataSource /// </summary> [JsonProperty(PropertyName = "dataSource")] public string DataSource { get; set; } } }
29
110
0.558429
[ "BSD-3-Clause" ]
TheTechArch/altinn-studio
src/Altinn.Platform/Altinn.Platform.Storage/Storage.Interface/Models/TextResource.cs
2,088
C#
using System.IO; using LogSharp; using LogSharp.Appenders; namespace RollFileLogging { class Program { static void Main(string[] args) { InitializeLogging(); for (int x = 0; x < 1000; ++x) { Logger.Warning($"X is at {x}"); } } static void InitializeLogging() { LogManager.Initialize(); string logPattern = "[{hour}:{minute}:{second} {meridian}] {severity}: {message}"; LogManager.Instance.LogPattern = logPattern; string directory = Path.Combine(Directory.GetCurrentDirectory(), "Log"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } RollingFileAppender fileAppender = new RollingFileAppender(1024, "application_{filenumber}.log", directory); LogManager.Instance.AddAppender(fileAppender); LogManager.Instance.AddAppender(new ConsoleAppender()); } } }
27
120
0.577973
[ "MIT" ]
mohitisgreat/LogSharp
Examples/RollFileLogging/Program.cs
1,028
C#
using Net.FreeORM.SecureHash.Encryption; using Net.FreeORM.SecureHash.Test; using System; using System.Xml; namespace Net.FreeORM.SecureHash.Property { internal class PropertyBuilder { public static string Build(ConnectionTypes connType, string propertyName, string strProperty) { try { if (string.IsNullOrWhiteSpace(strProperty) == true) throw new Exception("StrProperty is null or empty."); string strConnType = GetConnectionType(connType); string[] crypted = strProperty.Split(';', '='); for (int i = 0; i < crypted.Length; i++) { crypted[i] = Encryptor.EncodeString(crypted[i]); } XmlDocument xmlDoc = new XmlDocument(); XmlNode mainNode = CreateNode(xmlDoc, "properties", "name", "driver-type", "conn-str"); mainNode.Attributes["name"].InnerText = propertyName; mainNode.Attributes["driver-type"].InnerText = strConnType; mainNode.Attributes["conn-str"].InnerText = strProperty; XmlNode childNode = null; for (int cryptedCounter = 0; cryptedCounter < crypted.Length - 1; cryptedCounter += 2) { childNode = CreateNode(xmlDoc, "property", "key", "value"); childNode.Attributes["key"].InnerText = crypted[cryptedCounter]; childNode.Attributes["value"].InnerText = crypted[cryptedCounter + 1]; mainNode.AppendChild(childNode); } childNode = null; xmlDoc.AppendChild(mainNode); return xmlDoc.OuterXml; } catch (Exception) { throw; } } internal static XmlNode CreateNode(XmlDocument xml_doc, string nodeName, params object[] attrs) { try { XmlNode node = xml_doc.CreateElement(nodeName); XmlAttribute attr; foreach (object obj in attrs) { if (String.Format("{0}", obj).Length > 0) { attr = xml_doc.CreateAttribute(obj.ToString()); node.Attributes.Append(attr); } } return node; } catch (Exception) { throw; } } internal static string GetConnectionType(ConnectionTypes connType) { switch (connType) { default: return string.Empty; case ConnectionTypes.SqlExpress: return "sqlexpress"; case ConnectionTypes.SqlServer: return "sqlserver"; case ConnectionTypes.PostgreSQL: return "postgresql"; case ConnectionTypes.DB2: return "db2"; case ConnectionTypes.OracleNet: return "oracle"; case ConnectionTypes.OracleManaged: return "oracle-managed"; case ConnectionTypes.MySQL: return "mysql"; case ConnectionTypes.MariaDB: return "mariadb"; case ConnectionTypes.VistaDB: return "vistadb"; case ConnectionTypes.OleDb: return "oledb"; case ConnectionTypes.SQLite: return "sqlite"; case ConnectionTypes.FireBird: return "firebird"; case ConnectionTypes.SqlServerCe: return "sqlserverce"; case ConnectionTypes.Sybase: return "sybase"; case ConnectionTypes.Informix: return "informix"; case ConnectionTypes.U2: return "u2"; case ConnectionTypes.Synergy: return "synergy"; case ConnectionTypes.Ingres: return "ingres"; case ConnectionTypes.SqlBase: return "sqlbase"; case ConnectionTypes.Odbc: return "odbc"; } } } }
31.013793
103
0.483433
[ "Apache-2.0" ]
mustafasacli/Net.FreeORM.Repo
Net.FreeORM/Net.FreeORM.SecureHash/Property/PropertyBuilder.cs
4,499
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.WebSites.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Static Site User ARM resource. /// </summary> [Rest.Serialization.JsonTransformation] public partial class StaticSiteUserARMResource : ProxyOnlyResource { /// <summary> /// Initializes a new instance of the StaticSiteUserARMResource class. /// </summary> public StaticSiteUserARMResource() { CustomInit(); } /// <summary> /// Initializes a new instance of the StaticSiteUserARMResource class. /// </summary> /// <param name="id">Resource Id.</param> /// <param name="name">Resource Name.</param> /// <param name="kind">Kind of resource.</param> /// <param name="type">Resource type.</param> /// <param name="provider">The identity provider for the static site /// user.</param> /// <param name="userId">The user id for the static site user.</param> /// <param name="displayName">The display name for the static site /// user.</param> /// <param name="roles">The roles for the static site user, in /// free-form string format</param> public StaticSiteUserARMResource(string id = default(string), string name = default(string), string kind = default(string), string type = default(string), string provider = default(string), string userId = default(string), string displayName = default(string), string roles = default(string)) : base(id, name, kind, type) { Provider = provider; UserId = userId; DisplayName = displayName; Roles = roles; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the identity provider for the static site user. /// </summary> [JsonProperty(PropertyName = "properties.provider")] public string Provider { get; private set; } /// <summary> /// Gets the user id for the static site user. /// </summary> [JsonProperty(PropertyName = "properties.userId")] public string UserId { get; private set; } /// <summary> /// Gets the display name for the static site user. /// </summary> [JsonProperty(PropertyName = "properties.displayName")] public string DisplayName { get; private set; } /// <summary> /// Gets or sets the roles for the static site user, in free-form /// string format /// </summary> [JsonProperty(PropertyName = "properties.roles")] public string Roles { get; set; } } }
37.25
300
0.611653
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/websites/Microsoft.Azure.Management.WebSites/src/Generated/Models/StaticSiteUserARMResource.cs
3,278
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 08.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.String.String{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.String; using T_DATA2 =System.String; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__04__NN public static class TestSet_504__param__04__NN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ != /*}OP*/ ((object)vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ != /*}OP*/ ((object)vv2))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__04__NN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.String.String
26.262774
136
0.527793
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete2__objs/String/String/TestSet_504__param__04__NN.cs
3,600
C#
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.ProjectSystem.Properties; using Xunit; namespace Microsoft.VisualStudio.ProjectSystem.Rules { public sealed class RuleExporterTests : XamlRuleTestBase { [Theory(Skip="Waiting on all rules to be embedded")] [MemberData(nameof(GetAllRules))] public void AllRulesMustBeExported(string name, string fullPath) { name = name.Replace(".", ""); MemberInfo member = typeof(RuleExporter).GetField(name); Assert.True(member != null, $"Rule '{fullPath}' has not been exported by {nameof(RuleExporter)}. Export this rule from a member called {name}."); } [Theory] [MemberData(nameof(GetAllExportedMembers))] public void ExportedRulesMustBeStaticFields(MemberInfo member) { Assert.True(member is FieldInfo field && field.IsStatic, $"'{GetTypeQualifiedName(member)}' must be a static field."); } [Theory] [MemberData(nameof(GetAllExportedMembers))] public void ExportedRulesMustBeMarkedWithAppliesTo(MemberInfo member) { var attribute = member.GetCustomAttribute<AppliesToAttribute>(); Assert.True(attribute != null, $"'{GetTypeQualifiedName(member)}' must be marked with [AppliesTo]"); } [Theory] [MemberData(nameof(GetAllExportedMembers))] public void ExportedRulesMustBeMarkedWithOrder(MemberInfo member) { var attribute = member.GetCustomAttribute<OrderAttribute>(); Assert.True(attribute?.OrderPrecedence == Order.Default, $"'{GetTypeQualifiedName(member)}' must be marked with [Order(Order.Default)]"); } [Theory] [MemberData(nameof(GetAllExportedMembers))] public void ExportedFieldsMustEndInRule(MemberInfo member) { Assert.True(member.Name.EndsWith("Rule"), $"'{GetTypeQualifiedName(member)}' must be end in 'Rule' so that the '[ExportRule(nameof(RuleName))]' expression refers to the rule itself"); } [Theory] [MemberData(nameof(GetAllExportedMembersWithDeclaringType))] public void MembersInSameTypeMustBeMarkedWithSameAppliesTo(Type declaringType, IEnumerable<MemberInfo> members) { string? appliesTo = null; foreach (MemberInfo member in members) { var attribute = member.GetCustomAttribute<AppliesToAttribute>(); if (attribute == null) continue; // Another test will catch this if (appliesTo == null) { appliesTo = attribute.AppliesTo; } else { Assert.True(appliesTo == attribute.AppliesTo, $"{declaringType}'s member must be all have the same value for [AppliesTo]"); } } } [Theory] [MemberData(nameof(GetAllExportedMembersWithAttribute))] public void BrowseObjectsMustBeInBrowseObjectContext(MemberInfo member, ExportPropertyXamlRuleDefinitionAttribute attribute) { if (!member.Name.Contains("BrowseObject")) return; foreach (string context in attribute.Context.Split(';')) { if (context == PropertyPageContexts.BrowseObject) return; } Assert.True(false, $"'{GetTypeQualifiedName(member)}' must live in the PropertyPageContexts.BrowseObject context."); } [Theory] [MemberData(nameof(GetAllExportedMembersWithAttribute))] public void ExportedRulesMustExist(MemberInfo member, ExportPropertyXamlRuleDefinitionAttribute attribute) { Assert.NotNull(attribute); // HERE BE DRAGONS // Note the following are *not* equivalent: // Assembly.Load(assemblyNameString) // Assembly.Load(new AssemblyName(assemblyNameString)) // The first will accept certain malformed assembly names that the second does not, // and will successfully load the assembly where the second throws an exception. // CPS uses the second form when loading assemblies to extract embedded XAML, and // so we must do the same in this test. var assemblyName = new AssemblyName(attribute.XamlResourceAssemblyName); var assembly = Assembly.Load(assemblyName); using Stream stream = assembly.GetManifestResourceStream(attribute.XamlResourceStreamName); Assert.True(stream != null, $"The rule '{attribute.XamlResourceStreamName}' indicated by '{GetTypeQualifiedName(member)}' does not exist in assembly '{attribute.XamlResourceAssemblyName}'."); } private static string GetTypeQualifiedName(MemberInfo member) { return $"{member.DeclaringType.Name}.{member.Name}"; } public static IEnumerable<object[]> GetAllExportedMembers() { return RuleServices.GetAllExportedMembers().Select(member => new[] { member }); } public static IEnumerable<object[]> GetAllExportedMembersWithAttribute() { foreach (MemberInfo member in RuleServices.GetAllExportedMembers()) { Attribute attribute = member.GetCustomAttribute<ExportPropertyXamlRuleDefinitionAttribute>(); yield return new object[] { member, attribute }; } } public static IEnumerable<object[]> GetAllExportedMembersWithDeclaringType() { foreach (Type type in RuleServices.GetAllExportedTypes()) { yield return new object[] { type, RuleServices.GetDeclaredMembers(type) }; } } public static IEnumerable<object[]> GetAllRules() { return Project(GetRules(suffix: string.Empty, recursive: true)); } } }
42.091503
204
0.622516
[ "MIT" ]
Rahul-tcs/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/ProjectSystem/Rules/ExportedRuleTests.cs
6,290
C#
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Raygun.Druid4Net.IntegrationTests.Queries.Timeseries { [TestFixture] public class PagesAddedOverTimeByHour : TestQueryBase { private TimeseriesResult<QueryResult> _results; [SetUp] public void Execute() { var response = DruidClient.Timeseries<QueryResult>(q => q .Descending(true) .Aggregations(new LongSumAggregator("totalAdded", Wikipedia.Metrics.Added)) .Filter(new SelectorFilter(Wikipedia.Dimensions.CountryCode, "US")) .DataSource(Wikipedia.DataSource) .Interval(FromDate, ToDate) .Granularity(Granularities.Hour) ); _results = response.Data; } [Test] public void QueryHasCorrectNumberOfResults() { Assert.That(_results.Count, Is.EqualTo(22)); } [Test] public void FirstResultIsCorrect() { Assert.That(_results.First().Timestamp, Is.EqualTo(new DateTime(2016, 6, 27, 21, 0, 0,DateTimeKind.Utc))); Assert.That(_results.First().Result.TotalAdded, Is.EqualTo(1260)); } [Test] public void LastResultIsCorrect() { Assert.That(_results.Last().Timestamp, Is.EqualTo(new DateTime(2016, 6, 27, 0, 0, 0,DateTimeKind.Utc))); Assert.That(_results.Last().Result.TotalAdded, Is.EqualTo(1423)); } private class QueryResult { public int TotalAdded { get; set; } } } }
27.45283
112
0.67354
[ "MIT" ]
MindscapeHQ/druid4net
Raygun.Druid4Net.IntegrationTests/Queries/Timeseries/PagesAddedOverTimeByHour.cs
1,457
C#
using MediatR; using Watchster.Domain.Entities; namespace Watchster.Application.Features.Commands { public class UpdateAppSettingsCommand : IRequest<AppSettings> { public int Id { get; set; } public string Section { get; set; } public string Parameter { get; set; } public string Description { get; set; } public string Value { get; set; } } }
22.277778
65
0.648379
[ "MIT" ]
iulianPeiu6/Watchster
WatchsterSolution/Watchster.Application/Features/Commands/UpdateAppSettingsCommand.cs
403
C#
using System; using System.Reflection; using UnityEngine; using UnityEditor; using UnityEditorInternal; using Object = UnityEngine.Object; using Beans.Unity.Editor; namespace DeformEditor { /// <summary> /// Draws a reorderabe list of IComponentElements. /// </summary> /// <typeparam name="T">The type of component the element holds.</typeparam> public class ReorderableComponentElementList<T> : IDisposable where T : Component { private readonly ReorderableList list; private Editor selectedComponentInspectorEditor; /// <summary> /// Make sure your implementation of IComponentElement has a PropertyDrawer and /// serialized fields for for the component reference and active bool called "component" and "active". /// </summary> public ReorderableComponentElementList (SerializedObject serializedObject, SerializedProperty elements) { list = new ReorderableList (serializedObject, elements); list.elementHeight = EditorGUIUtility.singleLineHeight; list.onAddCallback = (list) => { var property = list.serializedProperty; property.arraySize++; // Even though in the DeformerElement class, active defaults to true, serialized bools default to false. var lastElement = property.GetArrayElementAtIndex (property.arraySize - 1); lastElement.FindPropertyRelative ("active").boolValue = true; }; list.drawHeaderCallback = (r) => GUI.Label (r, new GUIContent ($"{typeof (T).Name}s")); list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { try { var elementProperty = list.serializedProperty.GetArrayElementAtIndex (index); EditorGUI.PropertyField (rect, elementProperty); // get the current element's component property var componentProperty = elementProperty.FindPropertyRelative ("component"); if (componentProperty == null) { elementProperty.serializedObject.SetIsDifferentCacheDirty (); elementProperty.serializedObject.Update (); componentProperty = elementProperty.FindPropertyRelative ("component"); } // and the property's object reference var component = (Component)componentProperty.objectReferenceValue; // if the current element is selected if (!componentProperty.hasMultipleDifferentValues && index == list.index && component != null) { // create it's editor and draw it Editor.CreateCachedEditor (component, null, ref selectedComponentInspectorEditor); #if UNITY_2019_1_OR_NEWER SceneView.duringSceneGui -= SceneGUI; SceneView.duringSceneGui += SceneGUI; #else SceneView.onSceneGUIDelegate -= SceneGUI; SceneView.onSceneGUIDelegate += SceneGUI; #endif var foldoutName = $"{ObjectNames.NicifyVariableName (componentProperty.objectReferenceValue.GetType ().Name)} Properties"; using (var foldout = new EditorGUILayoutx.FoldoutContainerScope (list.serializedProperty, foldoutName, DeformEditorResources.GetStyle ("Box"), EditorStyles.foldout)) { if (foldout.isOpen) { selectedComponentInspectorEditor.OnInspectorGUI (); } } } } catch (NullReferenceException) { list.serializedProperty.serializedObject.SetIsDifferentCacheDirty (); list.serializedProperty.serializedObject.Update (); } }; } private void SceneGUI (SceneView sceneView) { if (selectedComponentInspectorEditor == null) return; var method = selectedComponentInspectorEditor.GetType().GetMethod("OnSceneGUI", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (method == null) return; method.Invoke (selectedComponentInspectorEditor, null); selectedComponentInspectorEditor.Repaint (); } public void DoLayoutList () { try { // list.DoLayoutList doesn't support indenting so list.DoList will be used with a manually indented rect. var rect = GUILayoutUtility.GetRect (1, list.GetHeight ()); rect = EditorGUI.IndentedRect (rect); list.DoList (rect); } // If an error is thrown, the serialized object was modified but not marked as dirty so we need to force it to sync back up with the targets. catch (InvalidOperationException) { var so = list.serializedProperty.serializedObject; so.SetIsDifferentCacheDirty (); so.Update (); } } public void Dispose () { #if UNITY_2019_1_OR_NEWER SceneView.duringSceneGui -= SceneGUI; #else SceneView.onSceneGUIDelegate -= SceneGUI; #endif Object.DestroyImmediate (selectedComponentInspectorEditor, true); selectedComponentInspectorEditor = null; } } }
35.029851
171
0.715807
[ "MIT" ]
ConstantineRudenko/Deform
Code/Editor/Data/ReorderableComponentElementList.cs
4,696
C#
namespace Havit.Business.BusinessLayerGenerator.Helpers { public enum CloneMode { /// <summary> /// Žádná kopie. /// </summary> No, /// <summary> /// Mělká kopie. /// </summary> Shallow, /// <summary> /// Hluboká kopie /// </summary> Deep } }
13
56
0.575092
[ "MIT" ]
havit/HavitFramework
Havit.Business.BusinessLayerGenerator/Helpers/CloneMode.cs
281
C#
using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using Foundatio.Repositories.Models; using Foundatio.Skeleton.Core.Collections; using Foundatio.Skeleton.Core.Models; namespace Foundatio.Skeleton.Domain.Models { public class User : IHaveData, IIdentity, IHaveDates { public string Id { get; set; } public string FullName { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public string Salt { get; set; } public string PasswordResetToken { get; set; } public DateTime PasswordResetTokenCreated { get; set; } public bool EmailNotificationsEnabled { get; set; } public bool IsActive { get; set; } public bool IsEmailAddressVerified { get; set; } public string VerifyEmailAddressToken { get; set; } public DateTime VerifyEmailAddressTokenCreated { get; set; } public string ProfileImagePath { get; set; } public DataDictionary Data { get; set; } public DateTime CreatedUtc { get; set; } public DateTime UpdatedUtc { get; set; } /// <summary> /// The organizations that the user has access to. /// </summary> public ICollection<Membership> Memberships { get; set; } /// <summary> /// General user role (type of user) /// </summary> public ICollection<string> Roles { get; set; } public ICollection<OAuthAccount> OAuthAccounts { get; set; } public User() { EmailNotificationsEnabled = true; IsActive = true; OAuthAccounts = new Collection<OAuthAccount>(); Memberships = new Collection<Membership>(); Roles = new Collection<string>(); Data = new DataDictionary(); } } public class Membership { public Membership() { Roles = new List<string>(); } public string OrganizationId { get; set; } public ICollection<string> Roles { get; set; } } public class OAuthAccount : IEquatable<OAuthAccount> { public string Provider { get; set; } public string ProviderUserId { get; set; } public string Username { get; set; } public SettingsDictionary ExtraData { get; private set; } public OAuthAccount() { ExtraData = new SettingsDictionary(); } public string EmailAddress() { if (!String.IsNullOrEmpty(Username) && Username.Contains("@")) return Username; foreach (var kvp in ExtraData) { if ((String.Equals(kvp.Key, "email") || String.Equals(kvp.Key, "account_email") || String.Equals(kvp.Key, "preferred_email") || String.Equals(kvp.Key, "personal_email")) && !String.IsNullOrEmpty(kvp.Value)) return kvp.Value; } return null; } public string FullName() { foreach (var kvp in ExtraData.Where(kvp => String.Equals(kvp.Key, "name") && !String.IsNullOrEmpty(kvp.Value))) return kvp.Value; return !String.IsNullOrEmpty(Username) && Username.Contains(" ") ? Username : null; } public bool Equals(OAuthAccount other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Provider.Equals(Provider) && other.ProviderUserId.Equals(ProviderUserId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(OAuthAccount)) return false; return Equals((OAuthAccount)obj); } public override int GetHashCode() { unchecked { int hash = 2153; if (Provider != null) hash = hash * 9929 + Provider.GetHashCode(); if (ProviderUserId != null) hash = hash * 9929 + ProviderUserId.GetHashCode(); return hash; } } } }
32.537879
222
0.57858
[ "Apache-2.0" ]
FoundatioFx/Foundatio.Skeleton
api/src/Domain/Models/User.cs
4,297
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using TypesGenerators.ArrayTypes; using TypesGenerators.BaseTypes; using TypesGenerators.CollectionTypes; namespace TypesGenerators { public static class TypesGeneratorsInitialize { private static void AddGeneratorToDictionary(IBaseGenerator generator, Dictionary<Type, IBaseGenerator> dictionary) { dictionary.Add(generator.GenerateType, generator); } public static Dictionary<Type, IBaseGenerator> InitBaseGeneratorsDictionary() { Dictionary<Type, IBaseGenerator> dictionary = new Dictionary<Type, IBaseGenerator>(); Parallel.Invoke(() => AddGeneratorToDictionary(new BoolValueGenerator(), dictionary), () => AddGeneratorToDictionary(new ByteValueGenerator(), dictionary), () => AddGeneratorToDictionary(new DateTimeValueGenerator(), dictionary), () => AddGeneratorToDictionary(new CharValueGenerator(), dictionary), () => AddGeneratorToDictionary(new DoubleValueGenerator(), dictionary), () => AddGeneratorToDictionary(new FloatValueGenerator(), dictionary), () => AddGeneratorToDictionary(new IntValueGenerator(), dictionary), () => AddGeneratorToDictionary(new LongValueGenerator(), dictionary), () => AddGeneratorToDictionary(new SByteValueGenerator(), dictionary), () => AddGeneratorToDictionary(new ShortValueGenerator(), dictionary), () => AddGeneratorToDictionary(new UIntValueGenerator(), dictionary), () => AddGeneratorToDictionary(new ULongValueGenerator(), dictionary), () => AddGeneratorToDictionary(new UShortValueGenerator(), dictionary)); return dictionary; } public static Dictionary<Type, ICollectionGenerator> InitCollectionGeneratorsDictionary(Dictionary<Type, IBaseGenerator> baseGenerators) { Dictionary<Type, ICollectionGenerator> dictionary = new Dictionary<Type, ICollectionGenerator>(); ICollectionGenerator generator = new ListGenerator(baseGenerators); dictionary.Add(generator.GenerateType, generator); return dictionary; } public static Dictionary<int, IArrayGenerator> InitArrayGeneratorsDictionary(Dictionary<Type, IBaseGenerator> baseGenerators) { Dictionary<int, IArrayGenerator> dictionary = new Dictionary<int, IArrayGenerator>(); IArrayGenerator generator = new SingleRankArrayGenerator(baseGenerators); dictionary.Add(generator.ArrayRank, generator); return dictionary; } } }
51.754717
144
0.687204
[ "MIT" ]
RedDiamond69/Faker
TypesGenerators/TypesGeneratorsInitialize.cs
2,745
C#
/* * Copyright 2009-2010 Jon Klein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using System.Collections.Generic; using Psh; using Psh.TestCase; namespace Psh.Coevolution { /// <summary> /// This problem class implements symbolic regression for floating point numbers /// using co-evolved prediction. /// </summary> /// <remarks> /// This problem class implements symbolic regression for floating point numbers /// using co-evolved prediction. The class must keep track of the amount of /// effort it takes compared to the effort of the co-evolving predictor /// population, and use about 95% of the effort. Effort based on the number of /// evaluation executions thus far, which is tracked by the interpreter. /// </remarks> public class CEFloatSymbolicRegression : PushGP { protected internal float _currentInput; protected internal long _effort; protected internal float _predictorEffortPercent; protected internal PredictionGA _predictorGA; private bool _success; private float _noResultPenalty = 1000f; /// <exception cref="System.Exception"/> protected internal override void InitFromParameters() { base.InitFromParameters(); _effort = 0; string cases = GetParam("test-cases", true); string casesClass = GetParam("test-case-class", true); if (cases == null && casesClass == null) { throw new Exception("No acceptable test-case parameter."); } if (casesClass != null) { // Get test cases from the TestCasesClass. Type iclass = Type.GetType(casesClass); object iObject = System.Activator.CreateInstance(iclass); if (!(iObject is TestCaseGenerator)) { throw (new Exception("test-case-class must inherit from class TestCaseGenerator")); } TestCaseGenerator testCaseGenerator = (TestCaseGenerator)iObject; int numTestCases = testCaseGenerator.TestCaseCount(); for (int i = 0; i < numTestCases; i++) { ObjectPair testCase = testCaseGenerator.TestCase(i); float @in = (float)testCase._first; float @out = (float)testCase._second; Print(";; Fitness case #" + i + " input: " + @in + " output: " + @out + "\n"); _testCases.Add(new GATestCase(@in, @out)); } } else { // Get test cases from test-cases. Program caselist = new Program(cases); for (int i = 0; i < caselist.Size(); i++) { Program p = (Program)caselist.DeepPeek(i); if (p.Size() < 2) { throw new Exception("Not enough elements for fitness case \"" + p + "\""); } float @in = System.Convert.ToSingle(p.DeepPeek(0).ToString()); float @out = System.Convert.ToSingle(p.DeepPeek(1).ToString()); Print(";; Fitness case #" + i + " input: " + @in + " output: " + @out + "\n"); _testCases.Add(new GATestCase(@in, @out)); } } // Create and initialize predictors _predictorEffortPercent = GetFloatParam("PREDICTOR-effort-percent", true); _predictorGA = PredictionGA.PredictionGAWithParameters(this, GetPredictorParameters(_parameters)); } protected internal override void InitInterpreter(Interpreter inInterpreter) { } /// <exception cref="System.Exception"/> protected internal override void BeginGeneration() { //trh Temporary solution, needs to actually use effort info if (_generationCount % 2 == 1) { _predictorGA.Run(1); } } /// <summary>Evaluates a solution individual using the best predictor so far.</summary> protected internal virtual void PredictIndividual(GAIndividual inIndividual, bool duringSimplify) { FloatRegFitPredictionIndividual predictor = (FloatRegFitPredictionIndividual)_predictorGA.GetBestPredictor(); float fitness = predictor.PredictSolutionFitness((PushGPIndividual)inIndividual); inIndividual.SetFitness(fitness); inIndividual.SetErrors(new List<float>()); } public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput) { _effort++; _interpreter.ClearStacks(); _currentInput = (float)inInput; FloatStack fstack = _interpreter.FloatStack(); fstack.Push(_currentInput); // Must be included in order to use the input stack. _interpreter.InputStack().Push(_currentInput); _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit); float result = fstack.Top(); // System.out.println( _interpreter + " " + result ); //trh /* * System.out.println("\nevaluations according to interpreter " + * Interpreter.GetEvaluationExecutions()); * System.out.println("evaluations according to effort " + _effort); */ // Penalize individual if there is no result on the stack. if (fstack.Size() == 0) { return _noResultPenalty; } return result - ((float)inOutput); } protected internal override bool Success() { if (_success) { return true; } GAIndividual best = _populations[_currentPopulation][_bestIndividual]; float predictedFitness = best.GetFitness(); _predictorGA.EvaluateSolutionIndividual((PushGPIndividual)best); _bestMeanFitness = best.GetFitness(); if (_bestMeanFitness <= 0.1) { _success = true; return true; } best.SetFitness(predictedFitness); return false; } protected internal override string Report() { Success(); // Finds the real fitness of the best individual return base.Report(); } /// <exception cref="System.Exception"/> private Dictionary<string, string> GetPredictorParameters(Dictionary<string, string> parameters) { Dictionary<string, string> predictorParameters = new Dictionary<string, string>(); predictorParameters["max-generations"] = int.MaxValue.ToString(); predictorParameters["problem-class"] = GetParam("PREDICTOR-problem-class"); predictorParameters["individual-class"] = GetParam("PREDICTOR-individual-class"); predictorParameters["population-size"] = GetParam("PREDICTOR-population-size"); predictorParameters["mutation-percent"] = GetParam("PREDICTOR-mutation-percent"); predictorParameters["crossover-percent"] = GetParam("PREDICTOR-crossover-percent"); predictorParameters["tournament-size"] = GetParam("PREDICTOR-tournament-size"); predictorParameters["trivial-geography-radius"] = GetParam("PREDICTOR-trivial-geography-radius"); predictorParameters["generations-between-trainers"] = GetParam("PREDICTOR-generations-between-trainers"); predictorParameters["trainer-population-size"] = GetParam("PREDICTOR-trainer-population-size"); return predictorParameters; } /// <summary> /// NOTE: This is entirely copied from PushGP, except EvaluateIndividual /// was changed to PredictIndividual, as noted below. /// </summary> protected internal override void Evaluate() { float totalFitness = 0; _bestMeanFitness = float.MaxValue; for (int n = 0; n < _populations[_currentPopulation].Length; n++) { GAIndividual i = _populations[_currentPopulation][n]; PredictIndividual(i, false); totalFitness += i.GetFitness(); if (i.GetFitness() < _bestMeanFitness) { _bestMeanFitness = i.GetFitness(); _bestIndividual = n; _bestSize = ((PushGPIndividual)i)._program.ProgramSize(); _bestErrors = i.GetErrors(); } } _populationMeanFitness = totalFitness / _populations[_currentPopulation].Length; } /// <summary> /// NOTE: This is entirely copied from PushGP, except EvaluateIndividual /// was changed to PredictIndividual, as noted below (twice). /// </summary> protected internal override PushGPIndividual Autosimplify(PushGPIndividual inIndividual, int steps) { PushGPIndividual simplest = (PushGPIndividual)inIndividual.Clone(); PushGPIndividual trial = (PushGPIndividual)inIndividual.Clone(); PredictIndividual(simplest, true); // Changed from EvaluateIndividual float bestError = simplest.GetFitness(); bool madeSimpler = false; for (int i = 0; i < steps; i++) { madeSimpler = false; float method = Rng.Next(100); if (trial._program.ProgramSize() <= 0) { break; } if (method < _simplifyFlattenPercent) { // Flatten random thing int pointIndex = Rng.Next(trial._program.ProgramSize()); object point = trial._program.Subtree(pointIndex); if (point is Program) { trial._program.Flatten(pointIndex); madeSimpler = true; } } else { // Remove small number of random things int numberToRemove = Rng.Next(3) + 1; for (int j = 0; j < numberToRemove; j++) { int trialSize = trial._program.ProgramSize(); if (trialSize > 0) { int pointIndex = Rng.Next(trialSize); trial._program.ReplaceSubtree(pointIndex, new Program()); trial._program.Flatten(pointIndex); madeSimpler = true; } } } if (madeSimpler) { PredictIndividual(trial, true); // Changed from EvaluateIndividual if (trial.GetFitness() <= bestError) { simplest = (PushGPIndividual)trial.Clone(); bestError = trial.GetFitness(); } } trial = (PushGPIndividual)simplest.Clone(); } return simplest; } } }
40.081633
113
0.686558
[ "Apache-2.0" ]
shanecelis/PshSharp
src/Coevolution/CEFloatSymbolicRegression.cs
9,820
C#
using FileHelpers; namespace ExamplesFx { public class EnumConverterExample : ExampleBase { //-> Name:Enum Converter //-> Description:When you have a string field in your files that can be better handled if you map it to an enum. //-> FileIn:Input.txt /*ALFKI|Alfreds Futterkiste|Maria Anders|SalesRepresentative ANATR|Ana Trujillo Emparedados y helados|Ana Trujillo|Owner FRANR|France restauration|Carine Schmitt|MarketingManager ANTON|Antonio Moreno Taquería|Antonio Moreno|Owner*/ //-> /File //-> File:CustomerTitle.cs public enum CustomerTitle { Owner, SalesRepresentative, MarketingManager } //-> /File //-> File:Customers with Enum.cs [DelimitedRecord("|")] public class Customer { public string CustomerID; public string CompanyName; public string ContactName; // Notice last field is our enumeration // argument "s" means converting to string representation of enum value // argument "n" means converting as integer representation of enum value // omitting FieldConverterAttribute means that enum members will be written // as their string representation // Note: this attribute makes sense only when writing records - when reading, // converter automatically supports both string and integer representation // of enum members [FieldConverter(typeof(CustomerTitle),"s")] public CustomerTitle ContactTitle; } //-> /File //-> File:RunEngine.cs public override void Run() { var engine = new DelimitedFileEngine<Customer>(); // Read input records, enumeration automatically converted Customer[] customers = engine.ReadFile("Input.txt"); foreach (var cust in customers) Console.WriteLine("Customer name {0} is a {1}", cust.ContactName, cust.ContactTitle); } //-> /File } }
33.681818
121
0.587944
[ "MIT" ]
3dsoft/FileHelpers
FileHelpers.Examples/Examples/18.Converters/50.EnumConverter.cs
2,226
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace HotFix { public class HelloWorld { public static void Start(HelloWorld self) { Debug.Log("Hello ILXTime, this method is injected"); } public static int Add(HelloWorld self, int a , int b) { return a * b; } } }
20.090909
64
0.61086
[ "MIT" ]
qq576067421/ILXTime
HotFixProject/HotFix/HotFix/Class1.cs
444
C#
using Company.Data; using Company.Domain; using Microsoft.EntityFrameworkCore; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Company.DBOperations.Repository { public class EmployeeOperations : IEmployeeOp { /// <summary> /// Global variable, instantiating the Context connection. /// </summary> private CompanyContext _companyContext = new CompanyContext(); /// <summary> /// Adds an employee to the database /// </summary> /// <param name="employee"></param> /// <returns>returns true if successful, else false</returns> public bool Add(Employee employee) { try { using (var companyContext = new CompanyContext()) { companyContext.Employees.Add(employee); companyContext.SaveChanges(); } return true; } catch (Exception ex) { return false; } } /// <summary> /// Deletes an employee from the database /// </summary> /// <param name="employee"></param> /// <returns>true if successful, else false</returns> public bool Delete(Employee employee) { try { using (var companyContext = new CompanyContext()) { companyContext.Employees.Remove(employee); companyContext.SaveChanges(); } return true; } catch (Exception) { return false; } } /// <summary> /// A query method that filters the database based on a salary(150000) threshold /// </summary> /// <returns>the data with salary above 150000</returns> public IEnumerable FilterBySalary() { using (var companyContext = new CompanyContext()) { var filtered = _companyContext.Employees .Where(e => e.SALARY > 150000) .Include(d => d.Departments) .Select(e => new { e.EMPLOYEEID, e.FIRST_NAME, e.LAST_NAME, e.EMAIL, e.PHONE_NUMBER, e.HIRE_DATE, e.SALARY, e.Departments.DEPARTMENT_NAME, e.Departments.DEPARTMENTID }) .ToList(); return filtered; } } /// <summary> /// Queries the database and gets all employee records /// that has a department /// </summary> /// <returns>an enumerable containing database data</returns> public IEnumerable GetAllButNull() { var allEmployees = _companyContext.Employees .Where(w => !string.IsNullOrEmpty(w.DEPARTMENTID.ToString())) .Include(d => d.Departments) .Select(e => new { e.EMPLOYEEID, e.FIRST_NAME, e.LAST_NAME, e.EMAIL, e.PHONE_NUMBER, e.HIRE_DATE, e.SALARY, e.Departments.DEPARTMENT_NAME, e.Departments.DEPARTMENTID }) .ToList(); return allEmployees; } /// <summary> /// Queries the database and gets all employee records /// with or without a department /// </summary> /// <returns>an enumerable containing database data</returns> public IEnumerable GetAll() { var allEmployees = _companyContext.Employees .Include(d => d.Departments) .Select(e => new { e.EMPLOYEEID, e.FIRST_NAME, e.LAST_NAME, e.EMAIL, e.PHONE_NUMBER, e.HIRE_DATE, e.SALARY, e.Departments.DEPARTMENT_NAME, e.Departments.DEPARTMENTID }) .ToList(); return allEmployees; } /// <summary> /// Updates the employee data /// </summary> /// <param name="employee"></param> /// <returns>true if successful, else false</returns> public bool Update(Employee employee) { try { if (employee.Departments.DEPARTMENTID == -1) { var d = _companyContext.Departments .Where(e => e.DEPARTMENT_NAME == employee.Departments.DEPARTMENT_NAME) .FirstOrDefault(); employee.Departments = d; } using (var companyContext = new CompanyContext()) { companyContext.Employees.Update(employee); companyContext.SaveChanges(); } return true; } catch (Exception) { return false; } } } }
32.112426
94
0.463239
[ "MIT" ]
Danotsonof/CompanyDashboard
CompanyApp/Company.DBOperations/Repository/EmployeeOperations.cs
5,429
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using HandyControlDemo.Data; namespace HandyControlDemo.ViewModel; public class ItemsDisplayViewModel : DemoViewModelBase<AvatarModel> { public ItemsDisplayViewModel(Func<List<AvatarModel>> getDataAction) { #if NET40 Task.Factory.StartNew(() => DataList = getDataAction?.Invoke()).ContinueWith(obj => DataGot = true); #else Task.Run(() => DataList = getDataAction?.Invoke()).ContinueWith(obj => DataGot = true); #endif } private bool _dataGot; public bool DataGot { get => _dataGot; #if NET40 set => Set(nameof(DataGot), ref _dataGot, value); #else set => Set(ref _dataGot, value); #endif } }
24.258065
112
0.679521
[ "MIT" ]
Muzsor/HandyControl
src/Shared/HandyControlDemo_Shared/ViewModel/Main/ItemsDisplayViewModel.cs
754
C#
using System; using System.Collections.Generic; using System.Reflection; namespace JXml { public static class TypeResolver { public static readonly Dictionary<string, Type> CustomTypeNames = new Dictionary<string, Type>(); private static readonly Dictionary<string, Type> cache = new Dictionary<string, Type>(); private static Assembly[] assemblies; public static Type Resolve(string className) { if (cache.TryGetValue(className, out Type type)) return type; if(CustomTypeNames.TryGetValue(className, out Type type2)) { cache.Add(className, type2); return type2; } if (assemblies == null) { assemblies = AppDomain.CurrentDomain.GetAssemblies(); } foreach (var ass in assemblies) { var t = ass.GetType(className, false, true); if(t != null) { type = t; break; } } if (type != null) { cache.Add(className, type); return type; } return null; } public static void ClearCache() { cache.Clear(); } } }
25.811321
105
0.490497
[ "MIT" ]
Epicguru/JDef2
JXml/TypeResolver.cs
1,370
C#
using System; class TelerikLogo { static void Main() { //input int x = int.Parse(Console.ReadLine()); int y = x; int z = x / 2 + 1; //logic char asteriks = '*'; char dot = '.'; int length = 2 * z + 2 * y - 3; int height = y + 2 * x - 2; for (int i = 0; i < height; i++) { for (int j = 0; j < length; j++) { if ((i + j == z - 1) || (j - i == length - z) || //printing z (((j - i == z - 1) || (i + j == length - z)) && (i < x + y - 1)) || //printing y and upper x (((i - j == height - x - z + 1) || (j + i == height + z + (x - 3))) && (i >= x + y - 1))) //printing lower x { Console.Write(asteriks); } else { Console.Write(dot); } } Console.WriteLine(); } } }
24.891892
124
0.34962
[ "MIT" ]
pavelhristov/CSharpFundamentals
ExamPreparation28Dec2012/Problem4-TelerikLogo/TelerikLogo.cs
923
C#
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo using System; using DotNetNuke.Services.Cache; using DotNetNuke.Services.Social.Subscriptions; using DotNetNuke.Services.Social.Subscriptions.Data; using DotNetNuke.Services.Social.Subscriptions.Entities; using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; using DotNetNuke.Tests.Utilities.Mocks; using Moq; using NUnit.Framework; namespace DotNetNuke.Tests.Core.Controllers.Messaging { [TestFixture] public class SubscriptionControllerTests { private Mock<IDataService> mockDataService; private Mock<ISubscriptionSecurityController> subscriptionSecurityController; private Mock<CachingProvider> mockCacheProvider; private SubscriptionController subscriptionController; [SetUp] public void SetUp() { // Setup Mocks and Stub mockDataService = new Mock<IDataService>(); mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); subscriptionSecurityController = new Mock<ISubscriptionSecurityController>(); DataService.SetTestableInstance(mockDataService.Object); SubscriptionSecurityController.SetTestableInstance(subscriptionSecurityController.Object); // Setup SUT subscriptionController = new SubscriptionController(); } [TearDown] public void TearDown() { DataService.ClearInstance(); SubscriptionSecurityController.ClearInstance(); MockComponentProvider.ResetContainer(); } #region IsSubscribed method tests [Test] public void IsSubscribed_ShouldReturnFalse_IfUserIsNotSubscribed() { // Arrange var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny<int>(), It.IsAny<int>())).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()); //Act var isSubscribed = subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(false, isSubscribed); } [Test] public void IsSubscribed_ShouldReturnFalse_WhenUserDoesNotHavePermissionOnTheSubscription() { // Arrange var subscription = new SubscriptionBuilder() .Build(); var subscriptionCollection = new[] {subscription}; mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny<int>(), It.IsAny<int>())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(subscriptionCollection)); subscriptionSecurityController .Setup(ssc => ssc.HasPermission(It.IsAny<Subscription>())).Returns(false); //Act var isSubscribed = subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(false, isSubscribed); } [Test] public void IsSubscribed_ShouldReturnTrue_WhenUserHasPermissionOnTheSubscription() { // Arrange var subscription = new SubscriptionBuilder() .Build(); var subscriptionCollection = new[] { subscription }; mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny<int>(), It.IsAny<int>())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(subscriptionCollection)); subscriptionSecurityController .Setup(ssc => ssc.HasPermission(It.IsAny<Subscription>())).Returns(true); //Act var isSubscribed = subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(true, isSubscribed); } [Test] public void IsSubscribed_ShouldCallDataService_WhenNoError() { // Arrange var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.ModuleId, subscription.TabId)).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()).Verifiable(); //Act subscriptionController.IsSubscribed(subscription); // Assert mockDataService.Verify(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.ModuleId, subscription.TabId), Times.Once); } #endregion #region AddSubscription method tests [Test] public void AddSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { //Act, Arrange Assert.Throws<ArgumentNullException>(() => subscriptionController.AddSubscription(null)); } [Test] public void AddSubscription_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionUserIdPropertyIsNegative() { // Arrange var subscription = new SubscriptionBuilder() .WithUserId(-1) .Build(); //Act, Assert Assert.Throws<ArgumentOutOfRangeException>(() => subscriptionController.AddSubscription(subscription)); } [Test] public void AddSubscription_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionSubscriptionTypePropertyIsNegative() { // Arrange var subscription = new SubscriptionBuilder() .WithSubscriptionTypeId(-1) .Build(); //Act, Assert Assert.Throws<ArgumentOutOfRangeException>(() => subscriptionController.AddSubscription(subscription)); } [Test] public void AddSubscription_ShouldThrowArgumentNullException_WhenSubscriptionObjectKeyIsNull() { // Arrange var subscription = new SubscriptionBuilder() .WithObjectKey(null) .Build(); //Act, Assert Assert.Throws<ArgumentNullException>(() => subscriptionController.AddSubscription(subscription)); } [Test] public void AddSubscription_ShouldCallDataService_WhenNoError() { // Arrange var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.Description, subscription.ModuleId, subscription.TabId, subscription.ObjectData)).Verifiable(); //Act subscriptionController.AddSubscription(subscription); // Assert mockDataService.Verify(ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.Description, subscription.ModuleId, subscription.TabId, subscription.ObjectData), Times.Once); } [Test] public void AddSubscription_ShouldFilledUpTheSubscriptionIdPropertyOfTheInputSubscriptionEntity_WhenNoError() { // Arrange const int expectedSubscriptionId = 12; var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.Description, subscription.ModuleId, subscription.TabId, subscription.ObjectData)).Returns(expectedSubscriptionId); //Act subscriptionController.AddSubscription(subscription); // Assert Assert.AreEqual(expectedSubscriptionId, subscription.SubscriptionId); } #endregion #region DeleteSubscription method tests [Test] public void DeleteSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { //Act, Assert Assert.Throws<ArgumentNullException>(() => subscriptionController.DeleteSubscription(null)); } [Test] public void DeleteSubscriptionType_ShouldCallDeleteSubscriptionDataService_WhenSubscriptionExists() { // Arrange var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny<int>(), It.IsAny<int>())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(new [] { subscription })); mockDataService.Setup(ds => ds.DeleteSubscription(It.IsAny<int>())).Verifiable(); //Act subscriptionController.DeleteSubscription(subscription); //Assert mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny<int>()), Times.Once); } [Test] public void DeleteSubscriptionType_ShouldNotCallDeleteSubscriptionDataService_WhenSubscriptionDoesNotExist() { // Arrange var subscription = new SubscriptionBuilder() .Build(); mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny<int>(), It.IsAny<int>())).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()); //Act subscriptionController.DeleteSubscription(subscription); //Assert mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny<int>()), Times.Never); } #endregion } }
37.1261
127
0.620379
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs
12,663
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Media { /// <summary> /// An Asset. /// API Version: 2020-05-01. /// </summary> [AzureNativeResourceType("azure-native:media:Asset")] public partial class Asset : Pulumi.CustomResource { /// <summary> /// The alternate ID of the Asset. /// </summary> [Output("alternateId")] public Output<string?> AlternateId { get; private set; } = null!; /// <summary> /// The Asset ID. /// </summary> [Output("assetId")] public Output<string> AssetId { get; private set; } = null!; /// <summary> /// The name of the asset blob container. /// </summary> [Output("container")] public Output<string?> Container { get; private set; } = null!; /// <summary> /// The creation date of the Asset. /// </summary> [Output("created")] public Output<string> Created { get; private set; } = null!; /// <summary> /// The Asset description. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The last modified date of the Asset. /// </summary> [Output("lastModified")] public Output<string> LastModified { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The name of the storage account. /// </summary> [Output("storageAccountName")] public Output<string?> StorageAccountName { get; private set; } = null!; /// <summary> /// The Asset encryption format. One of None or MediaStorageEncryption. /// </summary> [Output("storageEncryptionFormat")] public Output<string> StorageEncryptionFormat { get; private set; } = null!; /// <summary> /// The system metadata relating to this resource. /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a Asset resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Asset(string name, AssetArgs args, CustomResourceOptions? options = null) : base("azure-native:media:Asset", name, args ?? new AssetArgs(), MakeResourceOptions(options, "")) { } private Asset(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:media:Asset", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:media:Asset"}, new Pulumi.Alias { Type = "azure-native:media/v20180330preview:Asset"}, new Pulumi.Alias { Type = "azure-nextgen:media/v20180330preview:Asset"}, new Pulumi.Alias { Type = "azure-native:media/v20180601preview:Asset"}, new Pulumi.Alias { Type = "azure-nextgen:media/v20180601preview:Asset"}, new Pulumi.Alias { Type = "azure-native:media/v20180701:Asset"}, new Pulumi.Alias { Type = "azure-nextgen:media/v20180701:Asset"}, new Pulumi.Alias { Type = "azure-native:media/v20200501:Asset"}, new Pulumi.Alias { Type = "azure-nextgen:media/v20200501:Asset"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Asset resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Asset Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Asset(name, id, options); } } public sealed class AssetArgs : Pulumi.ResourceArgs { /// <summary> /// The Media Services account name. /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; /// <summary> /// The alternate ID of the Asset. /// </summary> [Input("alternateId")] public Input<string>? AlternateId { get; set; } /// <summary> /// The Asset name. /// </summary> [Input("assetName")] public Input<string>? AssetName { get; set; } /// <summary> /// The name of the asset blob container. /// </summary> [Input("container")] public Input<string>? Container { get; set; } /// <summary> /// The Asset description. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name of the resource group within the Azure subscription. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the storage account. /// </summary> [Input("storageAccountName")] public Input<string>? StorageAccountName { get; set; } public AssetArgs() { } } }
37.486772
117
0.568384
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Media/Asset.cs
7,085
C#
using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.IO.Compression; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace YorotInstaller { public partial class frmMain : Form { /// <summary> /// General purpose WebClient /// </summary> private readonly WebClient GPWC = new WebClient(); private readonly Settings Settings; private readonly VersionManager VersionManager; private StringEventhHybrid workOn; private readonly List<StringEventhHybrid> downloadStrings = new List<StringEventhHybrid>(); private bool allowClose = true; private bool allowSwitch = false; private YorotVersion versionToInstall; private static string YorotPath => Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot.exe"; private static string YorotFolderPath => Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\"; private static string YorotBetaPath => Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot Beta.exe"; private readonly bool YorotExists = File.Exists(YorotPath); private readonly bool betaExists = File.Exists(YorotBetaPath); #region "Translations" private string UIChangeVerMissing = "We couldn't find this version at our archives."; private string UIChangeVerArchNotSupported = "Your platform is not supported in this version."; private string DownloadProgress = "Downloading [NAME]... [CURRENT]/[TOTAL]"; private string DownloadYorotDesktop = "Yorot Desktop"; private string DownloadsComplete = "All downloads are finished."; private string InstallComplete = "All installations are finished."; private string RegistryComplete = "All registries are registered."; private string RegistryStart = "Registering..."; private string UIYes = "Yes"; private string UINo = "No"; private string UIOK = "OK"; private string UICancel = "Cancel"; private string UIRepairButton = "Repair"; private string UIUpdateButton = "Update"; private string UIInstallVer = "Install [VER]"; private string UIGatherInfo = "Gathering Information..."; private string UICheckUpdate = "Checking for updates..."; private string UIReadyDesc = "Your Yorot is ready to be installed."; private string UINotReadyDesc = "You don't meet the requirements for installing Yorot."; private string UIChangeVerO1 = "Latest PreOut Version ([PREOUT])"; private string UIChangeVerO2 = "Latest Stable Version ([LATEST])"; private string UICreateRecovery = "Creating a restore point..."; private string UIDoneUninstall = "Yorot successfully uninstalled." + Environment.NewLine + "" + Environment.NewLine + "It's improtant for us to listen to your reason why you decided to uninstall Yorot so please open an issue in GitHub by clickng &quot;Send Feedback&quot; button below." + Environment.NewLine + "" + Environment.NewLine + "Farewell, old firend." + Environment.NewLine + "" + Environment.NewLine + ""; private string UIDoneInstall = "Yorot installed successfully." + Environment.NewLine + "" + Environment.NewLine + "Closing this program will start the application."; private string UIDoneUpdate = "Yorot updated successfully."; private string UIDoneRepair = "Yorot repaired successfully."; private string UIDoneError = "An error occured while doing your request. Don't worry, we restored your Yorot installation. Please create an issue on GitHub by clicking &quot;Send Feedback&quot; and copy-paste this information below:"; private string UIPreOutAvailable = "You meet the requirements."; private string UIPreOutDisable = "You don't meet the requirements. Update or Repair your Yorot first."; private string UICreateShortcut = "Creating shortcuts..."; private string UIUpdating = "Updating Installer... Please wait..." + Environment.NewLine + "[PERC]% | [CURRENT] KiB downloaded out of [TOTAL] KiB."; public void LoadLang() { UIInstallVer = Settings.GetItemText("UIInstallVer"); lbChangeVerDesc.Text = Settings.GetItemText("UIChangeVerDesc"); UIChangeVerMissing = Settings.GetItemText("UIChangeVerMissing"); UIChangeVerArchNotSupported = Settings.GetItemText("UIChangeVerArchNotSupported"); DownloadProgress = Settings.GetItemText("DownloadProgress"); DownloadYorotDesktop = Settings.GetItemText("DownloadYorotDesktop"); DownloadsComplete = Settings.GetItemText("DownloadsComplete"); InstallComplete = Settings.GetItemText("InstallComplete"); RegistryComplete = Settings.GetItemText("RegistryComplete"); RegistryStart = Settings.GetItemText("RegistryStart"); UIYes = Settings.GetItemText("UIYes"); UINo = Settings.GetItemText("UINo"); UIOK = Settings.GetItemText("UIOK"); UICancel = Settings.GetItemText("UICancel"); btClose.Text = Settings.GetItemText("UIClose"); UIGatherInfo = Settings.GetItemText("UIGatherInfo"); UICheckUpdate = Settings.GetItemText("UICheckUpdate"); UIReadyDesc = Settings.GetItemText("UIReadyDesc"); UINotReadyDesc = Settings.GetItemText("UINotReadyDesc"); lbModifyDesc.Text = Settings.GetItemText("UIModifyDesc"); btInstall.Text = Settings.GetItemText("UIReadyButton"); UIRepairButton = Settings.GetItemText("UIRepairButton"); UIUpdateButton = Settings.GetItemText("UIUpdateButton"); btUninstall.Text = Settings.GetItemText("UIUninstallButton"); btChangeVer.Text = Settings.GetItemText("UIChangeVerButton"); UIChangeVerO1 = Settings.GetItemText("UIChangeVerO1"); UIChangeVerO2 = Settings.GetItemText("UIChangeVerO2"); rbOld.Text = Settings.GetItemText("UIChangeVerO3"); lbDownloading.Text = Settings.GetItemText("UIDownloading"); lbInstalling.Text = Settings.GetItemText("UIInstalling"); UICreateRecovery = Settings.GetItemText("UICreateRecovery"); UIDoneUninstall = Settings.GetItemText("UIDoneUninstall"); UIDoneInstall = Settings.GetItemText("UIDoneInstall"); UIDoneUpdate = Settings.GetItemText("UIDoneUpdate"); UIDoneRepair = Settings.GetItemText("UIDoneRepair"); UIDoneError = Settings.GetItemText("UIDoneError"); btSendFeedback.Text = Settings.GetItemText("UISendFeedback"); UIPreOutAvailable = Settings.GetItemText("UIPreOutAvailable"); UIPreOutDisable = Settings.GetItemText("UIPreOutDisable"); lbVersionToInstall.Text = Settings.GetItemText("UIVersionToInstall"); UICreateShortcut = Settings.GetItemText("CreateShortcut"); UIUpdating = Settings.GetItemText("UIUpdating"); if (VersionManager.PreOutVerNumber != 0 && VersionManager.LatestVersionNumber != 0) { rbPreOut.Text = UIChangeVerO1.Replace("[PREOUT]", VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber).VersionText); rbStable.Text = UIChangeVerO2.Replace("[LATEST]", VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber).VersionText); if (supportsLatestPreOut()) { lbPerOutReq.Text = UIPreOutAvailable; rbPreOut.Enabled = true; } else { lbPerOutReq.Text = UIPreOutDisable; rbPreOut.Enabled = false; } } if (VersionManager.Versions.Count > 0 && YorotExists) { YorotVersion current = VersionManager.GetVersionFromVersionName(FileVersionInfo.GetVersionInfo(YorotExists ? YorotPath : YorotBetaPath).ProductVersion); btRepair.Text = current != null ? VersionManager.LatestVersionNumber != current.VersionNo || VersionManager.PreOutVerNumber != current.VersionNo ? UIUpdateButton : UIRepairButton : UIRepairButton; } switch (DoneType) { case DoneType.Install: lbDoneDesc.Text = UIDoneInstall; break; case DoneType.Repair: lbDoneDesc.Text = UIDoneRepair; break; case DoneType.Update: lbDoneDesc.Text = UIDoneUpdate; break; case DoneType.Uninstall: lbDoneDesc.Text = UIDoneUninstall; break; } label4.Text = isUpdatingInstaller ? UIUpdating.Replace("[NAME]", workOn.String3).Replace("[PERC]", "" + updatePerc).Replace("[CURRENT]", updateCurrent).Replace("[TOTAL]", updateTotal) : UIGatherInfo; btInstall1.Text = UIInstallVer.Replace("[VER]", versionToInstall != null ? versionToInstall.VersionText : ""); lbReady.Text = canInstall ? UIReadyDesc : UINotReadyDesc; cbOld.Location = new Point(lbVersionToInstall.Location.X + lbVersionToInstall.Width, cbOld.Location.Y); } #endregion "Translations" public frmMain(Settings settings) { Settings = settings; VersionManager = new VersionManager(); isShiftPressed = false; isUpdatingInstaller = false; reqs = new List<PreResqs.PreResq>(); InitializeComponent(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; GPWC.DownloadStringCompleted += GPWC_DownloadStringComplete; GPWC.DownloadProgressChanged += GPWC_ProgressChanged; GPWC.DownloadFileCompleted += GPWC_DownloadFileComplete; string[] langFiles = Directory.GetFiles(Settings.WorkFolder, "*.language"); DoneType = DoneType.Install; cbLang.Items.Clear(); for (int i = 0; i < langFiles.Length; i++) { cbLang.Items.Add(Path.GetFileNameWithoutExtension(langFiles[i])); } lbDoneDesc.MaximumSize = new Size(tbDoneError.Width, 0); cbLang.Text = Path.GetFileNameWithoutExtension(Settings.LanguageFile); LoadLang(); updateTheme(); } private bool isUpdatingInstaller; private int updatePerc; private string updateCurrent; private string updateTotal; private void GPWC_DownloadStringComplete(object sender, DownloadStringCompletedEventArgs e) { if (GPWC.IsBusy) { GPWC.CancelAsync(); } if (workOn.Type == StringEventhHybrid.StringType.String) { workOn.RunEvent(this, e); downloadStrings.Remove(workOn); workOn = downloadStrings.Find(i => i.Type == StringEventhHybrid.StringType.String); if (workOn != null) { GPWC.DownloadStringAsync(new Uri(workOn.String)); } else { GPWC_AllJobsDone(); } } } private int installJobCount = 0; private int installDoneCount = 0; private bool isPreparing = true; private int doneCount = 0; private void GPWC_ProgressChanged(object sender, DownloadProgressChangedEventArgs e) { if (workOn.Type == StringEventhHybrid.StringType.File && !isPreparing) { Invoke(new Action(() => { lbDownloadInfo.Text = DownloadProgress.Replace("[NAME]", workOn.String3).Replace("[PERC]", "" + e.ProgressPercentage).Replace("[CURRENT]", (e.BytesReceived / 1024) + " KiB").Replace("[TOTAL]", (e.TotalBytesToReceive / 1024) + " KiB"); int downloadTotoalJobs = downloadStrings.FindAll(i => i.Type == StringEventhHybrid.StringType.File).Count; lbDownloadCount.Text = (doneCount == downloadTotoalJobs ? doneCount : doneCount + 1) + "/" + downloadTotoalJobs; pbDownload.Width = e.ProgressPercentage * (pDownload.Width / 100); })); } if (isUpdatingInstaller) { Invoke(new Action(() => { updatePerc = e.ProgressPercentage; updateCurrent = (e.BytesReceived / 1024) + " KiB"; updateTotal = (e.TotalBytesToReceive / 1024) + " KiB"; label4.Text = UIUpdating.Replace("[NAME]", workOn.String3).Replace("[PERC]", "" + e.ProgressPercentage).Replace("[CURRENT]", (e.BytesReceived / 1024) + " KiB").Replace("[TOTAL]", (e.TotalBytesToReceive / 1024) + " KiB"); })); } } private void GPWC_DownloadFileComplete(object sender, AsyncCompletedEventArgs e) { if (GPWC.IsBusy) { GPWC.CancelAsync(); } if (workOn.Type == StringEventhHybrid.StringType.File) { workOn.RunEvent(this, e); downloadStrings.Remove(workOn); workOn = downloadStrings.Find(i => i.Type == StringEventhHybrid.StringType.File); doneCount++; if (workOn != null) { GPWC.DownloadFileAsync(new Uri(workOn.String), workOn.String2); } else { GPWC_AllJobsDone(); if (!isPreparing) { lbDownloadInfo.Text = DownloadsComplete; } } } } private void updateInstaller(object sender, EventArgs E) { if (E is AsyncCompletedEventArgs) { AsyncCompletedEventArgs e = E as AsyncCompletedEventArgs; if (e.Error != null) { Error(new Exception("Error while updating Installer. Error: " + e.ToString())); } else if (e.Cancelled) { Error(new Exception("Error while updating Installer. Error: Cancelled.")); } else { allowClose = true; Settings.Save(); Process.Start(new ProcessStartInfo(Settings.WorkFolder + "YorotInstaller.exe") { UseShellExecute = true, Verb = "runas" }); Application.Exit(); } } else { Error(new Exception("\"E\" is not an AsyncCompletedEventArgs [in void \"updateInstaller\"].")); } } private bool canInstall; private void GPWC_AllJobsDone() { if (downloadStrings.Count > 0 && !GPWC.IsBusy && workOn == null) { if (downloadStrings[0].Type == StringEventhHybrid.StringType.File) { DoFileWork(downloadStrings[0]); } else { DoStringWork(downloadStrings[0]); } return; } if (isPreparing) { if (VersionManager.InstallerVer < VersionManager.LatestInstallerVer) { isUpdatingInstaller = true; allowClose = false; StringEventhHybrid seh = new StringEventhHybrid() { String = VersionManager.InstallerLoc, String2 = Settings.WorkFolder + "YorotInstaller.exe", String3 = "Installer", Type = StringEventhHybrid.StringType.File, }; seh.Event += updateInstaller; DoFileWork(seh); return; } isPreparing = false; allowSwitch = true; if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot.exe") && !File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot Beta.exe")) { allowSwitch = true; tabControl1.SelectedTab = tpFirst; if (supportsThisVer(VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber))) { canInstall = true; lbReady.Text = UIReadyDesc; btInstall.Enabled = true; btInstall.Visible = true; } else { canInstall = false; lbReady.Text = UINotReadyDesc; btInstall.Enabled = false; btInstall.Visible = false; } } else { allowSwitch = true; tabControl1.SelectedTab = tpModify; if (VersionManager.Versions.Count > 0) { YorotVersion current = VersionManager.GetVersionFromVersionName(FileVersionInfo.GetVersionInfo(YorotExists ? YorotPath : YorotBetaPath).ProductVersion); btRepair.Text = current != null ? VersionManager.LatestVersionNumber != current.VersionNo || VersionManager.PreOutVerNumber != current.VersionNo ? UIUpdateButton : UIRepairButton : UIRepairButton; } } } else { lbDownloadInfo.Text = DownloadsComplete; pbDownload.Width = pDownload.Width; } } private void frmMain_Load(object sender, EventArgs e) { StringEventhHybrid htupdate = new StringEventhHybrid() { String = "https://raw.githubusercontent.com/Haltroy/Yorot/master/Yorot.htupdate", Type = StringEventhHybrid.StringType.String, }; htupdate.Event += htupdateDownloaded; DoStringWork(htupdate); } private void DoStringWork(StringEventhHybrid seh) { if (!downloadStrings.Contains(seh)) { downloadStrings.Add(seh); } if (!GPWC.IsBusy) { workOn = seh; GPWC.DownloadStringAsync(new Uri(seh.String)); } } private void DoFileWork(StringEventhHybrid seh) { if (!downloadStrings.Contains(seh)) { downloadStrings.Add(seh); } if (!GPWC.IsBusy) { workOn = seh; GPWC.DownloadFileAsync(new Uri(seh.String), seh.String2); } } private DoneType DoneType; private void Successful() { timer1.Stop(); allowClose = true; allowSwitch = true; tabControl1.SelectedTab = tpDone; switch (DoneType) { case DoneType.Install: lbDoneDesc.Text = UIDoneInstall; break; case DoneType.Repair: lbDoneDesc.Text = UIDoneRepair; break; case DoneType.Update: lbDoneDesc.Text = UIDoneUpdate; break; case DoneType.Uninstall: lbDoneDesc.Text = UIDoneUninstall; break; } tbDoneError.Visible = false; tbDoneError.Enabled = false; } private void htupdateDownloaded(object sender, EventArgs E) { if (E is DownloadStringCompletedEventArgs) { DownloadStringCompletedEventArgs e = E as DownloadStringCompletedEventArgs; if (e.Error == null && !e.Cancelled) { XmlDocument doc = new XmlDocument(); doc.LoadXml(e.Result); XmlNode firstnode = doc.FirstChild.Name != "HaltroyUpdate" ? doc.FirstChild.NextSibling : doc.FirstChild; int workCount = 0; foreach (XmlNode node in firstnode.ChildNodes) { if (node.Name == "PreOutVer") { VersionManager.LatesPreOut = node.InnerXml; workCount++; } else if (node.Name == "PreOutNo") { VersionManager.PreOutVerNumber = Convert.ToInt32(node.InnerXml); workCount++; } else if (node.Name == "PreOutLow") { VersionManager.PreOutMinVer = Convert.ToInt32(node.InnerXml); workCount++; } else if (node.Name == "AppVersionNo") { VersionManager.LatestVersionNumber = Convert.ToInt32(node.InnerXml); workCount++; } else if (node.Name == "MinimumNo") { VersionManager.LatestUpdateMinVer = Convert.ToInt32(node.InnerXml); workCount++; } else if (node.Name == "InstallerVer") { VersionManager.LatestInstallerVer = Convert.ToInt32(node.InnerXml); workCount++; } else if (node.Name == "AppVersion") { VersionManager.LatesVersion = node.InnerXml; workCount++; } else if (node.Name == "InstallerUrl") { VersionManager.InstallerLoc = node.InnerXml; workCount++; } else if (node.Name == "Versions") { foreach (XmlNode subnode in node.ChildNodes) { if (subnode.Name == "Version") { if (subnode.Attributes["VersionNo"] != null && subnode.Attributes["Flags"] != null && subnode.Attributes["Text"] != null) { if (subnode.Attributes["Flags"].Value.Contains("missing")) { YorotVersion ver = new YorotVersion(subnode.Attributes["Text"].Value, Convert.ToInt32(subnode.Attributes["VersionNo"].Value), subnode.Attributes["Flags"].Value); VersionManager.Versions.Add(ver); } else { YorotVersion ver = new YorotVersion(subnode.Attributes["Text"].Value, Convert.ToInt32(subnode.Attributes["VersionNo"].Value), subnode.Attributes["ZipPath"].Value, subnode.Attributes["Flags"].Value, subnode.Attributes["Reg"].Value); VersionManager.Versions.Add(ver); } } } } workCount++; } } } else { StringEventhHybrid htupdate = new StringEventhHybrid() { String = "https://raw.githubusercontent.com/Haltroy/Yorot/master/Yorot.htupdate", Type = StringEventhHybrid.StringType.String, }; htupdate.Event += htupdateDownloaded; } } else { Console.WriteLine(" [HTUPDATE] Error: EventArgs is not suitable."); } } private void label3_Click(object sender, EventArgs e) { if (allowClose) { Settings.Save(); Close(); } } private void label1_MouseDown(object sender, MouseEventArgs e) { OnMouseDown(e); } private void updateTheme() { BackColor = Settings.BackColor; ForeColor = Settings.ForeColor; cbLang.ForeColor = Settings.MidColor; btInstall.ForeColor = Settings.ForeColor; btInstall1.ForeColor = Settings.ForeColor; cbOld.ForeColor = Settings.ForeColor; pChangeVer.ForeColor = Settings.ForeColor; btRepair.ForeColor = Settings.ForeColor; btUninstall.ForeColor = Settings.ForeColor; btChangeVer.ForeColor = Settings.ForeColor; btClose.ForeColor = Settings.ForeColor; btSendFeedback.ForeColor = Settings.ForeColor; tbDoneError.ForeColor = Settings.ForeColor; panel1.ForeColor = Settings.ForeColor; pictureBox2.Image = Settings.isDarkMode ? Properties.Resources.dark : Properties.Resources.light; for (int i = 0; i < tabControl1.TabPages.Count; i++) { TabPage page = tabControl1.TabPages[i]; page.BackColor = Settings.BackColor1; page.ForeColor = Settings.ForeColor; } BackColor = Settings.BackColor; pDownload.BackColor = Settings.BackColor2; panel1.BackColor = Settings.BackColor; pInstall.BackColor = Settings.BackColor2; pChangeVer.BackColor = Settings.BackColor2; flowLayoutPanel1.BackColor = Settings.BackColor1; tbDoneError.BackColor = Settings.BackColor2; cbOld.BackColor = Settings.BackColor3; btInstall.BackColor = Settings.BackColor2; btRepair.BackColor = Settings.BackColor2; btUninstall.BackColor = Settings.BackColor2; btChangeVer.BackColor = Settings.BackColor2; btInstall1.BackColor = Settings.BackColor3; cbLang.BackColor = Settings.BackColor1; } private void pictureBox2_Click(object sender, EventArgs e) { Settings.isDarkMode = !Settings.isDarkMode; updateTheme(); } private bool isBusy = false; private readonly List<PreResqs.PreResq> reqs; private PreResqs.PreResq workingReq; private async Task<bool> InstallPreResq(PreResqs.PreResq req) { await Task.Run(() => { if (isBusy) { reqs.Add(req); return; } isBusy = true; workingReq = req; ProcessStartInfo info = new ProcessStartInfo(Settings.WorkFolder + req.FileName, req.SilentArgs) { UseShellExecute = true, Verb = "runas" }; Process process = new Process { StartInfo = info }; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { isBusy = false; if (reqs.Contains(req)) { reqs.Remove(req); } if (reqs.Count > 0) { workingReq = reqs[0]; Task.Run(() => InstallPreResq(workingReq)); } else { workingReq = null; } } else { Error(new Exception("Required component \"" + req.Name + "\" is not installed. Exit Code: " + process.ExitCode)); } }); return false; } private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e) { if (allowSwitch) { allowSwitch = false; } else { e.Cancel = true; } } private void cbLang_DropDown(object sender, EventArgs e) { string[] langFiles = Directory.GetFiles(Settings.WorkFolder, "*.language"); cbLang.Items.Clear(); for (int i = 0; i < langFiles.Length; i++) { cbLang.Items.Add(Path.GetFileNameWithoutExtension(langFiles[i])); } } private void cbLang_SelectedIndexChanged(object sender, EventArgs e) { Settings.LanguageFile = Settings.WorkFolder + cbLang.SelectedItem.ToString() + ".language"; Settings.LoadLang(Settings.WorkFolder + cbLang.SelectedItem.ToString() + ".language"); LoadLang(); } private bool supportsLatestPreOut() { if (!YorotExists && !betaExists) { return false; } YorotVersion vPreOut = VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber); if (vPreOut.isOnlyx64 & !PreResqs.is64BitMachine) { return false; } YorotVersion currentVer = VersionManager.GetVersionFromVersionName(FileVersionInfo.GetVersionInfo(YorotExists ? YorotPath : YorotBetaPath).ProductVersion); if (currentVer == null) { rbPreOut.Checked = true; return true; } if (currentVer.VersionNo < VersionManager.LatestVersionNumber || currentVer.VersionNo < VersionManager.PreOutMinVer) { return false; } return true; } private bool supportsThisVer(YorotVersion ver) { if (ver.isOnlyx64 && !PreResqs.is64BitMachine) { return false; } if (ver.RequiresNet452 && !PreResqs.SystemSupportsNet452) { return false; } if (ver.RequiresNet461 && !PreResqs.SystemSupportsNet461) { return false; } if (ver.RequiresNet48 && !PreResqs.SystemSupportsNet48) { return false; } if (ver.RequiresVisualC2015 && !PreResqs.SystemSupportsVisualC2015x86) { return false; } return true; } private void Error(Exception ex) { allowClose = true; allowSwitch = true; reqs.Clear(); downloadStrings.Clear(); if (GPWC.IsBusy) { GPWC.CancelAsync(); } workOn = null; tabControl1.SelectedTab = tpDone; lbDoneDesc.Text = UIDoneError; tbDoneError.Text = ex.ToString(); tbDoneError.Location = new Point(tbDoneError.Location.X, lbDoneDesc.Location.Y + lbDoneDesc.Height); tbDoneError.Height = Height - (panel1.Height + flowLayoutPanel1.Height + lbDoneDesc.Height + 35); } private void appShortcut() { HTAltTools.appShortcut(YorotExists ? YorotPath : YorotBetaPath, Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\" + "Yorot"); HTAltTools.appShortcut(YorotExists ? YorotPath : YorotBetaPath, Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms) + "\\" + "Yorot"); if (versionToInstall.VersionNo >= 36) { HTAltTools.appShortcut(YorotExists ? YorotPath : YorotBetaPath, Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\" + "Yorot", "--make-ext"); HTAltTools.appShortcut(YorotExists ? YorotPath : YorotBetaPath, Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms) + "\\" + "Yorot", "--make-ext"); } installDoneCount++; } private void StartInstallation(bool forceReqs = false) { allowSwitch = true; allowClose = false; tabControl1.SelectedTab = tpProgress; if (versionToInstall.isMissing) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" is missing.")); } if (versionToInstall.RequiresNet452 && !PreResqs.SystemSupportsNet452) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" requires .NEt Framework 4.5.2 but your computer does not supports it.")); } if (versionToInstall.RequiresNet461 && !PreResqs.SystemSupportsNet461) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" requires .NEt Framework 4.6.1 but your computer does not supports it.")); } if (versionToInstall.RequiresNet48 && !PreResqs.SystemSupportsNet48) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" requires .NEt Framework 4.8 but your computer does not supports it.")); } if (versionToInstall.RequiresVisualC2015 && !PreResqs.SystemSupportsVisualC2015x86) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" requires Visual C++ 2015 but your computer does not supports it.")); } if (versionToInstall.isOnlyx64 && !PreResqs.is64BitMachine) { Error(new Exception("This version \"" + versionToInstall.ToString() + "\" requires 64-bit machine but this machine is not a 64 bit machine.")); } isPreparing = false; if (versionToInstall.RequiresNet452 && (!PreResqs.isInstalled(PreResqs.NetFramework452) || forceReqs)) { StringEventhHybrid seh = new StringEventhHybrid() { String = PreResqs.NetFramework452.Url, String2 = Settings.WorkFolder + PreResqs.NetFramework452.FileName, String3 = PreResqs.NetFramework452.Name, Type = StringEventhHybrid.StringType.File, }; seh.Event += new StringEventhHybrid.EventDelegate((sender, e) => { Task.Run(() => InstallPreResq(PreResqs.NetFramework452)); }); installJobCount++; downloadStrings.Add(seh); } if (versionToInstall.RequiresNet461 && (!PreResqs.isInstalled(PreResqs.NetFramework461) || forceReqs)) { StringEventhHybrid seh = new StringEventhHybrid() { String = PreResqs.NetFramework461.Url, String2 = Settings.WorkFolder + PreResqs.NetFramework461.FileName, String3 = PreResqs.NetFramework461.Name, Type = StringEventhHybrid.StringType.File, }; seh.Event += new StringEventhHybrid.EventDelegate((sender, e) => { Task.Run(() => InstallPreResq(PreResqs.NetFramework461)); }); installJobCount++; downloadStrings.Add(seh); } if (versionToInstall.RequiresNet48 && (!PreResqs.isInstalled(PreResqs.NetFramework48) || forceReqs)) { StringEventhHybrid seh = new StringEventhHybrid() { String = PreResqs.NetFramework48.Url, String2 = Settings.WorkFolder + PreResqs.NetFramework48.FileName, String3 = PreResqs.NetFramework48.Name, Type = StringEventhHybrid.StringType.File, }; seh.Event += new StringEventhHybrid.EventDelegate((sender, e) => { Task.Run(() => InstallPreResq(PreResqs.NetFramework48)); }); installJobCount++; downloadStrings.Add(seh); } if (versionToInstall.RequiresVisualC2015 && (!PreResqs.isInstalled(PreResqs.VisualC2015x86) || forceReqs)) { StringEventhHybrid seh = new StringEventhHybrid() { String = PreResqs.VisualC2015x86.Url, String2 = Settings.WorkFolder + PreResqs.VisualC2015x86.FileName, String3 = PreResqs.VisualC2015x86.Name, Type = StringEventhHybrid.StringType.File, }; seh.Event += new StringEventhHybrid.EventDelegate((sender, e) => { Task.Run(() => InstallPreResq(PreResqs.VisualC2015x86)); }); installJobCount++; downloadStrings.Add(seh); if (PreResqs.is64BitMachine && (!PreResqs.isInstalled(PreResqs.VisualC2015x64) || forceReqs)) { StringEventhHybrid seh2 = new StringEventhHybrid() { String = PreResqs.VisualC2015x64.Url, String2 = Settings.WorkFolder + PreResqs.VisualC2015x64.FileName, String3 = PreResqs.VisualC2015x64.Name, Type = StringEventhHybrid.StringType.File, }; seh.Event += new StringEventhHybrid.EventDelegate((sender, e) => { Task.Run(() => InstallPreResq(PreResqs.VisualC2015x64)); }); installJobCount++; downloadStrings.Add(seh2); } } StringEventhHybrid sehK = new StringEventhHybrid() { String = versionToInstall.ZipPath.Replace("[VERSION]", versionToInstall.VersionText).Replace("[ARCH]", PreResqs.is64BitMachine ? "x64" : "x86").Replace("[U]", "F"), String2 = Settings.WorkFolder + versionToInstall.VersionText + ".htpackage", String3 = DownloadYorotDesktop, Type = StringEventhHybrid.StringType.File, }; sehK.Event += installYorot; installJobCount++; downloadStrings.Add(sehK); if (workOn == null) { workOn = downloadStrings[0]; } timer1.Start(); installJobCount += 3; DoFileWork(workOn); Task.Run(() => GetBackup()); lbInstallInfo.Text = UICreateRecovery; } private async Task<bool> GetBackup(bool retrieve = false) { await Task.Run(() => { string backupLocation = Settings.WorkFolder + "backup.htpackage"; if (!retrieve) { if (YorotExists) { if (File.Exists(backupLocation)) { File.Delete(backupLocation); } ZipFile.CreateFromDirectory(YorotFolderPath, backupLocation, CompressionLevel.NoCompression, false, Encoding.UTF8); } installDoneCount++; } else { if (File.Exists(backupLocation)) { if (new FileInfo(backupLocation).Length > 0) { if (File.Exists(YorotPath) || File.Exists(YorotBetaPath)) { Directory.Delete(YorotFolderPath, true); } Directory.CreateDirectory(YorotFolderPath); ZipFile.ExtractToDirectory(backupLocation, YorotFolderPath, Encoding.UTF8); } } } }); return true; } private void installYorot(object sender, EventArgs E) { if (E is AsyncCompletedEventArgs) { AsyncCompletedEventArgs e = E as AsyncCompletedEventArgs; if (e.Error != null) { Error(new Exception("Error while downloading Yorot Desktop files [\"" + versionToInstall.ZipPath.Replace("[VERSION]", versionToInstall.VersionText).Replace("[ARCH]", PreResqs.is64BitMachine ? "x64" : "x86").Replace("[U]", "F") + "\"]. Error: " + e.Error.ToString())); } else if (e.Cancelled) { Error(new Exception("Error while downloading Yorot Desktop files [\"" + versionToInstall.ZipPath.Replace("[VERSION]", versionToInstall.VersionText).Replace("[ARCH]", PreResqs.is64BitMachine ? "x64" : "x86").Replace("[U]", "F") + "\"]. Error: Cancelled.")); } else { Task.Run(() => InstallYorotFoReal()); } } else { Error(new Exception("\"E\" is not an AsyncCompletedEventArgs (in void \"installYorot\").")); } } /// <summary> /// use this dog this one wont lag - ryder /// </summary> /// <returns></returns> private async Task<bool> InstallYorotFoReal() { await Task.Run(async () => { try { if (Directory.Exists(YorotFolderPath)) { Directory.Delete(YorotFolderPath, true); } Directory.CreateDirectory(YorotFolderPath); ZipFile.ExtractToDirectory(Settings.WorkFolder + versionToInstall.VersionText + ".htpackage", YorotFolderPath, Encoding.UTF8); installDoneCount++; } catch (Exception ex) { Error(ex); await Task.Run(() => GetBackup(true)); } try { appShortcut(); Register(); Successful(); } catch (Exception ex) { Error(ex); await Task.Run(() => GetBackup(true)); } }); return false; } private async void Register() { await Task.Run(() => { // Register to Uninstall Programs list. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall", true)) { RegistryKey key1 = key.CreateSubKey("Yorot"); key1.SetValue("DisplayName", "Yorot", RegistryValueKind.String); key1.SetValue("DisplayVersion", versionToInstall.VersionText, RegistryValueKind.String); key1.SetValue("DisplayIcon", YorotExists ? YorotPath : YorotBetaPath, RegistryValueKind.String); key1.SetValue("Publisher", "haltroy", RegistryValueKind.String); key1.SetValue("UninstallString", Application.ExecutablePath, RegistryValueKind.String); key1.SetValue("ModifyString", Application.ExecutablePath, RegistryValueKind.String); key1.SetValue("InstallLocation", YorotFolderPath, RegistryValueKind.String); key1.SetValue("NoRemove", "1", RegistryValueKind.DWord); key1.SetValue("NoRepair", "1", RegistryValueKind.DWord); } // FILE ASSOCIATIONS // extensions using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".html\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".html\OpenWithProgids"); } key.SetValue("YorotHTML", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".htm\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".htm\OpenWithProgids"); } key.SetValue("YorotHTML", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".pdf\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".pdf\OpenWithProgids"); } key.SetValue("YorotPDF", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".http\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".http\OpenWithProgids"); } key.SetValue("YorotHTTP", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".https\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".https\OpenWithProgids"); } key.SetValue("YorotHTTP", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".kef\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".kef\OpenWithProgids"); } key.SetValue("YorotEXT", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".ktf\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".ktf\OpenWithProgids"); } key.SetValue("YorotEXT", "", RegistryValueKind.String); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@".klf\OpenWithProgids")) { if (key == null) { Registry.ClassesRoot.CreateSubKey(@".klf\OpenWithProgids"); } key.SetValue("YorotEXT", "", RegistryValueKind.String); } // progids using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@"YorotEXT")) { key.SetValue("", "Yorot Addon", RegistryValueKind.String); key.SetValue("AppUserModelID", "Yorot", RegistryValueKind.String); RegistryKey appKey = key.CreateSubKey("Application"); appKey.SetValue("AppUserModelID", "Yorot"); appKey.SetValue("ApplicationIcon", YorotExists ? YorotPath : YorotBetaPath); appKey.SetValue("ApplicationName", "Yorot"); appKey.SetValue("ApplicationDecription", "Surf the universe."); appKey.SetValue("ApplicationCompany", "haltroy"); key.CreateSubKey("DefaultIcon").SetValue("", YorotExists ? YorotPath : YorotBetaPath, RegistryValueKind.String); RegistryKey shellKey = key.CreateSubKey("shell"); RegistryKey openKey = shellKey.CreateSubKey("open"); openKey.CreateSubKey("command").SetValue("", "\"" + (YorotExists ? YorotPath : YorotBetaPath) + "\" %1"); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@"YorotPDF")) { key.SetValue("", "Yorot PDF Document", RegistryValueKind.String); key.SetValue("AppUserModelID", "Yorot", RegistryValueKind.String); RegistryKey appKey = key.CreateSubKey("Application"); appKey.SetValue("AppUserModelID", "Yorot"); appKey.SetValue("ApplicationIcon", YorotExists ? YorotPath : YorotBetaPath); appKey.SetValue("ApplicationName", "Yorot"); appKey.SetValue("ApplicationDecription", "Surf the universe."); appKey.SetValue("ApplicationCompany", "haltroy"); key.CreateSubKey("DefaultIcon").SetValue("", YorotExists ? YorotPath : YorotBetaPath, RegistryValueKind.String); RegistryKey shellKey = key.CreateSubKey("shell"); RegistryKey openKey = shellKey.CreateSubKey("open"); openKey.CreateSubKey("command").SetValue("", "\"" + (YorotExists ? YorotPath : YorotBetaPath) + "\" %1"); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@"YorotHTML")) { key.SetValue("", "Yorot HTML Document", RegistryValueKind.String); key.SetValue("AppUserModelID", "Yorot", RegistryValueKind.String); RegistryKey appKey = key.CreateSubKey("Application"); appKey.SetValue("AppUserModelID", "Yorot"); appKey.SetValue("ApplicationIcon", YorotExists ? YorotPath : YorotBetaPath); appKey.SetValue("ApplicationName", "Yorot"); appKey.SetValue("ApplicationDecription", "Surf the universe."); appKey.SetValue("ApplicationCompany", "haltroy"); key.CreateSubKey("DefaultIcon").SetValue("", YorotExists ? YorotPath : YorotBetaPath, RegistryValueKind.String); RegistryKey shellKey = key.CreateSubKey("shell"); RegistryKey openKey = shellKey.CreateSubKey("open"); openKey.CreateSubKey("command").SetValue("", "\"" + (YorotExists ? YorotPath : YorotBetaPath) + "\" %1"); } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@"YorotHTTP")) { key.SetValue("", "Yorot Site", RegistryValueKind.String); key.SetValue("AppUserModelID", "Yorot", RegistryValueKind.String); RegistryKey appKey = key.CreateSubKey("Application"); appKey.SetValue("AppUserModelID", "Yorot"); appKey.SetValue("ApplicationIcon", YorotExists ? YorotPath : YorotBetaPath); appKey.SetValue("ApplicationName", "Yorot"); appKey.SetValue("ApplicationDecription", "Surf the universe."); appKey.SetValue("ApplicationCompany", "haltroy"); key.CreateSubKey("DefaultIcon").SetValue("", YorotExists ? YorotPath : YorotBetaPath, RegistryValueKind.String); RegistryKey shellKey = key.CreateSubKey("shell"); RegistryKey openKey = shellKey.CreateSubKey("open"); openKey.CreateSubKey("command").SetValue("", "\"" + (YorotExists ? YorotPath : YorotBetaPath) + "\" %1"); } // PROTOCOL if (versionToInstall.Reg == RegType.StandartWithProtocol || versionToInstall.Reg == RegType.StandartWithCommandProtocol) { using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(@"Yorot")) { key.CreateSubKey("DefaultIcon").SetValue("", YorotExists ? YorotPath : YorotBetaPath); RegistryKey shellKey = key.CreateSubKey("shell"); RegistryKey openKey = shellKey.CreateSubKey("open"); openKey.CreateSubKey("command").SetValue("", "\"" + (YorotExists ? YorotPath : YorotBetaPath) + "\" " + (versionToInstall.Reg == RegType.StandartWithCommandProtocol ? "Yorot://command/?c=" : "") + "%1", RegistryValueKind.String); key.SetValue("", "URL:Yorot protocol", RegistryValueKind.String); } } installDoneCount++; }); } private async void Unregister() { await Task.Run(() => { // Unregister to Uninstall Programs list. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall", true)) { key.DeleteSubKeyTree("Yorot", false); } // Unregister the rest using (RegistryKey key = Registry.ClassesRoot) { using (RegistryKey subkey = key.CreateSubKey(@".html\OpenWithProgids")) { subkey.DeleteValue("YorotHTML", false); } using (RegistryKey subkey = key.CreateSubKey(@".htm\OpenWithProgids")) { subkey.DeleteValue("YorotHTML", false); } using (RegistryKey subkey = key.CreateSubKey(@".pdf\OpenWithProgids")) { subkey.DeleteValue("YorotPDF", false); } using (RegistryKey subkey = key.CreateSubKey(@".http\OpenWithProgids")) { subkey.DeleteValue("YorotHTTP", false); } using (RegistryKey subkey = key.CreateSubKey(@".https\OpenWithProgids")) { subkey.DeleteValue("YorotHTTP", false); } using (RegistryKey subkey = key.CreateSubKey(@".kef\OpenWithProgids")) { subkey.DeleteValue("YorotEXT", false); } using (RegistryKey subkey = key.CreateSubKey(@".ktf\OpenWithProgids")) { subkey.DeleteValue("YorotEXT", false); } using (RegistryKey subkey = key.CreateSubKey(@".klf\OpenWithProgids")) { subkey.DeleteValue("YorotEXT", false); } key.DeleteSubKeyTree("Yorot", false); key.DeleteSubKeyTree("YorotEXT", false); key.DeleteSubKeyTree("YorotPDF", false); key.DeleteSubKeyTree("YorotHTTP", false); key.DeleteSubKeyTree("YorotHTML", false); } }); } private void btChangeVer_Click(object sender, EventArgs e) { lbModifyDesc.Enabled = false; btRepair.Enabled = false; btUninstall.Enabled = false; btChangeVer.Enabled = false; pChangeVer.Visible = true; pChangeVer.Enabled = true; rbPreOut.Text = UIChangeVerO1.Replace("[PREOUT]", VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber).VersionText); rbPerOut_CheckedChanged(this, new EventArgs()); rbStable_CheckedChanged(this, new EventArgs()); rbStable.Text = UIChangeVerO2.Replace("[LATEST]", VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber).VersionText); if (supportsLatestPreOut()) { lbPerOutReq.Text = UIPreOutAvailable; rbPreOut.Enabled = true; } else { lbPerOutReq.Text = UIPreOutDisable; rbPreOut.Enabled = false; } } private void label5_Click(object sender, EventArgs e) { lbModifyDesc.Enabled = true; btRepair.Enabled = true; btUninstall.Enabled = true; btChangeVer.Enabled = true; pChangeVer.Visible = false; pChangeVer.Enabled = false; } private void rbPerOut_CheckedChanged(object sender, EventArgs e) { if (rbPreOut.Checked) { rbStable.Checked = false; rbOld.Checked = false; cbOld.Enabled = false; lbVersionToInstall.Enabled = false; YorotVersion ver = VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber); versionToInstall = ver; btInstall1.Text = UIInstallVer.Replace("[VER]", ver.VersionText); } } private void rbStable_CheckedChanged(object sender, EventArgs e) { if (rbStable.Checked) { rbPreOut.Checked = false; rbOld.Checked = false; cbOld.Enabled = false; lbVersionToInstall.Enabled = false; YorotVersion ver = VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber); versionToInstall = ver; btInstall1.Text = UIInstallVer.Replace("[VER]", ver.VersionText); } } private void rbOld_CheckedChanged(object sender, EventArgs e) { if (rbOld.Checked) { rbPreOut.Checked = false; rbPreOut.Checked = false; cbOld.Enabled = true; lbVersionToInstall.Enabled = true; cbOld.Items.Clear(); for (int i = VersionManager.PreOutVersions.Count + 1; i < VersionManager.Versions.Count; i++) { if (i != VersionManager.LatestVersionNumber && i != VersionManager.PreOutVerNumber) { YorotVersion ver = VersionManager.Versions[i]; cbOld.Items.Add(ver.VersionText + " (" + ver.VersionNo + ")"); } } cbOld.SelectedIndex = 0; } } private void cbOld_SelectedIndexChanged(object sender, EventArgs e) { int indexOfO = cbOld.Text.IndexOf("(") + 1; int indexOfC = cbOld.Text.IndexOf(")"); int getVerNoLenght = indexOfC - indexOfO; int verNo = Convert.ToInt32(cbOld.Text.Substring(indexOfO, getVerNoLenght)); YorotVersion ver = VersionManager.GetVersionFromVersionNo(verNo); btInstall1.Text = UIInstallVer.Replace("[VER]", ver.VersionText); if (ver.isMissing) { lbInstallError.Text = UIChangeVerMissing; btInstall1.Enabled = false; return; } if (!supportsThisVer(ver)) { lbInstallError.Text = UIChangeVerArchNotSupported; btInstall1.Enabled = false; return; } versionToInstall = ver; lbInstallError.Text = ""; btInstall1.Enabled = true; } private void btRepair_Click(object sender, EventArgs e) { string YorotPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot.exe"; string YorotBetaPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Haltroy\\Yorot\\Yorot Beta.exe"; bool YorotExists = File.Exists(YorotPath); YorotVersion current = VersionManager.GetVersionFromVersionName(FileVersionInfo.GetVersionInfo(YorotExists ? YorotPath : YorotBetaPath).ProductVersion); if (current is null) //PreOut { versionToInstall = VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber); } else { versionToInstall = VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber); } if (btRepair.Text == UIUpdateButton) { DoneType = DoneType.Update; } else { DoneType = DoneType.Repair; } StartInstallation(isShiftPressed); } private void btInstall1_Click(object sender, EventArgs e) { if (rbPreOut.Checked) { versionToInstall = VersionManager.GetVersionFromVersionNo(VersionManager.PreOutVerNumber); } else if (rbStable.Checked) { versionToInstall = VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber); } else if (rbOld.Checked) { int indexOfO = cbOld.Text.IndexOf("(") + 1; int indexOfC = cbOld.Text.IndexOf(")"); int getVerNoLenght = indexOfC - indexOfO; int verNo = Convert.ToInt32(cbOld.Text.Substring(indexOfO, getVerNoLenght)); YorotVersion ver = VersionManager.GetVersionFromVersionNo(verNo); versionToInstall = ver; } DoneType = DoneType.Install; StartInstallation(); } private void btInstall_Click(object sender, EventArgs e) { versionToInstall = VersionManager.GetVersionFromVersionNo(VersionManager.LatestVersionNumber); DoneType = DoneType.Install; StartInstallation(isShiftPressed); } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (!allowClose) { e.Cancel = true; } } private void frmMain_SizeChanged(object sender, EventArgs e) { lbDoneDesc.MaximumSize = new Size(tbDoneError.Width, 0); } private void btSendFeedback_Click(object sender, EventArgs e) { Process.Start("https://github.com/Haltroy/Yorot/issues/new/choose"); } private void btClose_Click(object sender, EventArgs e) { if (DoneType == DoneType.Install) { Process.Start(YorotExists ? YorotPath : YorotBetaPath, "-oobe"); } Settings.Save(); Application.Exit(); } private void timer1_Tick(object sender, EventArgs e) { lbInstallCount.Text = (installDoneCount == installJobCount ? installDoneCount : installDoneCount + 1) + "/" + installJobCount; if (installDoneCount == 0) { lbInstallInfo.Text = UICreateRecovery; } else if (installDoneCount == installJobCount - 2) { lbInstallInfo.Text = UICreateShortcut; } else if (installDoneCount == installJobCount - 1) { lbInstallInfo.Text = RegistryStart; } else { lbInstallInfo.Text = workingReq != null ? workingReq.Name : DownloadYorotDesktop; } double perc = (Convert.ToDouble(installDoneCount) / Convert.ToDouble(installJobCount)) * 100; pbInstall.Width = Convert.ToInt32(perc) * (pInstall.Width / 100); if (installDoneCount == installJobCount) { Successful(); } } private void btUninstall_Click(object sender, EventArgs e) { Directory.Delete(YorotFolderPath, true); Unregister(); DoneType = DoneType.Uninstall; Successful(); } private bool isShiftPressed; private void frmMain_KeyDown(object sender, KeyEventArgs e) { isShiftPressed = e.Shift; } private void frmMain_KeyUp(object sender, KeyEventArgs e) { isShiftPressed = !e.Shift; } } public class StringEventhHybrid { public string String { get; set; } public string String2 { get; set; } public string String3 { get; set; } public StringType Type { get; set; } public delegate void EventDelegate(object sender, EventArgs e); public event EventDelegate Event; public void RunEvent(object sender, EventArgs e) { if (Event != null) { Event(sender, e); } } public override string ToString() { return Type == StringType.String ? " [STRING]" + String : " [FILE]" + String + "-" + String2 + "-" + String3; } public enum StringType { String, File } } internal enum DoneType { Install, Repair, Update, Uninstall } public enum RegType { Standart, StandartWithProtocol, StandartWithCommandProtocol, } }
47.81069
424
0.546358
[ "MIT" ]
liuchenggong/Yorot
YorotUpdate/frmMain.cs
64,403
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.FileProviders; namespace SmartBundleTags { public class FileVersionProvider : IFileVersionProvider { private const string VersionKey = "v"; private static readonly char[] QueryStringAndFragmentTokens = new[] { '?', '#' }; private readonly IFileProvider _fileProvider; private readonly IMemoryCache _cache; private PathString _requestPathBase; /// <summary> /// Creates a new instance of <see cref="Microsoft.AspNetCore.Mvc.TagHelpers.Internal.FileVersionProvider"/>. /// </summary> /// <param name="fileProvider">The file provider to get and watch files.</param> /// <param name="cache"><see cref="IMemoryCache"/> where versioned urls of files are cached.</param> /// <param name="requestPathBase">The base path for the current HTTP request.</param> public FileVersionProvider( IFileProvider fileProvider, IMemoryCache cache, PathString requestPathBase) { if (fileProvider == null) { throw new ArgumentNullException(nameof(fileProvider)); } if (cache == null) { throw new ArgumentNullException(nameof(cache)); } _fileProvider = fileProvider; _cache = cache; _requestPathBase = requestPathBase; } /// <summary> /// Adds version query parameter to the specified file path. /// </summary> /// <param name="path">The path of the file to which version should be added.</param> /// <returns>Path containing the version query string.</returns> /// <remarks> /// The version query string is appended with the key "v". /// </remarks> public string AddFileVersionToPath(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var resolvedPath = path; var queryStringOrFragmentStartIndex = path.IndexOfAny(QueryStringAndFragmentTokens); if (queryStringOrFragmentStartIndex != -1) { resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex); } Uri uri; if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out uri) && !uri.IsFile) { // Don't append version if the path is absolute. return path; } string value; if (!_cache.TryGetValue(path, out value)) { var cacheEntryOptions = new MemoryCacheEntryOptions(); cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(resolvedPath)); var fileInfo = _fileProvider.GetFileInfo(resolvedPath); if (!fileInfo.Exists && _requestPathBase.HasValue && resolvedPath.StartsWith(_requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { var requestPathBaseRelativePath = resolvedPath.Substring(_requestPathBase.Value.Length); cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(requestPathBaseRelativePath)); fileInfo = _fileProvider.GetFileInfo(requestPathBaseRelativePath); } if (fileInfo.Exists) { value = QueryHelpers.AddQueryString(path, VersionKey, GetHashForFile(fileInfo)); } else { // if the file is not in the current server. value = path; } value = _cache.Set(path, value, cacheEntryOptions); } return value; } public string AddFileVersionToPath(PathString requestPathBase, string path) { _requestPathBase = requestPathBase; return AddFileVersionToPath(path); } private static string GetHashForFile(IFileInfo fileInfo) { using (var sha256 = CryptographyAlgorithms.CreateSHA256()) { using (var readStream = fileInfo.CreateReadStream()) { var hash = sha256.ComputeHash(readStream); return WebEncoders.Base64UrlEncode(hash); } } } } }
41.018018
117
0.609269
[ "MIT" ]
BrandenMartin/SmartBundleTags
SmartBundleTags/FileVersionProvider.cs
4,555
C#
namespace NeoSharp.Core.Models { public enum HeaderType : byte { /// <summary> /// Block unavailable, no hashes, no TX data /// </summary> Header = 0, /// <summary> /// Block available, with TX hashes /// </summary> Extended = 1, } }
20.733333
52
0.491961
[ "MIT" ]
BSathvik/neo-sharp
src/NeoSharp.Core/Models/HeaderType.cs
313
C#
// Transcript from interactive session var wasmSDK = "C:/Users/stas_/Downloads/mono-wasm"; var build = "C:/Users/stas_/Downloads/build"; var files = new List<string>(); files.AddRange(Directory.GetFiles($@"{wasmSDK}/framework/", "*.dll")); files.AddRange(Directory.GetFiles($@"{wasmSDK}/wasm-bcl/wasm/", "*.dll")); files.AddRange(Directory.GetFiles($@"{wasmSDK}/wasm-bcl/wasm/Facades/", "*.dll")); Directory.CreateDirectory(build); Directory.CreateDirectory($@"{build}/bin"); File.Copy($@"{wasmSDK}/builds/release/dotnet.js", $@"{build}/dotnet.js", true); File.Copy($@"{wasmSDK}/builds/release/dotnet.wasm", $@"{build}/dotnet.wasm", true); foreach (var file in files) { File.Copy(file, $@"{build}/bin/{Path.GetFileName(file)}", true); } var text = File.ReadAllText($@"{build}/dotnet.js"); text = text.Replace("debugger", ""); File.WriteAllText($@"{build}/dotnet.js", text); Console.WriteLine( string.Join( Environment.NewLine, files .Select(f => Path.GetFileName(f)) .Select(f => f?.Replace(".dll", "")) .OrderBy(n => n) .ToArray()) );
37
83
0.665424
[ "MIT" ]
StanislavSeregin/ngx-dotnet
projects/ngx-dotnet/build-script.cs
1,073
C#
#nullable enable using Maps.Graphics; using Maps.Rendering; using Maps.Utilities; using System; using System.Drawing; using System.Web; namespace Maps.API { internal class PosterHandler : ImageHandlerBase { protected override DataResponder GetResponder(HttpContext context) => new Responder(context); private class Responder : ImageResponder { public Responder(HttpContext context) : base(context) { } public override void Process(ResourceManager resourceManager) { Selector selector; RectangleF tileRect; MapOptions options = MapOptions.SectorGrid | MapOptions.SubsectorGrid | MapOptions.BordersMajor | MapOptions.BordersMinor | MapOptions.NamesMajor | MapOptions.NamesMinor | MapOptions.WorldsCapitals | MapOptions.WorldsHomeworlds; Style style = Style.Poster; ParseOptions(ref options, ref style); string title; bool clipOutsectorBorders; if (HasOption("x1") && HasOption("x2") && HasOption("y1") && HasOption("y2")) { // Arbitrary rectangle int x1 = GetIntOption("x1", 0); int x2 = GetIntOption("x2", 0); int y1 = GetIntOption("y1", 0); int y2 = GetIntOption("y2", 0); tileRect = new RectangleF() { X = Math.Min(x1, x2), Y = Math.Min(y1, y2) }; tileRect.Width = Math.Max(x1, x2) - tileRect.X; tileRect.Height = Math.Max(y1, y2) - tileRect.Y; // NOTE: This (re)initializes a static data structure used for // resolving names into sector locations, so needs to be run // before any other objects (e.g. Worlds) are loaded. SectorMap.Milieu map = SectorMap.ForMilieu(resourceManager, GetStringOption("milieu")); selector = new RectSelector(map, resourceManager, tileRect, slop: false); // Include specified hexes tileRect.Offset(-1, -1); tileRect.Width += 1; tileRect.Height += 1; title = $"Poster ({x1},{y1}) - ({x2},{y2})"; clipOutsectorBorders = true; } else if (HasOption("domain")) { string domain = GetStringOption("domain")!; double x, y, w = 2, h = 2; switch (domain.ToLowerInvariant()) { case "deneb": x = -4; y = -1; title = "Domain of Deneb"; break; case "vland": x = -2; y = -1; title = "Domain of Vland"; break; case "ilelish": x = -2; y = 1; title = "Domain of Ilelish"; break; case "antares": x = 0; y = -2; title = "Domain of Antares"; break; case "sylea": x = 0; y = 0; title = "Domain of Sylea"; break; case "sol": x = 0; y = 2; title = "Domain of Sol"; break; case "gateway": x = 2; y = 0; title = "Domain of Gateway"; break; // And these aren't domains, but... case "foreven": x = -6; y = -1; title = "Land Grant / Foreven"; break; case "imperium": x = -4; y = -1; w = 7; h = 5; title = "Third Imperium"; break; case "solomani": x = -1.5; y = 2.75; w = 4; h = 2.25; title = "Solomani Confederacy"; break; case "zhodani": x = -8; y = -3; w = 5; h = 3; title = "Zhodani Consulate"; break; case "hive": case "hiver": x = 2; y = 1; w = 6; h = 4; title = "Hive Federation"; break; case "aslan": x = -8; y = 1; w = 7; h = 4; title = "Aslan Hierate"; break; case "vargr": x = -4; y = -4; w = 8; h = 3; title = "Vargr Extents"; break; case "kkree": x = 4; y = -2; w = 4; h = 4; title = "Two Thousand Worlds"; break; case "jp": x = 0; y = -3; w = 4; h = 3; title = "Julian Protectorate"; break; // TODO: Zhodani provinces case "chartedspace": x = -8; y = -3; w = 16; h = 8; title = "Charted Space"; break; case "jg": x = 160; y = 0; w = 2; h = 2; title = "Judges Guild"; break; default: throw new HttpError(404, "Not Found", $"Unknown domain: {domain}"); } int x1 = (int)Math.Round(x * Astrometrics.SectorWidth - Astrometrics.ReferenceHex.X + 1); int y1 = (int)Math.Round(y * Astrometrics.SectorHeight - Astrometrics.ReferenceHex.Y + 1); int x2 = (int)Math.Round(x1 + w * Astrometrics.SectorWidth - 1); int y2 = (int)Math.Round(y1 + h * Astrometrics.SectorHeight - 1); tileRect = new RectangleF() { X = Math.Min(x1, x2), Y = Math.Min(y1, y2) }; tileRect.Width = Math.Max(x1, x2) - tileRect.X; tileRect.Height = Math.Max(y1, y2) - tileRect.Y; // NOTE: This (re)initializes a static data structure used for // resolving names into sector locations, so needs to be run // before any other objects (e.g. Worlds) are loaded. SectorMap.Milieu map = SectorMap.ForMilieu(resourceManager, GetStringOption("milieu")); selector = new RectSelector(map, resourceManager, tileRect, slop: false); // Include selected hexes tileRect.Offset(-1, -1); tileRect.Width += 1; tileRect.Height += 1; // Account for jagged hexes tileRect.Height += 0.5f; tileRect.Inflate(0.25f, 0.10f); if (style == Style.Candy) tileRect.Width += 0.75f; clipOutsectorBorders = true; } else { // Sector - either POSTed or specified by name Sector? sector = null; options &= ~MapOptions.SectorGrid; if (Context.Request.HttpMethod == "POST") { bool lint = GetBoolOption("lint", defaultValue: false); Func<ErrorLogger.Record, bool>? filter = null; if (lint) { bool hide_uwp = GetBoolOption("hide-uwp", defaultValue: false); bool hide_tl = GetBoolOption("hide-tl", defaultValue: false); filter = (ErrorLogger.Record record) => { if (hide_uwp && record.message.StartsWith("UWP")) return false; if (hide_tl && record.message.StartsWith("UWP: TL")) return false; return true; }; } ErrorLogger errors = new ErrorLogger(filter); sector = GetPostedSector(Context.Request, errors) ?? throw new HttpError(400, "Bad Request", "Either file or data must be supplied in the POST data."); if (lint && !errors.Empty) throw new HttpError(400, "Bad Request", errors.ToString()); title = sector.Names.Count > 0 ? sector.Names[0].Text : "User Data"; // TODO: Suppress all OTU rendering. options &= ~(MapOptions.WorldsHomeworlds | MapOptions.WorldsCapitals); } else { string sectorName = GetStringOption("sector") ?? throw new HttpError(400, "Bad Request", "No sector specified."); SectorMap.Milieu map = SectorMap.ForMilieu(resourceManager, GetStringOption("milieu")); sector = map.FromName(sectorName) ?? throw new HttpError(404, "Not Found", $"The specified sector '{sectorName}' was not found."); title = sector.Names[0].Text; } if (sector != null && HasOption("subsector") && GetStringOption("subsector")!.Length > 0) { string subsector = GetStringOption("subsector")!; int index = sector.SubsectorIndexFor(subsector); if (index == -1) throw new HttpError(404, "Not Found", $"The specified subsector '{subsector}' was not found."); selector = new SubsectorSelector(resourceManager, sector, index); tileRect = sector.SubsectorBounds(index); options &= ~(MapOptions.SectorGrid | MapOptions.SubsectorGrid); title = $"{title} - Subsector {'A' + index}"; } else if (sector != null && HasOption("quadrant") && GetStringOption("quadrant")!.Length > 0) { string quadrant = GetStringOption("quadrant")!; int index; switch (quadrant.ToLowerInvariant()) { case "alpha": index = 0; quadrant = "Alpha"; break; case "beta": index = 1; quadrant = "Beta"; break; case "gamma": index = 2; quadrant = "Gamma"; break; case "delta": index = 3; quadrant = "Delta"; break; default: throw new HttpError(400, "Bad Request", $"The specified quadrant '{quadrant}' is invalid."); } selector = new QuadrantSelector(resourceManager, sector, index); tileRect = sector.QuadrantBounds(index); options &= ~(MapOptions.SectorGrid | MapOptions.SubsectorGrid | MapOptions.SectorsMask); title = $"{title} - {quadrant} Quadrant"; } else if (sector == null) { throw new HttpError(400, "Bad Request", "No sector specified."); } else { selector = new SectorSelector(resourceManager, sector); tileRect = sector.Bounds; options &= ~(MapOptions.SectorGrid); } // Account for jagged hexes tileRect.Height += 0.5f; tileRect.Inflate(0.25f, 0.10f); if (style == Style.Candy) tileRect.Width += 0.75f; clipOutsectorBorders = false; } const double NormalScale = 64; // pixels/parsec - standard subsector-rendering scale double scale = GetDoubleOption("scale", NormalScale).Clamp(MinScale, MaxScale); int rot = GetIntOption("rotation", 0) % 4; int hrot = GetIntOption("hrotation", 0); bool thumb = GetBoolOption("thumb", false); Stylesheet stylesheet = new Stylesheet(scale, options, style); Size tileSize = new Size((int)Math.Floor(tileRect.Width * scale * Astrometrics.ParsecScaleX), (int)Math.Floor(tileRect.Height * scale * Astrometrics.ParsecScaleY)); if (thumb) { tileSize.Width = (int)Math.Floor(16 * tileSize.Width / scale); tileSize.Height = (int)Math.Floor(16 * tileSize.Height / scale); scale = 16; } int bitmapWidth = tileSize.Width, bitmapHeight = tileSize.Height; AbstractMatrix rotTransform = AbstractMatrix.Identity; switch (rot) { case 1: // 90 degrees clockwise rotTransform.RotatePrepend(90); rotTransform.TranslatePrepend(0, -bitmapHeight); Util.Swap(ref bitmapWidth, ref bitmapHeight); break; case 2: // 180 degrees rotTransform.RotatePrepend(180); rotTransform.TranslatePrepend(-bitmapWidth, -bitmapHeight); break; case 3: // 270 degrees clockwise rotTransform.RotatePrepend(270); rotTransform.TranslatePrepend(-bitmapWidth, 0); Util.Swap(ref bitmapWidth, ref bitmapHeight); break; } // TODO: Figure out how to compose rot and hrot properly. AbstractMatrix hexTransform = AbstractMatrix.Identity; Size bitmapSize = new Size(bitmapWidth, bitmapHeight); if (hrot != 0) ApplyHexRotation(hrot, stylesheet, ref bitmapSize, ref hexTransform); AbstractMatrix clampTransform = AbstractMatrix.Identity; if (GetBoolOption("clampar", defaultValue: false)) { // Landscape: 1.91:1 (1.91) // Portrait: 4:5 (0.8) const double MIN_ASPECT_RATIO = 0.8; const double MAX_ASPECT_RATIO = 1.91; double aspectRatio = (double)bitmapSize.Width / (double)bitmapSize.Height; Size newSize = bitmapSize; if (aspectRatio < MIN_ASPECT_RATIO) { newSize.Width = (int)Math.Floor(bitmapSize.Height * MIN_ASPECT_RATIO); } else if (aspectRatio > MAX_ASPECT_RATIO) { newSize.Height = (int)Math.Floor(bitmapSize.Width / MAX_ASPECT_RATIO); } if (newSize != bitmapSize) { clampTransform.TranslatePrepend( (newSize.Width - bitmapSize.Width) / 2f, (newSize.Height - bitmapSize.Height) / 2f); bitmapSize = newSize; } } // Compose in this order so aspect ratio adjustments to image size (computed last) // are applied first. AbstractMatrix transform = AbstractMatrix.Identity; transform.Prepend(clampTransform); transform.Prepend(hexTransform); transform.Prepend(rotTransform); RenderContext ctx = new RenderContext(resourceManager, selector, tileRect, scale, options, stylesheet, tileSize) { ClipOutsectorBorders = clipOutsectorBorders }; ProduceResponse(Context, title, ctx, bitmapSize, transform); } } } }
49.809524
244
0.471192
[ "Apache-2.0" ]
SerpentineOwl/travellermap
server/api/PosterHandler.cs
15,692
C#
using Microsoft.AspNetCore.Mvc; namespace app.Controllers { [ApiController] [Route("ping")] public class PingController : ControllerBase { public IActionResult Ping() { return Ok("Pong!"); } } }
18.166667
48
0.669725
[ "MIT" ]
keotl/sgt-mapper
e2e_tests/app/Controllers/PingController.cs
218
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ServiceCatalog.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServiceCatalog.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ProductViewAggregationValue Object /// </summary> public class ProductViewAggregationValueUnmarshaller : IUnmarshaller<ProductViewAggregationValue, XmlUnmarshallerContext>, IUnmarshaller<ProductViewAggregationValue, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ProductViewAggregationValue IUnmarshaller<ProductViewAggregationValue, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ProductViewAggregationValue Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ProductViewAggregationValue unmarshalledObject = new ProductViewAggregationValue(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ApproximateCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.ApproximateCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Value", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Value = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ProductViewAggregationValueUnmarshaller _instance = new ProductViewAggregationValueUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ProductViewAggregationValueUnmarshaller Instance { get { return _instance; } } } }
37.112245
195
0.63019
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/Internal/MarshallTransformations/ProductViewAggregationValueUnmarshaller.cs
3,637
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace EveCM.Models { public class Profile { [Display(Name = "User Name")] public string UserName { get; set; } public string Email { get; set; } public IEnumerable<CharacterDetails> AssociatedCharacters { get; set; } } }
24.294118
79
0.690073
[ "MIT" ]
reecebedding/EveCM
EveCM/Models/Profile.cs
415
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using ZptSharp.Config; namespace ZptSharp.Mvc5 { /// <summary> /// Implementation of <see cref="IGetsRootContextBuilder"/> which sets up the /// 'root variables' which are made available to ZPT MVC5 views. /// </summary> /// <remarks> /// <para> /// This class adds a number of predefined global variables to the root of the TALES context, /// such that they are all available in ZPT views. Where possible, these mimic the same variables /// which would have been made available to Razor views. There are some small differences between /// MVC versions. /// </para> /// <list type="bullet"> /// <item>For ASP.NET MVC5 see <c>ViewPage&lt;TModel&gt;</c> at https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.viewpage-1?view=aspnet-mvc-5.2</item> /// <item>For ASP.NET Core MVC see <c>RazorPage&lt;TModel&gt;</c> at https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.razor.razorpage-1?view=aspnetcore-2.0</item> /// </list> /// <para> /// Some properties which would have been available to Razor views are excluded, especially where they /// are meaningless or do not make sense in the context of a ZPT view. /// </para> /// <para> /// Note that the source for this class uses a number of 'compiler flags' (preprocessor directives) /// to cater for either MVC5 or MVC Core. /// </para> /// </remarks> public class MvcContextBuilderProvider : MvcContextBuilderProviderBase { /// <summary> /// Builds/adds-to the root TALES context using a helper. /// </summary> /// <param name="helper">The helper object for adding to the root TALES context.</param> /// <param name="serviceProvider">A service provider.</param> protected override void BuildContext(IConfiguresRootContext helper, IServiceProvider serviceProvider) { base.BuildContext(helper, serviceProvider); helper.AddToRootContext("Application", GetApplicationDictionary()); helper.AddToRootContext("Cache", ViewContext.HttpContext.Cache); helper.AddToRootContext("Server", ViewContext.HttpContext.Server); helper.AddToRootContext("Session", ViewContext.HttpContext.Session); } /// <summary> /// Gets the Uri to the current HTTP request. /// </summary> /// <returns>The request Uri.</returns> protected override Uri GetUrl() => ViewContext.HttpContext.Request.Url; /// <summary> /// Gets an object which shall be used to fulfil the 'Views' global variable. /// </summary> /// <remarks> /// <para> /// The views object provides access to the root directory which contains all of /// the views for the application. /// </para> /// </remarks> /// <returns>The views object.</returns> protected override object GetViewsObject() => new TemplateDirectory(ViewContext.HttpContext.Server.MapPath(ViewsPath)); IDictionary<string, object> GetApplicationDictionary() { var app = ViewContext.HttpContext.Application; if(app == null) return new Dictionary<string, object>(); return app.AllKeys.ToDictionary(k => k, v => app[v]); } /// <summary> /// Initializes a new instance of the <see cref="MvcContextBuilderProvider"/> class. /// </summary> /// <param name="viewContext">View context.</param> /// <param name="viewsPath">Views path.</param> public MvcContextBuilderProvider(ViewContext viewContext, string viewsPath) : base(viewContext, viewsPath) {} } }
45.759036
186
0.645603
[ "MIT" ]
csf-dev/ZPT-Sharp
MvcViewEngines/ZptSharp.Mvc5/MvcContextBuilderProvider.cs
3,798
C#
using CoachLancer.Data.Models; using CoachLancer.Data.Repositories; using CoachLancer.Data.SaveContext; using Moq; using NUnit.Framework; using System; namespace CoachLancer.Services.Tests.CoachServiceTests { [TestFixture] public class UpdateCoach_Should { [Test] public void ThrowArgumentNullException_WhenCoachIsNull() { var contextMock = new Mock<ISaveContext>(); var efRepoMock = new Mock<IEfRepository<Coach>>(); var coachService = new CoachService(efRepoMock.Object, contextMock.Object); Assert.Throws<ArgumentNullException>(() => coachService.UpdateCoach(null)); } [Test] public void CallRepositoryUpdateMethod_WhenExecuted() { // Arrange var contextMock = new Mock<ISaveContext>(); var efRepoMock = new Mock<IEfRepository<Coach>>(); var coachService = new CoachService(efRepoMock.Object, contextMock.Object); var player = new Mock<Coach>(); // Act coachService.UpdateCoach(player.Object); // Assert efRepoMock.Verify(e => e.Update(player.Object), Times.Once); } [Test] public void CallContextCommitMethod_WhenExecuted() { // Arrange var contextMock = new Mock<ISaveContext>(); var efRepoMock = new Mock<IEfRepository<Coach>>(); var coachService = new CoachService(efRepoMock.Object, contextMock.Object); var player = new Mock<Coach>(); // Act coachService.UpdateCoach(player.Object); // Assert contextMock.Verify(c => c.Commit(), Times.Once); } } }
30.559322
88
0.588464
[ "MIT" ]
ikonomov17/CoachLancer
CoachLancer/CoachLancer.Services.Tests/CoachServiceTests/UpdateCoach_Should.cs
1,805
C#
namespace VsProjEdit.Models { class PropsTypeItem { public string Name { get; set; } public NewProjectModel.EPropsType Id { get; set; } public PropsTypeItem(string name, NewProjectModel.EPropsType id) { Name = name; Id = id; } } }
19.375
72
0.554839
[ "MIT" ]
honzaq/vsprojedit
Models/PropsTypeItem.cs
312
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpLearning.CrossValidation.TrainingTestSplitters; namespace SharpLearning.CrossValidation.Test.TrainingTestSplitters { [TestClass] public class NoShuffleTrainingTestIndexSplitterTest { [TestMethod] public void NoShuffleTrainingValidationIndexSplitter_Split() { var sut = new NoShuffleTrainingTestIndexSplitter<double>(0.8); var targets = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var actual = sut.Split(targets); var expected = new TrainingTestIndexSplit(new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }, new int[] { 8, 9 }); Assert.AreEqual(expected, actual); } } }
31.25
91
0.634667
[ "MIT" ]
JTOne123/SharpLearning
src/SharpLearning.CrossValidation.Test/TrainingTestSplitters/NoShuffleTrainingTestIndexSplitterTest.cs
752
C#
using System; using System.Globalization; using HotChocolate.Language; using HotChocolate.Properties; namespace HotChocolate.Types { public sealed class DateTimeType : ScalarType<DateTimeOffset, StringValueNode> { private const string _utcFormat = "yyyy-MM-ddTHH\\:mm\\:ss.fffZ"; private const string _localFormat = "yyyy-MM-ddTHH\\:mm\\:ss.fffzzz"; public DateTimeType() : base(ScalarNames.DateTime) { Description = TypeResources.DateTimeType_Description; } public DateTimeType(NameString name) : base(name) { } public DateTimeType(NameString name, string description) : base(name) { Description = description; } protected override DateTimeOffset ParseLiteral(StringValueNode literal) { if (TryDeserializeFromString(literal.Value, out DateTimeOffset? value)) { return value.Value; } throw new ScalarSerializationException( TypeResourceHelper.Scalar_Cannot_ParseLiteral( Name, literal.GetType())); } protected override StringValueNode ParseValue(DateTimeOffset value) { return new StringValueNode(Serialize(value)); } public override bool TrySerialize(object value, out object serialized) { if (value is null) { serialized = null; return true; } if (value is DateTimeOffset dt) { serialized = Serialize(dt); return true; } serialized = null; return false; } public override bool TryDeserialize(object serialized, out object value) { if (serialized is null) { value = null; return true; } if (serialized is string s && TryDeserializeFromString(s, out DateTimeOffset? d)) { value = d; return true; } if (serialized is DateTimeOffset) { value = serialized; return true; } if (serialized is DateTime dt) { value = new DateTimeOffset( dt.ToUniversalTime(), TimeSpan.Zero); return true; } value = null; return false; } private static string Serialize(DateTimeOffset value) { if (value.Offset == TimeSpan.Zero) { return value.ToString( _utcFormat, CultureInfo.InvariantCulture); } return value.ToString( _localFormat, CultureInfo.InvariantCulture); } private static bool TryDeserializeFromString(string serialized, out DateTimeOffset? value) { if (serialized != null && serialized.EndsWith("Z") && DateTime.TryParse( serialized, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out DateTime zuluTime)) { value = new DateTimeOffset( zuluTime.ToUniversalTime(), TimeSpan.Zero); return true; } if (DateTimeOffset.TryParse( serialized, out DateTimeOffset dt)) { value = dt; return true; } value = null; return false; } } }
27.601449
98
0.498294
[ "MIT" ]
Elywejnak/hotchocolate
src/Core/Types/Types/Scalars/DateTimeType.cs
3,809
C#
using System; using System.Linq; using JetBrains.Annotations; using Lykke.Service.HFT.Core.Services; using Lykke.Service.HFT.Core.Services.ApiKey; using WampSharp.V2.Authentication; namespace Lykke.Service.HFT.Wamp.Security { public class WampSessionAuthenticatorFactory : IWampSessionAuthenticatorFactory { private readonly ISessionRepository _sessionRepository; private readonly IApiKeyValidator _apiKeyValidator; public WampSessionAuthenticatorFactory( [NotNull] IApiKeyValidator apiKeyValidator, [NotNull] ISessionRepository sessionRepository) { _apiKeyValidator = apiKeyValidator ?? throw new ArgumentNullException(nameof(apiKeyValidator)); _sessionRepository = sessionRepository ?? throw new ArgumentNullException(nameof(sessionRepository)); } public IWampSessionAuthenticator GetSessionAuthenticator(WampPendingClientDetails details, IWampSessionAuthenticator transportAuthenticator) { if (details.HelloDetails.AuthenticationMethods.Contains(AuthMethods.Ticket)) { return new TicketSessionAuthenticator(details, _apiKeyValidator, _sessionRepository); } return new AnonymousWampSessionAuthenticator(); } } }
42.064516
148
0.736963
[ "MIT" ]
LykkeCity/Lykke.Service.HFT
src/Lykke.Service.HFT.Wamp/Security/WampSessionAuthenticatorFactory.cs
1,306
C#
namespace NxBRE.FlowEngine { using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Xml.Xsl; using NxBRE.Util; using NxBRE.FlowEngine; using NxBRE.FlowEngine.Core; using NxBRE.FlowEngine.IO; /// <summary>The Rule Interpretor implementation of IBRE, the Flow Engine of NxBRE.</summary> /// <remarks>[Author: Sloan Seaman] Take a deep breath.... Inhale... Exhale... Lets begin: /// <P> /// BREImpl is a reference implementation of a Business Rule Engine(BRE). /// </P> /// <P> /// <B>10000' view</B><BR/> /// This accomplishes its task by traversing (DOM) an XML document that should be passed /// in through the init() method. The XML document MUST adhere to the /// businessRules.xsd Schema. If it does not you may get some odd behaviors from this /// class. It then call all the executeRule() methods in the defined factories. /// The factories get passed a RuleContext, a Step, and any Parameters that have /// been set. The RuleContext contains all /// the generated results so far as well as other BRE related information. The Step /// is a nullable object that can be used to have one executeRule() execute differently /// depending on the "step" that it is on. The results of the call to executeRule() /// are wrapped in a BRERuleResult and added to the RuleContext. /// </P> /// <P> /// It is key to note that this class will not throw ANY exceptions unless they are so /// severe that the whole class crashes (99.9% impossible). Instead it listeners.dispatches all /// errors to registered listeners who implement ExceptionListener. This allows multiple /// object the ability to handle exceptions. /// </P> /// <P> /// Logging occurs via listeners.dispatching to any registered listener who implements /// BRELogListener. DEBUG as well as WARN, ERROR, and FATAL are created by this class. /// </P> /// <P> /// <B>100' view</B><BR/> /// </P> /// Lets get to the meat of it shall we? /// <P> /// The first method executed should be the init() method. /// The init() method preloads ALL defined Rule factories /// even if they may never be used. This is to catch any classload /// exceptions as early on as possible to allows the calling class /// the ability to fix any issues realtime. If a rule is defined /// without a factory BREImpl checks to see if it already exists in /// the RuleContext. This is because RuleContext may be passed in /// and may already be populated. If it does not find a factory anywhere it /// will listeners.dispatch a warning to alert the registered listeners of the issue. /// </P> /// <P> /// The error is only a warning at this point because the process() method /// should not have been called yet thus allowing the calling class the /// ability to still set things in the RuleContext. /// </P> /// <P> /// The process method should be called next to actually execute the /// the business rules. The process method traverses the XML document /// making calls to the defined Factories that implement BRERuleFactory. /// We still have to make sure that the classes implements BRERuleFactory /// because the RuleContext may have changed. This is a FATAL if this /// occurs. /// </P> /// <P> /// Next it takes the results from the executeRule() and wraps it into a /// RuleResult type. /// </P> /// <P> /// If an exception occurs within executeRule() BREImpl will listeners.dispatch an ERROR /// to any listening classes and then will take the exception and wrap it with /// BRERuleResult. This allows the developer the ability to define exception /// cases within the XML document. In English, you can throw exceptions on /// purpose and handle them accordingly in the XML doc. /// </P> /// <P> /// The last steps are to add the final RuleResult to the call stack, inform /// any listeners implementing BRERuleResultListener that we have a RuleResult, /// and add the RuleResult to the RuleContext so that other RuleFactories may /// utilize and share the data. /// </P> /// <P> /// <B>Key Notes</B><BR/> /// <OL> /// <LI>This object does not intentionally throw Exceptions. If a Error listener is /// not registered, you will not know when something blows up! /// </LI> /// <LI>Errors will only be thrown if the object hits a fatal runtime /// error within itself and cannot continue /// </LI> /// </OL> /// </P> /// </remarks> /// <author> Sloan Seaman </author> /// <author> David Dossot </author> public sealed class BREImpl : IFlowEngine { // XML Related info private const string BUSINESS_RULES = "BusinessRules"; private const string COMPARE = "Compare"; private const string CONDITION = "Condition"; private const string DO = "Do"; private const string ELSEIF = "ElseIf"; private const string ELSE = "Else"; private const string FOREACH = "ForEach"; private const string IF = "If"; private const string INVOKESET = "InvokeSet"; private const string LOG = "Log"; private const string LOGIC = "Logic"; private const string PARAMETER = "Parameter"; private const string RETRACT = "Retract"; private const string RULE = "Rule"; private const string SET = "Set"; private const string WHILE = "While"; private sealed class COMPARE_ATTRS { public const string LEFTID = "leftId"; public const string RIGHTID = "rightId"; public const string OPERATOR = "operator"; } private sealed class CONDITION_ATTRS { public const string TYPE = "type"; public const string AND = "AND"; public const string OR = "OR"; public const string NOT = "NOT"; } private sealed class FOREACH_ATTRS { public const string ID = "id"; public const string RULE_VALUE = "ruleValue"; } private sealed class INVOKESET_ATTRS { public const string ID = "id"; public const string RULE_VALUE = "ruleValue"; } private sealed class LOG_ATTRS { public const string MESSAGE = "msg"; public const string MESSAGE_ID = "msgId"; public const string LEVEL = "level"; } private sealed class PARAMETER_ATTRS { public const string NAME = "name"; public const string VALUE = "value"; public const string TYPE = "type"; public const string RULE_VALUE = "ruleValue"; } private sealed class RULE_ATTRS { public const string FACTORY = "factory"; public const string ID = "id"; public const string STEP = "step"; } private sealed class SET_ATTRS { public const string ID = "id"; } private sealed class RETRACT_ATTRS { public const string ID = "id"; } private bool running = false; private bool initialized = false; private IBRERuleContext ruleContext = null; private XPathDocument xmlDocument = null; private IRulesDriver rulesDriver = null; private BackwardChainer backwardChainer = null; public event DispatchRuleResult ResultHandlers; /// <summary> Returns or Sets the RuleContext in it's current state. /// <P> /// If the developer wishes to have a private copy, make sure /// to use Clone(). /// </P> /// <P> /// This method allows developers to provide an already populated BRERuleContext. /// </P> /// <P> /// This is provides to allow for RuleFactories that have already created, thus /// allowing a more stateful RuleFactory /// </P> /// </summary> /// <returns> The RuleContext in its current state</returns> public IBRERuleContext RuleContext { get { return ruleContext; } set { if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "RuleContext provided by external entity"); ruleContext = value; } } /// <summary> Returns the loaded XML Rules in the native NxBRE syntax /// </summary> /// <returns> The loaded Business Rules</returns> public XPathDocument XmlDocumentRules { get { return xmlDocument; } } /// <summary> Running state of the engine, i.e. when processing. /// </summary> /// <returns> True if the engine is processing. </returns> public bool Running { get { return !running; } } private void DispatchRuleResult(IBRERuleResult ruleResult) { if (ResultHandlers != null) ResultHandlers(this, ruleResult); } private DispatchRuleResult GetResultHandlers() { return ResultHandlers; } /// <summary> Performs a shallow copy of a pre-initialized BRE, i.e. returns a new BRE /// containing a shallow copied rule context, ready to fire! /// </summary> public object Clone() { if (!initialized) throw new BREException("Clone in not available if BRE is not initialized."); BREImpl newBRE = new BREImpl(); // pass the result handler newBRE.ResultHandlers += GetResultHandlers(); // pass a cloned context newBRE.RuleContext = (IBRERuleContext)ruleContext.Clone(); // pass the loaded rule newBRE.Init(xmlDocument); return newBRE; } /// <summary> /// Initialize the engine with a specific rule base. /// </summary> /// <param name="rulebase"></param> /// <returns></returns> public bool Init(XPathDocument rulebase) { return DoInit(rulebase); } /// <summary> /// Initialize the engine by loading rules from a rules driver. /// </summary> /// <param name="rulesDriver"></param> /// <returns></returns> public bool Init(IRulesDriver rulesDriver) { return DoInit(rulesDriver); } private bool DoInit(object aObj) { if (running) { if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceEvent(TraceEventType.Error, 0, "BRE already running: a violent Stop will be tried!"); Stop(); } else { if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE Starting..."); } if (aObj == null) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceEvent(TraceEventType.Critical, 0, "Business Rules provided by external entity\nObject passed to init() must not be Null"); return false; } if (aObj is IRulesDriver) { rulesDriver = (IRulesDriver) aObj; xmlDocument = null; } else if (aObj is XPathDocument) { xmlDocument = (XPathDocument) aObj; } else { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceEvent(TraceEventType.Critical, 0, "Business Rules provided by external entity\nObject passed to init() must be of type System.Xml.XPath.XPathDocument or NxBRE.FlowEngine.IO.IRulesDriver and not " + aObj.GetType()); return false; } if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE Initializing..."); if (ruleContext == null) ruleContext = new BRERuleContextImpl(new Stack(), new Hashtable(), new Hashtable(), new Hashtable()); // pre-load all operators foreach(Type type in Reflection.NxBREAssembly.GetTypes()) if (null != type.GetInterface(typeof(IBREOperator).FullName, false)) GetOperator(type.FullName); // pre-load factories initialized = LoadFactories(GetXmlDocumentRules().Select("//"+RULE+"[@"+RULE_ATTRS.FACTORY+"]")); return initialized; } /// <summary>Reset the context's call stack and results /// </summary> public void Reset() { if (running) { if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceEvent(TraceEventType.Error, 0, "BRE already running: a violent Stop will be tried!"); Stop(); } if (ruleContext != null) { ruleContext.ResultsMap.Clear(); ruleContext.CallStack.Clear(); } if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE has been reset."); } /// <summary> Returns either an XPathNavigator containing the rules that was passed to Init(), /// or the XmlDocument that the IRuleDriver passed to Init() is set to provide. /// </summary> private XPathNavigator GetXmlDocumentRules() { if ((rulesDriver != null) && (xmlDocument == null)) { XmlReader reader = rulesDriver.GetXmlReader(); xmlDocument = new XPathDocument(reader); // this close is very important for freeing the underlying resource, which can be a file reader.Close(); } if (xmlDocument != null) { XPathNodeIterator navDoc = xmlDocument.CreateNavigator().Select(BUSINESS_RULES); navDoc.MoveNext(); return navDoc.Current; } else throw new BREException("No RulesDriver nor Business Rules available."); } /// <summary> Execute the BRE. /// </summary> /// <returns> True if successful, False otherwise /// /// </returns> public bool Process() { return Process(null); } /// <summary> Execute the BRE but only do a certain set. /// </summary> /// <returns> True if successful, False otherwise /// /// </returns> public bool Process(string setId) { if (!initialized) throw new BREException("Process in not available if BRE is not initialized."); bool wasRunning = running; // an empty string is of no interest if (setId == String.Empty) setId = null; if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "NxBRE v" + Reflection.NXBRE_VERSION + " Flow Engine Processing" + ((setId == null)?String.Empty:" Set: " + setId) + ((wasRunning)?" (Re-entrant)":String.Empty)); if (ruleContext == null) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceEvent(TraceEventType.Critical, 0, "RuleContext is null"); return false; } if (!running) running = true; try { ProcessXML(GetXmlDocumentRules(), setId, null); } catch (BREProcessInterruptedException pie) { Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE Terminated" + pie.Message + ((setId == null)?String.Empty:" Set: " + setId) + ((wasRunning)?" (Re-entrant)":String.Empty)); return false; } if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE Finished" + ((setId == null)?String.Empty:" Set: " + setId) + ((wasRunning)?" (Re-entrant)":String.Empty)); if (!wasRunning) running=false; return true; } /// <summary> Violently stop the BRE </summary> public void Stop() { running = false; } /// <summary> /// Schedule the execution of sets to try to create the passed object ID in the rule context (backward chaining). /// </summary> /// <param name="objectId">The ID to resolve.</param> /// <returns>The value of the object ID to resolve, or null if the resolution was not possible.</returns> public object Resolve(string objectId) { if (backwardChainer == null) { backwardChainer = new BackwardChainer(this); } return backwardChainer.Resolve(objectId); } /// <summary> /// Schedule the execution of sets to try to create the passed object ID in the rule context (backward chaining). /// </summary> /// <param name="objectId">The ID to resolve.</param> /// <param name="defaultValue">The value to return if the ID was not resolvable.</param> /// <returns>The value of the object ID to resolve, or defaultValue if the resolution was not possible.</returns> public object Resolve(string objectId, object defaultValue) { object result = Resolve(objectId); return result==null?defaultValue:result; } /// <summary> This method preloads all defined factories with the XML document. /// This is to catch any errors relating to class loading up front before we /// get to the real document parsing and business logic. /// <P> /// This does not support graceful degradation on purpose. /// If I can't get to a business rule, it should be understood /// that technically, in the end, the rules fail. /// </P> /// </summary> /// <param name="aNodeList">The List of Nodes to process /// </param> /// <returns> True if successful, False otherwise /// /// </returns> private bool LoadFactories(XPathNodeIterator aNodeList) { if (Logger.IsInferenceEngineInformation) Logger.FlowEngineSource.TraceEvent(TraceEventType.Information, 0, "BRE Loading RuleFactories..."); if (aNodeList != null) { try { while(aNodeList.MoveNext()) { string factory = aNodeList.Current.GetAttribute(RULE_ATTRS.FACTORY, String.Empty); if (factory != String.Empty) { string id = aNodeList.Current.GetAttribute(RULE_ATTRS.ID, String.Empty); if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Found Factory: " + factory + " Id: " + id); if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Loading Factory: " + id); object tmpClass = Reflection.ClassNew(factory, null); if (tmpClass is IBRERuleFactory) { IBRERuleFactory brf = (IBRERuleFactory) tmpClass; ruleContext.SetFactory(id, brf); if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "BRE RuleFactory " + id + " loaded and added to RuleContext"); } else { throw new BREException("Specified Rule Factory " + factory + " with id " + id + " not of type IBRERuleFactory"); } } } return true; } catch (System.Exception e) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, e); } } return false; } /// <summary> This method processes the XML Document. /// <P> /// This is a recursive alg. So be careful if editing it!!!!!!! /// </P> /// </summary> /// <param name="aNode">The Node to process /// </param> /// <param name="aSetId">The set to process</param> /// <param name="aObj">A bland object for anything /// </param> /// <returns> True if successful, False otherwise /// /// </returns> private object ProcessXML(XPathNavigator aNode, string aSetId, object aObj) { if (!running) throw new BREProcessInterruptedException("Processing stopped in node: "+aNode); if (aNode == null) return null; string nodeName = aNode.LocalName; if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Element Node: " + nodeName); /* A lot of this code is the same but it is broken up for scalability reasons... */ if (nodeName == BUSINESS_RULES) { // Instead of parsing all sub nodes perform an xPath pre-selection of nodes // depending if a set is selected or not. XPathNodeIterator selectedNodes; if (aSetId == null) selectedNodes = aNode.Select("*[count(ancestor-or-self::"+SET+")=0]"); else selectedNodes = aNode.Select("*[count(ancestor-or-self::"+SET+")=0] | "+SET+"[@"+SET_ATTRS.ID+"='"+aSetId+"']/*"); while(selectedNodes.MoveNext()) ProcessXML(selectedNodes.Current, aSetId, aObj); } else if (nodeName == COMPARE) { Hashtable map = new Hashtable(); DoRecursion(aNode, aSetId, map); aObj = ProcessCompareNode(aNode, map); map = null; } else if (nodeName == CONDITION) { aObj = ProcessConditionNode(aNode, aSetId, aObj); } else if (nodeName == DO) { DoRecursion(aNode, aSetId, aObj); } else if (nodeName == ELSE) { DoRecursion(aNode, aSetId, aObj); } else if (nodeName == FOREACH) { string resultToAssert = aNode.GetAttribute(FOREACH_ATTRS.ID, String.Empty); string objectToEnumerate = aNode.GetAttribute(FOREACH_ATTRS.RULE_VALUE, String.Empty); IBRERuleResult ruleObjectToEnumerate = ruleContext.GetResult(objectToEnumerate); if (ruleObjectToEnumerate != null) { IEnumerable enumerable = (IEnumerable)ruleObjectToEnumerate.Result; if (enumerable != null) { foreach(object parser in enumerable) { ruleContext.SetObject(resultToAssert, parser); DoRecursion(aNode, aSetId, aObj); } } } } else if ((nodeName == IF) || (nodeName == ELSEIF) || (nodeName == WHILE)) { bool exitWhile = false; do { bool firstChild = true; XPathNodeIterator children = aNode.SelectChildren(XPathNodeType.Element); while ((children.MoveNext()) && (running)) { // Thanks Sihong & Bernhard aObj = ProcessXML(children.Current, aSetId, firstChild?null:aObj); // Only the first child node is considered as test, the rest are executed blindely if ((firstChild) && (aObj is System.Boolean) && (!Convert.ToBoolean(aObj))) { exitWhile = true; break; } firstChild=false; } } while ((nodeName == WHILE) && (!exitWhile) && (running)); } else if (nodeName== INVOKESET) { ProcessInvokeSetNode(aNode); } else if (nodeName == LOG) { ProcessLogNode(aNode); } else if (nodeName == LOGIC) { XPathNodeIterator children = aNode.SelectChildren(XPathNodeType.Element); while ((children.MoveNext()) && (running)) { aObj = ProcessXML(children.Current, aSetId, aObj); if ((aObj is System.Boolean) && (Convert.ToBoolean(aObj))) break; } } else if (nodeName == PARAMETER) { if (aObj is Hashtable) ProcessParameterNode(aNode, (Hashtable) aObj); } else if (nodeName == RETRACT) { string idToRetract = aNode.GetAttribute(RETRACT_ATTRS.ID, String.Empty); if (ruleContext.ResultsMap.Contains(idToRetract)) ruleContext.ResultsMap.Remove(idToRetract); } else if (nodeName == RULE) { Hashtable map = new Hashtable(); DoRecursion(aNode, aSetId, map); ProcessRuleNode(aNode, map); map = null; } else if (nodeName == SET) { // If I reach a SET node, it has been pre-filtered at document level // therefore I process it blindely DoRecursion(aNode, aSetId, aObj); } return aObj; } /// <summary> doRecursive actually does the recursion in terms of callback /// into the algorythm. It is in it's own method for code reuse /// reasons. /// <P> /// This may be a bit confusing to some because the recursive alg. /// (processXML) actually calls out to an external method to do the /// calls to go back in. (if that makes sense...) /// </P> /// </summary> /// <param name="aNode">The node to use /// </param> /// <param name="aSetId">The set to process</param> /// <param name="aObj">The generic object to use /// </param> /// <returns>s The object returned by processXML /// /// </returns> private object DoRecursion(XPathNavigator aNode, string aSetId, object aObj) { object o = null; if (running) { XPathNodeIterator children = aNode.SelectChildren(XPathNodeType.Element); while(children.MoveNext()) o = ProcessXML(children.Current, aSetId, aObj); } return o; } /// <summary> Processes the Condition Node. /// <P> /// Internally this method is slightly different than the others because it /// handles the children internally. This is to support the OR/AND /// functionality that is required. /// </P> /// <P> /// Verbose:</P><P> /// We go through the list of children within a defined BLOCK. /// The BLOCK is defined so we can exit out quickly when we hit our /// criteria. /// </P> /// <P> /// We only wish to deal with ELEMENT_NODEs. This is key to note because /// children actually contains other types of nodes. /// </P> /// <P> /// If the processState is null (i.e. they did not specifiy AND or OR in /// the XML) we default to AND. /// </P> /// <P> /// If it is not null we check for AND or OR. If AND and the call to /// processXML() (which would end up calling processCompareNode()) /// is false, we know the AND fails so we can break out of the loop. /// Otherwise we just increment our TRUE count. Incrementing the /// TRUE count isn't really necessary here, but it is for the OR /// condition, and this is a work around. /// </P> /// <P> /// If we get an OR we are only looking for 1 TRUE so we can break /// as soon as we hit it. We increment the TRUE count here as well. /// This is so that later, if the TRUE count == 0, we know that the /// OR never hit a true statement and should then fail. /// REMEBER: we only break if we hit TRUE, the loop will exit nomally /// if it doesn't. And since we are optimistic with returnBool being /// set to TRUE (for the AND stmt) we must set it to false afer the OR /// loop finishes if the trueCount = 0. /// </P> /// </summary> /// <param name="aNode">The Node to process /// </param> /// <param name="aSetId">The set to rule process</param> /// <param name="aObj">The object to evaluate</param> /// <returns> True if the If stmt passes, False otherwise /// /// </returns> private bool ProcessConditionNode(XPathNavigator aNode, string aSetId, object aObj) { bool returnBool = true; bool childrenBool = true; string processType = aNode.GetAttribute(CONDITION_ATTRS.TYPE, String.Empty); int trueCount = 0; XPathNodeIterator children = aNode.SelectChildren(XPathNodeType.Element); while(children.MoveNext()) { object tmpObj = ProcessXML(children.Current, aSetId, aObj); childrenBool = ((Boolean) tmpObj); if (tmpObj is Boolean) { /* If we are doing a NOT, break at first child element */ if (processType == CONDITION_ATTRS.NOT) { childrenBool = !childrenBool; trueCount++; break; } /* If we are doing an OR, count the number of TRUE, we only need one. */ else if (processType == CONDITION_ATTRS.OR) { if (childrenBool) { trueCount++; break; } } /* If we are doing an AND (or anything else that we default to AND) * break out any time we hit a FALSE */ else { if (!childrenBool) { trueCount = 0; break; } else trueCount++; } } } if (trueCount == 0) returnBool = false; else returnBool = childrenBool; return returnBool; } ///<summary>Lazy loading of operator.</summary> /// <param name="operatorId">Full qualified name of an operator</param> /// <returns>An operator object implementing IBREOperator</returns> private IBREOperator GetOperator(string operatorId) { IBREOperator ruleOperator = null; if (!ruleContext.OperatorMap.Contains(operatorId)) { if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Loading Operator: " + operatorId); ruleOperator = (IBREOperator) Reflection.ClassNew(operatorId, null); ruleContext.SetOperator(operatorId, ruleOperator); } else { ruleOperator = ruleContext.GetOperator(operatorId); } return ruleOperator; } /// <summary> This methods processes the Compare nodes that may exist in the XML. /// <P> /// The best comparison works when the object implements Comparable. /// </P> /// <P> /// If the object does not do so, it eliminates the &lt;,&gt;,&lt;=,&gt;= /// functionality as we are left with .equals(), !.equals(), and /// exception /// </P> /// </summary> /// <param name="aNode">The Node to process /// </param> /// <param name="aMap"/> /// <returns> True if the If stmt passes, False otherwise /// /// </returns> private bool ProcessCompareNode(XPathNavigator aNode, Hashtable aMap) { bool resultBool = false; // This is required in the XML, so we shouldn't have to worry about nulls.... string leftId = aNode.GetAttribute(COMPARE_ATTRS.LEFTID, String.Empty); string rightId = aNode.GetAttribute(COMPARE_ATTRS.RIGHTID, String.Empty); string operatorId = aNode.GetAttribute(COMPARE_ATTRS.OPERATOR, String.Empty); IBREOperator ruleOperator = GetOperator(operatorId); if (ruleOperator != null) { // Get the results IBRERuleResult leftResult = (IBRERuleResult) ruleContext.GetResult(leftId); IBRERuleResult rightResult = (IBRERuleResult) ruleContext.GetResult(rightId); // If it does not, consider a null in left or right members as exceptions! if ((!ruleOperator.AcceptsNulls) && (leftResult == null)) { if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceEvent(TraceEventType.Error, 0, "RuleResult " + leftId + " not found in RuleContext"); } else if ((!ruleOperator.AcceptsNulls) && (rightResult == null)) { if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceEvent(TraceEventType.Error, 0, "RuleResult " + rightId + " not found in RuleContext"); } else { if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Retrieved results for comparison"); object left = (leftResult==null)?null:leftResult.Result; object right = (rightResult==null)?null:rightResult.Result; try { if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "BREOperator " + operatorId + " executing"); resultBool = ruleOperator.ExecuteComparison(ruleContext, aMap, left, right); } catch (InvalidCastException ice) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Specified BREOperator " + operatorId + " not of type BREOperator or objects being compared are not" + " of the same type.\n" + "Left Object Name:" + leftId + "\nLeft Object Type:" + left.GetType().FullName + "\nRight Object Name:" + rightId + "\nRight Object Type:" + right.GetType().FullName + "\n", ice)); } catch (Exception e) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Error when processing BREOperator " + operatorId + ".\n" + "Left Object Name:" + leftId + "\nLeft Object:" + left + "\nRight Object Name:" + rightId + "\nRight Object:" + right + "\n", e)); } } } else { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Operator could not be loaded from BRERuleContext")); } if (Logger.IsFlowEngineVerbose) Logger.FlowEngineSource.TraceEvent(TraceEventType.Verbose, 0, "Compare result: " + resultBool); return resultBool; } /// <summary> Gets a String Id from either the id attribute or the ruleValue attribute /// </summary> /// <param name="aNode">The node to process</param> /// <param name="idAttribute">The Id of the attribute to process</param> /// <param name="valueAttribute">The value used in this node.</param> /// <returns> The Id found in the node attributes, null if nothing found</returns> private string ProcessIdValueAttributes(XPathNavigator aNode, string idAttribute, string valueAttribute) { string idNode = aNode.GetAttribute(idAttribute, String.Empty); string ruleValueNode = aNode.GetAttribute(valueAttribute, String.Empty); if ((idNode == String.Empty) && (ruleValueNode != String.Empty)) { IBRERuleResult result = ruleContext.GetResult(ruleValueNode); if (result != null) return result.Result.ToString(); } else if (idNode != String.Empty) return idNode; return null; } /// <summary> Handles the InvokeSet Node /// </summary> /// <param name="aNode">The InvokeSet node to process</param> private void ProcessInvokeSetNode(XPathNavigator aNode) { string id = ProcessIdValueAttributes(aNode, INVOKESET_ATTRS.ID, INVOKESET_ATTRS.RULE_VALUE); if (id == null) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Can not invoke a set with no Id: " + aNode.OuterXml)); } else if (!Process(id)) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Error when invoking set Id: " + id)); } } /// <summary> Handles the Log Node /// </summary> /// <param name="aNode">The Node to process /// /// </param> private void ProcessLogNode(XPathNavigator aNode) { string msg = ProcessIdValueAttributes(aNode, LOG_ATTRS.MESSAGE, LOG_ATTRS.MESSAGE_ID); int level = Int32.Parse(aNode.GetAttribute(LOG_ATTRS.LEVEL, String.Empty)); Logger.FlowEngineRuleBaseSource.TraceEvent(Logger.ConvertFromObsoleteIntLevel(level), 0, msg); } /// <summary> Handles the Parameter node /// </summary> /// <param name="aNode">The Node to process /// </param> /// <param name="aMap">The Parameters map /// /// </param> private void ProcessParameterNode(XPathNavigator aNode, Hashtable aMap) { string valueNode = aNode.GetAttribute(PARAMETER_ATTRS.VALUE, String.Empty); string typeNode = aNode.GetAttribute(PARAMETER_ATTRS.TYPE, String.Empty); string ruleValueNode = aNode.GetAttribute(PARAMETER_ATTRS.RULE_VALUE, String.Empty); // Used to be initialized with null: changed to String.Empty to solve bug #1190485 object finalValue = String.Empty; if (valueNode != String.Empty) { if (typeNode != String.Empty) finalValue = Reflection.CastValue(valueNode, typeNode); else finalValue = valueNode; } else if (ruleValueNode != String.Empty) { IBRERuleResult result = ruleContext.GetResult(ruleValueNode); if (result != null) finalValue = result.Result; } aMap.Add(aNode.GetAttribute(PARAMETER_ATTRS.NAME, String.Empty), finalValue); } /// <summary> Handles the Rule Node and calls doRule() /// </summary> /// <param name="aNode">The Node to process /// </param> /// <param name="aMap">The Parameters map /// /// </param> private void ProcessRuleNode(XPathNavigator aNode, Hashtable aMap) { DoRule(aNode.GetAttribute(RULE_ATTRS.ID, String.Empty), aNode.GetAttribute(RULE_ATTRS.STEP, String.Empty), aMap); } /// <summary> This methods processes the Rule nodes that may exist in the XML. /// <P> /// It executes as follows (this may not look so straightforward in the code...): /// <OL> /// <LI>Executes Factories executeRule()</LI> /// <LI>takes the result and puts it into a RuleResult object</LI> /// <LI>listeners.dispatches an error if it could not find the factory /// (See docs in code)</LI> /// <LI>Catches any exceptions from the executeRule() and makes it a /// RuleResult so it can be handled gracefully</LI> /// <LI>Adds the RuleResult to the CallStack</LI> /// <LI>listeners.dispatched the RuleResult to any listeners</LI> /// <LI>Adds the RuleResult to the RuleContext</LI> /// </OL> /// </P> /// </summary> /// <param name="id">The ID of the Rule /// </param> /// <param name="step">The current Step /// </param> /// <param name="aMap">The Parameters map /// </param> private void DoRule(object id, object step, Hashtable aMap) { int nextStackLoc = ruleContext.CallStack.Count; IBRERuleResult ruleResult = null; try { IBRERuleFactory factory = ruleContext.GetFactory(id); /* I have to check for null because if the RuleContext was passed in, an external reference exists and can be modified at any time */ if (factory != null) { //setup metadata IBRERuleMetaData metaData = new BRERuleMetaDataImpl(id, factory, aMap, nextStackLoc, step); object result = factory.ExecuteRule(ruleContext, aMap, step); ruleResult = new BRERuleResultImpl(metaData, result); } else { /* A WARN version of this error can occur when the Factories are loaded. But if the developer passed in a RuleContext, they can place the Factory into the RuleContext still. If we get to this point it is now a full blown error because if it is not in the RuleContext at this point and it to late and can cause issues */ if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceData(TraceEventType.Error, 0, new BREException("Factory Id " + id + " defined, but not found in RuleContext")); } } // This can occur internally in the RuleContext catch (System.InvalidCastException cce) { if (Logger.IsFlowEngineCritical) Logger.FlowEngineSource.TraceData(TraceEventType.Critical, 0, new BREException("Object in RuleContext not of correct type. " + cce.ToString())); } // Catch unknown exceptions in the factory itself catch (System.Exception e) { if (Logger.IsFlowEngineError) Logger.FlowEngineSource.TraceData(TraceEventType.Error, 0, new BREException("Error when processing RuleFactory id: " + id, e)); /* Set the RuleResult to an exception so I can test for it in the If Hey, technically it IS what it returned ;) The factory can return null here, but that could have caused the exception anyway..... */ IBRERuleMetaData metaData = new BRERuleMetaDataImpl(id, ruleContext.GetFactory(id), aMap, nextStackLoc, step); ruleResult = new BRERuleResultImpl(metaData, e); } ruleContext.CallStack.Push(ruleResult); // call listeners DispatchRuleResult(ruleResult); ruleContext.SetResult(id, ruleResult); } } }
36.805915
281
0.632583
[ "MIT" ]
Peidyen/NxBRE
NxBRE3/Source/FlowEngine/BREImpl.cs
39,824
C#
#region License // Copyright 2012 Julien Lebosquain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.ObjectModel; using JetBrains.Annotations; namespace GammaJul.ReSharper.ForTea.Psi.Directives { public class OutputDirectiveInfo : DirectiveInfo { private readonly DirectiveAttributeInfo _extensionAttribute; private readonly DirectiveAttributeInfo _encodingAttribute; private readonly ReadOnlyCollection<DirectiveAttributeInfo> _supportedAttributes; [NotNull] public DirectiveAttributeInfo ExtensionAttribute { get { return _extensionAttribute; } } [NotNull] public DirectiveAttributeInfo EncodingAttribute { get { return _encodingAttribute; } } public override ReadOnlyCollection<DirectiveAttributeInfo> SupportedAttributes { get { return _supportedAttributes; } } public OutputDirectiveInfo() : base("output") { _extensionAttribute = new DirectiveAttributeInfo("extension", DirectiveAttributeOptions.None); _encodingAttribute = new EncodingDirectiveAttributeInfo("encoding", DirectiveAttributeOptions.None); _supportedAttributes = Array.AsReadOnly(new[] { _extensionAttribute, _encodingAttribute }); } } }
32.607143
104
0.740416
[ "Apache-2.0" ]
citizenmatt/ForTea
GammaJul.ReSharper.ForTea/Psi/Directives/OutputDirectiveInfo.cs
1,828
C#
using System; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Dom; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core.Handlers { /// <summary> /// Handler for text selection in the html. /// </summary> internal sealed class SelectionHandler : IDisposable { #region Fields and Consts /// <summary> /// the root of the handled html tree /// </summary> private readonly CssBox _root; /// <summary> /// handler for showing context menu on right click /// </summary> private readonly ContextMenuHandler _contextMenuHandler; /// <summary> /// the mouse location when selection started used to ignore small selections /// </summary> private RPoint _selectionStartPoint; /// <summary> /// the starting word of html selection<br/> /// where the user started the selection, if the selection is backwards then it will be the last selected word. /// </summary> private CssRect _selectionStart; /// <summary> /// the ending word of html selection<br/> /// where the user ended the selection, if the selection is backwards then it will be the first selected word. /// </summary> private CssRect _selectionEnd; /// <summary> /// the selection start index if the first selected word is partially selected (-1 if not selected or fully selected) /// </summary> private int _selectionStartIndex = -1; /// <summary> /// the selection end index if the last selected word is partially selected (-1 if not selected or fully selected) /// </summary> private int _selectionEndIndex = -1; /// <summary> /// the selection start offset if the first selected word is partially selected (-1 if not selected or fully selected) /// </summary> private double _selectionStartOffset = -1; /// <summary> /// the selection end offset if the last selected word is partially selected (-1 if not selected or fully selected) /// </summary> private double _selectionEndOffset = -1; /// <summary> /// is the selection goes backward in the html, the starting word comes after the ending word in DFS traversing.<br/> /// </summary> private bool _backwardSelection; /// <summary> /// used to ignore mouse up after selection /// </summary> private bool _inSelection; /// <summary> /// current selection process is after double click (full word selection) /// </summary> private bool _isDoubleClickSelect; /// <summary> /// used to know if selection is in the control or started outside so it needs to be ignored /// </summary> private bool _mouseDownInControl; /// <summary> /// used to handle drag & drop /// </summary> private bool _mouseDownOnSelectedWord; /// <summary> /// is the cursor on the control has been changed by the selection handler /// </summary> private bool _cursorChanged; /// <summary> /// used to know if double click selection is requested /// </summary> private DateTime _lastMouseDown; /// <summary> /// used to know if drag & drop was already started not to execute the same operation over /// </summary> private object _dragDropData; #endregion /// <summary> /// Init. /// </summary> /// <param name="root">the root of the handled html tree</param> public SelectionHandler(CssBox root) { ArgChecker.AssertArgNotNull(root, "root"); _root = root; _contextMenuHandler = new ContextMenuHandler(this, root.HtmlContainer); } /// <summary> /// Select all the words in the html. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> public void SelectAll(RControl control) { if (_root.HtmlContainer.IsSelectionEnabled) { ClearSelection(); SelectAllWords(_root); control.Invalidate(); } } /// <summary> /// Select the word at the given location if found. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> /// <param name="loc">the location to select word at</param> public void SelectWord(RControl control, RPoint loc) { if (_root.HtmlContainer.IsSelectionEnabled) { var word = DomUtils.GetCssBoxWord(_root, loc); if (word != null) { word.Selection = this; _selectionStartPoint = loc; _selectionStart = _selectionEnd = word; control.Invalidate(); } } } /// <summary> /// Handle mouse down to handle selection. /// </summary> /// <param name="parent">the control hosting the html to invalidate</param> /// <param name="loc">the location of the mouse on the html</param> /// <param name="isMouseInContainer"> </param> public void HandleMouseDown(RControl parent, RPoint loc, bool isMouseInContainer) { bool clear = !isMouseInContainer; if (isMouseInContainer) { _mouseDownInControl = true; _isDoubleClickSelect = (DateTime.Now - _lastMouseDown).TotalMilliseconds < 400; _lastMouseDown = DateTime.Now; _mouseDownOnSelectedWord = false; if (_root.HtmlContainer.IsSelectionEnabled && parent.LeftMouseButton) { var word = DomUtils.GetCssBoxWord(_root, loc); if (word != null && word.Selected) { _mouseDownOnSelectedWord = true; } else { clear = true; } } else if (parent.RightMouseButton) { var rect = DomUtils.GetCssBoxWord(_root, loc); var link = DomUtils.GetLinkBox(_root, loc); if (_root.HtmlContainer.IsContextMenuEnabled) { _contextMenuHandler.ShowContextMenu(parent, rect, link); } clear = rect == null || !rect.Selected; } } if (clear) { ClearSelection(); parent.Invalidate(); } } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> /// <param name="parent">the control hosting the html to invalidate</param> /// <param name="leftMouseButton">is the left mouse button has been released</param> /// <returns>is the mouse up should be ignored</returns> public bool HandleMouseUp(RControl parent, bool leftMouseButton) { bool ignore = false; _mouseDownInControl = false; if (_root.HtmlContainer.IsSelectionEnabled) { ignore = _inSelection; if (!_inSelection && leftMouseButton && _mouseDownOnSelectedWord) { ClearSelection(); parent.Invalidate(); } _mouseDownOnSelectedWord = false; _inSelection = false; } ignore = ignore || (DateTime.Now - _lastMouseDown > TimeSpan.FromSeconds(1)); return ignore; } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> /// <param name="parent">the control hosting the html to set cursor and invalidate</param> /// <param name="loc">the location of the mouse on the html</param> public void HandleMouseMove(RControl parent, RPoint loc) { if (_root.HtmlContainer.IsSelectionEnabled && _mouseDownInControl && parent.LeftMouseButton) { if (_mouseDownOnSelectedWord) { // make sure not to start drag-drop on click but when it actually moves as it fucks mouse-up if ((DateTime.Now - _lastMouseDown).TotalMilliseconds > 200) StartDragDrop(parent); } else { HandleSelection(parent, loc, !_isDoubleClickSelect); _inSelection = _selectionStart != null && _selectionEnd != null && (_selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex); } } else { // Handle mouse hover over the html to change the cursor depending if hovering word, link of other. var link = DomUtils.GetLinkBox(_root, loc); if (link != null) { _cursorChanged = true; parent.SetCursorHand(); } else if (_root.HtmlContainer.IsSelectionEnabled) { var word = DomUtils.GetCssBoxWord(_root, loc); _cursorChanged = word != null && !word.IsImage && !(word.Selected && (word.SelectedStartIndex < 0 || word.Left + word.SelectedStartOffset <= loc.X) && (word.SelectedEndOffset < 0 || word.Left + word.SelectedEndOffset >= loc.X)); if (_cursorChanged) parent.SetCursorIBeam(); else parent.SetCursorDefault(); } else if (_cursorChanged) { parent.SetCursorDefault(); } } } /// <summary> /// On mouse leave change the cursor back to default. /// </summary> /// <param name="parent">the control hosting the html to set cursor and invalidate</param> public void HandleMouseLeave(RControl parent) { if (_cursorChanged) { _cursorChanged = false; parent.SetCursorDefault(); } } /// <summary> /// Copy the currently selected html segment to clipboard.<br/> /// Copy rich html text and plain text. /// </summary> public void CopySelectedHtml() { if (_root.HtmlContainer.IsSelectionEnabled) { var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true); var plainText = DomUtils.GetSelectedPlainText(_root); if (!string.IsNullOrEmpty(plainText)) _root.HtmlContainer.Adapter.SetToClipboard(html, plainText); } } /// <summary> /// Get the currently selected text segment in the html.<br/> /// </summary> public string GetSelectedText() { return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GetSelectedPlainText(_root) : null; } /// <summary> /// Copy the currently selected html segment with style.<br/> /// </summary> public string GetSelectedHtml() { return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true) : null; } /// <summary> /// The selection start index if the first selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection start index for</param> /// <returns>data value or -1 if not applicable</returns> public int GetSelectingStartIndex(CssRect word) { return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndIndex : _selectionStartIndex) : -1; } /// <summary> /// The selection end index if the last selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection end index for</param> public int GetSelectedEndIndexOffset(CssRect word) { return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartIndex : _selectionEndIndex) : -1; } /// <summary> /// The selection start offset if the first selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection start offset for</param> public double GetSelectedStartOffset(CssRect word) { return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndOffset : _selectionStartOffset) : -1; } /// <summary> /// The selection end offset if the last selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection end offset for</param> public double GetSelectedEndOffset(CssRect word) { return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartOffset : _selectionEndOffset) : -1; } /// <summary> /// Clear the current selection. /// </summary> public void ClearSelection() { // clear drag and drop _dragDropData = null; ClearSelection(_root); _selectionStartOffset = -1; _selectionStartIndex = -1; _selectionEndOffset = -1; _selectionEndIndex = -1; _selectionStartPoint = RPoint.Empty; _selectionStart = null; _selectionEnd = null; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { _contextMenuHandler.Dispose(); } #region Private methods /// <summary> /// Handle html text selection by mouse move over the html with left mouse button pressed.<br/> /// Calculate the words in the selected range and set their selected property. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> /// <param name="loc">the mouse location</param> /// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param> private void HandleSelection(RControl control, RPoint loc, bool allowPartialSelect) { // get the line under the mouse or nearest from the top var lineBox = DomUtils.GetCssLineBox(_root, loc); if (lineBox != null) { // get the word under the mouse var word = DomUtils.GetCssBoxWord(lineBox, loc); // if no word found under the mouse use the last or the first word in the line if (word == null && lineBox.Words.Count > 0) { if (loc.Y > lineBox.LineBottom) { // under the line word = lineBox.Words[lineBox.Words.Count - 1]; } else if (loc.X < lineBox.Words[0].Left) { // before the line word = lineBox.Words[0]; } else if (loc.X > lineBox.Words[lineBox.Words.Count - 1].Right) { // at the end of the line word = lineBox.Words[lineBox.Words.Count - 1]; } } // if there is matching word if (word != null) { if (_selectionStart == null) { // on start set the selection start word _selectionStartPoint = loc; _selectionStart = word; if (allowPartialSelect) CalculateWordCharIndexAndOffset(control, word, loc, true); } // always set selection end word _selectionEnd = word; if (allowPartialSelect) CalculateWordCharIndexAndOffset(control, word, loc, false); ClearSelection(_root); if (CheckNonEmptySelection(loc, allowPartialSelect)) { CheckSelectionDirection(); SelectWordsInRange(_root, _backwardSelection ? _selectionEnd : _selectionStart, _backwardSelection ? _selectionStart : _selectionEnd); } else { _selectionEnd = null; } _cursorChanged = true; control.SetCursorIBeam(); control.Invalidate(); } } } /// <summary> /// Clear the selection from all the words in the css box recursively. /// </summary> /// <param name="box">the css box to selectionStart clear at</param> private static void ClearSelection(CssBox box) { foreach (var word in box.Words) { word.Selection = null; } foreach (var childBox in box.Boxes) { ClearSelection(childBox); } } /// <summary> /// Start drag & drop operation on the currently selected html segment. /// </summary> /// <param name="control">the control to start the drag & drop on</param> private void StartDragDrop(RControl control) { if (_dragDropData == null) { var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true); var plainText = DomUtils.GetSelectedPlainText(_root); _dragDropData = control.Adapter.GetClipboardDataObject(html, plainText); } control.DoDragDropCopy(_dragDropData); } /// <summary> /// Select all the words that are under <paramref name="box"/> DOM hierarchy.<br/> /// </summary> /// <param name="box">the box to start select all at</param> public void SelectAllWords(CssBox box) { foreach (var word in box.Words) { word.Selection = this; } foreach (var childBox in box.Boxes) { SelectAllWords(childBox); } } /// <summary> /// Check if the current selection is non empty, has some selection data. /// </summary> /// <param name="loc"></param> /// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param> /// <returns>true - is non empty selection, false - empty selection</returns> private bool CheckNonEmptySelection(RPoint loc, bool allowPartialSelect) { // full word selection is never empty if (!allowPartialSelect) return true; // if end selection location is near starting location then the selection is empty if (Math.Abs(_selectionStartPoint.X - loc.X) <= 1 && Math.Abs(_selectionStartPoint.Y - loc.Y) < 5) return false; // selection is empty if on same word and same index return _selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex; } /// <summary> /// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy.<br/> /// </summary> /// <param name="root">the root of the DOM sub-tree the selection is in</param> /// <param name="selectionStart">selection start word limit</param> /// <param name="selectionEnd">selection end word limit</param> private void SelectWordsInRange(CssBox root, CssRect selectionStart, CssRect selectionEnd) { bool inSelection = false; SelectWordsInRange(root, selectionStart, selectionEnd, ref inSelection); } /// <summary> /// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy. /// </summary> /// <param name="box">the current traversal node</param> /// <param name="selectionStart">selection start word limit</param> /// <param name="selectionEnd">selection end word limit</param> /// <param name="inSelection">used to know the traversal is currently in selected range</param> /// <returns></returns> private bool SelectWordsInRange(CssBox box, CssRect selectionStart, CssRect selectionEnd, ref bool inSelection) { foreach (var boxWord in box.Words) { if (!inSelection && boxWord == selectionStart) { inSelection = true; } if (inSelection) { boxWord.Selection = this; if (selectionStart == selectionEnd || boxWord == selectionEnd) { return true; } } } foreach (var childBox in box.Boxes) { if (SelectWordsInRange(childBox, selectionStart, selectionEnd, ref inSelection)) { return true; } } return false; } /// <summary> /// Calculate the character index and offset by characters for the given word and given offset.<br/> /// <seealso cref="CalculateWordCharIndexAndOffset(RControl,HtmlRenderer.Core.Dom.CssRect,RPoint,bool)"/>. /// </summary> /// <param name="control">used to create graphics to measure string</param> /// <param name="word">the word to calculate its index and offset</param> /// <param name="loc">the location to calculate for</param> /// <param name="selectionStart">to set the starting or ending char and offset data</param> private void CalculateWordCharIndexAndOffset(RControl control, CssRect word, RPoint loc, bool selectionStart) { int selectionIndex; double selectionOffset; CalculateWordCharIndexAndOffset(control, word, loc, selectionStart, out selectionIndex, out selectionOffset); if (selectionStart) { _selectionStartIndex = selectionIndex; _selectionStartOffset = selectionOffset; } else { _selectionEndIndex = selectionIndex; _selectionEndOffset = selectionOffset; } } /// <summary> /// Calculate the character index and offset by characters for the given word and given offset.<br/> /// If the location is below the word line then set the selection to the end.<br/> /// If the location is to the right of the word then set the selection to the end.<br/> /// If the offset is to the left of the word set the selection to the beginning.<br/> /// Otherwise calculate the width of each substring to find the char the location is on. /// </summary> /// <param name="control">used to create graphics to measure string</param> /// <param name="word">the word to calculate its index and offset</param> /// <param name="loc">the location to calculate for</param> /// <param name="inclusive">is to include the first character in the calculation</param> /// <param name="selectionIndex">return the index of the char under the location</param> /// <param name="selectionOffset">return the offset of the char under the location</param> private static void CalculateWordCharIndexAndOffset(RControl control, CssRect word, RPoint loc, bool inclusive, out int selectionIndex, out double selectionOffset) { selectionIndex = 0; selectionOffset = 0f; var offset = loc.X - word.Left; if (word.Text == null) { // not a text word - set full selection selectionIndex = -1; selectionOffset = -1; } else if (offset > word.Width - word.OwnerBox.ActualWordSpacing || loc.Y > DomUtils.GetCssLineBoxByWord(word).LineBottom) { // mouse under the line, to the right of the word - set to the end of the word selectionIndex = word.Text.Length; selectionOffset = word.Width; } else if (offset > 0) { // calculate partial word selection int charFit; double charFitWidth; var maxWidth = offset + (inclusive ? 0 : 1.5f * word.LeftGlyphPadding); control.MeasureString(word.Text, word.OwnerBox.ActualFont, maxWidth, out charFit, out charFitWidth); selectionIndex = charFit; selectionOffset = charFitWidth; } } /// <summary> /// Check if the selection direction is forward or backward.<br/> /// Is the selection start word is before the selection end word in DFS traversal. /// </summary> private void CheckSelectionDirection() { if (_selectionStart == _selectionEnd) { _backwardSelection = _selectionStartIndex > _selectionEndIndex; } else if (DomUtils.GetCssLineBoxByWord(_selectionStart) == DomUtils.GetCssLineBoxByWord(_selectionEnd)) { _backwardSelection = _selectionStart.Left > _selectionEnd.Left; } else { _backwardSelection = _selectionStart.Top >= _selectionEnd.Bottom; } } #endregion } }
41.508076
248
0.557611
[ "BSD-3-Clause" ]
DotNetBrightener/PdfSharp.HtmlToPdf
DotNetBrightener.PdfSharp.HtmlToPdf/Core/Handlers/SelectionHandler.cs
28,267
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; namespace Microsoft.Azure.WebJobs.Script.Description { [Serializable] public sealed class CompilationServiceException : Exception { public CompilationServiceException() { } public CompilationServiceException(string message) : base(message) { } public CompilationServiceException(string message, Exception innerException) : base(message, innerException) { } private CompilationServiceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
27.470588
116
0.713062
[ "Apache-2.0", "MIT" ]
AnatoliB/azure-functions-host
src/WebJobs.Script/Description/Compilation/CompilationServiceException.cs
936
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using Hazelcast.Client.Protocol.Util; using Hazelcast.IO.Serialization; // Client Protocol version, Since:1.0 - Update:1.0 namespace Hazelcast.Client.Protocol.Codec { internal static class MapValuesCodec { private static int CalculateRequestDataSize(string name) { var dataSize = ClientMessage.HeaderSize; dataSize += ParameterUtil.CalculateDataSize(name); return dataSize; } internal static ClientMessage EncodeRequest(string name) { var requiredDataSize = CalculateRequestDataSize(name); var clientMessage = ClientMessage.CreateForEncode(requiredDataSize); clientMessage.SetMessageType((int) MapMessageType.MapValues); clientMessage.SetRetryable(true); clientMessage.Set(name); clientMessage.UpdateFrameLength(); return clientMessage; } internal class ResponseParameters { public IList<IData> response; } internal static ResponseParameters DecodeResponse(IClientMessage clientMessage) { var parameters = new ResponseParameters(); var responseSize = clientMessage.GetInt(); var response = new List<IData>(responseSize); for (var responseIndex = 0; responseIndex < responseSize; responseIndex++) { var responseItem = clientMessage.GetData(); response.Add(responseItem); } parameters.response = response; return parameters; } } }
36.95082
87
0.663709
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.Client.Protocol.Codec/MapValuesCodec.cs
2,254
C#
/* * Copyright 2011 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: OnPaintTimeStatistics.cs,v 1.1 2011/12/25 03:12:09 kzmi Exp $ */ using System; using System.Diagnostics; using System.Collections.Generic; namespace Poderosa.Benchmark { internal class OnPaintTimeStatistics { private const int MAX_SAMPLES = 1024; private long[] _samples = new long[MAX_SAMPLES]; private int _sampleNextIndex = 0; private int _sampleCount = 0; private long[] _sortedSamples = null; private int _sortedSamplesFrom = -1; private int _sortedSamplesTo = -1; public OnPaintTimeStatistics() { } public void Update(Stopwatch s) { long ticks = s.ElapsedTicks; _samples[_sampleNextIndex] = ticks; _sampleNextIndex = (_sampleNextIndex + 1) % MAX_SAMPLES; if (_sampleCount < MAX_SAMPLES) _sampleCount++; } public int GetSampleCount() { PrepareSortedSamples(); return _sortedSamplesTo - _sortedSamplesFrom; } public double GetMinTimeMilliseconds() { PrepareSortedSamples(); if (_sortedSamplesFrom == _sortedSamplesTo) return 0.0; long minTicks = _sortedSamples[_sortedSamplesFrom]; return (double)(minTicks * 100000L / Stopwatch.Frequency) / 100.0; } public double GetMaxTimeMilliseconds() { PrepareSortedSamples(); if (_sortedSamplesFrom == _sortedSamplesTo) return 0.0; long maxTicks = _sortedSamples[_sortedSamplesTo - 1]; return (double)(maxTicks * 100000L / Stopwatch.Frequency) / 100.0; } public double GetAverageTimeMilliseconds() { PrepareSortedSamples(); if (_sortedSamplesFrom == _sortedSamplesTo) return 0.0; long sumTicks = 0; for(int i = _sortedSamplesFrom; i < _sortedSamplesTo; i++) { sumTicks += _sortedSamples[i]; } return (double)(sumTicks * 100000L / (Stopwatch.Frequency * (_sortedSamplesTo - _sortedSamplesFrom))) / 100.0; } private void PrepareSortedSamples() { if (_sortedSamples == null) { _sortedSamples = GetSortedSampleArray(); if (_sortedSamples.Length == 0) { _sortedSamplesFrom = _sortedSamplesTo = 0; } else { _sortedSamplesFrom = _sortedSamples.Length / 10; // ignore short cases _sortedSamplesTo = _sortedSamples.Length; } } } private long[] GetSortedSampleArray() { long[] sampleArray = GetSampleArray(); Array.Sort<long>(sampleArray); return sampleArray; } private long[] GetSampleArray() { if (_sampleCount == MAX_SAMPLES) return (long[])_samples.Clone(); long[] sampleArray = new long[_sampleCount]; Buffer.BlockCopy(_samples, 0, sampleArray, 0, _sampleCount * sizeof(long)); return sampleArray; } } }
32.543689
122
0.578461
[ "Apache-2.0" ]
FNKGino/poderosa
Benchmark/OnPaintTimeStatistics.cs
3,354
C#
using System; using System.Collections.Generic; namespace CYM { public class BasePlotMgr<TData> : BaseGFlowMgr, IBasePlotMgr where TData : TDBasePlotData, new() { #region Callback value public event Callback<bool, bool, int> Callback_OnPlotMode; public event Callback<int> Callback_OnChangePlotIndex; #endregion #region ghost unit /// <summary> /// 幽灵单位,专门为剧情特殊处理的幽灵单位 /// 比如:在剧情模式下其他角色都暂停,但是幽灵单位可以自由移动 /// 比如:在剧情模式下其他角色都暂停动画,但是幽灵动画可以播放动画 /// </summary> public HashList<BaseUnit> GhostUnits { get; private set; } = new HashList<BaseUnit>(); //单位是否可以被选择 public HashList<BaseUnit> GhostSelUnits { get; private set; } = new HashList<BaseUnit>(); //单位是否可以移动 public HashList<BaseUnit> GhostMoveUnits { get; private set; } = new HashList<BaseUnit>(); //单位是否可以执行AI逻辑 public HashList<BaseUnit> GhostAIUnits { get; private set; } = new HashList<BaseUnit>(); //单位是否可以播放动画 public HashList<BaseUnit> GhostAnimUnits { get; private set; } = new HashList<BaseUnit>(); #endregion #region prop /// <summary> /// 剧情标记 /// </summary> public HashList<string> TempPlotFlag { get; protected set; } = new HashList<string>(); public List<CoroutineHandle> TempPlotCoroutines { get; private set; } = new List<CoroutineHandle>(); public CoroutineHandle MainPlotCoroutine { get; private set; } public CoroutineHandle StartPlotCoroutine { get; private set; } /// <summary> /// 是否禁用AI /// </summary> public bool IsEnableAI { get; protected set; } = true; /// <summary> /// 当前的剧情节点 /// </summary> public int CurPlotIndex { get; protected set; } = 0; protected Coroutineter BattleCoroutine => BaseGlobal.BattleCoroutineter; /// <summary> /// 是否开启了剧情模式 /// </summary> public BoolState PlotPauseState { get; private set; } = new BoolState(); public TData CurData { get; private set; } ITDLuaMgr TDLuaMgr; #endregion #region life protected override void OnSetNeedFlag() { base.OnSetNeedFlag(); NeedUpdate = true; } public override void OnAffterAwake() { base.OnAffterAwake(); TDLuaMgr = BaseLuaMgr.GetTDLuaMgr(typeof(TData)); } public override void OnUpdate() { base.OnUpdate(); CurData?.OnUpdate(); } #endregion #region is public bool IsInPlot(params string[] tdid) { if (CurData == null) return false; foreach (var item in tdid) { if (item == CurData.TDID) return true; } return false; } public bool IsHavePlot() => BaseGlobal.DiffMgr.IsHavePlot() && Options.IsHavePlot; public bool IsInPlotPause() => PlotPauseState.IsIn(); public bool IsInPlot()=> IsInPlotPause() || CurData!=null || MainPlotCoroutine.IsRunning; public bool IsGhostSel(BaseUnit unit) => GhostSelUnits.Contains(unit); public bool IsGhostMove(BaseUnit unit) => GhostMoveUnits.Contains(unit); public bool IsGhostAI(BaseUnit unit) => GhostAIUnits.Contains(unit); public bool IsGhostAnim(BaseUnit unit) => GhostAnimUnits.Contains(unit); #endregion #region ghost public void AddToGhostSelUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Add(item); GhostSelUnits.Add(item); } } public void AddToGhostMoveUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Add(item); GhostMoveUnits.Add(item); } } public void RemoveFromGhostMoveUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Remove(item); GhostMoveUnits.Remove(item); } } public void AddToGhostAIUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Add(item); GhostAIUnits.Add(item); } } public void RemoveFromGhostSelUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Remove(item); GhostSelUnits.Remove(item); } } public void RemoveFromGhostAIUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Remove(item); GhostAIUnits.Remove(item); } } public void AddToGhostAnimUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Add(item); GhostAnimUnits.Add(item); } } public void RemoveFromGhostAnimUnits(params BaseUnit[] unit) { if (unit == null) return; foreach (var item in unit) { GhostUnits.Remove(item); GhostAnimUnits.Remove(item); } } #endregion #region set /// <summary> /// 禁用ai /// </summary> /// <param name="b"></param> public virtual void EnableAI(bool b) { IsEnableAI = b; } /// <summary> /// 启动剧情,自定义 /// </summary> public void SetPlotPause(bool b, int type = 0) { PlotPauseState.Push(b); OnPlotPause(b, PlotPauseState.IsIn(), type); } /// <summary> /// 开始一段剧情 /// </summary> public virtual void Start(string id) { if (!IsHavePlot()) return; if (id.IsInv()) return; var temp = TDLuaMgr.Get<TData>(id); if (temp == null) { CLog.Error("无法找到剧情:{0}", id); return; } else { CurData?.OnBeRemoved(); CurData = temp.Copy<TData>(); } CurPlotIndex = 0; var next = CurData.CheckForNext(); if (next.IsInv()) { ClearAllPlotData(); StopAllTempPlot(); CurData.OnBeAdded(SelfBaseGlobal); RunStart(); if (CurData.AutoStarPlot) { RunMain(); } } else { Start(next); } } void RunStart() { BattleCoroutine.Kill(StartPlotCoroutine); StartPlotCoroutine = BattleCoroutine.Run(CurData.OnPlotStart()); } public void RunMain() { BattleCoroutine.Kill(MainPlotCoroutine); MainPlotCoroutine = BattleCoroutine.Run(EnumMain()); } //开始一段附加剧情 public void RunTemp(IEnumerator<float> enumerator,string flag=null) { if (flag != null) { if (TempPlotFlag.Contains(flag)) return; TempPlotFlag.Add(flag); } var temp = BattleCoroutine.Run(enumerator); TempPlotCoroutines.Add(temp); } // 推进剧情 public virtual int PushIndex(int? index=null) { if (index == null) CurPlotIndex++; else { if (index.Value != (CurPlotIndex + 1)) { CLog.Error("错误!!剧情没有线性推进,PushIndex必须线性推进,否则可以使用SetIndex"); } CurPlotIndex = index.Value; } Callback_OnChangePlotIndex?.Invoke(CurPlotIndex); return CurPlotIndex; } //直接设置剧情Index public void SetIndex(int index) { CurPlotIndex = index; Callback_OnChangePlotIndex?.Invoke(CurPlotIndex); } //自定义战场片头剧情,适合闯关,和新游戏开始 public CoroutineHandle CustomStartBattleCoroutine() { if (CurData == null) return BattleCoroutine.Run(CustomStartBattleFlow()); return BattleCoroutine.Run(CurData.CustomStartBattleFlow()); } protected virtual IEnumerator<float> CustomStartBattleFlow() { yield break; } #endregion #region stop // 停止一段剧情 public virtual void Stop() { StopAllTempPlot(); BattleCoroutine.Kill(StartPlotCoroutine); BattleCoroutine.Kill(MainPlotCoroutine); if (CurData == null) return; CurData.OnBeRemoved(); CurData = null; } //停止所有的临时剧情 void StopAllTempPlot() { TempPlotFlag.Clear(); foreach (var item in TempPlotCoroutines) { BattleCoroutine.Kill(item); } TempPlotCoroutines.Clear(); } //清空剧情相关的数据 void ClearAllPlotData() { PlotPauseState.Reset(); ; GhostUnits.Clear(); GhostSelUnits.Clear(); GhostMoveUnits.Clear(); GhostAIUnits.Clear(); GhostAnimUnits.Clear(); } #endregion #region Callback protected override void OnBattleUnLoad() { base.OnBattleUnLoad(); ClearAllPlotData(); Stop(); } protected override void OnAllLoadEnd1() { } protected virtual void OnPlotPause(bool b, bool curState, int type) { Callback_OnPlotMode?.Invoke(b, curState, type); } IEnumerator<float> EnumMain() { if (CurData == null) yield break; yield return Timing.WaitUntilDone(CurData.OnPlotRun()); CurData?.OnPlotEnd(); } #endregion } }
30.655271
108
0.499535
[ "MIT" ]
chengyimingvb/CYMUni
Plugins/_CYM/_Base/Manager/Plot/BasePlotMgr.cs
11,262
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: ReferenceAssembly] [assembly: AssemblyTitle("System.Text.Encodings.Web")] [assembly: AssemblyDescription("System.Text.Encodings.Web")] [assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.29812.01")] [assembly: AssemblyInformationalVersion("4.6.29812.01 built by: SOURCEBUILD")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("", "")] [assembly: AssemblyVersion("4.0.3.1")] namespace System.Text.Encodings.Web { public abstract partial class HtmlEncoder : System.Text.Encodings.Web.TextEncoder { protected HtmlEncoder() { } public static System.Text.Encodings.Web.HtmlEncoder Default { get { throw null; } } public static System.Text.Encodings.Web.HtmlEncoder Create(System.Text.Encodings.Web.TextEncoderSettings settings) { throw null; } public static System.Text.Encodings.Web.HtmlEncoder Create(params System.Text.Unicode.UnicodeRange[] allowedRanges) { throw null; } } public abstract partial class JavaScriptEncoder : System.Text.Encodings.Web.TextEncoder { protected JavaScriptEncoder() { } public static System.Text.Encodings.Web.JavaScriptEncoder Default { get { throw null; } } public static System.Text.Encodings.Web.JavaScriptEncoder Create(System.Text.Encodings.Web.TextEncoderSettings settings) { throw null; } public static System.Text.Encodings.Web.JavaScriptEncoder Create(params System.Text.Unicode.UnicodeRange[] allowedRanges) { throw null; } } public abstract partial class TextEncoder { protected TextEncoder() { } public abstract int MaxOutputCharactersPerInputCharacter { get; } public virtual void Encode(System.IO.TextWriter output, char[] value, int startIndex, int characterCount) { } public void Encode(System.IO.TextWriter output, string value) { } public virtual void Encode(System.IO.TextWriter output, string value, int startIndex, int characterCount) { } public virtual string Encode(string value) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe abstract int FindFirstCharacterToEncode(char* text, int textLength); [System.CLSCompliantAttribute(false)] public unsafe abstract bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten); public abstract bool WillEncode(int unicodeScalar); } public partial class TextEncoderSettings { public TextEncoderSettings() { } public TextEncoderSettings(System.Text.Encodings.Web.TextEncoderSettings other) { } public TextEncoderSettings(params System.Text.Unicode.UnicodeRange[] allowedRanges) { } public virtual void AllowCharacter(char character) { } public virtual void AllowCharacters(params char[] characters) { } public virtual void AllowCodePoints(System.Collections.Generic.IEnumerable<int> codePoints) { } public virtual void AllowRange(System.Text.Unicode.UnicodeRange range) { } public virtual void AllowRanges(params System.Text.Unicode.UnicodeRange[] ranges) { } public virtual void Clear() { } public virtual void ForbidCharacter(char character) { } public virtual void ForbidCharacters(params char[] characters) { } public virtual void ForbidRange(System.Text.Unicode.UnicodeRange range) { } public virtual void ForbidRanges(params System.Text.Unicode.UnicodeRange[] ranges) { } public virtual System.Collections.Generic.IEnumerable<int> GetAllowedCodePoints() { throw null; } } public abstract partial class UrlEncoder : System.Text.Encodings.Web.TextEncoder { protected UrlEncoder() { } public static System.Text.Encodings.Web.UrlEncoder Default { get { throw null; } } public static System.Text.Encodings.Web.UrlEncoder Create(System.Text.Encodings.Web.TextEncoderSettings settings) { throw null; } public static System.Text.Encodings.Web.UrlEncoder Create(params System.Text.Unicode.UnicodeRange[] allowedRanges) { throw null; } } } namespace System.Text.Unicode { public sealed partial class UnicodeRange { public UnicodeRange(int firstCodePoint, int length) { } public int FirstCodePoint { get { throw null; } } public int Length { get { throw null; } } public static System.Text.Unicode.UnicodeRange Create(char firstCharacter, char lastCharacter) { throw null; } } public static partial class UnicodeRanges { public static System.Text.Unicode.UnicodeRange All { get { throw null; } } public static System.Text.Unicode.UnicodeRange AlphabeticPresentationForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange Arabic { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicPresentationFormsA { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicPresentationFormsB { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange Armenian { get { throw null; } } public static System.Text.Unicode.UnicodeRange Arrows { get { throw null; } } public static System.Text.Unicode.UnicodeRange Balinese { get { throw null; } } public static System.Text.Unicode.UnicodeRange Bamum { get { throw null; } } public static System.Text.Unicode.UnicodeRange BasicLatin { get { throw null; } } public static System.Text.Unicode.UnicodeRange Batak { get { throw null; } } public static System.Text.Unicode.UnicodeRange Bengali { get { throw null; } } public static System.Text.Unicode.UnicodeRange BlockElements { get { throw null; } } public static System.Text.Unicode.UnicodeRange Bopomofo { get { throw null; } } public static System.Text.Unicode.UnicodeRange BopomofoExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange BoxDrawing { get { throw null; } } public static System.Text.Unicode.UnicodeRange BraillePatterns { get { throw null; } } public static System.Text.Unicode.UnicodeRange Buginese { get { throw null; } } public static System.Text.Unicode.UnicodeRange Buhid { get { throw null; } } public static System.Text.Unicode.UnicodeRange Cham { get { throw null; } } public static System.Text.Unicode.UnicodeRange Cherokee { get { throw null; } } public static System.Text.Unicode.UnicodeRange CherokeeSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkCompatibility { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkCompatibilityForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkCompatibilityIdeographs { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkRadicalsSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkStrokes { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkSymbolsandPunctuation { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkUnifiedIdeographs { get { throw null; } } public static System.Text.Unicode.UnicodeRange CjkUnifiedIdeographsExtensionA { get { throw null; } } public static System.Text.Unicode.UnicodeRange CombiningDiacriticalMarks { get { throw null; } } public static System.Text.Unicode.UnicodeRange CombiningDiacriticalMarksExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange CombiningDiacriticalMarksforSymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange CombiningDiacriticalMarksSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange CombiningHalfMarks { get { throw null; } } public static System.Text.Unicode.UnicodeRange CommonIndicNumberForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange ControlPictures { get { throw null; } } public static System.Text.Unicode.UnicodeRange Coptic { get { throw null; } } public static System.Text.Unicode.UnicodeRange CurrencySymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange Cyrillic { get { throw null; } } public static System.Text.Unicode.UnicodeRange CyrillicExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange CyrillicExtendedB { get { throw null; } } public static System.Text.Unicode.UnicodeRange CyrillicSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange Devanagari { get { throw null; } } public static System.Text.Unicode.UnicodeRange DevanagariExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange Dingbats { get { throw null; } } public static System.Text.Unicode.UnicodeRange EnclosedAlphanumerics { get { throw null; } } public static System.Text.Unicode.UnicodeRange EnclosedCjkLettersandMonths { get { throw null; } } public static System.Text.Unicode.UnicodeRange Ethiopic { get { throw null; } } public static System.Text.Unicode.UnicodeRange EthiopicExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange EthiopicExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange EthiopicSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange GeneralPunctuation { get { throw null; } } public static System.Text.Unicode.UnicodeRange GeometricShapes { get { throw null; } } public static System.Text.Unicode.UnicodeRange Georgian { get { throw null; } } public static System.Text.Unicode.UnicodeRange GeorgianSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange Glagolitic { get { throw null; } } public static System.Text.Unicode.UnicodeRange GreekandCoptic { get { throw null; } } public static System.Text.Unicode.UnicodeRange GreekExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange Gujarati { get { throw null; } } public static System.Text.Unicode.UnicodeRange Gurmukhi { get { throw null; } } public static System.Text.Unicode.UnicodeRange HalfwidthandFullwidthForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange HangulCompatibilityJamo { get { throw null; } } public static System.Text.Unicode.UnicodeRange HangulJamo { get { throw null; } } public static System.Text.Unicode.UnicodeRange HangulJamoExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange HangulJamoExtendedB { get { throw null; } } public static System.Text.Unicode.UnicodeRange HangulSyllables { get { throw null; } } public static System.Text.Unicode.UnicodeRange Hanunoo { get { throw null; } } public static System.Text.Unicode.UnicodeRange Hebrew { get { throw null; } } public static System.Text.Unicode.UnicodeRange Hiragana { get { throw null; } } public static System.Text.Unicode.UnicodeRange IdeographicDescriptionCharacters { get { throw null; } } public static System.Text.Unicode.UnicodeRange IpaExtensions { get { throw null; } } public static System.Text.Unicode.UnicodeRange Javanese { get { throw null; } } public static System.Text.Unicode.UnicodeRange Kanbun { get { throw null; } } public static System.Text.Unicode.UnicodeRange KangxiRadicals { get { throw null; } } public static System.Text.Unicode.UnicodeRange Kannada { get { throw null; } } public static System.Text.Unicode.UnicodeRange Katakana { get { throw null; } } public static System.Text.Unicode.UnicodeRange KatakanaPhoneticExtensions { get { throw null; } } public static System.Text.Unicode.UnicodeRange KayahLi { get { throw null; } } public static System.Text.Unicode.UnicodeRange Khmer { get { throw null; } } public static System.Text.Unicode.UnicodeRange KhmerSymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange Lao { get { throw null; } } public static System.Text.Unicode.UnicodeRange Latin1Supplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedAdditional { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedB { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedC { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedD { get { throw null; } } public static System.Text.Unicode.UnicodeRange LatinExtendedE { get { throw null; } } public static System.Text.Unicode.UnicodeRange Lepcha { get { throw null; } } public static System.Text.Unicode.UnicodeRange LetterlikeSymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange Limbu { get { throw null; } } public static System.Text.Unicode.UnicodeRange Lisu { get { throw null; } } public static System.Text.Unicode.UnicodeRange Malayalam { get { throw null; } } public static System.Text.Unicode.UnicodeRange Mandaic { get { throw null; } } public static System.Text.Unicode.UnicodeRange MathematicalOperators { get { throw null; } } public static System.Text.Unicode.UnicodeRange MeeteiMayek { get { throw null; } } public static System.Text.Unicode.UnicodeRange MeeteiMayekExtensions { get { throw null; } } public static System.Text.Unicode.UnicodeRange MiscellaneousMathematicalSymbolsA { get { throw null; } } public static System.Text.Unicode.UnicodeRange MiscellaneousMathematicalSymbolsB { get { throw null; } } public static System.Text.Unicode.UnicodeRange MiscellaneousSymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange MiscellaneousSymbolsandArrows { get { throw null; } } public static System.Text.Unicode.UnicodeRange MiscellaneousTechnical { get { throw null; } } public static System.Text.Unicode.UnicodeRange ModifierToneLetters { get { throw null; } } public static System.Text.Unicode.UnicodeRange Mongolian { get { throw null; } } public static System.Text.Unicode.UnicodeRange Myanmar { get { throw null; } } public static System.Text.Unicode.UnicodeRange MyanmarExtendedA { get { throw null; } } public static System.Text.Unicode.UnicodeRange MyanmarExtendedB { get { throw null; } } public static System.Text.Unicode.UnicodeRange NewTaiLue { get { throw null; } } public static System.Text.Unicode.UnicodeRange NKo { get { throw null; } } public static System.Text.Unicode.UnicodeRange None { get { throw null; } } public static System.Text.Unicode.UnicodeRange NumberForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange Ogham { get { throw null; } } public static System.Text.Unicode.UnicodeRange OlChiki { get { throw null; } } public static System.Text.Unicode.UnicodeRange OpticalCharacterRecognition { get { throw null; } } public static System.Text.Unicode.UnicodeRange Oriya { get { throw null; } } public static System.Text.Unicode.UnicodeRange Phagspa { get { throw null; } } public static System.Text.Unicode.UnicodeRange PhoneticExtensions { get { throw null; } } public static System.Text.Unicode.UnicodeRange PhoneticExtensionsSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange Rejang { get { throw null; } } public static System.Text.Unicode.UnicodeRange Runic { get { throw null; } } public static System.Text.Unicode.UnicodeRange Samaritan { get { throw null; } } public static System.Text.Unicode.UnicodeRange Saurashtra { get { throw null; } } public static System.Text.Unicode.UnicodeRange Sinhala { get { throw null; } } public static System.Text.Unicode.UnicodeRange SmallFormVariants { get { throw null; } } public static System.Text.Unicode.UnicodeRange SpacingModifierLetters { get { throw null; } } public static System.Text.Unicode.UnicodeRange Specials { get { throw null; } } public static System.Text.Unicode.UnicodeRange Sundanese { get { throw null; } } public static System.Text.Unicode.UnicodeRange SundaneseSupplement { get { throw null; } } public static System.Text.Unicode.UnicodeRange SuperscriptsandSubscripts { get { throw null; } } public static System.Text.Unicode.UnicodeRange SupplementalArrowsA { get { throw null; } } public static System.Text.Unicode.UnicodeRange SupplementalArrowsB { get { throw null; } } public static System.Text.Unicode.UnicodeRange SupplementalMathematicalOperators { get { throw null; } } public static System.Text.Unicode.UnicodeRange SupplementalPunctuation { get { throw null; } } public static System.Text.Unicode.UnicodeRange SylotiNagri { get { throw null; } } public static System.Text.Unicode.UnicodeRange Syriac { get { throw null; } } public static System.Text.Unicode.UnicodeRange Tagalog { get { throw null; } } public static System.Text.Unicode.UnicodeRange Tagbanwa { get { throw null; } } public static System.Text.Unicode.UnicodeRange TaiLe { get { throw null; } } public static System.Text.Unicode.UnicodeRange TaiTham { get { throw null; } } public static System.Text.Unicode.UnicodeRange TaiViet { get { throw null; } } public static System.Text.Unicode.UnicodeRange Tamil { get { throw null; } } public static System.Text.Unicode.UnicodeRange Telugu { get { throw null; } } public static System.Text.Unicode.UnicodeRange Thaana { get { throw null; } } public static System.Text.Unicode.UnicodeRange Thai { get { throw null; } } public static System.Text.Unicode.UnicodeRange Tibetan { get { throw null; } } public static System.Text.Unicode.UnicodeRange Tifinagh { get { throw null; } } public static System.Text.Unicode.UnicodeRange UnifiedCanadianAboriginalSyllabics { get { throw null; } } public static System.Text.Unicode.UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended { get { throw null; } } public static System.Text.Unicode.UnicodeRange Vai { get { throw null; } } public static System.Text.Unicode.UnicodeRange VariationSelectors { get { throw null; } } public static System.Text.Unicode.UnicodeRange VedicExtensions { get { throw null; } } public static System.Text.Unicode.UnicodeRange VerticalForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange YijingHexagramSymbols { get { throw null; } } public static System.Text.Unicode.UnicodeRange YiRadicals { get { throw null; } } public static System.Text.Unicode.UnicodeRange YiSyllables { get { throw null; } } } }
78.887597
145
0.71444
[ "MIT" ]
chsienki/source-build-reference-packages
src/referencePackages/src/system.text.encodings.web/5.0.1/lib/netstandard1.0/System.Text.Encodings.Web.cs
20,355
C#
using DotNetBlog.Core.Model.Topic; namespace DotNetBlog.Core.Model.Tag { public class TagModel { public int Id { get; set; } public string Keyword { get; set; } public TopicCountModel Topics { get; set; } } }
17.785714
51
0.618474
[ "MIT" ]
OmidID/DotNetBlog
src/DotNetBlog.Core/Model/Tag/TagModel.cs
251
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; using Bio.Algorithms.Alignment; using Bio.Algorithms.MUMmer; using Bio.Algorithms.SuffixTree; using Bio.Extensions; using Bio.IO.FastA; using Bio.SimilarityMatrices; using Bio.TestAutomation.Util; using Bio.Util.Logging; using NUnit.Framework; namespace Bio.Tests.Algorithms.Alignment.NUCmer { /// <summary> /// NUCmer P1 Test case implementation. /// </summary> [TestFixture] public class NUCmerP1TestCases { /// <summary> /// Lis Parameters which are used for different test cases /// based on which the test cases are executed. /// </summary> private enum AdditionalParameters { FindUniqueMatches, PerformClusterBuilder, AlignSimilarityMatrix, Default }; /// <summary> /// Parameters which are used for different test cases /// based on which the properties are updated. /// </summary> private enum PropertyParameters { MaximumSeparation, MinimumScore, SeparationFactor, FixedSeparation, FixedSeparationAndSeparationFactor, MaximumFixedAndSeparationFactor, Default }; private readonly Utility utilityObj = new Utility(@"TestUtils\NUCmerTestsConfig.xml"); #region Suffix Tree Test Cases /// <summary> /// Validate FindMatches() method with one line sequences /// and valid MUM length for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with Valid MUM length /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesOneLineSequenceValidMUMLength() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneLineSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with DNA sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with Valid MUM length /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesDnaSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.DnaNucmerSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with RNA sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with Valid MUM length /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesRnaSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.RnaNucmerSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with medium sequences /// for both reference and query parameter and validate /// the unique matches /// Input : Medium size reference and query parameter /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesMediumSizeSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.MediumSizeSequenceNodeName, true, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with continous repeating character sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with continous /// repeating characters /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesContinousRepeatingSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneLineRepeatingCharactersNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with same sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with same characters /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesSameSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.SameSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with overlap sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with overlap /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesWithCrossOverlapSequences() { this.ValidateFindMatchSuffixGeneralTestCases( Constants.TwoUniqueMatchWithCrossOverlapSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with no match sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with no match /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesWithNoMatchSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneLineNoMatchSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with overlap sequences /// for both reference and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with overlap /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesWithOverlapSequences() { this.ValidateFindMatchSuffixGeneralTestCases( Constants.TwoUniqueMatchWithoutCrossOverlapSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with ambiguity characters in /// reference Dna sequence and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with ambiguity /// characters in reference Dna sequence /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesAmbiguityDnaReferenceSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.DnaAmbiguityReferenceSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with ambiguity characters in /// search Dna sequence and reference parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with ambiguity /// characters in search Dna sequence /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesAmbiguityDnaSearchSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.DnaAmbiguitySearchSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with ambiguity characters in /// reference Rna sequence and query parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with ambiguity /// characters in reference Rna sequence /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesAmbiguityRnaReferenceSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.RnaAmbiguityReferenceSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate FindMatches() method with ambiguity characters in /// search Rna sequence and reference parameter and validate /// the unique matches /// Input : One line sequence for both reference and query parameter with ambiguity /// characters in search Rna sequence /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void SuffixTreeFindMatchesAmbiguityRnaSearchSequences() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.RnaAmbiguitySearchSequenceNodeName, false, AdditionalParameters.FindUniqueMatches); } /// <summary> /// Validate BuildCluster() method with two unique match /// and without cross over lap and validate the clusters /// Input : Two unique matches without cross overlap /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderTwoUniqueMatchesWithoutCrossOverlap() { this.ValidateFindMatchSuffixGeneralTestCases( Constants.TwoUniqueMatchWithoutCrossOverlapSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder); } /// <summary> /// Validate BuildCluster() method with two unique match /// and with cross over lap and validate the clusters /// Input : Two unique matches with cross overlap /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderTwoUniqueMatchesWithCrossOverlap() { this.ValidateFindMatchSuffixGeneralTestCases( Constants.TwoUniqueMatchWithCrossOverlapSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder); } /// <summary> /// Validate BuildCluster() method with two unique match /// and with overlap and no cross overlap and validate the clusters /// Input : Two unique matches with overlap and no cross overlap /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithOverlapNoCrossOverlap() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder); } /// <summary> /// Validate BuildCluster() method with Minimum Score set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with minimum score 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithMinimumScoreZero() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.MinimumScore); } /// <summary> /// Validate BuildCluster() method with MaximumSeparation set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with MaximumSeparation 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithMaximumSeparationZero() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.MaximumSeparation); } /// <summary> /// Validate BuildCluster() method with SeperationFactor set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with SeperationFactor 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithSeperationFactoreZero() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.SeparationFactor); } /// <summary> /// Validate BuildCluster() method with FixedSeparation set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with FixedSeparation 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithFixedSeparationZero() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.FixedSeparation); } /// <summary> /// Validate BuildCluster() method with /// MinimumScore set to greater than MUMlength /// and validate the clusters /// Input : Reference and Search Sequences with /// MinimumScore set to greater than MUMlength /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithMinimumScoreGreater() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.MinimumScore); } /// <summary> /// Validate BuildCluster() method with /// FixedSeparation set to postive value and SeparationFactor=0 /// and validate the clusters /// Input : Reference and Search Sequences with /// FixedSeparation set to postive value and SeparationFactor=0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithFixedSeparationAndSeparationFactor() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.FixedSeparationAndSeparationFactor); } /// <summary> /// Validate BuildCluster() method with /// MaximumSeparation=6, FixedSeparation=7 and SeparationFactor=0 /// and validate the clusters /// Input : Reference and Search Sequences with /// MaximumSeparation=6, FixedSeparation=7 and SeparationFactor=0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void ClusterBuilderWithMaximumFixedAndSeparationFactor() { this.ValidateFindMatchSuffixGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, AdditionalParameters.PerformClusterBuilder, PropertyParameters.MaximumFixedAndSeparationFactor); } #endregion Suffix Tree Test Cases #region NUCmer Align Test Cases /// <summary> /// Validate Align() method with one line Dna sequence /// and validate the aligned sequences /// Input : One line Dna sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignDnaSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.DnaNucmerSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with one line Rna sequence /// and validate the aligned sequences /// Input : One line Rna sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignRnaSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.RnaNucmerSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with one line list of sequence /// and validate the aligned sequences /// Input : One line list of sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneLineListOfSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineOneReferenceQuerySequenceNodeName, false, true, false); } /// <summary> /// Validate Align() method with small size list of sequence /// and validate the aligned sequences /// Input : small size list of sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSmallSizeListOfSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineOneReferenceQuerySequenceNodeName, false, true, false); } /// <summary> /// Validate Align() method with one line Dna list of sequence /// and validate the aligned sequences /// Input : One line Dna list of sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneLineDnaListOfSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SingleDnaNucmerSequenceNodeName, false, true, false); } /// <summary> /// Validate Align() method with one line Rna list of sequence /// and validate the aligned sequences /// Input : One line Rna list of sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneLineRnaListOfSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SingleRnaNucmerSequenceNodeName, false, true, false); } /// <summary> /// Validate Align() method with medium size sequence /// and validate the aligned sequences /// Input : Medium size sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignMediumSizeSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.MediumSizeSequenceNodeName, true, false, false); } /// <summary> /// Validate Align() method with One Line Repeating Characters sequence /// and validate the aligned sequences /// Input : One Line Repeating Characters sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignRepeatingCharactersSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineRepeatingCharactersNodeName, false, false, false); } /// <summary> /// Validate Align() method with One Line Alternate Repeating Characters sequence /// and validate the aligned sequences /// Input : One Line Alternate Repeating Characters sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignAlternateRepeatingCharactersSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineAlternateRepeatingCharactersNodeName, false, false, false); } /// <summary> /// Validate Align() method with FastA file sequence /// and validate the aligned sequences /// Input : FastA file sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignFastASequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SimpleDnaFastaNodeName, true, false, false); } /// <summary> /// Validate Align() method with One Line only Repeating Characters sequence /// and validate the aligned sequences /// Input : One Line only Repeating Characters sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOnlyRepeatingCharactersSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineOnlyRepeatingCharactersNodeName, false, false, false); } /// <summary> /// Validate Align() method with one reference multi search sequence /// and validate the aligned sequences /// Input : one reference multi search sequence file /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneRefMultiSearchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SmallSizeSequenceNodeName, true, false, false); } /// <summary> /// Validate Align() method with valid MUM length /// and validate the aligned sequences /// Input : One line sequence with valid MUM length /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneLineSequenceValidMumLength() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with One Line same sequences /// and validate the aligned sequences /// Input : One Line same sequences /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSameSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SameSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with overlap sequences /// and validate the aligned sequences /// Input : One Line overlap sequences /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOverlapMatchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneOverlapMatchSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with no match sequences /// and validate the aligned sequences /// Input : One Line no match sequences /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignNoMatchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineNoMatchSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with cross overlap sequences /// and validate the aligned sequences /// Input : One Line cross overlap sequences /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignCrossOverlapMatchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.TwoUniqueMatchWithCrossOverlapSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with one line reference Dna sequence with ambiguity /// and validate the aligned sequences /// Input : One line Dna sequence with ambiguity /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignDnaReferenceAmbiguitySequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.DnaAmbiguityReferenceSequenceNodeName, false, false, true); } /// <summary> /// Validate Align() method with one line reference Rna sequence with ambiguity /// and validate the aligned sequences /// Input : One line Rna sequence with ambiguity /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignRnaReferenceAmbiguitySequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.RnaAmbiguityReferenceSequenceNodeName, false, false, true); } /// <summary> /// Validate Align() method with one line search Dna sequence with ambiguity /// and validate the aligned sequences /// Input : One line Dna sequence with ambiguity /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignDnaSearchAmbiguitySequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.DnaAmbiguitySearchSequenceNodeName, false, false, true); } /// <summary> /// Validate Align() method with one line search Rna sequence with ambiguity /// and validate the aligned sequences /// Input : One line Rna sequence with ambiguity /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignRnaSearchAmbiguitySequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.RnaAmbiguitySearchSequenceNodeName, false, false, true); } /// <summary> /// Validate Align() method with one ref. and one query sequence /// and validate the aligned sequences /// Input : one reference and one query sequence /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignOneRefOneQuerySequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.SingleDnaNucmerSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with multi reference one search sequence /// and validate the aligned sequences /// Input : multiple reference one search sequence file /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignMultiRefOneSearchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.MultiRefSingleQueryMatchSequenceNodeName, false, false, false); } /// <summary> /// Validate Align() method with multi reference multi search sequence /// and validate the aligned sequences /// Input : multiple reference multi search sequence file /// Validation : Validate the aligned sequences. /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignMultiRefMultiSearchSequence() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneLineSequenceNodeName, false, false, false); } /// <summary> /// Validate BuildCluster() method with Minimum Score set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with minimum score 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithMinimumScoreZero() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.MinimumScore, false); } /// <summary> /// Validate BuildCluster() method with MaximumSeparation set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with MaximumSeparation 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithMaximumSeparationZero() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.MaximumSeparation, false); } /// <summary> /// Validate BuildCluster() method with SeperationFactor set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with SeperationFactor 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithSeperationFactoreZero() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.SeparationFactor, false); } /// <summary> /// Validate BuildCluster() method with FixedSeparation set to 0 /// and validate the clusters /// Input : Reference and Search Sequences with FixedSeparation 0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithFixedSeparationZero() { this.ValidateNUCmerAlignGeneralTestCases(Constants.OneUniqueMatchSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.FixedSeparation, false); } /// <summary> /// Validate BuildCluster() method with /// MinimumScore set to greater than MUMlength /// and validate the clusters /// Input : Reference and Search Sequences with /// MinimumScore set to greater than MUMlength /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithMinimumScoreGreater() { this.ValidateNUCmerAlignGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.MinimumScore, false); } /// <summary> /// Validate BuildCluster() method with /// FixedSeparation set to postive value and SeparationFactor=0 /// and validate the clusters /// Input : Reference and Search Sequences with /// FixedSeparation set to postive value and SeparationFactor=0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithFixedSeparationAndSeparationFactor() { this.ValidateNUCmerAlignGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.FixedSeparationAndSeparationFactor, false); } /// <summary> /// Validate BuildCluster() method with /// MaximumSeparation=6, FixedSeparation=7 and SeparationFactor=0 /// and validate the clusters /// Input : Reference and Search Sequences with /// MaximumSeparation=6, FixedSeparation=7 and SeparationFactor=0 /// Validation : Validate the unique matches /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignWithMaximumFixedAndSeparationFactor() { this.ValidateNUCmerAlignGeneralTestCases(Constants.MinimumScoreGreaterSequenceNodeName, false, false, AdditionalParameters.Default, PropertyParameters.MaximumFixedAndSeparationFactor, false); } /// <summary> /// Validate Align() method with IsAlign set to true /// and with gaps in the reference and query sequence. /// </summary> [Category("Priority1")] public void NUCmerAlignWithIsAlignAndGaps() { IList<ISequence> seqList = new List<ISequence>(); seqList.Add(new Sequence(Alphabets.DNA, Encoding.ASCII.GetBytes("CAAAAGGGATTGC---TGTTGGAGTGAATGCCATTACCTACCGGCTAGGAGGAGTAGTACAAAGGAGC"))); seqList.Add(new Sequence(Alphabets.DNA, Encoding.ASCII.GetBytes("CAAAAGGGATTGC---"))); seqList.Add(new Sequence(Alphabets.DNA, Encoding.ASCII.GetBytes("TAGTAGTTCTGCTATATACATTTG"))); seqList.Add(new Sequence(Alphabets.DNA, Encoding.ASCII.GetBytes("GTTATCATGCGAACAATTCAACAGACACTGTAGA"))); var num = new NucmerPairwiseAligner { BreakLength = 8, FixedSeparation = 0, MinimumScore = 0, MaximumSeparation = 0, SeparationFactor = 0, LengthOfMUM = 8 }; IList<ISequence> sequenceList = seqList; IList<ISequenceAlignment> alignmentObj = num.Align(sequenceList); var alignedSeqs = (AlignedSequence) alignmentObj[0].AlignedSequences[0]; Assert.AreEqual("CAAAAGGGATTGC---", new string(alignedSeqs.Sequences[0].Select(a => (char) a).ToArray())); Assert.AreEqual("CAAAAGGGATTGC---", new string(alignedSeqs.Sequences[1].Select(a => (char) a).ToArray())); ApplicationLog.WriteLine("Successfully validated Align method with IsAlign and Gaps"); } #endregion NUCmer Align Test Cases #region NUCmer Align Simple Test Cases /// <summary> /// Validate AlignSimple() method with one line Dna list of sequence /// and validate the aligned sequences /// Input : Dna list of sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleDnaListOfSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleDnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Rna list of sequence /// and validate the aligned sequences /// Input : Rna list of sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleRnaListOfSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleRnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Dna sequence /// and validate the aligned sequences /// Input : Single Reference and Single Query Dna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleSingleRefSingleQueryDnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleDnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Rna sequence /// and validate the aligned sequences /// Input : Single Reference and Single Query Rna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleSingleRefSingleQueryRnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleRnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Dna sequence /// and validate the aligned sequences /// Input : Single Reference and Multi Query Dna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleSingleRefMultiQueryDnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleDnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Rna sequence /// and validate the aligned sequences /// Input : Single Reference and Multi Query Rna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleSingleRefMultiQueryRnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.SingleRnaNucmerSequenceNodeName, false, true); } /// <summary> /// Validate AlignSimple() method with one line Dna sequence /// and validate the aligned sequences /// Input : Multi Reference and Multi Query Dna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleMultiRefMultiQueryDnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.MultiRefMultiQueryDnaMatchSequence, false, true); } /// <summary> /// Validate AlignSimple() method with one line Rna sequence /// and validate the aligned sequences /// Input : Multi Reference and Multi Query Rna sequence /// Validation : Validate the aligned sequences /// </summary> [Test] [Category("Priority1")] public void NUCmerAlignSimpleMultiRefMultiQueryRnaSequence() { this.ValidateNUCmerAlignSimpleGeneralTestCases(Constants.MultiRefMultiQueryRnaMatchSequence, false, true); } #endregion NUCmer Align Simple Test Cases #region Supported Methods /// <summary> /// Validates most of the find matches suffix tree test cases with varying parameters. /// </summary> /// <param name="nodeName">Node name which needs to be read for execution.</param> /// <param name="isFilePath">Is File Path?</param> /// <param name="additionalParam">LIS action type enum</param> private void ValidateFindMatchSuffixGeneralTestCases(string nodeName, bool isFilePath, AdditionalParameters additionalParam) { this.ValidateFindMatchSuffixGeneralTestCases(nodeName, isFilePath, additionalParam, PropertyParameters.Default); } /// <summary> /// Validates most of the find matches suffix tree test cases with varying parameters. /// </summary> /// <param name="nodeName">Node name which needs to be read for execution.</param> /// <param name="isFilePath">Is File Path?</param> /// <param name="additionalParam">LIS action type enum</param> /// <param name="propParam">Property parameters</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ValidateFindMatchSuffixGeneralTestCases(string nodeName, bool isFilePath, AdditionalParameters additionalParam, PropertyParameters propParam) { ISequence referenceSeq; var searchSeqList = new List<ISequence>(); if (isFilePath) { // Gets the reference sequence from the FastA file string filePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FilePathNode).TestDir(); Assert.IsNotNull(filePath); ApplicationLog.WriteLine(string.Format(null, "NUCmer P1 : Successfully validated the File Path '{0}'.", filePath)); var parser = new FastAParser(); IEnumerable<ISequence> referenceSeqList = parser.Parse(filePath); var byteList = new List<Byte>(); foreach (ISequence seq in referenceSeqList) { byteList.AddRange(seq); byteList.Add((byte) '+'); } referenceSeq = new Sequence(referenceSeqList.First().Alphabet.GetMummerAlphabet(), byteList.ToArray()); // Gets the query sequence from the FastA file string queryFilePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SearchSequenceFilePathNode).TestDir(); Assert.IsNotNull(queryFilePath); ApplicationLog.WriteLine(string.Format(null, "NUCmer P1 : Successfully validated the File Path '{0}'.", queryFilePath)); var queryParserObj = new FastAParser(); IEnumerable<ISequence> querySeqList = queryParserObj.Parse(queryFilePath); searchSeqList.AddRange(querySeqList); } else { // Gets the reference & search sequences from the configuration file string[] referenceSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.ReferenceSequencesNode); string[] searchSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.SearchSequencesNode); IAlphabet seqAlphabet = Utility.GetAlphabet(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.AlphabetNameNode)); var refSeqList = referenceSequences.Select(t => new Sequence(seqAlphabet, Encoding.ASCII.GetBytes(t))).Cast<ISequence>().ToList(); var byteList = new List<Byte>(); foreach (ISequence seq in refSeqList) { byteList.AddRange(seq); byteList.Add((byte) '+'); } referenceSeq = new Sequence(refSeqList.First().Alphabet.GetMummerAlphabet(), byteList.ToArray()); searchSeqList.AddRange(searchSequences.Select(t => new Sequence(seqAlphabet, Encoding.ASCII.GetBytes(t)))); } string mumLength = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMLengthNode); // Builds the suffix for the reference sequence passed. var suffixTreeBuilder = new MultiWaySuffixTree(referenceSeq as Sequence) { MinLengthOfMatch = long.Parse(mumLength, null) }; var matches = searchSeqList.ToDictionary(t => t, suffixTreeBuilder.SearchMatchesUniqueInReference); var mums = new List<Match>(); foreach (var a in matches.Values) { mums.AddRange(a); } switch (additionalParam) { case AdditionalParameters.FindUniqueMatches: // Validates the Unique Matches. ApplicationLog.WriteLine("NUCmer P1 : Validating the Unique Matches"); Assert.IsTrue(this.ValidateUniqueMatches(mums, nodeName, isFilePath)); ApplicationLog.WriteLine("NUCmer P1 : Successfully validated the all the unique matches for the sequences."); break; case AdditionalParameters.PerformClusterBuilder: // Validates the Unique Matches. ApplicationLog.WriteLine( "NUCmer P1 : Validating the Unique Matches using Cluster Builder"); Assert.IsTrue(this.ValidateClusterBuilderMatches(mums, nodeName, propParam)); ApplicationLog.WriteLine("NUCmer P1 : Successfully validated the all the cluster builder matches for the sequences."); break; default: break; } ApplicationLog.WriteLine("NUCmer P1 : Successfully validated the all the unique matches for the sequences."); } /// <summary> /// Validates the NUCmer align method for several test cases for the parameters passed. /// </summary> /// <param name="nodeName">Node name to be read from xml</param> /// <param name="isFilePath">Is Sequence saved in File</param> /// <param name="isAlignList">Is align method to take list?</param> /// <param name="isAmbiguous"></param> private void ValidateNUCmerAlignGeneralTestCases(string nodeName, bool isFilePath, bool isAlignList, bool isAmbiguous) { this.ValidateNUCmerAlignGeneralTestCases(nodeName, isFilePath, isAlignList, AdditionalParameters.Default, PropertyParameters.Default, isAmbiguous); } /// <summary> /// Validates the NUCmer align method for several test cases for the parameters passed. /// </summary> /// <param name="nodeName">Node name to be read from xml</param> /// <param name="isFilePath">Is Sequence saved in File</param> /// <param name="isAlignList">Is align method to take list?</param> /// <param name="addParam">Additional parameters</param> /// <param name="propParam">Property parameters</param> /// <param name="isAmbiguous"></param> /// 1801 is suppressed as this variable would be used later [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity"), SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "parserParam")] private void ValidateNUCmerAlignGeneralTestCases(string nodeName, bool isFilePath, bool isAlignList, AdditionalParameters addParam, PropertyParameters propParam, bool isAmbiguous) { IList<ISequence> refSeqList = new List<ISequence>(); IList<ISequence> searchSeqList = new List<ISequence>(); if (isFilePath) { // Gets the reference sequence from the FastA file string filePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FilePathNode).TestDir(); Assert.IsNotNull(filePath); ApplicationLog.WriteLine(string.Format(null, "NUCmer P1 : Successfully validated the File Path '{0}'.", filePath)); var fastaparserobj = new FastAParser(); IEnumerable<ISequence> referenceSeqList = fastaparserobj.Parse(filePath); foreach (ISequence seq in referenceSeqList) { refSeqList.Add(seq); } // Gets the query sequence from the FastA file string queryFilePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SearchSequenceFilePathNode).TestDir(); Assert.IsNotNull(queryFilePath); ApplicationLog.WriteLine(string.Format(null, "NUCmer P1 : Successfully validated the File Path '{0}'.", queryFilePath)); var queryParserobj = new FastAParser(); IEnumerable<ISequence> serSeqList = queryParserobj.Parse(queryFilePath); foreach (ISequence seq in serSeqList) { searchSeqList.Add(seq); } } else { // Gets the reference & search sequences from the configuration file string[] referenceSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.ReferenceSequencesNode); string[] searchSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.SearchSequencesNode); IAlphabet seqAlphabet = Utility.GetAlphabet(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.AlphabetNameNode)); IAlphabet ambAlphabet = null; if (isAmbiguous) { switch (seqAlphabet.Name.ToLower(CultureInfo.CurrentCulture)) { case "dna": case "ambiguousdna": ambAlphabet = AmbiguousDnaAlphabet.Instance; break; case "rna": case "ambiguousrna": ambAlphabet = AmbiguousRnaAlphabet.Instance; break; case "protein": case "ambiguousprotein": ambAlphabet = AmbiguousProteinAlphabet.Instance; break; default: break; } } else { ambAlphabet = seqAlphabet; } for (int i = 0; i < referenceSequences.Length; i++) { ISequence referSeq = new Sequence(ambAlphabet, Encoding.ASCII.GetBytes(referenceSequences[i])); referSeq.ID = "ref " + i; refSeqList.Add(referSeq); } for (int i = 0; i < searchSequences.Length; i++) { ISequence searchSeq = new Sequence(ambAlphabet, Encoding.ASCII.GetBytes(searchSequences[i])); searchSeq.ID = "qry " + i; searchSeqList.Add(searchSeq); } } // Gets the mum length from the xml string mumLength = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode); var nucmerObj = new NucmerPairwiseAligner(); // Check for additional parameters and update the object accordingly switch (addParam) { case AdditionalParameters.AlignSimilarityMatrix: nucmerObj.SimilarityMatrix = new SimilarityMatrix(SimilarityMatrix.StandardSimilarityMatrix.Blosum50); break; default: break; } // Update other values for NUCmer object nucmerObj.MaximumSeparation = 0; nucmerObj.MinimumScore = 2; nucmerObj.SeparationFactor = 0.12f; nucmerObj.BreakLength = 2; nucmerObj.LengthOfMUM = long.Parse(mumLength, null); switch (propParam) { case PropertyParameters.MinimumScore: nucmerObj.MinimumScore = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MinimumScoreNode), null); break; case PropertyParameters.MaximumSeparation: nucmerObj.MaximumSeparation = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MaximumSeparationNode), null); break; case PropertyParameters.FixedSeparation: nucmerObj.FixedSeparation = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; case PropertyParameters.SeparationFactor: nucmerObj.SeparationFactor = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); break; case PropertyParameters.FixedSeparationAndSeparationFactor: nucmerObj.SeparationFactor = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); nucmerObj.FixedSeparation = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; case PropertyParameters.MaximumFixedAndSeparationFactor: nucmerObj.MaximumSeparation = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MaximumSeparationNode), null); nucmerObj.SeparationFactor = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); nucmerObj.FixedSeparation = int.Parse( this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; default: break; } IList<ISequenceAlignment> align = null; if (isAlignList) { var listOfSeq = new List<ISequence> {refSeqList.ElementAt(0), searchSeqList.ElementAt(0)}; align = nucmerObj.Align(listOfSeq); } else { align = nucmerObj.Align(refSeqList, searchSeqList); } string expectedSequences = isFilePath ? this.utilityObj.xmlUtil.GetFileTextValue(nodeName, Constants.ExpectedSequencesNode) : this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.ExpectedSequencesNode); string[] expSeqArray = expectedSequences.Split(','); // Gets all the aligned sequences in comma separated format foreach (IPairwiseSequenceAlignment seqAlignment in align) { foreach (PairwiseAlignedSequence alignedSeq in seqAlignment) { var actualStr = alignedSeq.FirstSequence.ConvertToString(); Assert.IsTrue(expSeqArray.Contains(actualStr)); actualStr = alignedSeq.SecondSequence.ConvertToString(); Assert.IsTrue(expSeqArray.Contains(actualStr)); } } ApplicationLog.WriteLine("NUCmer P1 : Successfully validated all the aligned sequences."); } /// <summary> /// Validates the NUCmer align method for several test cases for the parameters passed. /// </summary> /// <param name="nodeName">Node name to be read from xml</param> /// <param name="isFilePath">Is Sequence saved in File</param> /// <param name="isAlignList">Is align method to take list?</param> /// 1801 is suppressed as this variable would be used later [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "parserParam")] private void ValidateNUCmerAlignSimpleGeneralTestCases(string nodeName, bool isFilePath, bool isAlignList) { IList<ISequence> refSeqList = new List<ISequence>(); IList<ISequence> searchSeqList = new List<ISequence>(); if (isFilePath) { // Gets the reference sequence from the FastA file string filePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FilePathNode); Assert.IsNotNull(filePath); ApplicationLog.WriteLine(string.Format(null, "NUCmer P1 : Successfully validated the File Path '{0}'.", filePath)); var fastaparserobj = new FastAParser(); IEnumerable<ISequence> referenceSeqList = fastaparserobj.Parse(filePath); foreach (ISequence seq in referenceSeqList) { refSeqList.Add(seq); } // Gets the query sequence from the FastA file string queryFilePath = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SearchSequenceFilePathNode); Assert.IsNotNull(queryFilePath); ApplicationLog.WriteLine(string.Format(null,"NUCmer P1 : Successfully validated the File Path '{0}'.", queryFilePath)); var fastaParserobj = new FastAParser(); IEnumerable<ISequence> querySeqList = fastaParserobj.Parse(queryFilePath); foreach (ISequence seq in querySeqList) { searchSeqList.Add(seq); } } else { // Gets the reference & search sequences from the configuration file string[] referenceSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.ReferenceSequencesNode); string[] searchSequences = this.utilityObj.xmlUtil.GetTextValues(nodeName, Constants.SearchSequencesNode); IAlphabet seqAlphabet = Utility.GetAlphabet(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.AlphabetNameNode)); foreach (Sequence referSeq in referenceSequences.Select(t => new Sequence(seqAlphabet, Encoding.ASCII.GetBytes(t)))) { refSeqList.Add(referSeq); } foreach (Sequence searchSeq in searchSequences.Select(t => new Sequence(seqAlphabet, Encoding.ASCII.GetBytes(t)))) { searchSeqList.Add(searchSeq); } } // Gets the mum length from the xml string mumLength = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode); var nucmerObj = new NucmerPairwiseAligner { MaximumSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), null), MinimumScore = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), null), SeparationFactor = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), null), BreakLength = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), null), LengthOfMUM = long.Parse(mumLength, null) }; IList<ISequenceAlignment> alignSimple = null; if (isAlignList) { var listOfSeq = new List<ISequence> {refSeqList[0], searchSeqList[0]}; alignSimple = nucmerObj.AlignSimple(listOfSeq); } string expectedSequences = isFilePath ? this.utilityObj.xmlUtil.GetFileTextValue(nodeName, Constants.ExpectedSequencesNode) : this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.ExpectedSequencesNode); string[] expSeqArray = expectedSequences.Split(','); int j = 0; // Gets all the aligned sequences in comma separated format foreach (PairwiseAlignedSequence alignedSeq in alignSimple.Cast<IPairwiseSequenceAlignment>().SelectMany(seqAlignment => seqAlignment)) { Assert.AreEqual(expSeqArray[j], alignedSeq.FirstSequence.ConvertToString()); ++j; Assert.AreEqual(expSeqArray[j], alignedSeq.SecondSequence.ConvertToString()); j++; } ApplicationLog.WriteLine("NUCmer P1 : Successfully validated all the aligned sequences."); } /// <summary> /// Validates the Unique Matches for the input provided. /// </summary> /// <param name="matches">Max Unique Match list</param> /// <param name="nodeName">Node name to be read from xml</param> /// <param name="isFilePath">Nodes to be read from Text file?</param> /// <returns>True, if successfully validated</returns> private bool ValidateUniqueMatches(IEnumerable<Match> matches, string nodeName, bool isFilePath) { string[] firstSeqOrder; string[] length; string[] secondSeqOrder; if (isFilePath) { firstSeqOrder = this.utilityObj.xmlUtil.GetFileTextValue(nodeName, Constants.FirstSequenceMumOrderNode).Split(','); length = this.utilityObj.xmlUtil.GetFileTextValue(nodeName, Constants.LengthNode).Split(','); secondSeqOrder = this.utilityObj.xmlUtil.GetFileTextValue(nodeName, Constants.SecondSequenceMumOrderNode).Split(','); } else { firstSeqOrder = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FirstSequenceMumOrderNode).Split(','); length = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.LengthNode).Split(','); secondSeqOrder = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SecondSequenceMumOrderNode).Split(','); } int i = 0; IList<MatchExtension> meNewObj = matches.Select(m => new MatchExtension(m)).ToList(); // Order the mum list with query sequence order and // Assign query sequence to the MUM's for (int index = 0; index < meNewObj.Count(); index++) { meNewObj.ElementAt(index).ReferenceSequenceMumOrder = index + 1; meNewObj.ElementAt(index).QuerySequenceMumOrder = index + 1; } // Loops through all the matches and validates the same. foreach (MatchExtension match in meNewObj) { if ((0 != string.Compare(firstSeqOrder[i], match.ReferenceSequenceMumOrder.ToString((IFormatProvider) null), true, CultureInfo.CurrentCulture)) || (0 != string.Compare(length[i], match.Length.ToString((IFormatProvider) null), true, CultureInfo.CurrentCulture)) || (0 != string.Compare(secondSeqOrder[i], match.QuerySequenceMumOrder.ToString((IFormatProvider) null), true, CultureInfo.CurrentCulture))) { ApplicationLog.WriteLine(string.Format(null, "NUCmer BVT : Unique match not matching at index '{0}'", i)); return false; } i++; } return true; } /// <summary> /// Validates the Cluster Builder Matches for the input provided. /// </summary> /// <param name="matches">Max Unique Match list</param> /// <param name="nodeName">Node name to be read from xml</param> /// <param name="propParam">Property parameters</param> /// <returns>True, if successfully validated</returns> private bool ValidateClusterBuilderMatches(IEnumerable<Match> matches, string nodeName, PropertyParameters propParam) { // Validates the Cluster builder MUMs string firstSeqOrderExpected = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.ClustFirstSequenceMumOrderNode); string lengthExpected = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.ClustLengthNode); string secondSeqOrderExpected = this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.ClustSecondSequenceMumOrderNode); var firstSeqOrderActual = new StringBuilder(); var lengthActual = new StringBuilder(); var secondSeqOrderActual = new StringBuilder(); var cbObj = new ClusterBuilder {MinimumScore = 0}; switch (propParam) { case PropertyParameters.MinimumScore: cbObj.MinimumScore = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MinimumScoreNode), null); break; case PropertyParameters.MaximumSeparation: cbObj.MaximumSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MaximumSeparationNode), null); break; case PropertyParameters.FixedSeparation: cbObj.FixedSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; case PropertyParameters.SeparationFactor: cbObj.SeparationFactor = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); break; case PropertyParameters.FixedSeparationAndSeparationFactor: cbObj.SeparationFactor = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); cbObj.FixedSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; case PropertyParameters.MaximumFixedAndSeparationFactor: cbObj.MaximumSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MaximumSeparationNode), null); cbObj.SeparationFactor = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.SeparationFactorNode), null); cbObj.FixedSeparation = int.Parse(this.utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FixedSeparationNode), null); break; default: break; } var meObj = matches.Select(m => new MatchExtension(m)).ToList(); IEnumerable<Cluster> clusts = cbObj.BuildClusters(meObj); foreach (MatchExtension maxMatchExtension in clusts.SelectMany(clust => clust.Matches)) { firstSeqOrderActual.Append(maxMatchExtension.ReferenceSequenceOffset); secondSeqOrderActual.Append(maxMatchExtension.QuerySequenceOffset); lengthActual.Append(maxMatchExtension.Length); } if ((0 != string.Compare(firstSeqOrderExpected.Replace(",", ""), firstSeqOrderActual.ToString(), true, CultureInfo.CurrentCulture)) || (0 != string.Compare(lengthExpected.Replace(",", ""), lengthActual.ToString(), true, CultureInfo.CurrentCulture)) || (0 != string.Compare(secondSeqOrderExpected.Replace(",", ""), secondSeqOrderActual.ToString(), true, CultureInfo.CurrentCulture))) { ApplicationLog.WriteLine("NUCmer P1 : Cluster builder match not matching"); return false; } return true; } #endregion Supported Methods } }
46.921875
159
0.592075
[ "Apache-2.0" ]
dotnetbio/bio
Tests/Bio.Tests/Algorithms/Alignment/NUCmer/NUCmerP1TestCases.cs
72,074
C#
// Copyright(c) 2019 Ken Okabe // This software is released under the MIT License, see LICENSE. using System; using Xunit; public class TunrstileTest : IDisposable { SpyTurnstileController controllerSpoof; Turnstile t; public TunrstileTest() { controllerSpoof = new SpyTurnstileController(); t = new Turnstile(controllerSpoof); } public void Dispose() { } [Fact] public void TestInitialCondtions() { Assert.Equal(Turnstile.LOCKED, t.state); } [Fact] public void TestCoinInLockedState() { t.state = Turnstile.LOCKED; t.Event(Turnstile.COIN); Assert.Equal(Turnstile.UNLOCKED, t.state); Assert.True(controllerSpoof.UnlockCalled); } [Fact] public void TestCoinInUnlockedState() { t.state = Turnstile.UNLOCKED; t.Event(Turnstile.COIN); Assert.Equal(Turnstile.UNLOCKED, t.state); Assert.True(controllerSpoof.ThankyouCalled); } [Fact] public void TestPassInLockedState() { t.state = Turnstile.LOCKED; t.Event(Turnstile.PASS); Assert.Equal(Turnstile.LOCKED, t.state); Assert.True(controllerSpoof.AlarmCalled); } [Fact] public void TestPassInUnlockedState() { t.state = Turnstile.UNLOCKED; t.Event(Turnstile.PASS); Assert.Equal(Turnstile.LOCKED, t.state); Assert.True(controllerSpoof.LockCalled); } } class SpyTurnstileController : TurnstileController { public bool LockCalled { get; private set; } = false; public bool UnlockCalled { get; private set; } = false; public bool ThankyouCalled { get; private set; } = false; public bool AlarmCalled { get; private set; } = false; public void Lock() { LockCalled = true; } public void Unlock() { UnlockCalled = true; } public void Thankyou() { ThankyouCalled = true; } public void Alarm() { AlarmCalled = true; } }
20.638889
65
0.566622
[ "MIT" ]
kokabe2/Turnstile
Turnstile/test/TurnstileTest.cs
2,229
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a method in a RetargetingModuleSymbol. Essentially this is a wrapper around /// another MethodSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal sealed class RetargetingMethodSymbol : WrappedMethodSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; /// <summary> /// The underlying MethodSymbol. /// </summary> private readonly MethodSymbol _underlyingMethod; private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; private ImmutableArray<ParameterSymbol> _lazyParameters; private CustomModifiersTuple _lazyCustomModifiers; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; /// <summary> /// Retargeted return type custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyReturnTypeCustomAttributes; private ImmutableArray<MethodSymbol> _lazyExplicitInterfaceImplementations; private DiagnosticInfo _lazyUseSiteDiagnostic = CSDiagnosticInfo.EmptyErrorInfo; // Indicates unknown state. private TypeSymbol _lazyReturnType; public RetargetingMethodSymbol(RetargetingModuleSymbol retargetingModule, MethodSymbol underlyingMethod) { Debug.Assert((object)retargetingModule != null); Debug.Assert((object)underlyingMethod != null); Debug.Assert(!(underlyingMethod is RetargetingMethodSymbol)); _retargetingModule = retargetingModule; _underlyingMethod = underlyingMethod; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public RetargetingModuleSymbol RetargetingModule { get { return _retargetingModule; } } public override MethodSymbol UnderlyingMethod { get { return _underlyingMethod; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { if (_lazyTypeParameters.IsDefault) { if (!IsGenericMethod) { _lazyTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, this.RetargetingTranslator.Retarget(_underlyingMethod.TypeParameters), default(ImmutableArray<TypeParameterSymbol>)); } } return _lazyTypeParameters; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { if (IsGenericMethod) { return StaticCast<TypeSymbol>.From(this.TypeParameters); } else { return ImmutableArray<TypeSymbol>.Empty; } } } public override bool ReturnsVoid { get { return _underlyingMethod.ReturnsVoid; } } public override TypeSymbol ReturnType { get { if ((object)_lazyReturnType == null) { var type = this.RetargetingTranslator.Retarget(_underlyingMethod.ReturnType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); _lazyReturnType = type.AsDynamicIfNoPia(this.ContainingType); } return _lazyReturnType; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return CustomModifiersTuple.TypeCustomModifiers; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return CustomModifiersTuple.RefCustomModifiers; } } private CustomModifiersTuple CustomModifiersTuple { get { return RetargetingTranslator.RetargetModifiers( _underlyingMethod.ReturnTypeCustomModifiers, _underlyingMethod.RefCustomModifiers, ref _lazyCustomModifiers); } } public override ImmutableArray<ParameterSymbol> Parameters { get { if (_lazyParameters.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, this.RetargetParameters(), default(ImmutableArray<ParameterSymbol>)); } return _lazyParameters; } } private ImmutableArray<ParameterSymbol> RetargetParameters() { var list = _underlyingMethod.Parameters; int count = list.Length; if (count == 0) { return ImmutableArray<ParameterSymbol>.Empty; } else { ParameterSymbol[] parameters = new ParameterSymbol[count]; for (int i = 0; i < count; i++) { parameters[i] = new RetargetingMethodParameterSymbol(this, list[i]); } return parameters.AsImmutableOrNull(); } } public override Symbol AssociatedSymbol { get { var associatedPropertyOrEvent = _underlyingMethod.AssociatedSymbol; return (object)associatedPropertyOrEvent == null ? null : this.RetargetingTranslator.Retarget(associatedPropertyOrEvent); } } public override Symbol ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingMethod.ContainingSymbol); } } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return _retargetingModule.RetargetingTranslator.Retarget(_underlyingMethod.ReturnValueMarshallingInformation); } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingMethod.GetAttributes(), ref _lazyCustomAttributes); } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(ModuleCompilationState compilationState) { return this.RetargetingTranslator.RetargetAttributes(_underlyingMethod.GetCustomAttributesToEmit(compilationState)); } // Get return type attributes public override ImmutableArray<CSharpAttributeData> GetReturnTypeAttributes() { return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingMethod.GetReturnTypeAttributes(), ref _lazyReturnTypeCustomAttributes); } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } internal override bool IsExplicitInterfaceImplementation { get { return _underlyingMethod.IsExplicitInterfaceImplementation; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, this.RetargetExplicitInterfaceImplementations(), default(ImmutableArray<MethodSymbol>)); } return _lazyExplicitInterfaceImplementations; } } private ImmutableArray<MethodSymbol> RetargetExplicitInterfaceImplementations() { var impls = _underlyingMethod.ExplicitInterfaceImplementations; if (impls.IsEmpty) { return impls; } // CONSIDER: we could skip the builder until the first time we see a different method after retargeting var builder = ArrayBuilder<MethodSymbol>.GetInstance(); for (int i = 0; i < impls.Length; i++) { var retargeted = this.RetargetingTranslator.Retarget(impls[i], MemberSignatureComparer.RetargetedExplicitImplementationComparer); if ((object)retargeted != null) { builder.Add(retargeted); } } return builder.ToImmutableAndFree(); } internal override DiagnosticInfo GetUseSiteDiagnostic() { if (ReferenceEquals(_lazyUseSiteDiagnostic, CSDiagnosticInfo.EmptyErrorInfo)) { DiagnosticInfo result = null; CalculateUseSiteDiagnostic(ref result); _lazyUseSiteDiagnostic = result; } return _lazyUseSiteDiagnostic; } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal override bool GenerateDebugInfo { get { return false; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { // retargeting symbols refer to a symbol from another compilation, they don't define locals in the current compilation throw ExceptionUtilities.Unreachable; } } }
33.162722
161
0.594165
[ "MIT" ]
1Crazymoney/cs2cpp
CSharpSource/Symbols/Retargeting/RetargetingMethodSymbol.cs
11,211
C#
using BTDToolbox.Lib.Json; using ICSharpCode.AvalonEdit; using ICSharpCode.AvalonEdit.Folding; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; namespace BTDToolbox.Wpf { public class JsonEditor : TextEditor { public FoldingManager FoldingMgr { get; private set; } public JsonEditor() : base() { FontSize = 16; ShowLineNumbers = true; Background = FindResource("backgroundColor") as SolidColorBrush; Foreground = FindResource("foregroundColor") as SolidColorBrush; Options.EnableRectangularSelection = true; Options.AllowScrollBelowDocument = true; Options.CutCopyWholeLine = true; Options.EnableHyperlinks = true; Options.HighlightCurrentLine = true; } public void InstallFoldingMgr() { FoldingMgr = FoldingManager.Install(TextArea); } public async Task UpdateFoldingsAsync() { FoldingMgr.Clear(); BracketPairFinder pairFinder = new BracketPairFinder(Text, '[', ']'); var pairs = await pairFinder.GetBracketPairsAsync(); for (int i = 0; i < pairs.Count; i++) { var pair = pairs.ElementAt(i); FoldingMgr.CreateFolding(pair.Key, pair.Value + 1); } pairFinder = new BracketPairFinder(Text, '{', '}'); pairs = await pairFinder.GetBracketPairsAsync(); for (int i = 0; i < pairs.Count; i++) { var pair = pairs.ElementAt(i); FoldingMgr.CreateFolding(pair.Key, pair.Value + 1); } } public void UninstallFoldingMgr() { FoldingManager.Uninstall(FoldingMgr); FoldingMgr = null; } } }
31.1
81
0.57717
[ "MIT" ]
gurrenm3/BTD-Toolbox
BTDToolbox.Wpf/Jet Stuff/JsonEditor.cs
1,868
C#
using System; using System.Collections.Generic; using Top.Api.Response; using Top.Api.Util; namespace Top.Api.Request { /// <summary> /// TOP API: taobao.fenxiao.orders.get /// </summary> public class FenxiaoOrdersGetRequest : ITopRequest<FenxiaoOrdersGetResponse> { /// <summary> /// 结束时间 格式 yyyy-MM-dd HH:mm:ss.支持到秒的查询。若不传时分秒,默认为0时0分0秒。若purchase_order_id没传,则此参数必传。 /// </summary> public Nullable<DateTime> EndCreated { get; set; } /// <summary> /// 多个字段用","分隔。 fields 如果为空:返回所有采购单对象(purchase_orders)字段。 如果不为空:返回指定采购单对象(purchase_orders)字段。 例1: sub_purchase_orders.tc_order_id 表示只返回tc_order_id 例2: sub_purchase_orders表示只返回子采购单列表 /// </summary> public string Fields { get; set; } /// <summary> /// 页码。(大于0的整数。默认为1)<br /> 支持最大值为:2147483647<br /> 支持最小值为:-21474836478 /// </summary> public Nullable<long> PageNo { get; set; } /// <summary> /// 每页条数。(每页条数不超过50条)<br /> 支持最大值为:2147483647<br /> 支持最小值为:-21474836478 /// </summary> public Nullable<long> PageSize { get; set; } /// <summary> /// 采购单编号或分销流水号,若其它参数没传,则此参数必传。<br /> 支持最大值为:9223372036854775807<br /> 支持最小值为:-9223372036854775808 /// </summary> public Nullable<long> PurchaseOrderId { get; set; } /// <summary> /// 起始时间 格式 yyyy-MM-dd HH:mm:ss.支持到秒的查询。若不传时分秒,默认为0时0分0秒。若purchase_order_id没传,则此参数必传。 /// </summary> public Nullable<DateTime> StartCreated { get; set; } /// <summary> /// 交易状态,不传默认查询所有采购单根据身份选择自身状态可选值:<br> *供应商:<br> WAIT_SELLER_SEND_GOODS(等待发货)<br> WAIT_SELLER_CONFIRM_PAY(待确认收款)<br> WAIT_BUYER_PAY(等待付款)<br> WAIT_BUYER_CONFIRM_GOODS(已发货)<br> TRADE_REFUNDING(退款中)<br> TRADE_FINISHED(采购成功)<br> TRADE_CLOSED(已关闭)<br> *分销商:<br> WAIT_BUYER_PAY(等待付款)<br> WAIT_BUYER_CONFIRM_GOODS(待收货确认)<br> TRADE_FOR_PAY(已付款)<br> TRADE_REFUNDING(退款中)<br> TRADE_FINISHED(采购成功)<br> TRADE_CLOSED(已关闭)<br> /// </summary> public string Status { get; set; } /// <summary> /// 采购单下游买家订单id /// </summary> public Nullable<long> TcOrderId { get; set; } /// <summary> /// 可选值:trade_time_type(采购单按照成交时间范围查询),update_time_type(采购单按照更新时间范围查询) /// </summary> public string TimeType { get; set; } private IDictionary<string, string> otherParameters; #region ITopRequest Members public string GetApiName() { return "taobao.fenxiao.orders.get"; } public IDictionary<string, string> GetParameters() { TopDictionary parameters = new TopDictionary(); parameters.Add("end_created", this.EndCreated); parameters.Add("fields", this.Fields); parameters.Add("page_no", this.PageNo); parameters.Add("page_size", this.PageSize); parameters.Add("purchase_order_id", this.PurchaseOrderId); parameters.Add("start_created", this.StartCreated); parameters.Add("status", this.Status); parameters.Add("tc_order_id", this.TcOrderId); parameters.Add("time_type", this.TimeType); parameters.AddAll(this.otherParameters); return parameters; } public void Validate() { RequestValidator.ValidateMaxValue("page_no", this.PageNo, 2147483647); RequestValidator.ValidateMinValue("page_no", this.PageNo, -21474836478); RequestValidator.ValidateMaxValue("page_size", this.PageSize, 2147483647); RequestValidator.ValidateMinValue("page_size", this.PageSize, -21474836478); RequestValidator.ValidateMaxValue("purchase_order_id", this.PurchaseOrderId, 9223372036854775807); RequestValidator.ValidateMinValue("purchase_order_id", this.PurchaseOrderId, -9223372036854775808); } #endregion public void AddOtherParameter(string key, string value) { if (this.otherParameters == null) { this.otherParameters = new TopDictionary(); } this.otherParameters.Add(key, value); } } }
40.133333
421
0.62767
[ "MIT" ]
objectyan/MyTools
OY.Solution/OY.TopSdk/Request/FenxiaoOrdersGetRequest.cs
4,940
C#
namespace Dufry.Comissoes.Data.Context.Interfaces { public interface IContextManager<TContext> where TContext : IDbContext, new() { IDbContext GetContext(); void Finish(); } }
21.3
50
0.647887
[ "MIT" ]
robertohermes/Comissoes
Dufry.Comissoes.Data.Context/Interfaces/IContextManager.cs
215
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIGravehagCombatLogicParams : CAIMonsterCombatLogicParams { [Ordinal(1)] [RED("mistForm")] public CBool MistForm { get; set;} [Ordinal(2)] [RED("mudThrow")] public CBool MudThrow { get; set;} [Ordinal(3)] [RED("witchSpecialAttack")] public CBool WitchSpecialAttack { get; set;} public CAIGravehagCombatLogicParams(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIGravehagCombatLogicParams(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.62069
140
0.727179
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CAIGravehagCombatLogicParams.cs
947
C#
namespace Reductech.Sequence.Core.Tests.Steps; public partial class GetVariableTests : StepTestBase<GetVariable<SCLInt>, SCLInt> { /// <inheritdoc /> protected override IEnumerable<StepCase> StepCases { get { var sequence = new Core.Steps.Sequence<Unit> { InitialSteps = new List<IStep<Unit>> { new SetVariable<SCLInt> { Variable = new VariableName("Foo"), Value = Constant(42) }, new Log { Value = new GetVariable<SCLInt> { Variable = new VariableName("Foo") } } }, FinalStep = new DoNothing() }; yield return new StepCase("Get Variable", sequence, Unit.Default, "42") .WithExpectedFinalState("Foo", 42); } } /// <inheritdoc /> protected override IEnumerable<DeserializeCase> DeserializeCases { get { yield return new DeserializeCase( "Short Form", $"- <Foo> = 42\r\n- Log Value: <Foo>", (Unit.Default), "42" ) .WithExpectedFinalState("Foo", 42); } } /// <inheritdoc /> protected override IEnumerable<SerializeCase> SerializeCases { get { yield return new SerializeCase( "Short form", new GetVariable<SCLInt>() { Variable = new VariableName("Foo") }, "<Foo>" ); } } ///// <inheritdoc /> //protected override IEnumerable<ErrorCase> ErrorCases //{ // get { yield return CreateDefaultErrorCase(false); } //} }
28.308824
83
0.451429
[ "Apache-2.0" ]
reductech/Core
Core.Tests/Steps/GetVariableTests.cs
1,927
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { private readonly ProjectInfo _projectInfo; private readonly HostLanguageServices _languageServices; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<DocumentId, DocumentState> _documentStates; private readonly ImmutableDictionary<DocumentId, TextDocumentState> _additionalDocumentStates; private readonly IReadOnlyList<DocumentId> _documentIds; private readonly IReadOnlyList<DocumentId> _additionalDocumentIds; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentVersion; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentTopLevelChangeVersion; // Checksums for this solution state private readonly ValueSource<ProjectStateChecksums> _lazyChecksums; // this will be initialized lazily. private AnalyzerOptions _analyzerOptionsDoNotAccessDirectly; private ProjectState( ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices, IEnumerable<DocumentId> documentIds, IEnumerable<DocumentId> additionalDocumentIds, ImmutableDictionary<DocumentId, DocumentState> documentStates, ImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion) { _solutionServices = solutionServices; _languageServices = languageServices; _documentIds = documentIds.ToImmutableReadOnlyListOrEmpty(); _additionalDocumentIds = additionalDocumentIds.ToImmutableReadOnlyListOrEmpty(); _documentStates = documentStates; _additionalDocumentStates = additionalDocumentStates; _lazyLatestDocumentVersion = lazyLatestDocumentVersion; _lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecesarily by projectInfo even after // the info has changed by DocumentState. _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfo); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices) { Contract.ThrowIfNull(projectInfo); Contract.ThrowIfNull(languageServices); Contract.ThrowIfNull(solutionServices); _languageServices = languageServices; _solutionServices = solutionServices; var projectInfoFixed = FixProjectInfo(projectInfo); _documentIds = projectInfoFixed.Documents.Select(d => d.Id).ToImmutableArray(); _additionalDocumentIds = projectInfoFixed.AdditionalDocuments.Select(d => d.Id).ToImmutableArray(); var parseOptions = projectInfoFixed.ParseOptions; var docStates = ImmutableDictionary.CreateRange<DocumentId, DocumentState>( projectInfoFixed.Documents.Select(d => new KeyValuePair<DocumentId, DocumentState>(d.Id, CreateDocument(d, parseOptions, languageServices, solutionServices)))); _documentStates = docStates; var additionalDocStates = ImmutableDictionary.CreateRange<DocumentId, TextDocumentState>( projectInfoFixed.AdditionalDocuments.Select(d => new KeyValuePair<DocumentId, TextDocumentState>(d.Id, TextDocumentState.Create(d, solutionServices)))); _additionalDocumentStates = additionalDocStates; _lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(docStates, additionalDocStates, c), cacheResult: true); _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(docStates, additionalDocStates, c), cacheResult: true); // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecesarily by projectInfo even after // the info has changed by DocumentState. // we hold onto the info so that we don't need to duplicate all information info already has in the state _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } private static ProjectInfo ClearAllDocumentsFromProjectInfo(ProjectInfo projectInfo) { return projectInfo.WithDocuments(ImmutableArray<DocumentInfo>.Empty).WithAdditionalDocuments(ImmutableArray<DocumentInfo>.Empty); } private ProjectInfo FixProjectInfo(ProjectInfo projectInfo) { if (projectInfo.CompilationOptions == null) { var compilationFactory = _languageServices.GetService<ICompilationFactoryService>(); if (compilationFactory != null) { projectInfo = projectInfo.WithCompilationOptions(compilationFactory.GetDefaultCompilationOptions()); } } if (projectInfo.ParseOptions == null) { var syntaxTreeFactory = _languageServices.GetService<ISyntaxTreeFactoryService>(); if (syntaxTreeFactory != null) { projectInfo = projectInfo.WithParseOptions(syntaxTreeFactory.GetDefaultParseOptions()); } } return projectInfo; } private static async Task<VersionStamp> ComputeLatestDocumentVersionAsync(ImmutableDictionary<DocumentId, DocumentState> documentStates, ImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var doc in documentStates.Values) { cancellationToken.ThrowIfCancellationRequested(); if (!doc.IsGenerated) { var version = await doc.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } } foreach (var additionalDoc in additionalDocumentStates.Values) { cancellationToken.ThrowIfCancellationRequested(); var version = await additionalDoc.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } private AsyncLazy<VersionStamp> CreateLazyLatestDocumentTopLevelChangeVersion( TextDocumentState newDocument, ImmutableDictionary<DocumentId, DocumentState> newDocumentStates, ImmutableDictionary<DocumentId, TextDocumentState> newAdditionalDocumentStates) { if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion)) { return new AsyncLazy<VersionStamp>(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true); } else { return new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true); } } private static async Task<VersionStamp> ComputeTopLevelChangeTextVersionAsync(VersionStamp oldVersion, TextDocumentState newDocument, CancellationToken cancellationToken) { var newVersion = await newDocument.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); return newVersion.GetNewerVersion(oldVersion); } private static async Task<VersionStamp> ComputeLatestDocumentTopLevelChangeVersionAsync(ImmutableDictionary<DocumentId, DocumentState> documentStates, ImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var doc in documentStates.Values) { cancellationToken.ThrowIfCancellationRequested(); var version = await doc.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } foreach (var additionalDoc in additionalDocumentStates.Values) { cancellationToken.ThrowIfCancellationRequested(); var version = await additionalDoc.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } private static DocumentState CreateDocument(DocumentInfo documentInfo, ParseOptions parseOptions, HostLanguageServices languageServices, SolutionServices solutionServices) { var doc = DocumentState.Create(documentInfo, parseOptions, languageServices, solutionServices); if (doc.SourceCodeKind != documentInfo.SourceCodeKind) { doc = doc.UpdateSourceCodeKind(documentInfo.SourceCodeKind); } return doc; } public AnalyzerOptions AnalyzerOptions { get { if (_analyzerOptionsDoNotAccessDirectly == null) { _analyzerOptionsDoNotAccessDirectly = new AnalyzerOptions(_additionalDocumentStates.Values.Select(d => new AdditionalTextDocument(d)).ToImmutableArray<AdditionalText>()); } return _analyzerOptionsDoNotAccessDirectly; } } private static AnalyzerOptions CreateAnalyzerOptions(ImmutableDictionary<DocumentId, TextDocumentState> additionalDocStates) { return new AnalyzerOptions(additionalDocStates.Values.Select(d => new AdditionalTextDocument(d)).ToImmutableArray<AdditionalText>()); } public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken) { return _lazyLatestDocumentVersion.GetValueAsync(cancellationToken); } public Task<VersionStamp> GetLatestDocumentTopLevelChangeVersionAsync(CancellationToken cancellationToken) { return _lazyLatestDocumentTopLevelChangeVersion.GetValueAsync(cancellationToken); } public async Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default(CancellationToken)) { var docVersion = await this.GetLatestDocumentTopLevelChangeVersionAsync(cancellationToken).ConfigureAwait(false); return docVersion.GetNewerVersion(this.Version); } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectId Id => this.ProjectInfo.Id; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string FilePath => this.ProjectInfo.FilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string OutputFilePath => this.ProjectInfo.OutputFilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public HostLanguageServices LanguageServices => _languageServices; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Language => LanguageServices.Language; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Name => this.ProjectInfo.Name; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool IsSubmission => this.ProjectInfo.IsSubmission; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public Type HostObjectType => this.ProjectInfo.HostObjectType; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public VersionStamp Version => this.ProjectInfo.Version; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectInfo ProjectInfo => _projectInfo; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string AssemblyName => this.ProjectInfo.AssemblyName; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public CompilationOptions CompilationOptions => this.ProjectInfo.CompilationOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ParseOptions ParseOptions => this.ProjectInfo.ParseOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<MetadataReference> MetadataReferences => this.ProjectInfo.MetadataReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<AnalyzerReference> AnalyzerReferences => this.ProjectInfo.AnalyzerReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<ProjectReference> ProjectReferences => this.ProjectInfo.ProjectReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool HasAllInformation => this.ProjectInfo.HasAllInformation; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool HasDocuments => _documentIds.Count > 0; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IEnumerable<DocumentState> OrderedDocumentStates => this.DocumentIds.Select(GetDocumentState); [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<DocumentId> DocumentIds => _documentIds; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<DocumentId> AdditionalDocumentIds => _additionalDocumentIds; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ImmutableDictionary<DocumentId, DocumentState> DocumentStates => _documentStates; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ImmutableDictionary<DocumentId, TextDocumentState> AdditionalDocumentStates => _additionalDocumentStates; public bool ContainsDocument(DocumentId documentId) { return _documentStates.ContainsKey(documentId); } public bool ContainsAdditionalDocument(DocumentId documentId) { return _additionalDocumentStates.ContainsKey(documentId); } public DocumentState GetDocumentState(DocumentId documentId) { _documentStates.TryGetValue(documentId, out var state); return state; } public TextDocumentState GetAdditionalDocumentState(DocumentId documentId) { _additionalDocumentStates.TryGetValue(documentId, out var state); return state; } private ProjectState With( ProjectInfo projectInfo = null, ImmutableArray<DocumentId> documentIds = default(ImmutableArray<DocumentId>), ImmutableArray<DocumentId> additionalDocumentIds = default(ImmutableArray<DocumentId>), ImmutableDictionary<DocumentId, DocumentState> documentStates = null, ImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates = null, AsyncLazy<VersionStamp> latestDocumentVersion = null, AsyncLazy<VersionStamp> latestDocumentTopLevelChangeVersion = null) { return new ProjectState( projectInfo ?? _projectInfo, _languageServices, _solutionServices, documentIds.IsDefault ? _documentIds : documentIds, additionalDocumentIds.IsDefault ? _additionalDocumentIds : additionalDocumentIds, documentStates ?? _documentStates, additionalDocumentStates ?? _additionalDocumentStates, latestDocumentVersion ?? _lazyLatestDocumentVersion, latestDocumentTopLevelChangeVersion ?? _lazyLatestDocumentTopLevelChangeVersion); } public ProjectState UpdateName(string name) { if (name == this.Name) { return this; } return this.With(projectInfo: this.ProjectInfo.WithName(name).WithVersion(this.Version.GetNewerVersion())); } public ProjectState UpdateFilePath(string filePath) { if (filePath == this.FilePath) { return this; } return this.With(projectInfo: this.ProjectInfo.WithFilePath(filePath).WithVersion(this.Version.GetNewerVersion())); } public ProjectState UpdateAssemblyName(string assemblyName) { if (assemblyName == this.AssemblyName) { return this; } return this.With(projectInfo: this.ProjectInfo.WithAssemblyName(assemblyName).WithVersion(this.Version.GetNewerVersion())); } public ProjectState UpdateOutputPath(string outputFilePath) { if (outputFilePath == this.OutputFilePath) { return this; } return this.With(projectInfo: this.ProjectInfo.WithOutputFilePath(outputFilePath).WithVersion(this.Version.GetNewerVersion())); } public ProjectState UpdateCompilationOptions(CompilationOptions options) { if (options == this.CompilationOptions) { return this; } return this.With(projectInfo: this.ProjectInfo.WithCompilationOptions(options).WithVersion(this.Version.GetNewerVersion())); } public ProjectState UpdateParseOptions(ParseOptions options) { if (options == this.ParseOptions) { return this; } // update parse options for all documents too var docMap = _documentStates; foreach (var docId in _documentStates.Keys) { var oldDocState = this.GetDocumentState(docId); var newDocState = oldDocState.UpdateParseOptions(options); docMap = docMap.SetItem(docId, newDocState); } return this.With( projectInfo: this.ProjectInfo.WithParseOptions(options).WithVersion(this.Version.GetNewerVersion()), documentStates: docMap); } public ProjectState UpdateHasAllInformation(bool hasAllInformation) { if (hasAllInformation == this.HasAllInformation) { return this; } return this.With(projectInfo: this.ProjectInfo.WithHasAllInformation(hasAllInformation).WithVersion(this.Version.GetNewerVersion())); } public static bool IsSameLanguage(ProjectState project1, ProjectState project2) { return project1.LanguageServices == project2.LanguageServices; } public ProjectState AddProjectReference(ProjectReference projectReference) { Contract.Requires(!this.ProjectReferences.Contains(projectReference)); return this.With( projectInfo: this.ProjectInfo.WithProjectReferences(this.ProjectReferences.ToImmutableArray().Add(projectReference)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState RemoveProjectReference(ProjectReference projectReference) { Contract.Requires(this.ProjectReferences.Contains(projectReference)); return this.With( projectInfo: this.ProjectInfo.WithProjectReferences(this.ProjectReferences.ToImmutableArray().Remove(projectReference)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddProjectReferences(IEnumerable<ProjectReference> projectReferences) { var newProjectRefs = this.ProjectReferences; foreach (var projectReference in projectReferences) { Contract.Requires(!newProjectRefs.Contains(projectReference)); newProjectRefs = newProjectRefs.ToImmutableArray().Add(projectReference); } return this.With( projectInfo: this.ProjectInfo.WithProjectReferences(newProjectRefs).WithVersion(this.Version.GetNewerVersion())); } public ProjectState WithProjectReferences(IEnumerable<ProjectReference> projectReferences) { return this.With( projectInfo: this.ProjectInfo.WithProjectReferences(projectReferences).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddMetadataReference(MetadataReference toMetadata) { Contract.Requires(!this.MetadataReferences.Contains(toMetadata)); return this.With( projectInfo: this.ProjectInfo.WithMetadataReferences(this.MetadataReferences.ToImmutableArray().Add(toMetadata)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState RemoveMetadataReference(MetadataReference toMetadata) { Contract.Requires(this.MetadataReferences.Contains(toMetadata)); return this.With( projectInfo: this.ProjectInfo.WithMetadataReferences(this.MetadataReferences.ToImmutableArray().Remove(toMetadata)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences) { var newMetaRefs = this.MetadataReferences; foreach (var metadataReference in metadataReferences) { Contract.Requires(!newMetaRefs.Contains(metadataReference)); newMetaRefs = newMetaRefs.ToImmutableArray().Add(metadataReference); } return this.With( projectInfo: this.ProjectInfo.WithMetadataReferences(newMetaRefs).WithVersion(this.Version.GetNewerVersion())); } public ProjectState WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences) { return this.With( projectInfo: this.ProjectInfo.WithMetadataReferences(metadataReferences).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddAnalyzerReference(AnalyzerReference analyzerReference) { Contract.Requires(!this.AnalyzerReferences.Contains(analyzerReference)); return this.With( projectInfo: this.ProjectInfo.WithAnalyzerReferences(this.AnalyzerReferences.ToImmutableArray().Add(analyzerReference)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { Contract.Requires(this.AnalyzerReferences.Contains(analyzerReference)); return this.With( projectInfo: this.ProjectInfo.WithAnalyzerReferences(this.AnalyzerReferences.ToImmutableArray().Remove(analyzerReference)).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) { var newAnalyzerReferences = this.AnalyzerReferences; foreach (var analyzerReference in analyzerReferences) { Contract.Requires(!newAnalyzerReferences.Contains(analyzerReference)); newAnalyzerReferences = newAnalyzerReferences.ToImmutableArray().Add(analyzerReference); } return this.With( projectInfo: this.ProjectInfo.WithAnalyzerReferences(newAnalyzerReferences).WithVersion(this.Version.GetNewerVersion())); } public ProjectState WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) { return this.With( projectInfo: this.ProjectInfo.WithAnalyzerReferences(analyzerReferences).WithVersion(this.Version.GetNewerVersion())); } public ProjectState AddDocument(DocumentState document) { Contract.Requires(!this.DocumentStates.ContainsKey(document.Id)); return this.With( projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()), documentIds: this.DocumentIds.ToImmutableArray().Add(document.Id), documentStates: this.DocumentStates.Add(document.Id, document)); } public ProjectState AddAdditionalDocument(TextDocumentState document) { Contract.Requires(!this.AdditionalDocumentStates.ContainsKey(document.Id)); return this.With( projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()), additionalDocumentIds: this.AdditionalDocumentIds.ToImmutableArray().Add(document.Id), additionalDocumentStates: this.AdditionalDocumentStates.Add(document.Id, document)); } public ProjectState RemoveDocument(DocumentId documentId) { Contract.Requires(this.DocumentStates.ContainsKey(documentId)); return this.With( projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()), documentIds: this.DocumentIds.ToImmutableArray().Remove(documentId), documentStates: this.DocumentStates.Remove(documentId)); } public ProjectState RemoveAdditionalDocument(DocumentId documentId) { Contract.Requires(this.AdditionalDocumentStates.ContainsKey(documentId)); return this.With( projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()), additionalDocumentIds: this.AdditionalDocumentIds.ToImmutableArray().Remove(documentId), additionalDocumentStates: this.AdditionalDocumentStates.Remove(documentId)); } public ProjectState RemoveAllDocuments() { return this.With( projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()).WithDocuments(SpecializedCollections.EmptyEnumerable<DocumentInfo>()), documentIds: ImmutableArray.Create<DocumentId>(), documentStates: ImmutableDictionary<DocumentId, DocumentState>.Empty); } public ProjectState UpdateDocument(DocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { Contract.Requires(this.ContainsDocument(newDocument.Id)); var oldDocument = this.GetDocumentState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = this.DocumentStates.SetItem(newDocument.Id, newDocument); GetLatestDependentVersions( newDocumentStates, _additionalDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return this.With( documentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } public ProjectState UpdateAdditionalDocument(TextDocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { Contract.Requires(this.ContainsAdditionalDocument(newDocument.Id)); var oldDocument = this.GetAdditionalDocumentState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = this.AdditionalDocumentStates.SetItem(newDocument.Id, newDocument); GetLatestDependentVersions( _documentStates, newDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return this.With( additionalDocumentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } private void GetLatestDependentVersions( ImmutableDictionary<DocumentId, DocumentState> newDocumentStates, ImmutableDictionary<DocumentId, TextDocumentState> newAdditionalDocumentStates, TextDocumentState oldDocument, TextDocumentState newDocument, bool recalculateDependentVersions, bool textChanged, out AsyncLazy<VersionStamp> dependentDocumentVersion, out AsyncLazy<VersionStamp> dependentSemanticVersion) { var recalculateDocumentVersion = false; var recalculateSemanticVersion = false; if (recalculateDependentVersions) { if (oldDocument.TryGetTextVersion(out var oldVersion)) { if (!_lazyLatestDocumentVersion.TryGetValue(out var documentVersion) || documentVersion == oldVersion) { recalculateDocumentVersion = true; } if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var semanticVersion) || semanticVersion == oldVersion) { recalculateSemanticVersion = true; } } } dependentDocumentVersion = recalculateDocumentVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? new AsyncLazy<VersionStamp>(newDocument.GetTextVersionAsync, cacheResult: true) : _lazyLatestDocumentVersion; dependentSemanticVersion = recalculateSemanticVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? CreateLazyLatestDocumentTopLevelChangeVersion(newDocument, newDocumentStates, newAdditionalDocumentStates) : _lazyLatestDocumentTopLevelChangeVersion; } } }
46.835036
272
0.686179
[ "Apache-2.0" ]
DanMcNultyDev/roslyn
src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs
32,084
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type DeviceManagementResourceAccessProfileBaseAssignCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class DeviceManagementResourceAccessProfileBaseAssignCollectionResponse { /// <summary> /// Gets or sets the <see cref="IDeviceManagementResourceAccessProfileBaseAssignCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Required.Default)] public IDeviceManagementResourceAccessProfileBaseAssignCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
42.4
153
0.634097
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/DeviceManagementResourceAccessProfileBaseAssignCollectionResponse.cs
1,484
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ContainerRegistry.V20170601Preview.Outputs { /// <summary> /// The registry node that generated the event. Put differently, while the actor initiates the event, the source generates it. /// </summary> [OutputType] public sealed class SourceResponse { /// <summary> /// The IP or hostname and the port of the registry node that generated the event. Generally, this will be resolved by os.Hostname() along with the running port. /// </summary> public readonly string? Addr; /// <summary> /// The running instance of an application. Changes after each restart. /// </summary> public readonly string? InstanceID; [OutputConstructor] private SourceResponse( string? addr, string? instanceID) { Addr = addr; InstanceID = instanceID; } } }
31.692308
169
0.648058
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ContainerRegistry/V20170601Preview/Outputs/SourceResponse.cs
1,236
C#
using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Abp.Runtime.Security; namespace PWD.Schedule.Web.Host.Startup { public static class AuthConfigurer { public static void Configure(IServiceCollection services, IConfiguration configuration) { if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"])) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }).AddJwtBearer("JwtBearer", options => { options.Audience = configuration["Authentication:JwtBearer:Audience"]; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = configuration["Authentication:JwtBearer:Issuer"], // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = configuration["Authentication:JwtBearer:Audience"], // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here ClockSkew = TimeSpan.Zero }; options.Events = new JwtBearerEvents { OnMessageReceived = QueryStringTokenResolver }; }); } } /* This method is needed to authorize SignalR javascript client. * SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */ private static Task QueryStringTokenResolver(MessageReceivedContext context) { if (!context.HttpContext.Request.Path.HasValue || !context.HttpContext.Request.Path.Value.StartsWith("/signalr")) { // We are just looking for signalr clients return Task.CompletedTask; } var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault(); if (qsAuthToken == null) { // Cookie value does not matches to querystring value return Task.CompletedTask; } // Set auth token from cookie context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase); return Task.CompletedTask; } } }
41.101266
148
0.582384
[ "MIT" ]
Faridium/pwd.schedule
src/PWD.Schedule.Web.Host/Startup/AuthConfigurer.cs
3,249
C#
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `bool`. Inherits from `AtomEventReferenceListener&lt;bool, BoolEvent, BoolEventReference, BoolUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/Bool Event Reference Listener")] public sealed class BoolEventReferenceListener : AtomEventReferenceListener< bool, BoolEvent, BoolEventReference, BoolUnityEvent> { } }
31.352941
151
0.705441
[ "MIT" ]
AdamRamberg/unity-atoms
Packages/BaseAtoms/Runtime/EventReferenceListeners/BoolEventReferenceListener.cs
533
C#
//--------------------------------------------------------------------------- // // <copyright file=IUndoUnit.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // // See spec at http://avalon/uis/Stock%20Services/Undo%20spec.htm // // History: // 07/21/2003 : psarrett ported to WCP tree // //--------------------------------------------------------------------------- using System; namespace MS.Internal.Documents { /// <summary> /// IUndoUnit interface /// </summary> /// internal interface IUndoUnit { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Perform the appropriate action for this unit. If this is a parent undo unit, the /// parent must create an appropriate parent undo unit to contain the redo units. /// </summary> void Do(); /// <summary> /// Attempt to merge the given undo unit with this unit. /// Merge is typically called by a ParentUndoUnit's Add() method. If the merge /// succeeds, the parent should not add the merged unit. /// </summary> /// <param name="unit">Unit to merge into this one</param> /// <returns> /// true if unit was merged. /// false otherwise /// </returns> bool Merge(IUndoUnit unit); #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ //------------------------------------------------------ // // Protected Properties // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ } }
29.217742
93
0.255589
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Framework/MS/Internal/Documents/IUndoUnit.cs
3,623
C#
using CadEditor; using System; //css_include shared_settings/BlockUtils.cs; //css_include shared_settings/SharedUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x10810, 20, 16*15, 16, 15); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk("chr4.bin"); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x10110, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0x10710; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksAlignedWithSeparatePal;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksAlignedWithSeparatePal;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal4.bin"}); } public SetPalFunc setPalFunc() { return null;} }
49.857143
111
0.706304
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/breakthru/Settings_BreakThru-4.cs
1,396
C#
using Autodesk.Revit.DB; using Autodesk.Revit.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RvtElectrical { public class DeviceBox { public IList<Element> Box { get; private set; } //Stores element reference in DeviceBox public IList<DeviceConnector> Connectors { get; private set; } //List of Connector Elements public int BoxId { get; private set; } //Box ID Integer public DeviceId DeviceId { get; private set; } //Device ID Value public System System { get; private set; } //Device Box System public string Venue { get; private set; } //Venue Value public string PlateCode { get; private set; } //public DeviceBox(Document doc, IList<Element> elements) ////OLD CONSTRUCTOR - NO LONGER USED //{ // // Get GUID Values for Shared Parameters // Guid boxIdGuid = TCCElecSettings.BoxIdGuid; // Guid venueIdGuid = TCCElecSettings.VenueGuid; // //Assign Elements to Box Property // Box = elements; // this.Connectors = new List<DeviceConnector>(); // try // { // //Find Faceplate Element // foreach (Element ele in elements) // { // DeviceId deviceId = new DeviceId(DeviceId.GetDeviceId(ele, doc)); // if (deviceId.IsFaceplate()) // { // DeviceId = deviceId; // System = deviceId.System; // BoxId = ele.get_Parameter(boxIdGuid).AsInteger(); // Venue = ele.get_Parameter(venueIdGuid).AsString(); // } // //If not the plate, add connectors to the Connector list // else // { // Connectors.Add(new DeviceConnector(ele, Venue, doc)); // } // } // //If no faceplate is found, return exception // if (DeviceId == null) // { // Exception ex = new Exception("No Plate ID Passed"); // } // } // catch (Exception ex) // { // throw ex; // } //} public DeviceBox(Document doc, Element ele) //Constructor { // Get GUID Values for Shared Parameters Guid boxIdGuid = TCCElecSettings.BoxIdGuid; Guid venueIdGuid = TCCElecSettings.VenueGuid; this.Connectors = new List<DeviceConnector>(); try { IList<Element> boxElements = new List<Element>(); //Test that this is a devicebox if (!IsDeviceBox(ele, doc)) throw new Exception(); //Assign Faceplate Element DeviceId deviceId = new DeviceId(DeviceId.GetDeviceId(ele, doc)); if (deviceId.IsFaceplate()) { DeviceId = deviceId; System = deviceId.System; BoxId = ele.get_Parameter(boxIdGuid).AsInteger(); Venue = ele.get_Parameter(venueIdGuid).AsString(); ElementType etype = doc.GetElement(ele.GetTypeId()) as ElementType; PlateCode = etype.get_Parameter(TCCElecSettings.PlateCodeGuid).AsString(); //Add main device element to box parameters boxElements.Add(ele); } //Get SubComponents FamilyInstance eleFam = ele as FamilyInstance; IList<ElementId> subComponentIds = (IList<ElementId>)eleFam.GetSubComponentIds(); if (subComponentIds.Count() > 0) { //Get elements from elementIds IList<Element> subComponents = new List<Element>(); foreach(ElementId eid in subComponentIds) { subComponents.Add(doc.GetElement(eid)); } foreach(Element subcomponent in subComponents) { if (null != subcomponent.get_Parameter(boxIdGuid)) { //Add elements as connectors Connectors.Add(new DeviceConnector(subcomponent, Venue, doc)); //Add elements to Box Parameter list of elements boxElements.Add(subcomponent); } //Get Subconnectors if they exist FamilyInstance subEleFam = subcomponent as FamilyInstance; IList<ElementId> subConnectorIds = (IList<ElementId>)subEleFam.GetSubComponentIds(); if (subConnectorIds.Count() > 0) { IList<Element> subConnectors = new List<Element>(); foreach (ElementId seid in subConnectorIds) { subConnectors.Add(doc.GetElement(seid)); } foreach (Element subConnector in subConnectors) { if (null != subConnector.get_Parameter(boxIdGuid)) { //Add elements as connectors Connectors.Add(new DeviceConnector(subConnector, Venue, doc)); //Add elements to Box Parameter list of elements boxElements.Add(subConnector); } } } } //Assign elements to Box Parameter for element access Box = boxElements; } //If no faceplate is found, return exception if (DeviceId == null) { Exception ex = new Exception("No Plate ID Passed"); } } catch (Exception ex) { throw ex; } } public void UpdateDeviceBoxConcat() // Filters through a Device Box's connectors to consolidate connector circuits { List<int> uniqueDeviceIds = new List<int>(); //Find the unique connector types to combine. //This is based on the specific Device ID value //Note that this will only combine specific connectors, not necessarily signal types //Identify if any devices are multi-connectors //If they are, change their Device ID to match the first connector they contain foreach (DeviceConnector connector in Connectors) { if (connector.DeviceId.IsMultConnector()) { connector.ChangeConnectorId(DeviceConnector.GetMultConnectorSubId(Connectors, connector.ConnectorPosition)); } } //Locate the unique connector IDs in the box foreach (DeviceConnector connector in Connectors) { uniqueDeviceIds.Add(connector.DeviceId.Value); } uniqueDeviceIds = uniqueDeviceIds.Distinct().ToList(); //Iterate through the unique Ids and create list of circuits of the same connector ID foreach(int uniqueDeviceId in uniqueDeviceIds) { //Get all connectors with the unique deviceid var tempConnectors = new List<DeviceConnector>(); foreach (DeviceConnector connector in Connectors) { if (connector.DeviceId.Value == uniqueDeviceId) { tempConnectors.Add(connector); } } if (tempConnectors.Count > 0) { //Find if connectors have unique prefixes var uniquePrefixes = new List<string>(); foreach (DeviceConnector connector in tempConnectors) { uniquePrefixes.Add(connector.ConnectorLabelPrefix); } uniquePrefixes = uniquePrefixes.Distinct().ToList(); //Create concat label for each connector with a unique prefix foreach(string prefix in uniquePrefixes) { var connectorCircuits = new List<int>(); string concatConnector = ""; foreach (DeviceConnector connector in tempConnectors) { if(connector.ConnectorLabelPrefix == prefix) { if(connector.ConnectorCircuit != 0) connectorCircuits.Add(connector.ConnectorCircuit); } } if(connectorCircuits.Count()>0) concatConnector = ElecUtils.CircuitListToString(connectorCircuits, prefix); foreach (DeviceConnector connector in tempConnectors) { if (connector.ConnectorLabelPrefix == prefix) { if(connector.ConnectorLabelOther == null || connector.ConnectorLabelOther == "") { connector.UpdateConnectorConcat(concatConnector); } else connector.UpdateConnectorConcat(connector.ConnectorLabelOther); } } } } } return; } public static IList<DeviceBox> GetDeviceBoxes(Document doc) { var deviceBoxes = FilterAllDeviceBoxes(doc); return deviceBoxes; } public static IList<DeviceBox> GetDeviceBoxes(Document doc, System deviceScope) //Get Device Boxes based on devices having a specific system scope { //Get all deviceboxes in model var deviceBoxes = FilterAllDeviceBoxes(doc); //If a device box contains a connector of the selected system //then change the scope of that devicebox to match the system deviceBoxes = ChangeDeviceBoxToConnectorScope(deviceBoxes, deviceScope); //Use Linq query to filter by System List<DeviceBox> filteredDeviceBoxes = deviceBoxes .Where(db => db.System == deviceScope) .ToList(); return filteredDeviceBoxes; } private static IList<DeviceBox> ChangeDeviceBoxToConnectorScope(IList<DeviceBox> deviceBoxes, System deviceScope) { var updatedDeviceBoxes = new List<DeviceBox>(); foreach(var deviceBox in deviceBoxes) { IList<DeviceConnector> connectors = deviceBox.Connectors .Where(dc => dc.System == deviceScope) .ToList(); if(deviceBox.System != deviceScope && connectors.Count > 0) { deviceBox.System = deviceScope; } updatedDeviceBoxes.Add(deviceBox); } return updatedDeviceBoxes; } private static IList<DeviceBox> FilterAllDeviceBoxes(Document doc) //Get all device boxes in model { //Get BoxIdGuid Guid boxIdGuid = TCCElecSettings.BoxIdGuid; Guid deviceIdGuid = TCCElecSettings.DeviceIdGuid; //Create Filtered Element Collector & Filter for Electrical Fixtures FilteredElementCollector collector = new FilteredElementCollector(doc); ElementQuickFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures); //Apply Filter IList<Element> devices = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); IList<Element> filteredDevices = devices .Where(d => d.get_Parameter(boxIdGuid) != null) .Where(d => d.get_Parameter(deviceIdGuid) != null) //.Where(d => (d as FamilyInstance).SuperComponent == null) .Where(d => IsDeviceBox(d, doc)) .ToList(); List<DeviceBox> deviceBoxes = new List<DeviceBox>(); foreach (Element device in filteredDevices) { deviceBoxes.Add(new DeviceBox(doc, device)); } return deviceBoxes; } //OLD VERSION - SEE ABOVE //private static IList<DeviceBox> FilterAllDeviceBoxes(Document doc) ////Get all device boxes in model //{ // //Get BoxIdGuid // Guid boxIdGuid = TCCElecSettings.BoxIdGuid; // Guid deviceIdGuid = TCCElecSettings.DeviceIdGuid; // //Create Filtered Element Collector & Filter for Electrical Fixtures // FilteredElementCollector collector = new FilteredElementCollector(doc); // ElementQuickFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures); // //Apply Filter // IList<Element> devices = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); // IList<Element> filteredDevices = devices // .Where(d => d.get_Parameter(boxIdGuid) != null) // .Where(d => d.get_Parameter(deviceIdGuid) != null) // .ToList(); // //Create List to capture Boxes and distinct Box numbers // IList<int> boxNumbers = new List<int>(); // foreach (Element device in filteredDevices) // { // boxNumbers.Add(device.get_Parameter(boxIdGuid).AsInteger()); // } // boxNumbers = boxNumbers.Distinct().ToList(); // List<DeviceBox> deviceBoxes = new List<DeviceBox>(); // foreach (int targetBoxNumber in boxNumbers) // { // //Retrieve device plate and connectors for a specific box number // IList<Element> box = ElecUtils.CollectDeviceByBoxNumber(filteredDevices, targetBoxNumber); // //Create a new DeviceBox // deviceBoxes.Add(new DeviceBox(doc, box)); // } // return deviceBoxes; //} public static IList<DeviceBox> FilterBoxByVenue(IList<DeviceBox> deviceBoxes, string venue) { IList<DeviceBox> venueBoxes = new List<DeviceBox>(); foreach (DeviceBox deviceBox in deviceBoxes) { if(deviceBox.Venue == venue) venueBoxes.Add(deviceBox); } return venueBoxes; } public static IList<DeviceBox> GetDuplicateDeviceBoxes(Document doc, int boxNumber) //Provides a list of deviceboxes based on the box number. { IList<DeviceBox> deviceBoxes = GetDeviceBoxes(doc); IList<DeviceBox> filteredDB = deviceBoxes .Where(d => d.BoxId == boxNumber) .ToList(); return filteredDB; } public static IList<DeviceBox> GetDuplicateDeviceBoxes(Document doc) //Searches the project and returns DeviceBoxes where there are duplicates in the project. { IList<DeviceBox> deviceBoxes = GetDeviceBoxes(doc); IList<DeviceBox> duplicateDeviceBoxes = new List<DeviceBox>(); foreach(DeviceBox db in deviceBoxes) { IList<DeviceBox> filteredDB = deviceBoxes .Where(d => d.BoxId == db.BoxId) .ToList(); if (filteredDB.Count > 1) foreach(DeviceBox fdb in filteredDB) { duplicateDeviceBoxes.Add(fdb); } } return duplicateDeviceBoxes; } public static bool IsDeviceBox(Element ele, Document doc) //Receives an element and determins whether it is a DeviceBox capable family { bool isDB = false; //Determine if the element is a family instance FamilyInstance fi; if (!(ele is FamilyInstance)) return isDB; //Get DeviceID and test if it is a devicebox try { DeviceId deviceId = new DeviceId(DeviceId.GetDeviceId(ele, doc)); if (deviceId.IsDeviceBox()) isDB = true; } catch { } return isDB; } public static int NextDeviceBoxNumber(int boxNumber, Document doc) //Returns the next available devicebox in a document //Returns the original box number if it is unused { int nextBox = boxNumber; bool found = true; //Get all device boxes IList<DeviceBox> deviceBoxes = GetDeviceBoxes(doc); do { IList<DeviceBox> filteredDeviceBoxes = deviceBoxes .Where(d => d.BoxId == nextBox) .ToList(); //If no devicebox with this number exists, return the box number if (filteredDeviceBoxes.Count() == 0) found = true; else { found = false; nextBox++; } } while (found == false); return nextBox; } } }
39.748918
128
0.509693
[ "MIT" ]
jtprichard/RvtTCC2021
RvtElectrical/DeviceBox.cs
18,366
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using Hg.DoomHistory.Properties; using Hg.DoomHistory.Types; namespace Hg.DoomHistory.Managers { public delegate void SettingEventHandler(); public class SettingManager { #region Fields & Properties public event SettingEventHandler BackupFolderChanged; public event SettingEventHandler HotKeysActiveChanged; public event SettingEventHandler HotKeysSoundChanged; public event SettingEventHandler NotificationModeChanged; public event SettingEventHandler SavedGameFolderChanged; public event SettingEventHandler ScreenshotQualityChanged; public event SettingEventHandler SortKindChanged; public event SettingEventHandler SortOrderChanged; private string _backupFolder; private bool _hotKeysActive; private bool _hotKeysSound; private MessageMode _notificationMode; private string _savedGameFolder; private ScreenshotQuality _screenshotQuality; private SortKind _sortKind; private SortOrder _sortOrder; public string BackupFolder { get => _backupFolder; set { _backupFolder = value; BackupFolderChanged?.Invoke(); } } public bool HotKeysActive { get => _hotKeysActive; set { _hotKeysActive = value; HotKeysActiveChanged?.Invoke(); } } public bool HotKeysSound { get => _hotKeysSound; set { _hotKeysSound = value; HotKeysSoundChanged?.Invoke(); } } public List<HotKeyToAction> HotKeyToActions { get; set; } public MessageMode NotificationMode { get => _notificationMode; set { _notificationMode = value; NotificationModeChanged?.Invoke(); } } public string SavedGameFolder { get => _savedGameFolder; set { _savedGameFolder = value; SavedGameFolderChanged?.Invoke(); } } public ScreenshotQuality ScreenshotQuality { get => _screenshotQuality; set { _screenshotQuality = value; ScreenshotQualityChanged?.Invoke(); } } public SortKind SortKind { get => _sortKind; set { _sortKind = value; SortKindChanged?.Invoke(); } } public SortOrder SortOrder { get => _sortOrder; set { _sortOrder = value; SortOrderChanged?.Invoke(); } } #endregion #region Members public SettingManager() { HotKeyToActions = new List<HotKeyToAction>(); ResetSettings(); } public void LoadSettings() { BackupFolder = Settings.Default.BackupFolder; SavedGameFolder = Settings.Default.SavedGameFolder; NotificationMode = (MessageMode) Settings.Default.NotificationMode; ScreenshotQuality = (ScreenshotQuality) Settings.Default.ScreenshotQuality; SortOrder = (SortOrder) Settings.Default.SortOrder; SortKind = (SortKind) Settings.Default.SortKind; HotKeysActive = Settings.Default.HotKeysActive; HotKeysSound = Settings.Default.HotKeysSound; if (NotificationMode == MessageMode.None) { NotificationMode = MessageMode.MessageBox; } if (ScreenshotQuality == ScreenshotQuality.None) { ScreenshotQuality = ScreenshotQuality.Jpg; } if (SortOrder == SortOrder.None) { SortOrder = SortOrder.Ascending; } if (SortKind == SortKind.None) { SortKind = SortKind.SavedAt; } if (!Directory.Exists(SavedGameFolder)) { SavedGameFolder = ""; } if (!Directory.Exists(BackupFolder)) { BackupFolder = ""; } string allHotKeys = Settings.Default.HotKeysToActions; List<string> hotKeys = allHotKeys.Split(new[] {"|"}, StringSplitOptions.RemoveEmptyEntries).ToList(); if (hotKeys.Count > 0) { HotKeyToActions.Clear(); foreach (string hotKey in hotKeys) { HotKeyToActions.Add(HotKeyToAction.DeserializeFromString(hotKey)); } } CompleteHotKeyToActions(); } public void ResetSettings() { BackupFolder = ""; SavedGameFolder = ""; NotificationMode = MessageMode.MessageBox; ScreenshotQuality = ScreenshotQuality.Jpg; SortOrder = SortOrder.Descending; SortKind = SortKind.SavedAt; HotKeysActive = false; HotKeysSound = false; HotKeyToActions.Clear(); CompleteHotKeyToActions(); } public void SaveSettings() { Settings.Default.BackupFolder = BackupFolder; Settings.Default.SavedGameFolder = SavedGameFolder; Settings.Default.NotificationMode = (int) NotificationMode; Settings.Default.ScreenshotQuality = (int) ScreenshotQuality; Settings.Default.SortOrder = (int) SortOrder; Settings.Default.SortKind = (int)SortKind; Settings.Default.HotKeysActive = HotKeysActive; Settings.Default.HotKeysSound = HotKeysSound; List<string> hotKeys = new List<string>(); foreach (HotKeyToAction hotKeyToAction in HotKeyToActions) { hotKeys.Add(HotKeyToAction.SerializeToString(hotKeyToAction)); } string allHotKeys = string.Join("|", hotKeys); Settings.Default.HotKeysToActions = allHotKeys; Settings.Default.Save(); } private void CompleteHotKeyToActions() { if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SavePrevious)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SavePrevious, HotKey = new HotKey(Keys.Up, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveNext)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveNext, HotKey = new HotKey(Keys.Down, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.MapPrevious)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.MapPrevious, HotKey = new HotKey(Keys.Left, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.MapNext)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.MapNext, HotKey = new HotKey(Keys.Right, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveFirst)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveFirst, HotKey = new HotKey(Keys.PageUp, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveLast)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveLast, HotKey = new HotKey(Keys.PageDown, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveBackup)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveBackup, HotKey = new HotKey(Keys.NumPad1, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveDelete)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveDelete, HotKey = new HotKey(Keys.NumPad2, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SaveRestore)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SaveRestore, HotKey = new HotKey(Keys.NumPad3, true, true, false) }); } if (!HotKeyToActions.Exists(i => i.Action == HotKeyAction.SettingSwitchAutoBackup)) { HotKeyToActions.Add(new HotKeyToAction { Enabled = true, Action = HotKeyAction.SettingSwitchAutoBackup, HotKey = new HotKey(Keys.NumPad8, true, true, false) }); } } #endregion } }
31.385321
113
0.515444
[ "MIT" ]
HgAlexx/Hg.DoomHistory
Hg.DoomHistory/Managers/SettingManager.cs
10,265
C#
using System.Threading.Tasks; using AVF.MemberManagement.StandardLibrary.Tbo; using AVF.MemberManagement.ReportsBusinessLogic; namespace AVF.MemberManagement.Console { class Mitgliederbeitraege { internal async Task Main( ) { OutputTarget oTarget = new OutputTarget( "Mitgliederbeitraege.txt" ); decimal decHalbjahresSumme = 0; int iLfdNr = 0; foreach (Mitglied mitglied in Globals.DatabaseWrapper.P_mitglieder) { if (mitglied.Faktor > 0) { int iProzentsatz = Globals.DatabaseWrapper.Familienrabatt(mitglied); if ( iProzentsatz > 0 ) { decimal decStdJahresbeitrag = Globals.DatabaseWrapper.BK(mitglied).Beitrag; decimal decJahresbeitrag = decStdJahresbeitrag * iProzentsatz / 100; decimal decHalbjahresbeitrag = decJahresbeitrag / 2; decHalbjahresSumme += decHalbjahresbeitrag; oTarget.Write($"{ ++iLfdNr, 3} "); oTarget.WriteMitglied( mitglied) ; oTarget.Write($"{ Globals.DatabaseWrapper.BK_Text(mitglied),3} "); oTarget.WriteAmount( decJahresbeitrag ); oTarget.Write($"{ mitglied.Familienmitglied } "); oTarget.WriteAmount( decHalbjahresbeitrag ); oTarget.WriteLine(); } } } oTarget.WriteLine(); oTarget.WriteLine("Halbjahressumme: "); oTarget.WriteAmount( decHalbjahresSumme ); oTarget.CloseAndReset2Console(); } } }
38.73913
100
0.543771
[ "Apache-2.0" ]
aikido-forchheim/membermanagement
AVF.MemberManagement.Console/Mitgliederbeitraege.cs
1,784
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Newtonsoft.Json; namespace ARKBreedingStats.ocr.PatternMatching { [JsonObject(MemberSerialization.OptIn)] public class RecognitionPatterns { private static readonly int[] OffsetX = { -1, 0, 1, 0 }; private static readonly int[] OffsetY = { 0, -1, 0, 1 }; [JsonProperty] internal List<TextData> Texts { get; } = new List<TextData>(); [JsonProperty] public TrainingSettings TrainingSettings { get; set; } = new TrainingSettings(); /// <summary> /// Save current ocr settings, e.g. after a new character was added. /// </summary> public event Action Save; public string FindMatchingChar(RecognizedCharData sym, Image originalImg, float tolerance = 0.15f, bool onlyNumbers = false) { var curPattern = sym.Pattern; var xSizeFound = curPattern.GetLength(0); var ySizeFound = curPattern.GetLength(1); float bestMatchDifference = float.MaxValue; string bestMatch = null; foreach (var c in Texts) { // if only numbers are expected, skip non numerical patterns if (onlyNumbers && !"0123456789.,%/:LEVEL".Contains(c.Text)) continue; foreach (var pattern in c.Patterns) { var possibleDif = ((pattern.Length + sym.Pattern.Length) / 2) * tolerance; if (Math.Abs(pattern.Length - curPattern.Length) > possibleDif) continue; possibleDif = pattern.SetPixels * 2 * tolerance; // Attempted to do offset shifting here but got too many false recognitions here, might need some tweaking. //var minOffsetX = xSizeFound > 2 ? -1 : 0; //var maxOffsetX = xSizeFound > 2 ? 1 : 0; //var minOffsetY = xSizeFound > 2 ? -1 : 0; //var maxOffsetY = xSizeFound > 2 ? 1 : 0; //for (var offSetX = minOffsetX; offSetX <= maxOffsetX; offSetX++) //{ // for (var offSetY = minOffsetY; offSetY <= maxOffsetY; offSetY++) // { var dif = 0f; var fail = false; // TODO sort out small recognized patterns that would match 100 % of their size with a lot of patterns, e.g. dots for (var x = 0; !fail && x < xSizeFound && x < pattern.Width; x++) { for (var y = 0; !fail && y < ySizeFound && y < pattern.Height; y++) { var curPatternX = x;// + offSetX; var curPatternY = y;// + offSetY; if (curPatternX >= 0 && curPatternY >= 0 && curPatternY < ySizeFound && curPatternX < xSizeFound) { var cHave = curPattern[curPatternX, curPatternY]; var pHave = pattern[x, y]; // if the bits are different, check if the total number of different bits is too large for a match and if to ignore this pattern if (cHave != pHave) { // tolerance of difference if a nearby bit is equal dif += IsNearby(cHave ? pattern.Data : curPattern, x, y) ? 0.33f : 1f; if (dif > possibleDif) { fail = true; } } } } } if (!fail && bestMatchDifference > dif) { if (dif == 0) return c.Text; // there is no better match bestMatchDifference = dif; bestMatch = c.Text; } // } //} } } if (!string.IsNullOrEmpty(bestMatch)) { return bestMatch; } // no match was found if (!TrainingSettings.IsTrainingEnabled) { return "�"; //string.Empty; } var manualChar = new RecognitionTrainingForm(sym, originalImg).Prompt(); if (string.IsNullOrEmpty(manualChar)) return manualChar; return AddNewPattern(sym, manualChar, curPattern); } /// <summary> /// Calculates the matching proportion between two patterns. /// </summary> internal static void PatternMatch(bool[,] template, bool[,] recognized, out float match, out int offset) { offset = 0; if (template == null || recognized == null) { match = 0; return; } int templateWidth = template.GetLength(0); int templateHeight = template.GetLength(1); int recognizedWidth = recognized.GetLength(0); int recognizedHeight = recognized.GetLength(1); int width = Math.Min(templateWidth, recognizedWidth); int height = Math.Min(templateHeight, recognizedHeight); int maxWidth = Math.Max(templateWidth, recognizedWidth); int maxHeight = Math.Max(templateHeight, recognizedHeight); int testArea = width * height; int maxArea = maxWidth * maxHeight; if (maxArea / testArea >= 2) { // match is less than 0.5 match = 0.5f; return; } float equalPixels = 0; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var curPatternX = x;// + offSetX; var curPatternY = y;// + offSetY; var cHave = recognized[curPatternX, curPatternY]; var pHave = template[x, y]; // if the bits are different, check if the total number of different bits is too large for a match and if to ignore this pattern if (cHave == pHave) { equalPixels += 1; } else { // tolerance of difference if a nearby bit is equal equalPixels += IsNearby(cHave ? template : recognized, x, y) ? 0.6f : 0; } } } match = equalPixels * 2 / (maxArea + testArea); } /// <summary> /// Returns true if a nearby bit is set. /// </summary> /// <param name="pattern"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> private static bool IsNearby(bool[,] pattern, int x, int y) { var width = pattern.GetLength(0); var height = pattern.GetLength(1); for (int i = 0; i < OffsetX.Length; i++) { var nextX = OffsetX[i] + x; var nextY = OffsetY[i] + y; var isSafe = nextX > 0 && nextX < width && nextY > 0 && nextY < height; if (!isSafe) { continue; } if (pattern[nextX, nextY]) { return true; } } return false; } private string AddNewPattern(RecognizedCharData sym, string manualChar, bool[,] curPattern) { var pat = Texts.FirstOrDefault(x => x.Text == manualChar); if (pat != null) { pat.Patterns.Add(curPattern); } else { Texts.Add(sym.ToCharData(manualChar)); } Save?.Invoke(); return manualChar; } public void AddPattern(string text, Bitmap bmp) { var newPattern = Pattern.FromBmp(bmp); if (newPattern == null) return; var textData = Texts.FirstOrDefault(x => x.Text == text); if (textData != null) { // check if pattern is already added bool alreadyAdded = false; foreach (var p in textData.Patterns) { if (p.Equals(newPattern)) { alreadyAdded = true; break; } } if (!alreadyAdded) textData.Patterns.Add(newPattern); } else { Texts.Add(new TextData { Patterns = new List<Pattern> { newPattern }, Text = text }); } } } }
35.547893
160
0.451929
[ "MIT" ]
AriesPlaysNation/ARKStatsExtractor
ARKBreedingStats/ocr/PatternMatching/RecognitionPatterns.cs
9,282
C#
using Microsoft.IdentityServer.Web.Authentication.External; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ADFSTK.ExternalMFA.AdapterTest { public class AuthenticationContext : IAuthenticationContext { public AuthenticationContext() { //ActivityId = activityId; } public string ActivityId { get; set; } public string ContextId { get; set; } public int Lcid { get; set; } public Dictionary<string, object> Data { get; set; } } }
23.72
63
0.671164
[ "Apache-2.0" ]
canariecaf/adfstoolkit
src/ADFSToolkitExternalMFAAdapter/AdapterTest/AuthenticationContext.cs
595
C#
// MIT License // // Copyright (c) Microsoft Corporation. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using Caliburn.Micro; using Microsoft.Knowzy.Authentication; using Microsoft.Knowzy.Common.Contracts; using Microsoft.Knowzy.WPF.Messages; using Microsoft.Knowzy.WPF.ViewModels.Models; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows; namespace Microsoft.Knowzy.WPF.ViewModels { public class MainViewModel : Screen { private const int TabListView = 0; private const int TabGridView = 1; private readonly IDataProvider _dataProvider; private readonly IEventAggregator _eventAggregator; private readonly IAuthenticationService _authenticationService; public MainViewModel(IDataProvider dataProvider, IEventAggregator eventAggregator, IAuthenticationService authenticationService) { _dataProvider = dataProvider; _eventAggregator = eventAggregator; _authenticationService = authenticationService; } private int _selectedIndexTab; public int SelectedIndexTab { get => _selectedIndexTab; set { _selectedIndexTab = value; NotifyOfPropertyChange(() => SelectedIndexTab); } } public List<Screen> ScreenList { get; set; } public ObservableCollection<ItemViewModel> DevelopmentItems { get; set; } = new ObservableCollection<ItemViewModel>(); public string LoggedUser { get { NotifyOfPropertyChange(() => HasLoggedUser); return _authenticationService.UserLogged; } } public bool HasLoggedUser => !string.IsNullOrWhiteSpace(_authenticationService.UserLogged); private bool _showAdaptiveCard; public bool ShowAdaptiveCard { get => _showAdaptiveCard; set { _showAdaptiveCard = value; NotifyOfPropertyChange(() => ShowAdaptiveCard); } } protected override void OnViewAttached(object view, object context) { foreach (var item in _dataProvider.GetData()) { DevelopmentItems.Add(new ItemViewModel(item, _eventAggregator)); } base.OnViewAttached(view, context); } public void ShowListView() { if (SelectedIndexTab == TabListView) return; SelectedIndexTab --; } public void ShowGridView() { if (SelectedIndexTab == TabGridView) return; SelectedIndexTab ++; } public void NewItem() { var item = new ItemViewModel(_eventAggregator); _eventAggregator.PublishOnUIThread(new EditItemMessage(item)); if (item.Id == null) return; DevelopmentItems.Add(item); // This prop. is just used to fire a visibility change in the UI, it should be improved in a real scenario ShowAdaptiveCard = true; } public void Login() { _eventAggregator.PublishOnUIThread(new OpenLoginMessage()); } public void Logout() { _authenticationService.Logout(); NotifyOfPropertyChange(() => LoggedUser); } public void About() { _eventAggregator.PublishOnUIThread(new OpenAboutMessage()); } public void Documentation() { _eventAggregator.PublishOnUIThread(new OpenDocumentationMessage()); } public void Exit() { Application.Current.Shutdown(); } public void Save() { var products = DevelopmentItems?.Select(item => item.Product).ToArray(); _dataProvider.SetData(products); } public void UpdateNotes(string notes) { var lastItem = DevelopmentItems.LastOrDefault(); if (lastItem != null) { lastItem.Notes = notes; } } } }
33.212291
136
0.629773
[ "MIT" ]
Bhaskers-Blu-Org2/InsiderDevTour18-Labs
modernize/SourceCode/src/Microsoft.Knowzy.WPF/ViewModels/MainViewModel.cs
5,949
C#
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Vertical.Pipelines; namespace Vertical.Examples.Shared { public class SendWelcomeEmailTask : IPipelineMiddleware<AddCustomerRequest> { private readonly INotificationService _notificationService; private readonly ILogger<SendWelcomeEmailTask> _logger; public SendWelcomeEmailTask(INotificationService notificationService, ILogger<SendWelcomeEmailTask> logger) { _notificationService = notificationService; _logger = logger; } /// <inheritdoc /> public async Task InvokeAsync(AddCustomerRequest request, PipelineDelegate<AddCustomerRequest> next, CancellationToken cancellationToken) { await _notificationService.SendEmailAsync( "admin@vertical-example.com", request.Record.EmailAddress, new { Subject = "Welcome to Vertical Software", Body = $"Welcome {request.Record.FirstName}, your account has been activated successfully" }); _logger.LogInformation("Welcome email sent"); await next(request, cancellationToken); } } }
34.230769
110
0.635206
[ "MIT" ]
verticalsoftware/vertical-pipelines
examples/Shared/SendWelcomeEmailTask.cs
1,335
C#
/* Copyright (C) 2011 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using IKVM.Reflection.Emit; using IKVM.Reflection.Reader; namespace IKVM.Reflection { public struct CustomModifiers : IEquatable<CustomModifiers>, IEnumerable<CustomModifiers.Entry> { private static readonly Type ModOpt = new MarkerType(); private static readonly Type ModReq = new MarkerType(); private static readonly Type Initial = ModOpt; private readonly Type[] types; internal CustomModifiers(List<CustomModifiersBuilder.Item> list) { bool required = Initial == ModReq; int count = list.Count; foreach (CustomModifiersBuilder.Item item in list) { if (item.required != required) { required = item.required; count++; } } types = new Type[count]; required = Initial == ModReq; int index = 0; foreach (CustomModifiersBuilder.Item item in list) { if (item.required != required) { required = item.required; types[index++] = required ? ModReq : ModOpt; } types[index++] = item.type; } } private CustomModifiers(Type[] types) { Debug.Assert(types == null || types.Length != 0); this.types = types; } public struct Enumerator : IEnumerator<Entry> { private readonly Type[] types; private int index; private bool required; internal Enumerator(Type[] types) { this.types = types; this.index = -1; this.required = Initial == ModReq; } void System.Collections.IEnumerator.Reset() { this.index = -1; this.required = Initial == ModReq; } public Entry Current { get { return new Entry(types[index], required); } } public bool MoveNext() { if (types == null || index == types.Length) { return false; } index++; if (index == types.Length) { return false; } else if (types[index] == ModOpt) { required = false; index++; } else if (types[index] == ModReq) { required = true; index++; } return true; } object System.Collections.IEnumerator.Current { get { return Current; } } void IDisposable.Dispose() { } } public struct Entry { private readonly Type type; private readonly bool required; internal Entry(Type type, bool required) { this.type = type; this.required = required; } public Type Type { get { return type; } } public bool IsRequired { get { return required; } } } public Enumerator GetEnumerator() { return new Enumerator(types); } IEnumerator<Entry> IEnumerable<Entry>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool IsEmpty { get { return types == null; } } public bool Equals(CustomModifiers other) { return Util.ArrayEquals(types, other.types); } public override bool Equals(object obj) { CustomModifiers? other = obj as CustomModifiers?; return other != null && Equals(other.Value); } public override int GetHashCode() { return Util.GetHashCode(types); } public override string ToString() { if (types == null) { return string.Empty; } StringBuilder sb = new StringBuilder(); string sep = ""; foreach (Entry e in this) { sb.Append(sep).Append(e.IsRequired ? "modreq(" : "modopt(").Append(e.Type.FullName).Append(')'); sep = " "; } return sb.ToString(); } private Type[] GetRequiredOrOptional(bool required) { if (types == null) { return Type.EmptyTypes; } int count = 0; foreach (Entry e in this) { if (e.IsRequired == required) { count++; } } Type[] result = new Type[count]; foreach (Entry e in this) { if (e.IsRequired == required) { // FXBUG reflection (and ildasm) return custom modifiers in reverse order // while SRE writes them in the specified order result[--count] = e.Type; } } return result; } internal Type[] GetRequired() { return GetRequiredOrOptional(true); } internal Type[] GetOptional() { return GetRequiredOrOptional(false); } internal CustomModifiers Bind(IGenericBinder binder) { if (types == null) { return this; } Type[] result = types; for (int i = 0; i < types.Length; i++) { if (types[i] == ModOpt || types[i] == ModReq) { continue; } Type type = types[i].BindTypeParameters(binder); if (!ReferenceEquals(type, types[i])) { if (result == types) { result = (Type[])types.Clone(); } result[i] = type; } } return new CustomModifiers(result); } internal static CustomModifiers Read(ModuleReader module, ByteReader br, IGenericContext context) { byte b = br.PeekByte(); if (!IsCustomModifier(b)) { return new CustomModifiers(); } List<Type> list = new List<Type>(); Type mode = Initial; do { Type cmod = br.ReadByte() == Signature.ELEMENT_TYPE_CMOD_REQD ? ModReq : ModOpt; if (mode != cmod) { mode = cmod; list.Add(mode); } list.Add(Signature.ReadTypeDefOrRefEncoded(module, br, context)); b = br.PeekByte(); } while (IsCustomModifier(b)); return new CustomModifiers(list.ToArray()); } internal static void Skip(ByteReader br) { byte b = br.PeekByte(); while (IsCustomModifier(b)) { br.ReadByte(); br.ReadCompressedInt(); b = br.PeekByte(); } } internal static CustomModifiers FromReqOpt(Type[] req, Type[] opt) { List<Type> list = null; if (opt != null && opt.Length != 0) { list = new List<Type>(opt); } if (req != null && req.Length != 0) { if (list == null) { list = new List<Type>(); } list.Add(ModReq); list.AddRange(req); } if (list == null) { return new CustomModifiers(); } else { return new CustomModifiers(list.ToArray()); } } private static bool IsCustomModifier(byte b) { return b == Signature.ELEMENT_TYPE_CMOD_OPT || b == Signature.ELEMENT_TYPE_CMOD_REQD; } internal static CustomModifiers Combine(CustomModifiers mods1, CustomModifiers mods2) { if (mods1.IsEmpty) { return mods2; } else if (mods2.IsEmpty) { return mods1; } else { Type[] combo = new Type[mods1.types.Length + mods2.types.Length]; Array.Copy(mods1.types, combo, mods1.types.Length); Array.Copy(mods2.types, 0, combo, mods1.types.Length, mods2.types.Length); return new CustomModifiers(combo); } } } }
21.509915
100
0.636244
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/class/IKVM.Reflection/CustomModifiers.cs
7,595
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticleAttractor : MonoBehaviour { // The particle system to operate on public ParticleSystem AffectedParticles = null; // Normalized treshold on the particle lifetime // 0: affect particles right after they are born // 1: never affect particles [Range(0.0f, 1.0f)] public float ActivationTreshold = 1.0f; // Transform cache private Transform m_rTransform = null; // Array to store particles info private ParticleSystem.Particle[] m_rParticlesArray = null; // Is this particle system simulating in world space? private bool m_bWorldPosition = false; // Multiplier to normalize movement cursor after treshold is crossed private float m_fCursorMultiplier = 1.0f; void Awake() { // Let's cache the transform m_rTransform = this.transform; // Setup particle system info Setup(); } // To store how many particles are active on each frame private int m_iNumActiveParticles = 0; // The attractor target private Vector3 m_vParticlesTarget = Vector3.zero; // A cursor for the movement interpolation private float m_fCursor = 0.0f; void LateUpdate() { // Work only if we have something to work on :) if (AffectedParticles != null) { // Let's fetch active particles info m_iNumActiveParticles = AffectedParticles.GetParticles(m_rParticlesArray); // The attractor's target is it's world space position m_vParticlesTarget = m_rTransform.position; // If the system is not simulating in world space, let's project the attractor's target in the system's local space if (!m_bWorldPosition) m_vParticlesTarget -= AffectedParticles.transform.position; // For each active particle... for (int iParticle = 0; iParticle < m_iNumActiveParticles; iParticle++) { // The movement cursor is the opposite of the normalized particle's lifetime m_fCursor = 1.0f - (m_rParticlesArray[iParticle].lifetime / m_rParticlesArray[iParticle].startLifetime); // Are we over the activation treshold? if (m_fCursor >= ActivationTreshold) { // Let's project the overall cursor in the "over treshold" normalized space m_fCursor -= ActivationTreshold; m_fCursor *= m_fCursorMultiplier; // Take over the particle system imposed velocity m_rParticlesArray[iParticle].velocity = Vector3.zero; // Interpolate the movement towards the target with a nice quadratic easing m_rParticlesArray[iParticle].position = Vector3.Lerp(m_rParticlesArray[iParticle].position, m_vParticlesTarget, m_fCursor * m_fCursor); } } // Let's update the active particles AffectedParticles.SetParticles(m_rParticlesArray, m_iNumActiveParticles); } } public void Setup() { // If we have a system to setup... if (AffectedParticles != null) { // Prepare enough space to store particles info m_rParticlesArray = new ParticleSystem.Particle[AffectedParticles.main.maxParticles]; // Is the particle system working in world space? Let's store this info m_bWorldPosition = AffectedParticles.main.simulationSpace == ParticleSystemSimulationSpace.World; // This the ratio of the total lifetime cursor to the "over treshold" section m_fCursorMultiplier = 1.0f / (1.0f - ActivationTreshold); } } }
42.235955
272
0.653099
[ "Apache-2.0" ]
exporl/lars-common
Tools/UtilScripts/ParticleAttractor.cs
3,761
C#
using SPICA.Formats.Common; using SPICA.Math3D; using SPICA.PICA; using SPICA.PICA.Commands; using System.IO; using System.Numerics; namespace SPICA.Formats.GFL2.Model.Material { public class GFMaterial : INamed { private const string MagicStr = "material"; public string Name { get => MaterialName; set => MaterialName = value; } public string MaterialName; public string ShaderName; public string VtxShaderName; public string FragShaderName; public uint LUT0HashId; public uint LUT1HashId; public uint LUT2HashId; public sbyte BumpTexture; public byte Constant0Assignment; public byte Constant1Assignment; public byte Constant2Assignment; public byte Constant3Assignment; public byte Constant4Assignment; public byte Constant5Assignment; public RGBA Constant0Color; public RGBA Constant1Color; public RGBA Constant2Color; public RGBA Constant3Color; public RGBA Constant4Color; public RGBA Constant5Color; public RGBA Specular0Color; public RGBA Specular1Color; public RGBA BlendColor; public RGBA EmissionColor; public RGBA AmbientColor; public RGBA DiffuseColor; public int EdgeType; public int IDEdgeEnable; public int EdgeID; public int ProjectionType; public float RimPower; public float RimScale; public float PhongPower; public float PhongScale; public int IDEdgeOffsetEnable; public int EdgeMapAlphaMask; public int BakeTexture0; public int BakeTexture1; public int BakeTexture2; public int BakeConstant0; public int BakeConstant1; public int BakeConstant2; public int BakeConstant3; public int BakeConstant4; public int BakeConstant5; public int VertexShaderType; public float ShaderParam0; public float ShaderParam1; public float ShaderParam2; public float ShaderParam3; public int RenderPriority; public int RenderLayer; public PICAColorOperation ColorOperation; public PICABlendFunction BlendFunction; public PICALogicalOp LogicalOperation; public PICAAlphaTest AlphaTest; public PICAStencilTest StencilTest; public PICAStencilOperation StencilOperation; public PICADepthColorMask DepthColorMask; public PICAFaceCulling FaceCulling; public PICALUTInAbs LUTInputAbsolute; public PICALUTInSel LUTInputSelection; public PICALUTInScale LUTInputScale; public bool ColorBufferRead; public bool ColorBufferWrite; public bool StencilBufferRead; public bool StencilBufferWrite; public bool DepthBufferRead; public bool DepthBufferWrite; public readonly GFTextureCoord[] TextureCoords; public readonly RGBA[] BorderColor; public readonly float[] TextureSources; public GFMaterial() { TextureCoords = new GFTextureCoord[3]; BorderColor = new RGBA[3]; TextureSources = new float[4]; } public GFMaterial(BinaryReader Reader) : this() { GFSection MaterialSection = new GFSection(Reader); long Position = Reader.BaseStream.Position; MaterialName = new GFHashName(Reader).Name; ShaderName = new GFHashName(Reader).Name; VtxShaderName = new GFHashName(Reader).Name; FragShaderName = new GFHashName(Reader).Name; LUT0HashId = Reader.ReadUInt32(); LUT1HashId = Reader.ReadUInt32(); LUT2HashId = Reader.ReadUInt32(); Reader.ReadUInt32(); //16 bytes padding BumpTexture = Reader.ReadSByte(); Constant0Assignment = Reader.ReadByte(); Constant1Assignment = Reader.ReadByte(); Constant2Assignment = Reader.ReadByte(); Constant3Assignment = Reader.ReadByte(); Constant4Assignment = Reader.ReadByte(); Constant5Assignment = Reader.ReadByte(); Reader.ReadByte(); //8 bytes padding Constant0Color = new RGBA(Reader); Constant1Color = new RGBA(Reader); Constant2Color = new RGBA(Reader); Constant3Color = new RGBA(Reader); Constant4Color = new RGBA(Reader); Constant5Color = new RGBA(Reader); Specular0Color = new RGBA(Reader); Specular1Color = new RGBA(Reader); BlendColor = new RGBA(Reader); EmissionColor = new RGBA(Reader); AmbientColor = new RGBA(Reader); DiffuseColor = new RGBA(Reader); EdgeType = Reader.ReadInt32(); IDEdgeEnable = Reader.ReadInt32(); EdgeID = Reader.ReadInt32(); ProjectionType = Reader.ReadInt32(); RimPower = Reader.ReadSingle(); RimScale = Reader.ReadSingle(); PhongPower = Reader.ReadSingle(); PhongScale = Reader.ReadSingle(); IDEdgeOffsetEnable = Reader.ReadInt32(); EdgeMapAlphaMask = Reader.ReadInt32(); BakeTexture0 = Reader.ReadInt32(); BakeTexture1 = Reader.ReadInt32(); BakeTexture2 = Reader.ReadInt32(); BakeConstant0 = Reader.ReadInt32(); BakeConstant1 = Reader.ReadInt32(); BakeConstant2 = Reader.ReadInt32(); BakeConstant3 = Reader.ReadInt32(); BakeConstant4 = Reader.ReadInt32(); BakeConstant5 = Reader.ReadInt32(); VertexShaderType = Reader.ReadInt32(); ShaderParam0 = Reader.ReadSingle(); ShaderParam1 = Reader.ReadSingle(); ShaderParam2 = Reader.ReadSingle(); ShaderParam3 = Reader.ReadSingle(); uint UnitsCount = Reader.ReadUInt32(); for (int Unit = 0; Unit < UnitsCount; Unit++) { TextureCoords[Unit] = new GFTextureCoord(Reader); } GFSection.SkipPadding(Reader.BaseStream); uint CommandsLength = Reader.ReadUInt32(); RenderPriority = Reader.ReadInt32(); Reader.ReadUInt32(); //Seems to be a 24 bits value. RenderLayer = Reader.ReadInt32(); Reader.ReadUInt32(); //LUT 0 (Reflection R?) hash again? Reader.ReadUInt32(); //LUT 1 (Reflection G?) hash again? Reader.ReadUInt32(); //LUT 2 (Reflection B?) hash again? Reader.ReadUInt32(); //Another hash? uint[] Commands = new uint[CommandsLength >> 2]; for (int Index = 0; Index < Commands.Length; Index++) { Commands[Index] = Reader.ReadUInt32(); } PICACommandReader CmdReader = new PICACommandReader(Commands); while (CmdReader.HasCommand) { PICACommand Cmd = CmdReader.GetCommand(); uint Param = Cmd.Parameters[0]; switch (Cmd.Register) { case PICARegister.GPUREG_TEXUNIT0_BORDER_COLOR: BorderColor[0] = new RGBA(Param); break; case PICARegister.GPUREG_TEXUNIT1_BORDER_COLOR: BorderColor[1] = new RGBA(Param); break; case PICARegister.GPUREG_TEXUNIT2_BORDER_COLOR: BorderColor[2] = new RGBA(Param); break; case PICARegister.GPUREG_COLOR_OPERATION: ColorOperation = new PICAColorOperation(Param); break; case PICARegister.GPUREG_BLEND_FUNC: BlendFunction = new PICABlendFunction(Param); break; case PICARegister.GPUREG_LOGIC_OP: LogicalOperation = (PICALogicalOp)(Param & 0xf); break; case PICARegister.GPUREG_FRAGOP_ALPHA_TEST: AlphaTest = new PICAAlphaTest(Param); break; case PICARegister.GPUREG_STENCIL_TEST: StencilTest = new PICAStencilTest(Param); break; case PICARegister.GPUREG_STENCIL_OP: StencilOperation = new PICAStencilOperation(Param); break; case PICARegister.GPUREG_DEPTH_COLOR_MASK: DepthColorMask = new PICADepthColorMask(Param); break; case PICARegister.GPUREG_FACECULLING_CONFIG: FaceCulling = (PICAFaceCulling)(Param & 3); break; case PICARegister.GPUREG_COLORBUFFER_READ: ColorBufferRead = (Param & 0xf) == 0xf; break; case PICARegister.GPUREG_COLORBUFFER_WRITE: ColorBufferWrite = (Param & 0xf) == 0xf; break; case PICARegister.GPUREG_DEPTHBUFFER_READ: StencilBufferRead = (Param & 1) != 0; DepthBufferRead = (Param & 2) != 0; break; case PICARegister.GPUREG_DEPTHBUFFER_WRITE: StencilBufferWrite = (Param & 1) != 0; DepthBufferWrite = (Param & 2) != 0; break; case PICARegister.GPUREG_LIGHTING_LUTINPUT_ABS: LUTInputAbsolute = new PICALUTInAbs(Param); break; case PICARegister.GPUREG_LIGHTING_LUTINPUT_SELECT: LUTInputSelection = new PICALUTInSel(Param); break; case PICARegister.GPUREG_LIGHTING_LUTINPUT_SCALE: LUTInputScale = new PICALUTInScale(Param); break; } } TextureSources[0] = CmdReader.VtxShaderUniforms[0].X; TextureSources[1] = CmdReader.VtxShaderUniforms[0].Y; TextureSources[2] = CmdReader.VtxShaderUniforms[0].Z; TextureSources[3] = CmdReader.VtxShaderUniforms[0].W; Reader.BaseStream.Seek(Position + MaterialSection.Length, SeekOrigin.Begin); } public void Write(BinaryWriter Writer) { long StartPosition = Writer.BaseStream.Position; new GFSection(MagicStr).Write(Writer); new GFHashName(MaterialName) .Write(Writer); new GFHashName(ShaderName) .Write(Writer); new GFHashName(VtxShaderName) .Write(Writer); new GFHashName(FragShaderName).Write(Writer); Writer.Write(LUT0HashId); Writer.Write(LUT1HashId); Writer.Write(LUT2HashId); Writer.Write(0u); Writer.Write(BumpTexture); Writer.Write(Constant0Assignment); Writer.Write(Constant1Assignment); Writer.Write(Constant2Assignment); Writer.Write(Constant3Assignment); Writer.Write(Constant4Assignment); Writer.Write(Constant5Assignment); Writer.Write((byte)0); Constant0Color.Write(Writer); Constant1Color.Write(Writer); Constant2Color.Write(Writer); Constant3Color.Write(Writer); Constant4Color.Write(Writer); Constant5Color.Write(Writer); Specular0Color.Write(Writer); Specular1Color.Write(Writer); BlendColor .Write(Writer); EmissionColor .Write(Writer); AmbientColor .Write(Writer); DiffuseColor .Write(Writer); Writer.Write(EdgeType); Writer.Write(IDEdgeEnable); Writer.Write(EdgeID); Writer.Write(ProjectionType); Writer.Write(RimPower); Writer.Write(RimScale); Writer.Write(PhongPower); Writer.Write(PhongScale); Writer.Write(IDEdgeOffsetEnable); Writer.Write(EdgeMapAlphaMask); Writer.Write(BakeTexture0); Writer.Write(BakeTexture1); Writer.Write(BakeTexture2); Writer.Write(BakeConstant0); Writer.Write(BakeConstant1); Writer.Write(BakeConstant2); Writer.Write(BakeConstant3); Writer.Write(BakeConstant4); Writer.Write(BakeConstant5); Writer.Write(VertexShaderType); Writer.Write(ShaderParam0); Writer.Write(ShaderParam1); Writer.Write(ShaderParam2); Writer.Write(ShaderParam3); int UnitsCount = TextureCoords[2].Name != null ? 3 : TextureCoords[1].Name != null ? 2 : TextureCoords[0].Name != null ? 1 : 0; Writer.Write((uint)UnitsCount); float[] TexMtx = new float[UnitsCount * 12]; for (int Unit = 0; Unit < UnitsCount; Unit++) { TextureCoords[Unit].Write(Writer); Matrix3x4 Mtx = TextureCoords[Unit].GetTransform(); TexMtx[Unit * 12 + 0] = Mtx.M41; TexMtx[Unit * 12 + 1] = Mtx.M31; TexMtx[Unit * 12 + 2] = Mtx.M21; TexMtx[Unit * 12 + 3] = Mtx.M11; TexMtx[Unit * 12 + 4] = Mtx.M42; TexMtx[Unit * 12 + 5] = Mtx.M32; TexMtx[Unit * 12 + 6] = Mtx.M22; TexMtx[Unit * 12 + 7] = Mtx.M12; TexMtx[Unit * 12 + 8] = Mtx.M43; TexMtx[Unit * 12 + 9] = Mtx.M33; TexMtx[Unit * 12 + 10] = Mtx.M23; TexMtx[Unit * 12 + 11] = Mtx.M13; } Writer.Align(0x10, 0xff); PICACommandWriter CmdWriter = new PICACommandWriter(); CmdWriter.SetCommand(PICARegister.GPUREG_VSH_FLOATUNIFORM_INDEX, true, 0x80000000u, IOUtils.ToUInt32(TextureSources[3]), IOUtils.ToUInt32(TextureSources[2]), IOUtils.ToUInt32(TextureSources[1]), IOUtils.ToUInt32(TextureSources[0])); CmdWriter.SetCommand(PICARegister.GPUREG_VSH_FLOATUNIFORM_INDEX, 0x80000001u); CmdWriter.SetCommand(PICARegister.GPUREG_VSH_FLOATUNIFORM_DATA0, false, TexMtx); CmdWriter.SetCommand(PICARegister.GPUREG_FACECULLING_CONFIG, (uint)FaceCulling); CmdWriter.SetCommand(PICARegister.GPUREG_COLOR_OPERATION, ColorOperation.ToUInt32(), 3); CmdWriter.SetCommand(PICARegister.GPUREG_BLEND_FUNC, BlendFunction.ToUInt32()); if (BlendFunction.ColorSrcFunc != PICABlendFunc.One || BlendFunction.ColorDstFunc != PICABlendFunc.Zero || BlendFunction.AlphaSrcFunc != PICABlendFunc.One || BlendFunction.AlphaDstFunc != PICABlendFunc.Zero) { CmdWriter.SetCommand(PICARegister.GPUREG_LOGIC_OP, (uint)LogicalOperation); CmdWriter.SetCommand(PICARegister.GPUREG_BLEND_COLOR, BlendColor.ToUInt32() | 0xff000000u); } CmdWriter.SetCommand(PICARegister.GPUREG_FRAGOP_ALPHA_TEST, AlphaTest.ToUInt32(), 3); CmdWriter.SetCommand(PICARegister.GPUREG_STENCIL_TEST, StencilTest.ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_STENCIL_OP, StencilOperation.ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTH_COLOR_MASK, DepthColorMask.ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTHMAP_ENABLE, true); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTHMAP_SCALE, PICAVectorFloat24.GetWord24(-1)); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTHMAP_OFFSET, 0u); CmdWriter.SetCommand(PICARegister.GPUREG_FRAMEBUFFER_FLUSH, true); CmdWriter.SetCommand(PICARegister.GPUREG_FRAMEBUFFER_INVALIDATE, true); CmdWriter.SetCommand(PICARegister.GPUREG_COLORBUFFER_READ, ColorBufferRead ? 0xfu : 0u, 1); CmdWriter.SetCommand(PICARegister.GPUREG_COLORBUFFER_WRITE, ColorBufferWrite ? 0xfu : 0u, 1); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTHBUFFER_READ, StencilBufferRead, DepthBufferRead); CmdWriter.SetCommand(PICARegister.GPUREG_DEPTHBUFFER_WRITE, StencilBufferWrite, DepthBufferWrite); uint TexUnitConfig = 0x00011000u; TexUnitConfig |= (TextureCoords[0].Name != null ? 1u : 0u) << 0; TexUnitConfig |= (TextureCoords[1].Name != null ? 1u : 0u) << 1; TexUnitConfig |= (TextureCoords[2].Name != null ? 1u : 0u) << 2; CmdWriter.SetCommands(PICARegister.GPUREG_TEXUNIT_CONFIG, false, 0, 0, 0, 0); CmdWriter.SetCommand(PICARegister.GPUREG_TEXUNIT_CONFIG, TexUnitConfig); CmdWriter.SetCommand(PICARegister.GPUREG_TEXUNIT0_BORDER_COLOR, BorderColor[0].ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_TEXUNIT1_BORDER_COLOR, BorderColor[1].ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_TEXUNIT2_BORDER_COLOR, BorderColor[2].ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_LIGHTING_LUTINPUT_ABS, LUTInputAbsolute.ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_LIGHTING_LUTINPUT_SELECT, LUTInputSelection.ToUInt32()); CmdWriter.SetCommand(PICARegister.GPUREG_LIGHTING_LUTINPUT_SCALE, LUTInputScale.ToUInt32()); CmdWriter.WriteEnd(); uint[] Commands = CmdWriter.GetBuffer(); Writer.Write((uint)(Commands.Length * 4)); Writer.Write(RenderPriority); Writer.Write(0xd5738d); //FIXME: This number changes (depending on the cmd buff?) Writer.Write(RenderLayer); Writer.Write(LUT0HashId); Writer.Write(LUT1HashId); Writer.Write(LUT2HashId); Writer.Write(0xcd20dd3du); //TODO: Figure out what this means. foreach (uint Cmd in Commands) { Writer.Write(Cmd); } Writer.Write(0ul); Writer.Write(0ul); long EndPosition = Writer.BaseStream.Position; Writer.BaseStream.Seek(StartPosition + 8, SeekOrigin.Begin); Writer.Write((uint)(EndPosition - StartPosition - 0x10)); Writer.BaseStream.Seek(EndPosition, SeekOrigin.Begin); } } }
37.293033
124
0.610748
[ "Unlicense" ]
AkelaSnow/SPICA
SPICA/Formats/GFL2/Model/Material/GFMaterial.cs
18,201
C#
using Microsoft.IdentityModel.Tokens; using System; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; namespace AuthService.AccessTokenHandler.Settings { public class AccessTokenSettings : IAccessTokenSettings { private string _publicKey; [Required] public string PublicKey { get { return _publicKey; } set { _publicKey = value; RSA rsa = RSA.Create(); rsa.ImportRSAPublicKey( source: Convert.FromBase64String(_publicKey), bytesRead: out int _ ); RsaKey = new RsaSecurityKey(rsa); } } [Required] public string Issuer { get; set; } [Required] public string Audience { get; set; } public SecurityKey RsaKey { get; private set; } public void ValidateAttributes() { Validator.ValidateObject(this, new ValidationContext(this), validateAllProperties: true); } } }
23.645833
101
0.548899
[ "MIT" ]
makankuy-azure/auth-service
src/AuthService.AccessTokenHandler/Settings/AccessTokenSettings.cs
1,137
C#
using System; using System.IO; using Helpers = HunterPie.Core.Definitions.Helpers; namespace HunterPie.Core.Integrations.DataExporter { /* This class will help HunterPie export the in-game data to a file, the file can be used by streamers to share their build, session, in-game data with their viewers */ public struct Data { public string Name; public int HR; public int MR; public string BuildURL; public string Session; public string SteamSession; public int Playtime; public string WeaponName; } public class Exporter { public readonly string ExportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataExport"); public Exporter() { if (!Directory.Exists(ExportPath)) { Directory.CreateDirectory(ExportPath); } } public bool ExportData(Data playerData) { string filepath = Path.Combine(ExportPath, "PlayerData.json"); try { File.WriteAllText(filepath, Helpers.Serialize(playerData)); return true; } catch { return false; } } /// <summary> /// Function to export custom data to the ExportedData folder /// </summary> /// <param name="path">Relative path to the file</param> /// <param name="data">File content to be exported</param> /// <returns>True if the export was successful, false if not</returns> public bool ExportCustomData(string path, string data) { string filepath = Path.Combine(ExportPath, path); try { File.WriteAllText(filepath, data); return true; } catch { return false; }; } } }
28.712121
110
0.568338
[ "MIT" ]
Bombaclath97/HunterPie
HunterPie.Core/Core/Integrations/DataExporter/Exporter.cs
1,897
C#
namespace LedMatrixController.Server.Config.Source { public class FlatColorConfig : SourceConfig { public string Color { get; set; } } }
20.625
52
0.648485
[ "MIT" ]
patagonaa/led-matrix-control
src/LedMatrixController.Server/PipelineElements/Source/FlatColorConfig.cs
167
C#
using System; using System.Windows.Controls; namespace ProjectStatistics.View.HelpWindow.HelpContent { /// <summary> /// Логика взаимодействия для HelpAddPlayerView.xaml /// </summary> public partial class HelpAddPlayerView : UserControl { public HelpAddPlayerView() { InitializeComponent(); } } }
20.722222
56
0.627346
[ "MIT" ]
xEGOISTx/StatisticsProject
ProjectStatistics/View/HelpWindow/HelpContent/HelpAddPlayerView.xaml.cs
398
C#
using System; using System.Numerics; namespace MineCase.Algorithm { public class MathHelper { public static float DenormalizeClamp(float min, float max, float value) { if (value < 0) { return min; } else if (value > 1) { return max; } else { return min + (max - min) * value; } } } }
19.08
79
0.415094
[ "MIT" ]
CyberFlameGO/MineCase
src/MineCase.Algorithm/MathHelper.cs
477
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; namespace Microsoft.EntityFrameworkCore.Query { public partial class SimpleQuerySqlServerTest { private const string ConvertParams = #if NET461 null; #elif NETCOREAPP3_0 ", Object"; #else #error target frameworks need to be updated. #endif public override async Task Where_simple(bool isAsync) { await base.Where_simple(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = N'London'"); } public override async Task Where_as_queryable_expression(bool isAsync) { await base.Where_as_queryable_expression(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE EXISTS ( SELECT 1 FROM ( SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE [c].[CustomerID] = [o].[CustomerID] ) AS [t] WHERE [t].[CustomerID] = N'ALFKI')"); } public override async Task Where_simple_closure(bool isAsync) { await base.Where_simple_closure(isAsync); AssertSql( @"@__city_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_0"); } public override async Task Where_indexer_closure(bool isAsync) { await base.Where_indexer_closure(isAsync); AssertSql( @"@__p_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__p_0"); } public override async Task Where_dictionary_key_access_closure(bool isAsync) { await base.Where_dictionary_key_access_closure(isAsync); AssertSql( @"@__get_Item_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__get_Item_0"); } public override async Task Where_tuple_item_closure(bool isAsync) { await base.Where_tuple_item_closure(isAsync); AssertSql( @"@__predicateTuple_Item2_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__predicateTuple_Item2_0"); } public override async Task Where_named_tuple_item_closure(bool isAsync) { await base.Where_named_tuple_item_closure(isAsync); AssertSql( @"@__predicateTuple_Item2_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__predicateTuple_Item2_0"); } public override async Task Where_simple_closure_constant(bool isAsync) { await base.Where_simple_closure_constant(isAsync); AssertSql( @"@__predicate_0='True' SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE @__predicate_0 = CAST(1 AS bit)"); } public override async Task Where_simple_closure_via_query_cache(bool isAsync) { await base.Where_simple_closure_via_query_cache(isAsync); AssertSql( @"@__city_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_0", // @"@__city_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_0"); } public override async Task Where_method_call_nullable_type_closure_via_query_cache(bool isAsync) { await base.Where_method_call_nullable_type_closure_via_query_cache(isAsync); AssertSql( @"@__p_0='2' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0", // @"@__p_0='5' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0"); } public override async Task Where_method_call_nullable_type_reverse_closure_via_query_cache(bool isAsync) { await base.Where_method_call_nullable_type_reverse_closure_via_query_cache(isAsync); AssertSql( @"@__p_0='1' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[EmployeeID] > @__p_0", // @"@__p_0='5' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[EmployeeID] > @__p_0"); } public override async Task Where_method_call_closure_via_query_cache(bool isAsync) { await base.Where_method_call_closure_via_query_cache(isAsync); AssertSql( @"@__GetCity_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__GetCity_0", // @"@__GetCity_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__GetCity_0"); } public override async Task Where_field_access_closure_via_query_cache(bool isAsync) { await base.Where_field_access_closure_via_query_cache(isAsync); AssertSql( @"@__city_InstanceFieldValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_InstanceFieldValue_0", // @"@__city_InstanceFieldValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_InstanceFieldValue_0"); } public override async Task Where_property_access_closure_via_query_cache(bool isAsync) { await base.Where_property_access_closure_via_query_cache(isAsync); AssertSql( @"@__city_InstancePropertyValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_InstancePropertyValue_0", // @"@__city_InstancePropertyValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_InstancePropertyValue_0"); } public override async Task Where_static_field_access_closure_via_query_cache(bool isAsync) { await base.Where_static_field_access_closure_via_query_cache(isAsync); AssertSql( @"@__StaticFieldValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__StaticFieldValue_0", // @"@__StaticFieldValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__StaticFieldValue_0"); } public override async Task Where_static_property_access_closure_via_query_cache(bool isAsync) { await base.Where_static_property_access_closure_via_query_cache(isAsync); AssertSql( @"@__StaticPropertyValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__StaticPropertyValue_0", // @"@__StaticPropertyValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__StaticPropertyValue_0"); } public override async Task Where_nested_field_access_closure_via_query_cache(bool isAsync) { await base.Where_nested_field_access_closure_via_query_cache(isAsync); AssertSql( @"@__city_Nested_InstanceFieldValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_Nested_InstanceFieldValue_0", // @"@__city_Nested_InstanceFieldValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_Nested_InstanceFieldValue_0"); } public override async Task Where_nested_property_access_closure_via_query_cache(bool isAsync) { await base.Where_nested_property_access_closure_via_query_cache(isAsync); AssertSql( @"@__city_Nested_InstancePropertyValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_Nested_InstancePropertyValue_0", // @"@__city_Nested_InstancePropertyValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_Nested_InstancePropertyValue_0"); } public override async Task Where_new_instance_field_access_query_cache(bool isAsync) { await base.Where_new_instance_field_access_query_cache(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = N'London'", // @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = N'Seattle'"); } public override async Task Where_new_instance_field_access_closure_via_query_cache(bool isAsync) { await base.Where_new_instance_field_access_closure_via_query_cache(isAsync); AssertSql( @"@__InstanceFieldValue_0='London' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__InstanceFieldValue_0", // @"@__InstanceFieldValue_0='Seattle' (Size = 4000) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__InstanceFieldValue_0"); } public override async Task Where_simple_closure_via_query_cache_nullable_type(bool isAsync) { await base.Where_simple_closure_via_query_cache_nullable_type(isAsync); AssertSql( @"@__p_0='2' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0", // @"@__p_0='5' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0", // @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] IS NULL"); } public override async Task Where_simple_closure_via_query_cache_nullable_type_reverse(bool isAsync) { await base.Where_simple_closure_via_query_cache_nullable_type_reverse(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] IS NULL", // @"@__p_0='5' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0", // @"@__p_0='2' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__p_0"); } public override void Where_subquery_closure_via_query_cache() { base.Where_subquery_closure_via_query_cache(); AssertSql( @"@__customerID_0='ALFKI' (Size = 5) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE EXISTS ( SELECT 1 FROM [Orders] AS [o] WHERE ([o].[CustomerID] = @__customerID_0) AND ([o].[CustomerID] = [c].[CustomerID]))", // @"@__customerID_0='ANATR' (Size = 5) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE EXISTS ( SELECT 1 FROM [Orders] AS [o] WHERE ([o].[CustomerID] = @__customerID_0) AND ([o].[CustomerID] = [c].[CustomerID]))"); } public override async Task Where_bitwise_or(bool isAsync) { await base.Where_bitwise_or(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE (CASE WHEN [c].[CustomerID] = N'ALFKI' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END | CASE WHEN [c].[CustomerID] = N'ANATR' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) = CAST(1 AS bit)"); } public override async Task Where_bitwise_and(bool isAsync) { await base.Where_bitwise_and(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE (CASE WHEN [c].[CustomerID] = N'ALFKI' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END & CASE WHEN [c].[CustomerID] = N'ANATR' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END) = CAST(1 AS bit)"); } public override async Task Where_bitwise_xor(bool isAsync) { await base.Where_bitwise_xor(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_simple_shadow(bool isAsync) { await base.Where_simple_shadow(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[Title] = N'Sales Representative'"); } public override async Task Where_simple_shadow_projection(bool isAsync) { await base.Where_simple_shadow_projection(isAsync); AssertSql( @"SELECT [e].[Title] FROM [Employees] AS [e] WHERE [e].[Title] = N'Sales Representative'"); } public override async Task Where_shadow_subquery_FirstOrDefault(bool isAsync) { await base.Where_shadow_subquery_FirstOrDefault(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[Title] = ( SELECT TOP(1) [e2].[Title] FROM [Employees] AS [e2] ORDER BY [e2].[Title] )"); } public override async Task Where_client(bool isAsync) { await base.Where_client(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_subquery_correlated(bool isAsync) { await base.Where_subquery_correlated(isAsync); AssertSql( @"SELECT [c1].[CustomerID], [c1].[Address], [c1].[City], [c1].[CompanyName], [c1].[ContactName], [c1].[ContactTitle], [c1].[Country], [c1].[Fax], [c1].[Phone], [c1].[PostalCode], [c1].[Region] FROM [Customers] AS [c1] WHERE EXISTS ( SELECT 1 FROM [Customers] AS [c2] WHERE [c1].[CustomerID] = [c2].[CustomerID])"); } public override async Task Where_subquery_correlated_client_eval(bool isAsync) { await base.Where_subquery_correlated_client_eval(isAsync); AssertSql( @"@__p_0='5' SELECT [t].[CustomerID], [t].[Address], [t].[City], [t].[CompanyName], [t].[ContactName], [t].[ContactTitle], [t].[Country], [t].[Fax], [t].[Phone], [t].[PostalCode], [t].[Region] FROM ( SELECT TOP(@__p_0) [c1].[CustomerID], [c1].[Address], [c1].[City], [c1].[CompanyName], [c1].[ContactName], [c1].[ContactTitle], [c1].[Country], [c1].[Fax], [c1].[Phone], [c1].[PostalCode], [c1].[Region] FROM [Customers] AS [c1] ORDER BY [c1].[CustomerID] ) AS [t]", // @"@_outer_CustomerID='ALFKI' (Size = 5) SELECT [c2].[CustomerID], [c2].[Address], [c2].[City], [c2].[CompanyName], [c2].[ContactName], [c2].[ContactTitle], [c2].[Country], [c2].[Fax], [c2].[Phone], [c2].[PostalCode], [c2].[Region] FROM [Customers] AS [c2] WHERE @_outer_CustomerID = [c2].[CustomerID]", // @"@_outer_CustomerID='ANATR' (Size = 5) SELECT [c2].[CustomerID], [c2].[Address], [c2].[City], [c2].[CompanyName], [c2].[ContactName], [c2].[ContactTitle], [c2].[Country], [c2].[Fax], [c2].[Phone], [c2].[PostalCode], [c2].[Region] FROM [Customers] AS [c2] WHERE @_outer_CustomerID = [c2].[CustomerID]", // @"@_outer_CustomerID='ANTON' (Size = 5) SELECT [c2].[CustomerID], [c2].[Address], [c2].[City], [c2].[CompanyName], [c2].[ContactName], [c2].[ContactTitle], [c2].[Country], [c2].[Fax], [c2].[Phone], [c2].[PostalCode], [c2].[Region] FROM [Customers] AS [c2] WHERE @_outer_CustomerID = [c2].[CustomerID]", // @"@_outer_CustomerID='AROUT' (Size = 5) SELECT [c2].[CustomerID], [c2].[Address], [c2].[City], [c2].[CompanyName], [c2].[ContactName], [c2].[ContactTitle], [c2].[Country], [c2].[Fax], [c2].[Phone], [c2].[PostalCode], [c2].[Region] FROM [Customers] AS [c2] WHERE @_outer_CustomerID = [c2].[CustomerID]", // @"@_outer_CustomerID='BERGS' (Size = 5) SELECT [c2].[CustomerID], [c2].[Address], [c2].[City], [c2].[CompanyName], [c2].[ContactName], [c2].[ContactTitle], [c2].[Country], [c2].[Fax], [c2].[Phone], [c2].[PostalCode], [c2].[Region] FROM [Customers] AS [c2] WHERE @_outer_CustomerID = [c2].[CustomerID]"); } public override async Task Where_client_and_server_top_level(bool isAsync) { await base.Where_client_and_server_top_level(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] <> N'AROUT'"); } public override async Task Where_client_or_server_top_level(bool isAsync) { await base.Where_client_or_server_top_level(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_client_and_server_non_top_level(bool isAsync) { await base.Where_client_and_server_non_top_level(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_client_deep_inside_predicate_and_server_top_level(bool isAsync) { await base.Where_client_deep_inside_predicate_and_server_top_level(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] <> N'ALFKI'"); } public override async Task Where_equals_method_string(bool isAsync) { await base.Where_equals_method_string(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = N'London'"); } public override async Task Where_equals_method_int(bool isAsync) { await base.Where_equals_method_int(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[EmployeeID] = 1"); } public override async Task Where_equals_using_object_overload_on_mismatched_types(bool isAsync) { await base.Where_equals_using_object_overload_on_mismatched_types(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE 0 = 1"); Assert.Contains( RelationalResources.LogPossibleUnintendedUseOfEquals(new TestLogger<SqlServerLoggingDefinitions>()).GenerateMessage( $"e.EmployeeID.Equals(Convert(__longPrm_0{ConvertParams}))"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); } public override async Task Where_equals_using_int_overload_on_mismatched_types(bool isAsync) { await base.Where_equals_using_int_overload_on_mismatched_types(isAsync); AssertSql( @"@__p_0='1' SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[EmployeeID] = @__p_0"); } public override async Task Where_equals_on_mismatched_types_nullable_int_long(bool isAsync) { await base.Where_equals_on_mismatched_types_nullable_int_long(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE 0 = 1", // @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE 0 = 1"); Assert.Contains( RelationalResources.LogPossibleUnintendedUseOfEquals(new TestLogger<SqlServerLoggingDefinitions>()).GenerateMessage( $"__longPrm_0.Equals(Convert(e.ReportsTo{ConvertParams}))"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); Assert.Contains( RelationalResources.LogPossibleUnintendedUseOfEquals(new TestLogger<SqlServerLoggingDefinitions>()).GenerateMessage( $"e.ReportsTo.Equals(Convert(__longPrm_0{ConvertParams}))"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); } public override async Task Where_equals_on_mismatched_types_nullable_long_nullable_int(bool isAsync) { await base.Where_equals_on_mismatched_types_nullable_long_nullable_int(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE 0 = 1", // @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE 0 = 1"); Assert.Contains( RelationalResources.LogPossibleUnintendedUseOfEquals(new TestLogger<SqlServerLoggingDefinitions>()).GenerateMessage( $"__nullableLongPrm_0.Equals(Convert(e.ReportsTo{ConvertParams}))"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); Assert.Contains( RelationalResources.LogPossibleUnintendedUseOfEquals(new TestLogger<SqlServerLoggingDefinitions>()).GenerateMessage( $"e.ReportsTo.Equals(Convert(__nullableLongPrm_0{ConvertParams}))"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); } public override async Task Where_equals_on_mismatched_types_int_nullable_int(bool isAsync) { await base.Where_equals_on_mismatched_types_int_nullable_int(isAsync); AssertSql( @"@__intPrm_0='2' SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__intPrm_0", // @"@__intPrm_0='2' SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE @__intPrm_0 = [e].[ReportsTo]"); } public override async Task Where_equals_on_matched_nullable_int_types(bool isAsync) { await base.Where_equals_on_matched_nullable_int_types(isAsync); AssertSql( @"@__nullableIntPrm_0='2' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE @__nullableIntPrm_0 = [e].[ReportsTo]", // @"@__nullableIntPrm_0='2' (Nullable = true) SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = @__nullableIntPrm_0"); } public override async Task Where_equals_on_null_nullable_int_types(bool isAsync) { await base.Where_equals_on_null_nullable_int_types(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] IS NULL", // @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] IS NULL"); } public override async Task Where_comparison_nullable_type_not_null(bool isAsync) { await base.Where_comparison_nullable_type_not_null(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] = 2"); } public override async Task Where_comparison_nullable_type_null(bool isAsync) { await base.Where_comparison_nullable_type_null(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE [e].[ReportsTo] IS NULL"); } public override async Task Where_string_length(bool isAsync) { await base.Where_string_length(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE CAST(LEN([c].[City]) AS int) = 6"); } public override async Task Where_string_indexof(bool isAsync) { await base.Where_string_indexof(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE ((CHARINDEX(N'Sea', [c].[City]) - 1) <> -1) OR [c].[City] IS NULL"); } public override async Task Where_string_replace(bool isAsync) { await base.Where_string_replace(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE REPLACE([c].[City], N'Sea', N'Rea') = N'Reattle'"); } public override async Task Where_string_substring(bool isAsync) { await base.Where_string_substring(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE SUBSTRING([c].[City], 2, 2) = N'ea'"); } public override async Task Where_datetime_now(bool isAsync) { await base.Where_datetime_now(isAsync); AssertSql( @"@__myDatetime_0='2015-04-10T00:00:00' SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE GETDATE() <> @__myDatetime_0"); } public override async Task Where_datetime_utcnow(bool isAsync) { await base.Where_datetime_utcnow(isAsync); AssertSql( @"@__myDatetime_0='2015-04-10T00:00:00' SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE GETUTCDATE() <> @__myDatetime_0"); } public override async Task Where_datetime_today(bool isAsync) { await base.Where_datetime_today(isAsync); AssertSql( @"SELECT [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Employees] AS [e] WHERE CONVERT(date, GETDATE()) = CONVERT(date, GETDATE())"); } public override async Task Where_datetime_date_component(bool isAsync) { await base.Where_datetime_date_component(isAsync); AssertSql( @"@__myDatetime_0='1998-05-04T00:00:00' (DbType = DateTime) SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE CONVERT(date, [o].[OrderDate]) = @__myDatetime_0"); } public override async Task Where_date_add_year_constant_component(bool isAsync) { await base.Where_date_add_year_constant_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(year, DATEADD(year, -1, [o].[OrderDate])) = 1997"); } public override async Task Where_datetime_year_component(bool isAsync) { await base.Where_datetime_year_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(year, [o].[OrderDate]) = 1998"); } public override async Task Where_datetime_month_component(bool isAsync) { await base.Where_datetime_month_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(month, [o].[OrderDate]) = 4"); } public override async Task Where_datetime_dayOfYear_component(bool isAsync) { await base.Where_datetime_dayOfYear_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(dayofyear, [o].[OrderDate]) = 68"); } public override async Task Where_datetime_day_component(bool isAsync) { await base.Where_datetime_day_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(day, [o].[OrderDate]) = 4"); } public override async Task Where_datetime_hour_component(bool isAsync) { await base.Where_datetime_hour_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(hour, [o].[OrderDate]) = 14"); } public override async Task Where_datetime_minute_component(bool isAsync) { await base.Where_datetime_minute_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(minute, [o].[OrderDate]) = 23"); } public override async Task Where_datetime_second_component(bool isAsync) { await base.Where_datetime_second_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(second, [o].[OrderDate]) = 44"); } public override async Task Where_datetime_millisecond_component(bool isAsync) { await base.Where_datetime_millisecond_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE DATEPART(millisecond, [o].[OrderDate]) = 88"); } public override async Task Where_datetimeoffset_now_component(bool isAsync) { await base.Where_datetimeoffset_now_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE [o].[OrderDate] = SYSDATETIMEOFFSET()"); } public override async Task Where_datetimeoffset_utcnow_component(bool isAsync) { await base.Where_datetimeoffset_utcnow_component(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE [o].[OrderDate] = CAST(SYSUTCDATETIME() AS datetimeoffset)"); } public override async Task Where_simple_reversed(bool isAsync) { await base.Where_simple_reversed(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE N'London' = [c].[City]"); } public override async Task Where_is_null(bool isAsync) { await base.Where_is_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] IS NULL"); } public override async Task Where_null_is_null(bool isAsync) { await base.Where_null_is_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_constant_is_null(bool isAsync) { await base.Where_constant_is_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE 0 = 1"); } public override async Task Where_is_not_null(bool isAsync) { await base.Where_is_not_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] IS NOT NULL"); } public override async Task Where_null_is_not_null(bool isAsync) { await base.Where_null_is_not_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE 0 = 1"); } public override async Task Where_constant_is_not_null(bool isAsync) { await base.Where_constant_is_not_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_identity_comparison(bool isAsync) { await base.Where_identity_comparison(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE ([c].[City] = [c].[City]) OR [c].[City] IS NULL"); } public override async Task Where_in_optimization_multiple(bool isAsync) { await base.Where_in_optimization_multiple(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE ([c].[City] IN (N'London', N'Berlin') OR ([c].[CustomerID] = N'ALFKI')) OR ([c].[CustomerID] = N'ABCDE')"); } public override async Task Where_not_in_optimization1(bool isAsync) { await base.Where_not_in_optimization1(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE (([c].[City] <> N'London') OR [c].[City] IS NULL) AND (([e].[City] <> N'London') OR [e].[City] IS NULL)"); } public override async Task Where_not_in_optimization2(bool isAsync) { await base.Where_not_in_optimization2(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE [c].[City] NOT IN (N'London', N'Berlin')"); } public override async Task Where_not_in_optimization3(bool isAsync) { await base.Where_not_in_optimization3(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE [c].[City] NOT IN (N'London', N'Berlin', N'Seattle')"); } public override async Task Where_not_in_optimization4(bool isAsync) { await base.Where_not_in_optimization4(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE [c].[City] NOT IN (N'London', N'Berlin', N'Seattle', N'Lisboa')"); } public override async Task Where_select_many_and(bool isAsync) { await base.Where_select_many_and(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title] FROM [Customers] AS [c] CROSS JOIN [Employees] AS [e] WHERE (([c].[City] = N'London') AND ([c].[Country] = N'UK')) AND (([e].[City] = N'London') AND ([e].[Country] = N'UK'))"); } public override async Task Where_primitive(bool isAsync) { await base.Where_primitive(isAsync); AssertSql( @"@__p_0='9' SELECT [t].[EmployeeID] FROM ( SELECT TOP(@__p_0) [e].[EmployeeID] FROM [Employees] AS [e] ) AS [t] WHERE [t].[EmployeeID] = 5"); } public override async Task Where_bool_member(bool isAsync) { await base.Where_bool_member(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(1 AS bit)"); } public override async Task Where_bool_member_false(bool isAsync) { await base.Where_bool_member_false(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(0 AS bit)"); } public override async Task Where_bool_client_side_negated(bool isAsync) { await base.Where_bool_client_side_negated(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = 1"); } public override async Task Where_bool_member_negated_twice(bool isAsync) { await base.Where_bool_member_negated_twice(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(1 AS bit)"); } public override async Task Where_bool_member_shadow(bool isAsync) { await base.Where_bool_member_shadow(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(1 AS bit)"); } public override async Task Where_bool_member_false_shadow(bool isAsync) { await base.Where_bool_member_false_shadow(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(0 AS bit)"); } public override async Task Where_bool_member_equals_constant(bool isAsync) { await base.Where_bool_member_equals_constant(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CAST(1 AS bit)"); } public override async Task Where_bool_member_in_complex_predicate(bool isAsync) { await base.Where_bool_member_in_complex_predicate(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE (([p].[ProductID] > 100) AND ([p].[Discontinued] = CAST(1 AS bit))) OR ([p].[Discontinued] = CAST(1 AS bit))"); } public override async Task Where_bool_member_compared_to_binary_expression(bool isAsync) { await base.Where_bool_member_compared_to_binary_expression(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CASE WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Where_not_bool_member_compared_to_not_bool_member(bool isAsync) { await base.Where_not_bool_member_compared_to_not_bool_member(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = [p].[Discontinued]"); } public override async Task Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(bool isAsync) { await base.Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE CASE WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END = CASE WHEN [p].[ProductID] > 20 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Where_not_bool_member_compared_to_binary_expression(bool isAsync) { await base.Where_not_bool_member_compared_to_binary_expression(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] <> CASE WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Where_bool_parameter(bool isAsync) { await base.Where_bool_parameter(isAsync); AssertSql( @"@__prm_0='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE @__prm_0 = CAST(1 AS bit)"); } public override async Task Where_bool_parameter_compared_to_binary_expression(bool isAsync) { await base.Where_bool_parameter_compared_to_binary_expression(isAsync); AssertSql( @"@__prm_0='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE CASE WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END <> @__prm_0"); } public override async Task Where_bool_member_and_parameter_compared_to_binary_expression_nested(bool isAsync) { await base.Where_bool_member_and_parameter_compared_to_binary_expression_nested(isAsync); AssertSql( @"@__prm_0='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[Discontinued] = CASE WHEN CASE WHEN [p].[ProductID] > 50 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END <> @__prm_0 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Where_de_morgan_or_optimizated(bool isAsync) { await base.Where_de_morgan_or_optimizated(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE ([p].[Discontinued] = CAST(0 AS bit)) AND ([p].[ProductID] >= 20)"); } public override async Task Where_de_morgan_and_optimizated(bool isAsync) { await base.Where_de_morgan_and_optimizated(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE ([p].[Discontinued] = CAST(0 AS bit)) OR ([p].[ProductID] >= 20)"); } public override async Task Where_complex_negated_expression_optimized(bool isAsync) { await base.Where_complex_negated_expression_optimized(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE (([p].[Discontinued] = CAST(0 AS bit)) AND ([p].[ProductID] < 60)) AND ([p].[ProductID] > 30)"); } public override async Task Where_short_member_comparison(bool isAsync) { await base.Where_short_member_comparison(isAsync); AssertSql( @"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE [p].[UnitsInStock] > CAST(10 AS smallint)"); } public override async Task Where_comparison_to_nullable_bool(bool isAsync) { await base.Where_comparison_to_nullable_bool(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE RIGHT([c].[CustomerID], LEN(N'KI')) = N'KI'"); } public override async Task Where_true(bool isAsync) { await base.Where_true(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_false(bool isAsync) { await base.Where_false(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE 0 = 1"); } public override async Task Where_default(bool isAsync) { await base.Where_default(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[Fax] IS NULL"); } public override async Task Where_expression_invoke(bool isAsync) { await base.Where_expression_invoke(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] = N'ALFKI'"); } public override async Task Where_concat_string_int_comparison1(bool isAsync) { await base.Where_concat_string_int_comparison1(isAsync); AssertSql( @"@__i_0='10' SELECT [c].[CustomerID] FROM [Customers] AS [c] WHERE ([c].[CustomerID] + CAST(@__i_0 AS nvarchar(max))) = [c].[CompanyName]"); } public override async Task Where_concat_string_int_comparison2(bool isAsync) { await base.Where_concat_string_int_comparison2(isAsync); AssertSql( @"@__i_0='10' SELECT [c].[CustomerID] FROM [Customers] AS [c] WHERE (CAST(@__i_0 AS nvarchar(max)) + [c].[CustomerID]) = [c].[CompanyName]"); } public override async Task Where_concat_string_int_comparison3(bool isAsync) { await base.Where_concat_string_int_comparison3(isAsync); AssertSql( @"@__p_0='30' @__j_1='21' SELECT [c].[CustomerID] FROM [Customers] AS [c] WHERE (((CAST(@__p_0 AS nvarchar(max)) + [c].[CustomerID]) + CAST(@__j_1 AS nvarchar(max))) + CAST(42 AS nvarchar(max))) = [c].[CompanyName]"); } public override async Task Where_ternary_boolean_condition_true(bool isAsync) { await base.Where_ternary_boolean_condition_true(isAsync); AssertSql( @"@__flag_0='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE ((@__flag_0 = CAST(1 AS bit)) AND ([p].[UnitsInStock] >= CAST(20 AS smallint))) OR ((@__flag_0 <> CAST(1 AS bit)) AND ([p].[UnitsInStock] < CAST(20 AS smallint)))"); } public override async Task Where_ternary_boolean_condition_false(bool isAsync) { await base.Where_ternary_boolean_condition_false(isAsync); AssertSql( @"@__flag_0='False' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE ((@__flag_0 = CAST(1 AS bit)) AND ([p].[UnitsInStock] >= CAST(20 AS smallint))) OR ((@__flag_0 <> CAST(1 AS bit)) AND ([p].[UnitsInStock] < CAST(20 AS smallint)))"); } public override async Task Where_ternary_boolean_condition_with_another_condition(bool isAsync) { await base.Where_ternary_boolean_condition_with_another_condition(isAsync); AssertSql( @"@__productId_0='15' @__flag_1='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE ([p].[ProductID] < @__productId_0) AND (((@__flag_1 = CAST(1 AS bit)) AND ([p].[UnitsInStock] >= CAST(20 AS smallint))) OR ((@__flag_1 <> CAST(1 AS bit)) AND ([p].[UnitsInStock] < CAST(20 AS smallint))))"); } public override async Task Where_ternary_boolean_condition_with_false_as_result_true(bool isAsync) { await base.Where_ternary_boolean_condition_with_false_as_result_true(isAsync); AssertSql( @"@__flag_0='True' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE (@__flag_0 = CAST(1 AS bit)) AND ([p].[UnitsInStock] >= CAST(20 AS smallint))"); } public override async Task Where_ternary_boolean_condition_with_false_as_result_false(bool isAsync) { await base.Where_ternary_boolean_condition_with_false_as_result_false(isAsync); AssertSql( @"@__flag_0='False' SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock] FROM [Products] AS [p] WHERE (@__flag_0 = CAST(1 AS bit)) AND ([p].[UnitsInStock] >= CAST(20 AS smallint))"); } public override async Task Where_compare_constructed_equal(bool isAsync) { await base.Where_compare_constructed_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Ternary_should_not_evaluate_both_sides(bool isAsync) { await base.Ternary_should_not_evaluate_both_sides(isAsync); AssertSql( @"@__p_0='none' (Size = 4000) @__p_1='none' (Size = 4000) @__p_2='none' (Size = 4000) SELECT [c].[CustomerID], @__p_0 AS [Data1], @__p_1 AS [Data2], @__p_2 AS [Data3] FROM [Customers] AS [c]"); } public override async Task Where_compare_constructed_multi_value_equal(bool isAsync) { await base.Where_compare_constructed_multi_value_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_constructed_multi_value_not_equal(bool isAsync) { await base.Where_compare_constructed_multi_value_not_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_constructed_equal(bool isAsync) { await base.Where_compare_tuple_constructed_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_constructed_multi_value_equal(bool isAsync) { await base.Where_compare_tuple_constructed_multi_value_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_constructed_multi_value_not_equal(bool isAsync) { await base.Where_compare_tuple_constructed_multi_value_not_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_create_constructed_equal(bool isAsync) { await base.Where_compare_tuple_create_constructed_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_create_constructed_multi_value_equal(bool isAsync) { await base.Where_compare_tuple_create_constructed_multi_value_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_tuple_create_constructed_multi_value_not_equal(bool isAsync) { await base.Where_compare_tuple_create_constructed_multi_value_not_equal(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_compare_null(bool isAsync) { await base.Where_compare_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] IS NULL AND ([c].[Country] = N'UK')"); } public override async Task Where_Is_on_same_type(bool isAsync) { await base.Where_Is_on_same_type(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"); } public override async Task Where_chain(bool isAsync) { await base.Where_chain(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE ([o].[CustomerID] = N'QUICK') AND ([o].[OrderDate] > '1998-01-01T00:00:00.000')"); } public override void Where_navigation_contains() { base.Where_navigation_contains(); AssertSql( @"SELECT TOP(2) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] = N'ALFKI' ORDER BY [c].[CustomerID]", // @"SELECT [c.Orders].[OrderID], [c.Orders].[CustomerID], [c.Orders].[EmployeeID], [c.Orders].[OrderDate] FROM [Orders] AS [c.Orders] INNER JOIN ( SELECT TOP(1) [c0].[CustomerID] FROM [Customers] AS [c0] WHERE [c0].[CustomerID] = N'ALFKI' ORDER BY [c0].[CustomerID] ) AS [t] ON [c.Orders].[CustomerID] = [t].[CustomerID] ORDER BY [t].[CustomerID]", // @"SELECT [od].[OrderID], [od].[ProductID], [od].[Discount], [od].[Quantity], [od].[UnitPrice] FROM [Order Details] AS [od]"); } public override async Task Where_array_index(bool isAsync) { await base.Where_array_index(isAsync); AssertSql( @"@__p_0='ALFKI' (Size = 5) SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[CustomerID] = @__p_0"); } public override async Task Where_multiple_contains_in_subquery_with_or(bool isAsync) { await base.Where_multiple_contains_in_subquery_with_or(isAsync); AssertSql( @"SELECT [od].[OrderID], [od].[ProductID], [od].[Discount], [od].[Quantity], [od].[UnitPrice] FROM [Order Details] AS [od] WHERE [od].[ProductID] IN ( SELECT TOP(1) [p].[ProductID] FROM [Products] AS [p] ORDER BY [p].[ProductID] ) OR [od].[OrderID] IN ( SELECT TOP(1) [o].[OrderID] FROM [Orders] AS [o] ORDER BY [o].[OrderID] )"); } public override async Task Where_multiple_contains_in_subquery_with_and(bool isAsync) { await base.Where_multiple_contains_in_subquery_with_and(isAsync); AssertSql( @"SELECT [od].[OrderID], [od].[ProductID], [od].[Discount], [od].[Quantity], [od].[UnitPrice] FROM [Order Details] AS [od] WHERE [od].[ProductID] IN ( SELECT TOP(20) [p].[ProductID] FROM [Products] AS [p] ORDER BY [p].[ProductID] ) AND [od].[OrderID] IN ( SELECT TOP(10) [o].[OrderID] FROM [Orders] AS [o] ORDER BY [o].[OrderID] )"); } public override async Task Where_contains_on_navigation(bool isAsync) { await base.Where_contains_on_navigation(isAsync); AssertSql( @"SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE EXISTS ( SELECT 1 FROM [Customers] AS [c] WHERE [o].[OrderID] IN ( SELECT [o0].[OrderID] FROM [Orders] AS [o0] WHERE [c].[CustomerID] = [o0].[CustomerID] ))"); } public override async Task Where_subquery_FirstOrDefault_is_null(bool isAsync) { await base.Where_subquery_FirstOrDefault_is_null(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE ( SELECT TOP(1) [o].[OrderID] FROM [Orders] AS [o] WHERE [c].[CustomerID] = [o].[CustomerID] ORDER BY [o].[OrderID] ) IS NULL"); } public override async Task Where_subquery_FirstOrDefault_compared_to_entity(bool isAsync) { await base.Where_subquery_FirstOrDefault_compared_to_entity(isAsync); AssertSql( @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE ( SELECT TOP(1) [o].[OrderID] FROM [Orders] AS [o] WHERE [c].[CustomerID] = [o].[CustomerID] ORDER BY [o].[OrderID] ) = 10243"); } public override async Task Time_of_day_datetime(bool isAsync) { await base.Time_of_day_datetime(isAsync); AssertSql( @"SELECT CAST([c].[OrderDate] AS time) FROM [Orders] AS [c]"); } public override async Task TypeBinary_short_circuit(bool isAsync) { await base.TypeBinary_short_circuit(isAsync); AssertSql( @"@__p_0='False' SELECT [o].[OrderID], [o].[CustomerID], [o].[EmployeeID], [o].[OrderDate] FROM [Orders] AS [o] WHERE @__p_0 = CAST(1 AS bit)"); } } }
41.60197
289
0.592911
[ "Apache-2.0" ]
BionStt/EntityFrameworkCore
test/EFCore.SqlServer.FunctionalTests/Query/SimpleQuerySqlServerTest.Where.cs
71,807
C#
using System.Diagnostics.CodeAnalysis; using System.Globalization; using AJTaskManagerMobile.DataServices; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using AJTaskManagerMobile.Model; using AJTaskManagerMobile.Views; namespace AJTaskManagerMobile.ViewModel { /// <summary> /// This class contains static references to the most relevant view models in the /// application and provides an entry point for the bindings. /// <para> /// See http://www.mvvmlight.net /// </para> /// </summary> public class ViewModelLocator { /// <summary> /// The key used by the NavigationService to go to the second page. /// </summary> public const string SecondPageKey = "SecondPage"; /// <summary> /// Gets the Main property. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } public ToDoItemsViewModel ToDoItemsViewModel { get { return ServiceLocator.Current.GetInstance<ToDoItemsViewModel>(); } } public ToDoListsViewModel ToDoListsViewModel { get { return ServiceLocator.Current.GetInstance<ToDoListsViewModel>(); } } public GroupsViewModel GroupsViewModel { get { return ServiceLocator.Current.GetInstance<GroupsViewModel>(); } } public GroupUsersViewModel GroupUsersViewModel { get { return ServiceLocator.Current.GetInstance<GroupUsersViewModel>(); } } public UsersPermissionsViewModel UsersPermissionsViewModel { get { return ServiceLocator.Current.GetInstance<UsersPermissionsViewModel>(); } } public TasksListViewModel TasksViewModel { get { return ServiceLocator.Current.GetInstance<TasksListViewModel>(); } } public TaskItemViewModel TaskItemViewModel { get { return ServiceLocator.Current.GetInstance<TaskItemViewModel>(); } } public TaskSubitemsListViewModel TaskSubitemsListViewModel { get { return ServiceLocator.Current.GetInstance<TaskSubitemsListViewModel>(); } } public TaskSubitemViewModel TaskSubitemViewModel { get { return ServiceLocator.Current.GetInstance<TaskSubitemViewModel>(); } } public TaskSubitemWorkPageViewModel TaskSubitemWorkPageViewModel { get { return ServiceLocator.Current.GetInstance<TaskSubitemWorkPageViewModel>(); } } public SettingsViewModel SettingsViewModel { get { return ServiceLocator.Current.GetInstance<SettingsViewModel>(); } } public PersonalSettingsViewModel PersonalSettingsViewModel { get { return ServiceLocator.Current.GetInstance<PersonalSettingsViewModel>(); } } public GroupsMembershipViewModel GroupsMembershipViewModel { get { return ServiceLocator.Current.GetInstance<GroupsMembershipViewModel>(); } } public ActualTasksViewModel ActualTasksViewModel { get { return ServiceLocator.Current.GetInstance<ActualTasksViewModel>(); } } public TasksInProgressViewModel TasksInProgressViewModel { get { return ServiceLocator.Current.GetInstance<TasksInProgressViewModel>(); } } public CalendarWithTaskItemsViewModel CalendarWithTaskItemsViewModel { get { return ServiceLocator.Current.GetInstance<CalendarWithTaskItemsViewModel>(); } } public SchedulerPageViewModel SchedulerPageViewModel { get { return ServiceLocator.Current.GetInstance<SchedulerPageViewModel>(); } } public TasksOverdueViewModel TasksOverdueViewModel { get { return ServiceLocator.Current.GetInstance<TasksOverdueViewModel>(); } } /// <summary> /// This property can be used to force the application to run with design time data. /// </summary> public static bool UseDesignTimeData { get { return false; } } static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<IUserDataService, UserDataService>(); SimpleIoc.Default.Register<ITodoListDataService, TodoListDataService>(); SimpleIoc.Default.Register<ITodoItemsDataService, TodoItemsDataService>(); SimpleIoc.Default.Register<IGroupDataService, GroupDataService>(); SimpleIoc.Default.Register<IUserGroupDataService, UserGroupDataService>(); SimpleIoc.Default.Register<IRoleTypeDataService, RoleTypeDataService>(); SimpleIoc.Default.Register<ITaskItemDataService, TaskItemDataService>(); SimpleIoc.Default.Register<ITaskSubitemDataService, TaskSubitemDataService>(); SimpleIoc.Default.Register<ITaskSubitemWorkDataService, TaskSubitemWorkDataService>(); SimpleIoc.Default.Register<ISettingsService, SettingsService>(); SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<ToDoItemsViewModel>(); SimpleIoc.Default.Register<ToDoListsViewModel>(); SimpleIoc.Default.Register<GroupsViewModel>(); SimpleIoc.Default.Register<GroupUsersViewModel>(); SimpleIoc.Default.Register<UsersPermissionsViewModel>(); SimpleIoc.Default.Register<TasksListViewModel>(); SimpleIoc.Default.Register<TaskItemViewModel>(); SimpleIoc.Default.Register<TaskSubitemViewModel>(); SimpleIoc.Default.Register<TaskSubitemsListViewModel>(); SimpleIoc.Default.Register<TaskSubitemWorkPageViewModel>(); SimpleIoc.Default.Register<SettingsViewModel>(); SimpleIoc.Default.Register<PersonalSettingsViewModel>(); SimpleIoc.Default.Register<GroupsMembershipViewModel>(); SimpleIoc.Default.Register<ActualTasksViewModel>(); SimpleIoc.Default.Register<TasksInProgressViewModel>(); SimpleIoc.Default.Register<CalendarWithTaskItemsViewModel>(); SimpleIoc.Default.Register<SchedulerPageViewModel>(); SimpleIoc.Default.Register<TasksOverdueViewModel>(); } /// <summary> /// Cleans up all the resources. /// </summary> public static void Cleanup() { } } }
38.005495
98
0.660546
[ "Apache-2.0" ]
qbasko/AJTaskManager
AJTaskManagerService/AJTaskManagerMobile/ViewModel/ViewModelLocator.cs
6,919
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Primitives; using Stardust.Interstellar.Rest.Annotations; using Stardust.Interstellar.Rest.Common; using Stardust.Interstellar.Rest.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace NetCoreTestWeb.Controllers { [Api("api/test")] //[AuthorizeWrapper] [ServiceInformation] public interface IMyServies { [Get("Echo/{value}","test")] string Echo([In(InclutionTypes.Path)] string value); [Obsolete("test")] [Get("Echo2/{value}")] Task<StringWrapper> Echo2Async([In(InclutionTypes.Path)] string value); } public class ServiceInformationAttribute : HeaderInspectorAttributeBase, IHeaderHandler { public override IHeaderHandler[] GetHandlers(IServiceProvider serviceLocator) { return new[] { this }; } public void SetHeader(HttpRequestMessage req) { } public void GetHeader(HttpResponseMessage response) { } public void GetServiceHeader(HttpRequestHeaders headers) { } public void GetServiceHeader(IDictionary<string, StringValues> headers) { } public void SetServiceHeaders(HttpResponseHeaders headers) { } public void SetServiceHeaders(IDictionary<string, StringValues> headers) { headers.Add("x-app-type", "netcore"); } public int ProcessingOrder { get { return 0; } } } public class StringWrapper { public string Value { get; set; } public string User { get; set; } } internal class MyServies : IMyServies { private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; public MyServies(IHttpContextAccessor httpContextAccessor, ILogger logger) { _httpContextAccessor = httpContextAccessor; _logger = logger; } public string Echo(string value) { return value; } public Task<StringWrapper> Echo2Async(string value) { _logger?.Message(string.Join("\n", _httpContextAccessor.HttpContext.User.Claims.Select(c => $"{c.Type} - {c.Value}"))); return Task.FromResult(new StringWrapper { Value = value, User = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value }); } } [Route("api/[controller]")] public class ValuesController : Controller { private readonly IDummyClient _client; public ValuesController(IDummyClient client) { _client = client; } // GET api/values [HttpGet] public async Task<IEnumerable<string>> Get() { var value = await _client.Echo("test"); return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet] [Route("get{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
26.049645
211
0.602777
[ "Apache-2.0" ]
JonasSyrstad/Stardust.Rest
NetCoreTestWeb/Controllers/ValuesController.cs
3,675
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable namespace Microsoft.AspNetCore.Mvc.Infrastructure { /// <summary> /// An <see cref="IStatusCodeActionResult"/> that can be transformed to a more descriptive client error. /// </summary> public interface IClientErrorActionResult : IStatusCodeActionResult { } }
29.333333
108
0.729545
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.Core/src/Infrastructure/IClientErrorActionResult.cs
440
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace Vim.VisualStudio { /// <summary> /// Id of an EnvDTE.Command object. The Name portion of a Command is optional and doesn't /// figure into the name. The Guid and ID are unique to a command /// </summary> public struct CommandId : IEquatable<CommandId> { public readonly Guid Group; public readonly uint Id; public CommandId(Guid group, uint id) { Group = group; Id = id; } public bool Equals(CommandId other) { return Id == other.Id && Group == other.Group; } public override bool Equals(object obj) { if (obj is CommandId) { return Equals((CommandId)obj); } return false; } public override int GetHashCode() { return (int)Id ^ Group.GetHashCode(); } public override string ToString() { return string.Format("{0} - {1}", Group, Id); } public static bool operator ==(CommandId left, CommandId right) { return left.Equals(right); } public static bool operator !=(CommandId left, CommandId right) { return !left.Equals(right); } } /// <summary> /// Represents the KeyBinding information for a Visual Studio command /// </summary> public sealed class CommandKeyBinding : IEquatable<CommandKeyBinding> { /// <summary> /// The unique id of the command /// </summary> public readonly CommandId Id; /// <summary> /// Name of the Visual Studio Command /// </summary> public readonly string Name; /// <summary> /// KeyBinding for this command /// </summary> public readonly KeyBinding KeyBinding; public CommandKeyBinding(CommandId commandId, string name, KeyBinding binding) { Id = commandId; Name = name; KeyBinding = binding; } public override int GetHashCode() { return Id.GetHashCode() ^ KeyBinding.GetHashCode(); } public override bool Equals(object obj) { return Equals(obj as CommandKeyBinding); } public bool Equals(CommandKeyBinding other) { if (other == null) { return false; } return Id == other.Id && StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name) && KeyBinding == other.KeyBinding; } public static bool operator ==(CommandKeyBinding left, CommandKeyBinding right) { return EqualityComparer<CommandKeyBinding>.Default.Equals(left, right); } public static bool operator !=(CommandKeyBinding left, CommandKeyBinding right) { return !EqualityComparer<CommandKeyBinding>.Default.Equals(left, right); } public override string ToString() { return Name + "::" + KeyBinding; } } }
27
95
0.523259
[ "Apache-2.0" ]
L1031353632/VsVim
Src/VsVimShared/CommandKeyBinding.cs
3,377
C#