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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestParser.Target { public class Function : Parameter { /// <summary> /// Default constructor. /// </summary> public Function() : base() { this.Arguments = new List<Parameter>(0); this.SubFunctions = new List<Function>(0); } /// <summary> /// Copy constructor /// </summary> /// <param name="src"></param> public Function(Function src) : base(src) { if (src is Function) { this.SubFunctions = new List<Function>(src.SubFunctions); this.Arguments = new List<Parameter>(src.Arguments); } } /// <summary> /// List of sub functions. /// </summary> public IEnumerable<Function> SubFunctions { get; set; } /// <summary> /// List of arguments. /// </summary> public IEnumerable<Parameter> Arguments { get; set; } /// <summary> /// Create string of funtion definition. /// </summary> /// <returns>Function definition in string.</returns> public override string ToString() { var toString = base.ToString(); toString += "("; try { bool isTop = true; foreach (var argument in this.Arguments) { if (!isTop) { toString += ", "; } toString += argument.ToString(); isTop = false; } } catch (NullReferenceException) { //No argumetn -> Skip! } toString += ")"; return toString; } /// <summary> /// Returns whether the function will return any value or not. /// </summary> /// <returns> /// Returns true if the function will return any value, /// otherwise return false. /// </returns> public bool HasReturn() { bool hasReturn = false; if ((("void").Equals(this.DataType.ToLower(), StringComparison.Ordinal)) && (PointerNum <= 0)) { //A case that the data type without pointer means the function returns no value via return value. hasReturn = false; } else { hasReturn = true; } return hasReturn; } } }
22.061856
102
0.585981
[ "MIT" ]
CountrySideEngineer/TestSupportTools
AutoTestPrep/dev/src/TestParser.SDK/Test/Target/Function.cs
2,142
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This file was generated by Extensibility Tools 2015 v1.7.160 // </auto-generated> // ------------------------------------------------------------------------------ namespace MadsKristensen.FileNesting { using System; /// <summary> /// Helper class that exposes all GUIDs used across VS Package. /// </summary> internal sealed partial class PackageGuids { public const string guidFileNestingPkgString = "6c799bc4-0d4c-4172-98bc-5d464b612dca"; public const string guidFileNestingCmdSetString = "a5bb8f41-d79a-4de2-bd13-857f39dd0f3f"; public const string guidImagesString = "c24fa2f3-0d5d-498f-8bee-2947e84addbd"; public static Guid guidFileNestingPkg = new Guid(guidFileNestingPkgString); public static Guid guidFileNestingCmdSet = new Guid(guidFileNestingCmdSetString); public static Guid guidImages = new Guid(guidImagesString); } /// <summary> /// Helper class that encapsulates all CommandIDs uses across VS Package. /// </summary> internal sealed partial class PackageIds { public const int NestingMenu = 0x1000; public const int MyMenuGroup = 0x1020; public const int cmdUnNest = 0x1030; public const int cmdNest = 0x1040; public const int AutoNestGroup = 0x1050; public const int cmdAutoNesting = 0x1060; public const int cmdRunNesting = 0x1070; public const int bmpPic1 = 0x0001; public const int bmpPic2 = 0x0002; public const int bmpPicSearch = 0x0003; public const int bmpPicX = 0x0004; public const int bmpPicArrows = 0x0005; public const int bmpPicStrikethrough = 0x0006; } }
42.97619
97
0.627147
[ "Apache-2.0" ]
Jesus210290/FileNesting
src/VSCommandTable.cs
1,805
C#
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using System.Net.Http; using System.Net.Http.Headers; using System.Linq; using System.Collections.Generic; using System.Threading; using Microsoft.Bot.Builder.Luis.Models; using Microsoft.Bot.Builder.Luis; namespace MioBot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { private const string CompareProduct = "比較不同型號產品"; private const string MapInforUpdate = "圖資更新"; private const string UpdateOption = "更新(提供選項)"; private const string ProductFault = "產品故障"; private const string RepairQuery = "維修查詢"; private const string MioFAQ = "常見問題咨詢"; private const string NavigatorOption = "导航"; private const string cdRecorderOption = "行车记录仪"; private readonly ResumeAfter<object> MessageReceived; public async Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); } public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) { var message = await result; if (message == null) { string msg = "請輸入文字!!"; await context.PostAsync(msg); } if (message.Text.ToLower().Contains("help") || message.Text.ToLower().Contains("support") || message.Text.ToLower().Contains("problem")) { await context.Forward(new SupportDialog(), this.ResumeAfterSupportDialog, message, CancellationToken.None); } else { this.ShowOptions(context); } } private void ShowOptions(IDialogContext context) { PromptDialog.Choice(context, this.OnOptionSelected, new List<string>() { CompareProduct,MapInforUpdate, UpdateOption, ProductFault, RepairQuery, MioFAQ }, "## 請選擇服務類型:", "無效選擇!", 7); } private async Task OnOptionSelected(IDialogContext context, IAwaitable<string> result) { try { string optionSelected = await result; switch (optionSelected) { case CompareProduct: context.Call(new CompareProductDialog(), this.ResumeAfterOptionDialog); break; case MapInforUpdate: context.Call(new MapInforUpdateDialog(), this.ResumeAfterOptionDialog); break; case UpdateOption: context.Call(new UpdateOptionDialog(), this.ResumeAfterOptionDialog); break; case ProductFault: context.Call(new ProductFaultDialog(), this.ResumeAfterOptionDialog); break; case RepairQuery: context.Call(new RepairQueryDialog(), this.ResumeAfterOptionDialog); break; case MioFAQ: context.Call(new QnaFAQDialog(), this.ResumeAfterOptionDialog); break; default: break; } } catch (TooManyAttemptsException ex) { await context.PostAsync($"Ooops! Too many attemps :(. But don't worry, I'm handling that exception and you can try again!"); await this.StartAsync(context); } } private async Task ResumeAfterSupportDialog(IDialogContext context, IAwaitable<int> result) { var ticketNumber = await result; await context.PostAsync($"Thanks for contacting our support team. Your ticket number is {ticketNumber}."); await this.StartAsync(context); } private async Task ResumeAfterOptionDialog(IDialogContext context, IAwaitable<object> result) { try { var message = await result; } catch (Exception ex) { //await context.PostAsync($"Failed with message: {ex.Message}"); } finally { await this.StartAsync(context); } } } }
35.592308
149
0.536633
[ "MIT" ]
BorisGray/ChatBot
MioBot/Dialogs/RootDialog.cs
4,751
C#
namespace _2.Oldest_Family_Member { using System; using System.Reflection; public class Startup { public static void Main() { MethodInfo oldestMemberMethod = typeof(Family).GetMethod("GetOldestMember"); MethodInfo addMemberMethod = typeof(Family).GetMethod("AddMember"); if (oldestMemberMethod == null || addMemberMethod == null) { throw new Exception(); } var n = int.Parse(Console.ReadLine()); Family family = new Family(); for (int i = 0; i < n; i++) { var tokens = Console.ReadLine().Split(' '); var name = tokens[0]; var age = int.Parse(tokens[1]); Person currentPerson = new Person(name, age); family.AddMember(currentPerson); } Person oldestMember = family.GetOldestMember(); Console.WriteLine("{0} {1}", oldestMember.name, oldestMember.age); } } }
32.59375
88
0.53116
[ "MIT" ]
alexandrateneva/CSharp-Fundamentals-SoftUni
CSharp OOP Basics/Defining Classes/2.Oldest Family Member/Startup.cs
1,045
C#
using Services.ServiceModels; using System.Collections.Generic; namespace Services.Interface { public interface ISeatingService { IEnumerable<SeatingModel> GetAll(); bool RemovePersonFromTable(int personId); bool AddPersonToTable(int personId, int tableId); } }
23.076923
57
0.723333
[ "MIT" ]
TB124/weddingapp
Services/Interface/ISeatingService.cs
302
C#
using System; using System.Collections.Generic; using System.Text; namespace BinaryConverter.models { public interface IBinaryReadable { byte GetNextByte(); bool EndOfSource(); } }
14.615385
33
0.763158
[ "MIT" ]
MasteroPL/BinaryConverter
BinaryConverter/BinaryConverter/models/IBinaryReadable.cs
192
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; /// <summary>A setting difference between two deployment slots of an app.</summary> public partial class SlotDifference : Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifference, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IValidates { /// <summary> /// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResource" /// /> /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResource __proxyOnlyResource = new Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ProxyOnlyResource(); /// <summary>Description of the setting difference.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Description; } /// <summary>Rule that describes how to process the setting difference during a slot swap.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string DiffRule { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).DiffRule; } /// <summary>Resource Id.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inherited)] public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Id; } /// <summary>Kind of resource.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inherited)] public string Kind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Kind; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Kind = value; } /// <summary>Level of the difference: Information, Warning or Error.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string Level { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Level; } /// <summary>Internal Acessors for Id</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Id = value; } /// <summary>Internal Acessors for Name</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Name = value; } /// <summary>Internal Acessors for Type</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Type = value; } /// <summary>Internal Acessors for Description</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Description = value; } /// <summary>Internal Acessors for DiffRule</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.DiffRule { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).DiffRule; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).DiffRule = value; } /// <summary>Internal Acessors for Level</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.Level { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Level; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).Level = value; } /// <summary>Internal Acessors for Property</summary> Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceProperties Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SlotDifferenceProperties()); set { {_property = value;} } } /// <summary>Internal Acessors for SettingName</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.SettingName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingName = value; } /// <summary>Internal Acessors for SettingType</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.SettingType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingType = value; } /// <summary>Internal Acessors for ValueInCurrentSlot</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.ValueInCurrentSlot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInCurrentSlot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInCurrentSlot = value; } /// <summary>Internal Acessors for ValueInTargetSlot</summary> string Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceInternal.ValueInTargetSlot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInTargetSlot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInTargetSlot = value; } /// <summary>Resource Name.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inherited)] public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Name; } /// <summary>Backing field for <see cref="Property" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceProperties _property; /// <summary>SlotDifference resource specific properties</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SlotDifferenceProperties()); set => this._property = value; } /// <summary>Name of the setting.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string SettingName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingName; } /// <summary>The type of the setting: General, AppSetting or ConnectionString.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string SettingType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).SettingType; } /// <summary>Resource type.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inherited)] public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)__proxyOnlyResource).Type; } /// <summary>Value of the setting in the current slot.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string ValueInCurrentSlot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInCurrentSlot; } /// <summary>Value of the setting in the target slot.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Inlined)] public string ValueInTargetSlot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferencePropertiesInternal)Property).ValueInTargetSlot; } /// <summary>Creates an new <see cref="SlotDifference" /> instance.</summary> public SlotDifference() { } /// <summary>Validates that this object meets the validation criteria.</summary> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IEventListener" /> instance that will receive validation /// events.</param> /// <returns> /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. /// </returns> public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IEventListener eventListener) { await eventListener.AssertNotNull(nameof(__proxyOnlyResource), __proxyOnlyResource); await eventListener.AssertObjectIsValid(nameof(__proxyOnlyResource), __proxyOnlyResource); } } /// A setting difference between two deployment slots of an app. public partial interface ISlotDifference : Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResource { /// <summary>Description of the setting difference.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Description of the setting difference.", SerializedName = @"description", PossibleTypes = new [] { typeof(string) })] string Description { get; } /// <summary>Rule that describes how to process the setting difference during a slot swap.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Rule that describes how to process the setting difference during a slot swap.", SerializedName = @"diffRule", PossibleTypes = new [] { typeof(string) })] string DiffRule { get; } /// <summary>Level of the difference: Information, Warning or Error.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Level of the difference: Information, Warning or Error.", SerializedName = @"level", PossibleTypes = new [] { typeof(string) })] string Level { get; } /// <summary>Name of the setting.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Name of the setting.", SerializedName = @"settingName", PossibleTypes = new [] { typeof(string) })] string SettingName { get; } /// <summary>The type of the setting: General, AppSetting or ConnectionString.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"The type of the setting: General, AppSetting or ConnectionString.", SerializedName = @"settingType", PossibleTypes = new [] { typeof(string) })] string SettingType { get; } /// <summary>Value of the setting in the current slot.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Value of the setting in the current slot.", SerializedName = @"valueInCurrentSlot", PossibleTypes = new [] { typeof(string) })] string ValueInCurrentSlot { get; } /// <summary>Value of the setting in the target slot.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = true, Description = @"Value of the setting in the target slot.", SerializedName = @"valueInTargetSlot", PossibleTypes = new [] { typeof(string) })] string ValueInTargetSlot { get; } } /// A setting difference between two deployment slots of an app. internal partial interface ISlotDifferenceInternal : Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal { /// <summary>Description of the setting difference.</summary> string Description { get; set; } /// <summary>Rule that describes how to process the setting difference during a slot swap.</summary> string DiffRule { get; set; } /// <summary>Level of the difference: Information, Warning or Error.</summary> string Level { get; set; } /// <summary>SlotDifference resource specific properties</summary> Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotDifferenceProperties Property { get; set; } /// <summary>Name of the setting.</summary> string SettingName { get; set; } /// <summary>The type of the setting: General, AppSetting or ConnectionString.</summary> string SettingType { get; set; } /// <summary>Value of the setting in the current slot.</summary> string ValueInCurrentSlot { get; set; } /// <summary>Value of the setting in the target slot.</summary> string ValueInTargetSlot { get; set; } } }
79.995098
408
0.7373
[ "MIT" ]
3quanfeng/azure-powershell
src/Functions/generated/api/Models/Api20190801/SlotDifference.cs
16,116
C#
namespace hx { partial class frmOrderSaleNew2 { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmOrderSaleNew2)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); this.textBoxStatus = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.textBoxCheckDate = new System.Windows.Forms.TextBox(); this.buttonSaveNew = new System.Windows.Forms.Button(); this.buttonReturn = new System.Windows.Forms.Button(); this.buttonDelete = new System.Windows.Forms.Button(); this.buttonFix = new System.Windows.Forms.Button(); this.buttonCheck = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.textBoxOrderid = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBoxInDate = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBoxOderperson = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.textBoxClientName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBoxMultiColumnsClientid = new ComboBoxMultiColumns.ComboBoxMultiColumns(); this.label5 = new System.Windows.Forms.Label(); this.textBoxMemo = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.textBoxCheckPerson = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.ProductdataGridView1 = new System.Windows.Forms.DataGridView(); this.OrderdateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.DeliveryTimePicker2 = new System.Windows.Forms.DateTimePicker(); this.buttonModify = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.ProductdataGridView1)).BeginInit(); this.SuspendLayout(); // // textBoxStatus // this.textBoxStatus.Enabled = false; this.textBoxStatus.Location = new System.Drawing.Point(632, 110); this.textBoxStatus.Name = "textBoxStatus"; this.textBoxStatus.Size = new System.Drawing.Size(158, 25); this.textBoxStatus.TabIndex = 108; this.textBoxStatus.Text = "待审"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(589, 113); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(37, 15); this.label8.TabIndex = 109; this.label8.Text = "状态"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(796, 74); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(67, 15); this.label10.TabIndex = 113; this.label10.Text = "交货日期"; // // textBoxCheckDate // this.textBoxCheckDate.Enabled = false; this.textBoxCheckDate.Location = new System.Drawing.Point(869, 107); this.textBoxCheckDate.Name = "textBoxCheckDate"; this.textBoxCheckDate.Size = new System.Drawing.Size(158, 25); this.textBoxCheckDate.TabIndex = 114; // // buttonSaveNew // this.buttonSaveNew.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonSaveNew.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonSaveNew.Image = ((System.Drawing.Image)(resources.GetObject("buttonSaveNew.Image"))); this.buttonSaveNew.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonSaveNew.Location = new System.Drawing.Point(12, 12); this.buttonSaveNew.Name = "buttonSaveNew"; this.buttonSaveNew.Size = new System.Drawing.Size(92, 42); this.buttonSaveNew.TabIndex = 70; this.buttonSaveNew.Text = "新增"; this.buttonSaveNew.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonSaveNew.UseVisualStyleBackColor = true; this.buttonSaveNew.Click += new System.EventHandler(this.buttonSaveNew_Click); // // buttonReturn // this.buttonReturn.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonReturn.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonReturn.Image = ((System.Drawing.Image)(resources.GetObject("buttonReturn.Image"))); this.buttonReturn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonReturn.Location = new System.Drawing.Point(529, 12); this.buttonReturn.Name = "buttonReturn"; this.buttonReturn.Size = new System.Drawing.Size(92, 42); this.buttonReturn.TabIndex = 71; this.buttonReturn.Text = " 返回"; this.buttonReturn.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonReturn.UseVisualStyleBackColor = true; this.buttonReturn.Click += new System.EventHandler(this.buttonReturn_Click); // // buttonDelete // this.buttonDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonDelete.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonDelete.Image = ((System.Drawing.Image)(resources.GetObject("buttonDelete.Image"))); this.buttonDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonDelete.Location = new System.Drawing.Point(208, 12); this.buttonDelete.Name = "buttonDelete"; this.buttonDelete.Size = new System.Drawing.Size(109, 42); this.buttonDelete.TabIndex = 72; this.buttonDelete.Text = "整单删除"; this.buttonDelete.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonDelete.UseVisualStyleBackColor = true; // // buttonFix // this.buttonFix.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonFix.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonFix.Image = ((System.Drawing.Image)(resources.GetObject("buttonFix.Image"))); this.buttonFix.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonFix.Location = new System.Drawing.Point(323, 12); this.buttonFix.Name = "buttonFix"; this.buttonFix.Size = new System.Drawing.Size(102, 42); this.buttonFix.TabIndex = 73; this.buttonFix.Text = "固定箱"; this.buttonFix.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonFix.UseVisualStyleBackColor = true; this.buttonFix.Click += new System.EventHandler(this.buttonFix_Click); // // buttonCheck // this.buttonCheck.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonCheck.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonCheck.Image = ((System.Drawing.Image)(resources.GetObject("buttonCheck.Image"))); this.buttonCheck.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonCheck.Location = new System.Drawing.Point(431, 12); this.buttonCheck.Name = "buttonCheck"; this.buttonCheck.Size = new System.Drawing.Size(92, 42); this.buttonCheck.TabIndex = 74; this.buttonCheck.Text = "审核"; this.buttonCheck.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonCheck.UseVisualStyleBackColor = true; this.buttonCheck.Click += new System.EventHandler(this.buttonCheck_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(19, 73); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(52, 15); this.label2.TabIndex = 75; this.label2.Text = "订单号"; // // textBoxOrderid // this.textBoxOrderid.Enabled = false; this.textBoxOrderid.Location = new System.Drawing.Point(83, 69); this.textBoxOrderid.Name = "textBoxOrderid"; this.textBoxOrderid.Size = new System.Drawing.Size(121, 25); this.textBoxOrderid.TabIndex = 76; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(210, 74); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 15); this.label3.TabIndex = 77; this.label3.Text = "录入日期"; // // textBoxInDate // this.textBoxInDate.Enabled = false; this.textBoxInDate.Location = new System.Drawing.Point(283, 71); this.textBoxInDate.Name = "textBoxInDate"; this.textBoxInDate.Size = new System.Drawing.Size(118, 25); this.textBoxInDate.TabIndex = 78; this.textBoxInDate.TextChanged += new System.EventHandler(this.textBoxInDate_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(407, 74); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(52, 15); this.label4.TabIndex = 79; this.label4.Text = "开单员"; // // textBoxOderperson // this.textBoxOderperson.Enabled = false; this.textBoxOderperson.Location = new System.Drawing.Point(465, 69); this.textBoxOderperson.Name = "textBoxOderperson"; this.textBoxOderperson.Size = new System.Drawing.Size(88, 25); this.textBoxOderperson.TabIndex = 80; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(4, 117); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(67, 15); this.label9.TabIndex = 87; this.label9.Text = "客户编码"; // // textBoxClientName // this.textBoxClientName.Enabled = false; this.textBoxClientName.Location = new System.Drawing.Point(210, 110); this.textBoxClientName.Name = "textBoxClientName"; this.textBoxClientName.Size = new System.Drawing.Size(191, 25); this.textBoxClientName.TabIndex = 88; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(559, 74); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(67, 15); this.label1.TabIndex = 98; this.label1.Text = "订单日期"; // // comboBoxMultiColumnsClientid // this.comboBoxMultiColumnsClientid.DisplayMember = "客户编码"; this.comboBoxMultiColumnsClientid.Location = new System.Drawing.Point(83, 112); this.comboBoxMultiColumnsClientid.Name = "comboBoxMultiColumnsClientid"; this.comboBoxMultiColumnsClientid.Size = new System.Drawing.Size(121, 23); this.comboBoxMultiColumnsClientid.TabIndex = 101; this.comboBoxMultiColumnsClientid.Text = "comboBoxMultiColumns1"; this.comboBoxMultiColumnsClientid.SelectedIndexChanged += new System.EventHandler(this.comboBoxMultiColumnsClientid_SelectedIndexChanged); this.comboBoxMultiColumnsClientid.TextChanged += new System.EventHandler(this.comboBoxMultiColumnsClientid_TextChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(34, 160); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(37, 15); this.label5.TabIndex = 102; this.label5.Text = "备注"; // // textBoxMemo // this.textBoxMemo.Location = new System.Drawing.Point(83, 157); this.textBoxMemo.Name = "textBoxMemo"; this.textBoxMemo.Size = new System.Drawing.Size(944, 25); this.textBoxMemo.TabIndex = 103; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(407, 114); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(52, 15); this.label6.TabIndex = 104; this.label6.Text = "审核人"; // // textBoxCheckPerson // this.textBoxCheckPerson.Enabled = false; this.textBoxCheckPerson.Location = new System.Drawing.Point(465, 110); this.textBoxCheckPerson.Name = "textBoxCheckPerson"; this.textBoxCheckPerson.Size = new System.Drawing.Size(88, 25); this.textBoxCheckPerson.TabIndex = 105; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(796, 114); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(67, 15); this.label7.TabIndex = 106; this.label7.Text = "审核时间"; this.label7.Click += new System.EventHandler(this.label7_Click); // // ProductdataGridView1 // this.ProductdataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.ProductdataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.ProductdataGridView1.BackgroundColor = System.Drawing.SystemColors.Control; this.ProductdataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.ControlDark; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.ProductdataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.ProductdataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.ControlDark; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.ProductdataGridView1.DefaultCellStyle = dataGridViewCellStyle2; this.ProductdataGridView1.Location = new System.Drawing.Point(1, 208); this.ProductdataGridView1.Name = "ProductdataGridView1"; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.ControlDark; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.ProductdataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; this.ProductdataGridView1.RowTemplate.Height = 27; this.ProductdataGridView1.Size = new System.Drawing.Size(1026, 155); this.ProductdataGridView1.TabIndex = 110; this.ProductdataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.ProductdataGridView1_CellContentClick); // // OrderdateTimePicker1 // this.OrderdateTimePicker1.Location = new System.Drawing.Point(632, 69); this.OrderdateTimePicker1.Name = "OrderdateTimePicker1"; this.OrderdateTimePicker1.Size = new System.Drawing.Size(158, 25); this.OrderdateTimePicker1.TabIndex = 111; // // DeliveryTimePicker2 // this.DeliveryTimePicker2.Location = new System.Drawing.Point(869, 67); this.DeliveryTimePicker2.Name = "DeliveryTimePicker2"; this.DeliveryTimePicker2.Size = new System.Drawing.Size(158, 25); this.DeliveryTimePicker2.TabIndex = 112; // // buttonModify // this.buttonModify.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonModify.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.buttonModify.Image = ((System.Drawing.Image)(resources.GetObject("buttonModify.Image"))); this.buttonModify.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonModify.Location = new System.Drawing.Point(110, 12); this.buttonModify.Name = "buttonModify"; this.buttonModify.Size = new System.Drawing.Size(92, 42); this.buttonModify.TabIndex = 69; this.buttonModify.Text = "修改"; this.buttonModify.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonModify.UseVisualStyleBackColor = true; this.buttonModify.Click += new System.EventHandler(this.buttonModify_Click); // // frmOrderSaleNew2 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1031, 375); this.Controls.Add(this.textBoxCheckDate); this.Controls.Add(this.label10); this.Controls.Add(this.DeliveryTimePicker2); this.Controls.Add(this.OrderdateTimePicker1); this.Controls.Add(this.ProductdataGridView1); this.Controls.Add(this.label8); this.Controls.Add(this.textBoxStatus); this.Controls.Add(this.label7); this.Controls.Add(this.textBoxCheckPerson); this.Controls.Add(this.label6); this.Controls.Add(this.textBoxMemo); this.Controls.Add(this.label5); this.Controls.Add(this.comboBoxMultiColumnsClientid); this.Controls.Add(this.label1); this.Controls.Add(this.textBoxClientName); this.Controls.Add(this.label9); this.Controls.Add(this.textBoxOderperson); this.Controls.Add(this.label4); this.Controls.Add(this.textBoxInDate); this.Controls.Add(this.label3); this.Controls.Add(this.textBoxOrderid); this.Controls.Add(this.label2); this.Controls.Add(this.buttonCheck); this.Controls.Add(this.buttonFix); this.Controls.Add(this.buttonDelete); this.Controls.Add(this.buttonReturn); this.Controls.Add(this.buttonSaveNew); this.Controls.Add(this.buttonModify); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "frmOrderSaleNew2"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "客户订单(新增)"; this.Load += new System.EventHandler(this.frmOrderSaleNew2_Load); ((System.ComponentModel.ISupportInitialize)(this.ProductdataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBoxStatus; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox textBoxCheckDate; public System.Windows.Forms.Button buttonSaveNew; private System.Windows.Forms.Button buttonReturn; public System.Windows.Forms.Button buttonDelete; private System.Windows.Forms.Button buttonFix; private System.Windows.Forms.Button buttonCheck; private System.Windows.Forms.Label label2; public System.Windows.Forms.TextBox textBoxOrderid; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBoxInDate; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBoxOderperson; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox textBoxClientName; private System.Windows.Forms.Label label1; public ComboBoxMultiColumns.ComboBoxMultiColumns comboBoxMultiColumnsClientid; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBoxMemo; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBoxCheckPerson; private System.Windows.Forms.Label label7; private System.Windows.Forms.DataGridView ProductdataGridView1; private System.Windows.Forms.DateTimePicker OrderdateTimePicker1; private System.Windows.Forms.DateTimePicker DeliveryTimePicker2; private System.Windows.Forms.Button buttonModify; } }
56.060268
160
0.637348
[ "Apache-2.0" ]
Vicky0708/bysj
hx/hx/Sale/frmOrderSaleNew2.Designer.cs
25,301
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { public partial class PassportElement : Object { /// <summary> /// Contains information about a Telegram Passport element /// </summary> public class PassportElementPersonalDetails : PassportElement { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "passportElementPersonalDetails"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Personal details of the user /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("personal_details")] public PersonalDetails PersonalDetails { get; set; } } } } }
31.358974
97
0.499591
[ "MIT" ]
0x25CBFC4F/tdsharp
TDLib.Api/Objects/PassportElementPersonalDetails.cs
1,223
C#
using System; using System.Collections.Generic; using System.IO; using ETModel; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; public class UICodeGeneratetor: EditorWindow { /// <summary> /// 使用方法: /// 把需要生成的UI组件拉如RC里面, 命名规则是: 类型_名字 如: Text_HeroLevel /// 然后根据需要填写namespace和ui继承对象, 输出路径等等 (根据自己需求修改) /// </summary> private string nameSpace = "ETHotfix"; private string outputPath = ""; private string scriptName = ""; private string uiBaseComponentName = "UIBaseComponent"; private string[] usingArray = { "ETModel", "UnityEngine", "UnityEngine.UI" }; // 根据自己需要添加 [MenuItem("CG工具/生成UI代码")] public static void ShowWindow() { var window = GetWindow<UICodeGeneratetor>(); window.minSize = new Vector2(800, 300); window.position = new Rect(Screen.width / 2f, Screen.height / 2f, 200, 300); } public void OnGUI() { nameSpace = EditorGUILayout.TextField("NameSpace:", nameSpace); outputPath = EditorGUILayout.TextField("代码输出路径:", outputPath); scriptName = EditorGUILayout.TextField("脚本命名:", scriptName); uiBaseComponentName = EditorGUILayout.TextField("UI继承类名字:", uiBaseComponentName); GameObject go = Selection.activeGameObject; GUILayout.Label(" "); GUILayout.Label("请从Hierarchy里选择需要生成的物体!"); GUILayout.Label(" "); if (go != null) { GUILayout.Label("当前选中的物体: " + Selection.activeGameObject.name); GUILayout.Label(" "); if (GUILayout.Button("生成RC持有的组件代码")) { if (scriptName == "") { Log.Debug("请填写脚本名字!"); return; } if (outputPath == "") { Log.Debug("请填写输出路径!"); return; } ReferenceCollector rc = go.GetComponent<ReferenceCollector>(); Dictionary<string, Object> dict = rc.GetAll(); Dictionary<string, string> resultDict = new Dictionary<string, string>(); foreach (var obj in dict) { string[] key = obj.Key.Split('_'); if(key.Length >= 3) { Log.Debug(obj.Key + " 分割线超出2个"); } if (key.Length < 2) { Log.Debug("注意: " + obj.Key + " 分割不足2个"); } else { if (resultDict.ContainsKey(key[1])) { Log.Error("错误 - 发现重名: " + obj.Key); break; } resultDict.Add(key[1], key[0]); } } if (resultDict.Count > 0) { // 覆盖清空文本 using (new FileStream(Path.Combine(this.outputPath, this.scriptName + ".cs"), FileMode.Create)) { } using (StreamWriter sw = new StreamWriter(Path.Combine(this.outputPath, this.scriptName + ".cs"))) { for (int i = 0; i < usingArray.Length; i++) { sw.WriteLine("using " + usingArray[i] + ";"); } sw.WriteLine("// Code Generate By Tool : " + DateTime.Now); sw.WriteLine("\nnamespace " + this.nameSpace); sw.WriteLine("{"); // sw.WriteLine("\t[ObjectSystem]"); sw.WriteLine("\tpublic class " + this.scriptName + "System : AwakeSystem<" + this.scriptName + ">"); sw.WriteLine("\t{"); sw.WriteLine("\t\tpublic override void Awake(" + this.scriptName + " self)"); sw.WriteLine("\t\t{"); sw.WriteLine("\t\t\tself.Awake();"); sw.WriteLine("\t\t}"); sw.WriteLine("\t}"); sw.WriteLine("\n\tpublic class " + this.scriptName + " : " + this.uiBaseComponentName); sw.WriteLine("\t{"); sw.WriteLine("\t\t#region Property"); // 属性 foreach (var result in resultDict) { sw.WriteLine("\t\tprivate " + result.Value + " " + result.Value + "_" + result.Key + ";"); } sw.WriteLine("\t\t#endregion"); // Awake sw.WriteLine("\n\t\tpublic void Awake()"); sw.WriteLine("\t\t{"); sw.WriteLine("\t\t\tReferenceCollector rc = this.GetParent<UI_Z>().GameObject.GetComponent<ReferenceCollector>();"); // 获取组件 foreach (var result in resultDict) { // 这里根据自己需要的写法去获得RC身上的组件 string _name = result.Value + "_" + result.Key; if (result.Value == "GameObject") { sw.WriteLine("\t\t\tthis." + _name + " = rc.Get<GameObject>(" + '"' + _name + '"' + ");"); } else { sw.WriteLine("\t\t\tthis." + _name + " = UIHelper.Get<" + result.Value + ">(rc, " + ('"' + _name + '"') + ");"); } } // 绑定按钮事件 sw.WriteLine("\n\t\t\t// 绑定按钮点击回调"); foreach (var result in resultDict) { if (result.Value == "Button") { string _name = result.Value + "_" + result.Key; sw.WriteLine("\t\t\tthis." + _name + ".onClick.Add(On" + _name + "Click);"); } } sw.WriteLine("\t\t}"); // 生成按钮绑定的对应方法 foreach (var result in resultDict) { if (result.Value == "Button") { string _name = result.Value + "_" + result.Key; sw.WriteLine("\n\t\tprivate void On" + _name + "Click()"); sw.WriteLine("\t\t{"); sw.WriteLine("\t\t}"); } } sw.WriteLine("\t}"); // sw.WriteLine("}"); } Log.Debug("Job Done!"); } } } } private void OnSelectionChange() { // 改变后自动刷新 Repaint(); } }
37.145729
144
0.393939
[ "MIT" ]
melontaro/Unity3D_Tools
Unity/Assets/Editor/UICodeGenerate/UICodeGenerateEditor.cs
7,806
C#
using System; using System.Net; using System.Threading; using EventStore.ClientAPI; using EventStore.Core.Tests.Http.Users.users; using NUnit.Framework; namespace EventStore.Core.Tests.Http.PersistentSubscription { [TestFixture, Category("LongRunning")] class when_deleting_existing_subscription : with_admin_user { private HttpWebResponse _response; protected override void Given() { _response = MakeJsonPut( "/subscriptions/stream/groupname156", new { ResolveLinkTos = true }, _admin); } protected override void When() { var req = CreateRequest("/subscriptions/stream/groupname156", "DELETE", _admin); _response = GetRequestResponse(req); } [Test] public void returns_ok_status_code() { Assert.AreEqual(HttpStatusCode.OK, _response.StatusCode); } } [TestFixture, Category("LongRunning")] class when_deleting_existing_subscription_with_subscribers : with_admin_user { private HttpWebResponse _response; private const string _stream = "astreamname"; private readonly string _groupName = Guid.NewGuid().ToString(); private SubscriptionDropReason _reason; private Exception _exception; private readonly AutoResetEvent _dropped = new AutoResetEvent(false); protected override void Given() { _response = MakeJsonPut( string.Format("/subscriptions/{0}/{1}", _stream, _groupName), new { ResolveLinkTos = true }, _admin); _connection.ConnectToPersistentSubscription(_stream, _groupName, (x, y) => { }, (sub, reason, e) => { _dropped.Set(); _reason = reason; _exception = e; }); } protected override void When() { var req = CreateRequest(string.Format("/subscriptions/{0}/{1}", _stream, _groupName), "DELETE", _admin); _response = GetRequestResponse(req); } [Test] public void returns_ok_status_code() { Assert.AreEqual(HttpStatusCode.OK, _response.StatusCode); } [Test] public void the_subscription_is_dropped() { Assert.IsTrue(_dropped.WaitOne(TimeSpan.FromSeconds(5))); Assert.AreEqual(SubscriptionDropReason.UserInitiated, _reason); Assert.IsNull(_exception); } } [TestFixture, Category("LongRunning")] class when_deleting_existing_subscription_without_permissions : with_admin_user { private HttpWebResponse _response; protected override void Given() { _response = MakeJsonPut( "/subscriptions/stream/groupname156", new { ResolveLinkTos = true }, _admin); } protected override void When() { var req = CreateRequest("/subscriptions/stream/groupname156", "DELETE"); _response = GetRequestResponse(req); } [Test] public void returns_unauthorized_status_code() { Assert.AreEqual(HttpStatusCode.Unauthorized, _response.StatusCode); } } [TestFixture, Category("LongRunning")] class when_deleting_non_existing_subscription : with_admin_user { private HttpWebResponse _response; protected override void Given() { } protected override void When() { var req = CreateRequest("/subscriptions/stream/groupname158", "DELETE", _admin); _response = GetRequestResponse(req); } [Test] public void returns_ok_status_code() { Assert.AreEqual(HttpStatusCode.NotFound, _response.StatusCode); } } }
29.693431
116
0.579154
[ "Apache-2.0" ]
betgenius/EventStore
src/EventStore.Core.Tests/Http/PersistentSubscription/deleting.cs
4,070
C#
 public class DemoOption { public Position Position { get; set; } public string MyKey { get; set; } public Logging Logging { get; set; } public string AllowedHosts { get; set; } } public class Position { public string Title { get; set; } public string Name { get; set; } } public class Logging { public Loglevel LogLevel { get; set; } } public class Loglevel { public string Default { get; set; } public string Microsoft { get; set; } public string MicrosoftHostingLifetime { get; set; } }
18.482759
56
0.654851
[ "MIT" ]
dotneterwhj/Abner.Extensions.Configuration.Db
UseMySqlDbConfigurationSample/DemoOption.cs
538
C#
// Copyright 2020 Energinet DataHub A/S // // Licensed under the Apache License, Version 2.0 (the "License2"); // 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 MediatR; using Microsoft.Extensions.DependencyInjection; namespace GreenEnergyHub.Messaging { public sealed class PipelineBehaviorConfiguration : IContinuePipelineBehavior, IApplyPipelineBehavior { private static readonly Type _mediatorPipelineBehavior = typeof(IPipelineBehavior<,>); private readonly IServiceCollection _services; internal PipelineBehaviorConfiguration(IServiceCollection services) { _services = services; } /// <summary> /// Continue with a pipeline behavior /// </summary> /// <param name="pipelineBehavior">pipeline behavior to add</param> /// <param name="depends">Dependencies to register</param> /// <exception cref="ArgumentException"><paramref name="pipelineBehavior"/> does not inherit from <see cref="IPipelineBehavior{TRequest,TResponse}"/></exception> public IContinuePipelineBehavior Apply(Type pipelineBehavior, Action<DependsOnConfiguration>? depends = null) { if (!IsPipelineBehavior(pipelineBehavior)) { throw new ArgumentException("This is not a pipeline behavior", nameof(pipelineBehavior)); } AddBehavior(pipelineBehavior, depends); return this; } /// <summary> /// Apply a pipeline behavior /// </summary> /// <param name="pipelineBehavior">pipeline behavior to add</param> /// <param name="depends">Dependencies to register</param> /// <exception cref="ArgumentException"><paramref name="pipelineBehavior"/> does not inherit from <see cref="IPipelineBehavior{TRequest,TResponse}"/></exception> public IContinuePipelineBehavior ContinueWith(Type pipelineBehavior, Action<DependsOnConfiguration>? depends = null) { if (!IsPipelineBehavior(pipelineBehavior)) { throw new ArgumentException("This is not a pipeline behavior", nameof(pipelineBehavior)); } AddBehavior(pipelineBehavior, depends); return this; } private static bool IsPipelineBehavior(Type type) { return type.FindInterfaces(PipelineBehaviorFilter, _mediatorPipelineBehavior).Length == 1; } private static bool PipelineBehaviorFilter(Type type, object? objectCriteria) { if (objectCriteria == null) return false; if (type.IsGenericType == false) return false; return objectCriteria is Type objectType && objectType == type.GetGenericTypeDefinition(); } private void AddBehavior(Type pipelineBehavior, Action<DependsOnConfiguration>? dependsConfig) { dependsConfig?.Invoke(new DependsOnConfiguration(_services)); _services.AddScoped(typeof(IPipelineBehavior<,>), pipelineBehavior); } } }
41.423529
169
0.675092
[ "Apache-2.0" ]
mhejle/geh-market-roles
source/shared/messaging/source/GreenEnergyHub.Messaging.Integration.ServiceCollection/PipelineBehaviorConfiguration.cs
3,523
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace myyou { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
21.913043
65
0.607143
[ "MIT" ]
contactsamie/mediaman
myyou/Program.cs
506
C#
namespace PetStore.Services.Interfaces { public interface IBreedService { void Add(string name); bool Exists(int breedId); } }
17.333333
39
0.641026
[ "MIT" ]
georgidelchev/CSharp-Databases
02 - [Entity Framework Core]/22 - [Best Practices And Architecture - Exercise]/Services/PetStore.Services/Interfaces/IBreedService.cs
158
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Labs.AbstractClasses { public class ContaPoupanca : Conta { private decimal taxaJuros; private DateTime dataAniversario; public ContaPoupanca(decimal j, DateTime d, string t) : base(t) { taxaJuros = j; dataAniversario = d; } public decimal Juros { get { return taxaJuros; } set { taxaJuros = value; } } public DateTime DataAniversario { get { return dataAniversario; } } public override string Id { get { return Titular + " (CP)"; } } public void AdicionarRendimento() { if (DateTime.Now.Equals(dataAniversario)) { decimal rendimento = Saldo * taxaJuros; Depositar(rendimento); } } } }
21.680851
61
0.527969
[ "MIT" ]
JaderTS/S2B_Exercises
Labs/Labs/AbstractClasses/ContaPoupanca.cs
1,021
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; namespace NuGet.VisualStudio.Implementation.Extensibility { internal class VsPackageMetadataComparer : IEqualityComparer<IVsPackageMetadata> { public bool Equals(IVsPackageMetadata x, IVsPackageMetadata y) { if (ReferenceEquals(x, y)) { return true; } if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(x.VersionString, y.VersionString) && StringComparer.OrdinalIgnoreCase.Equals(x.Id, y.Id); } public int GetHashCode(IVsPackageMetadata obj) { if (ReferenceEquals(obj, null)) { return 0; } return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Id) * 397 ^ StringComparer.OrdinalIgnoreCase.GetHashCode(obj.VersionString); } } }
30.4
111
0.600329
[ "Apache-2.0" ]
MarkKharitonov/NuGet.Client
src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageMetadataComparer.cs
1,216
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.DXGI { [NativeName("Name", "DXGI_JPEG_QUANTIZATION_TABLE")] public unsafe partial struct JpegQuantizationTable { [NativeName("Type", "BYTE [64]")] [NativeName("Type.Name", "BYTE [64]")] [NativeName("Name", "Elements")] public fixed byte Elements[64]; } }
25.233333
57
0.708058
[ "MIT" ]
ThomasMiz/Silk.NET
src/Microsoft/Silk.NET.DXGI/Structs/JpegQuantizationTable.gen.cs
757
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; namespace check_yo_self_api.Server { public static class IApplicationBuilderExtensions { // Usage (use only for dev purposes to simulate the request delays etc) // app.UseSimulatedLatency( // min: TimeSpan.FromMilliseconds(200), // max: TimeSpan.FromMilliseconds(400)); public static IApplicationBuilder UseSimulatedLatency(this IApplicationBuilder app, TimeSpan min, TimeSpan max) { var random = new Random(); return app.Use(async (context, next) => { int minDelayInMs = (int)min.TotalMilliseconds; int maxDelayInMs = (int)max.TotalMilliseconds; int delayInMs = random.Next(minDelayInMs, maxDelayInMs); await Task.Delay(delayInMs); await next(); }); } } }
30.516129
119
0.613108
[ "MIT" ]
tylertechgraves/check-yo-self-api
check-yo-self-api/Server/Middlewares/LatencyMiddleware.cs
946
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading.Tasks; namespace LinkedList { class DoubleLinkedList<T> where T : IComparable { public DNode<T> Head { get; private set; } public DNode<T> Tail { get { var temp = Head; while (temp.Next != null) { temp = temp.Next; } return temp; } } public void InsertFirst(T data) { var newNode = new DNode<T>(data); if (Head == null) { Head = newNode; Head.Next = null; Head.Previous = null; return; } newNode.Next = Head; Head.Previous = newNode; Head = newNode; } public void InsertFirst(T[] data) { foreach (var node in data) { this.InsertFirst(node); } } public void InsertLast(T data) { var newNode = new DNode<T>(data); if (Head == null) { Head = newNode; return; } newNode.Previous = Last; Last.Next = newNode; } public void InsertLast(T[] data) { foreach (var node in data) { this.InsertLast(node); } } public void InsertAfter(T after, T element) { var temp = Head; while (temp != null && temp.Data.CompareTo(after) != 0) { temp = temp.Next; } if (temp == null) { throw new Exception($"There is no such an element: {element}"); } if (temp.Data.CompareTo(after) == 0) { var newNode = new DNode<T>(element); var tempNext = temp.Next; newNode.Previous = temp; newNode.Next = tempNext; temp.Next = newNode; tempNext.Previous = newNode; } } public void DeleteNode(T key) { DNode<T> temp = Head; if (temp != null && temp.Data.CompareTo(key) == 0) { Head = temp.Next; Head.Previous = null; return; } while (temp != null && temp.Data.CompareTo(key) != 0) { temp = temp.Next; } if (temp == null) { return; } if (temp.Next != null) { temp.Next.Previous = temp.Previous; } if (temp.Previous != null) { temp.Previous.Next = temp.Next; } } public void ReverseIterative() { DNode<T> prev = null; DNode<T> current = Head; DNode<T> temp = null; while (current != null) { temp = current.Next; current.Next = prev; prev = current; current = temp; } Head = prev; } private DNode<T> ReverseRecursively(DNode<T> node) { if (node == null || node.Next == null) { return node; } DNode<T> reversedListHead = ReverseRecursively(node.Next); node.Next.Next = node; node.Next = null; return reversedListHead; } public DNode<T> ReverseRecursively() { return Head = ReverseRecursively(Head); } public override string ToString() { List<string> list = new List<string>(); var temp = Head; while (temp != null) { list.Add(temp.Data.ToString()); temp = temp.Next; } return string.Join(@" <--> ", list); } } }
22.763441
79
0.406471
[ "MIT" ]
vlemish/data-structures-and-algorithms
LinkedList/DoubleLinkedList/DoubleLinkedList.cs
4,236
C#
using EPiServer.Core; using System.Collections.Generic; using System.Web.Mvc; namespace Foundation.Features.Header.Language { public class LanguageViewModel { public IEnumerable<SelectListItem> Languages { get; set; } public string Language { get; set; } public ContentReference ContentLink { get; set; } } }
26.538462
66
0.707246
[ "Apache-2.0" ]
TheFetaxaFromNiN0/Foundation
src/Foundation/Features/Header/Language/LanguageViewModel.cs
345
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using OO2RDF; using OO2RDF.Framework.Serializer; namespace InstanceTest { class Program { static void Main(string[] args) { Person a = new Person(); a.Name = "James"; a.Age = 26; Person b = new Person(); b.Name = "Jack"; b.Age = 30; Person c = new Person(); c.Name = "Amanda"; c.Age = 19; a.Knows = new List<Person>(); a.Knows.Add(b); a.Knows.Add(c); c.Knows = new List<Person>(); c.Knows.Add(a); b.Knows = new List<Person>(); b.Knows.Add(a); List<object> l = new List<object>(); l.Add(a); l.Add(c); FileInfo f = new FileInfo(@"c:\test.txt"); OO2RDFOptions opcoes = new OO2RDFOptions(new Uri("http://www.base.com"), f, new NTriplesSerializer()); OO2RDFMapper o = new OO2RDFMapper(Assembly.GetExecutingAssembly(), l, opcoes); o.GenerateTriples(); } } }
21.220339
115
0.509585
[ "MIT" ]
mrxrsd/oo2rdf
source/OO2RDF/InstanceTest/Program.cs
1,254
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; namespace FlashCards.Helpers { /// <summary> /// Navigation system that decouples the View Model from knowledge of the View for navigation /// purposes. This class can be replaced with a simple mock implementation for test purposes. /// </summary> public class NavigationService : INavigationService { /// <summary> /// Keep track of the main Frame object, so we can issue Navigation calls to it, without /// the view models needing to maintain a reference to the views. /// </summary> private readonly Frame frame; public NavigationService(Frame frame) { this.frame = frame; } /// <summary> /// Navigate to the target page of type T /// </summary> /// <typeparam name="T">Type of the view to navigate to.</typeparam> /// <param name="parameter">Any parameters to pass to the newly loaded view</param> /// <returns></returns> public bool Navigate<T>(object parameter = null) { var type = typeof(T); return Navigate(type, parameter); } /// <summary> /// Navigate to the target page of the specified type. /// </summary> /// <param name="t">Type of the view to navigate to.</typeparam> /// <param name="parameter">Any parameters to pass to the newly loaded view</param> /// <returns></returns> public bool Navigate(Type t, object parameter = null) { return frame.Navigate(t, parameter); } /// <summary> /// Goes back a page in the back stack. /// </summary> public void GoBack() { frame.GoBack(); } } }
32.20339
97
0.59
[ "MIT" ]
stankovski/flash-cards
FlashCards.Core/Helpers/NavigationService.cs
1,902
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace QuantumGate.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.481481
151
0.581614
[ "MIT" ]
daerogami/FormPlayer
FormPlayer/Properties/Settings.Designer.cs
1,068
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace WebApplication.API.Models.Northwind; [Table("employee_territories", Schema = "public")] public partial class EmployeeTerritory { [Key] [Column("employee_id")] public int EmployeeId { get; set; } [Key] [Column("territory_id")] [StringLength(20)] public string TerritoryId { get; set; } [ForeignKey(nameof(EmployeeId))] [InverseProperty("EmployeeTerritories")] public virtual Employee Employee { get; set; } [ForeignKey(nameof(TerritoryId))] [InverseProperty("EmployeeTerritories")] public virtual Territory Territory { get; set; } }
31.074074
96
0.730632
[ "MIT" ]
mehmetuken/AutoFilterer
sandbox/WebApplication.API/Models/Northwind/EmployeeTerritory.cs
841
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.CognitoSync; using Amazon.CognitoSync.Model; namespace Amazon.PowerShell.Cmdlets.CGIS { /// <summary> /// Gets a list of identity pools registered with Cognito. /// /// /// <para> /// ListIdentityPoolUsage can only be called with developer credentials. You cannot make /// this API call with the temporary user credentials provided by Cognito Identity. /// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "CGISIdentityPoolUsageList")] [OutputType("Amazon.CognitoSync.Model.IdentityPoolUsage")] [AWSCmdlet("Calls the Amazon Cognito Sync ListIdentityPoolUsage API operation.", Operation = new[] {"ListIdentityPoolUsage"}, SelectReturnType = typeof(Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse))] [AWSCmdletOutput("Amazon.CognitoSync.Model.IdentityPoolUsage or Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse", "This cmdlet returns a collection of Amazon.CognitoSync.Model.IdentityPoolUsage objects.", "The service call response (type Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetCGISIdentityPoolUsageListCmdlet : AmazonCognitoSyncClientCmdlet, IExecutor { #region Parameter MaxResult /// <summary> /// <para> /// The maximum number of results to be returned. /// </para> /// <para> /// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet. /// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call. /// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxItems","MaxResults")] public int? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// A pagination token for obtaining the next page /// of results. /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'IdentityPoolUsages'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse). /// Specifying the name of a property of type Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "IdentityPoolUsages"; #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse, GetCGISIdentityPoolUsageListCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); } context.MaxResult = this.MaxResult; #if !MODULAR if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue) { WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." + " This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" + " retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" + " to the service to specify how many items should be returned by each service call."); } #endif context.NextToken = this.NextToken; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members #if MODULAR public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^"); // create request and set iteration invariants var request = new Amazon.CognitoSync.Model.ListIdentityPoolUsageRequest(); if (cmdletContext.MaxResult != null) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value); } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #else public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^"); // create request and set iteration invariants var request = new Amazon.CognitoSync.Model.ListIdentityPoolUsageRequest(); // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.NextToken)) { _nextToken = cmdletContext.NextToken; } if (cmdletContext.MaxResult.HasValue) { _emitLimit = cmdletContext.MaxResult; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; if (_emitLimit.HasValue) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(_emitLimit.Value); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.IdentityPoolUsages.Count; _nextToken = response.NextToken; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #endif public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse CallAWSServiceOperation(IAmazonCognitoSync client, Amazon.CognitoSync.Model.ListIdentityPoolUsageRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Cognito Sync", "ListIdentityPoolUsage"); try { #if DESKTOP return client.ListIdentityPoolUsage(request); #elif CORECLR return client.ListIdentityPoolUsageAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public int? MaxResult { get; set; } public System.String NextToken { get; set; } public System.Func<Amazon.CognitoSync.Model.ListIdentityPoolUsageResponse, GetCGISIdentityPoolUsageListCmdlet, object> Select { get; set; } = (response, cmdlet) => response.IdentityPoolUsages; } } }
44.432099
247
0.576341
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/CognitoSync/Basic/Get-CGISIdentityPoolUsageList-Cmdlet.cs
14,396
C#
#region License // Copyright 2004-2012 Castle Project - http://www.castleproject.org/ // // 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 namespace Castle.Facilities.NHibernateIntegration { using System; using NHibernate; /// <summary> /// Provides a bridge to NHibernate allowing the implementation /// to cache created session (through an invocation) and /// enlist it on transaction if one is detected on the thread. /// </summary> public interface ISessionManager { /// <summary> /// The flushmode the created session gets /// </summary> FlushMode DefaultFlushMode { get; set; } /// <summary> /// Returns a valid opened and connected ISession instance. /// </summary> /// <returns></returns> ISession OpenSession(); /// <summary> /// Returns a valid opened and connected ISession instance /// for the given connection alias. /// </summary> /// <param name="alias"></param> /// <returns></returns> ISession OpenSession(String alias); /// <summary> /// Returns a valid opened and connected IStatelessSession instance. /// </summary> /// <returns></returns> IStatelessSession OpenStatelessSession(); /// <summary> /// Returns a valid opened and connected IStatelessSession instance /// for the given connection alias. /// </summary> /// <param name="alias"></param> /// <returns></returns> IStatelessSession OpenStatelessSession(String alias); } }
32.564516
77
0.678058
[ "Apache-2.0" ]
hconceicao/Castle.Facilities.NHibernateIntegration3
src/Castle.Facilities.NHibernateIntegration/ISessionManager.cs
2,019
C#
#region Copyright (c) 2015 Atif Aziz. 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. // #endregion namespace Elmah.Fabmail { #region Imports using System; using System.Collections.Generic; using System.Linq; using DiagnosticsCollectionSelector = System.Func<System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, StringValues>>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, StringValues>>>; #endregion public class ErrorMailOptions { public bool DontSkipEmptyKeys { get; set; } public string ErrorDetailUrlFormat { get; set; } public ICollection<string> TimeZoneIds { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public string TimeZoneId { get { return TimeZoneIds.FirstOrDefault(); } set { TimeZoneIds.Clear(); if (value != null) TimeZoneIds.Add(value); } } public DiagnosticsCollectionSelector ServerVariablesSelector { get; set; } public DiagnosticsCollectionSelector FormSelector { get; set; } public DiagnosticsCollectionSelector QueryStringSelector { get; set; } public DiagnosticsCollectionSelector CookiesSelector { get; set; } } }
40.130435
260
0.709642
[ "Apache-2.0" ]
elmah/Fabmail
src/ErrorMailOptions.cs
1,846
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("InputHistory")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InputHistory")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e435375d-00fe-43f7-823c-84f61b36f484")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.621622
84
0.747845
[ "Apache-2.0" ]
SpiritsUnite/CelesteInputHistory
InputHistory/Properties/AssemblyInfo.cs
1,395
C#
using System; using System.Collections.Generic; using System.Linq; using WinWeelay.Utils; namespace WinWeelay.Core { /// <summary> /// Utility for tab completing nicknames based on latest activity. /// </summary> public class NickCompleter { private RelayBuffer _buffer; private int _nickCompleteIndex; private string _lastNickCompletion; private string _lastSearch; /// <summary> /// Currently in the process of trying to complete a nick. /// </summary> public bool IsNickCompleting { get; set; } /// <summary> /// Create a new instance of the nick completer for a given buffer. /// </summary> /// <param name="buffer">The buffer to create the nick completer for.</param> public NickCompleter(RelayBuffer buffer) { _buffer = buffer; _nickCompleteIndex = -1; } /// <summary> /// Try to complete the nickname based on a given test string. /// </summary> /// <param name="message">The given text string.</param> /// <returns>A completed nickname if found, otherwise the original message.</returns> public string HandleNickCompletion(string message) { _nickCompleteIndex++; string lastWord = string.Empty; bool isOnlyWord = true; if (!string.IsNullOrEmpty(message)) { string[] words = message.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); lastWord = _lastSearch ?? words.Last(); isOnlyWord = words.Length == 1; } _lastSearch = lastWord; string completedNick = GetCompletedNick(lastWord); if (completedNick != null) { if (isOnlyWord) completedNick = $"{completedNick}: "; if (string.IsNullOrEmpty(lastWord)) message = completedNick; else message = message.ReplaceLastOccurrence(_lastNickCompletion ?? lastWord, completedNick).Replace(" ", " "); _lastNickCompletion = completedNick.Trim(); return message; } return message; } private string GetCompletedNick(string message) { IEnumerable<string> sortedNicks = _buffer.GetSortedUniqueNicks(); if (!string.IsNullOrWhiteSpace(message)) { string lastWord = message.Split(' ').Last(); sortedNicks = sortedNicks.Where(x => x.ToLower().StartsWith(lastWord.ToLower())); } if (!sortedNicks.Any()) return null; if (_nickCompleteIndex > sortedNicks.Count() - 1) _nickCompleteIndex = 0; return sortedNicks.ElementAt(_nickCompleteIndex); } /// <summary> /// Stop trying to complete the nickname and clear the search. /// </summary> public void Reset() { _nickCompleteIndex = -1; _lastNickCompletion = null; _lastSearch = null; } } }
31.627451
127
0.554867
[ "MIT" ]
Heufneutje/WinWeeRelay
WinWeelay.Core/NickCompleter.cs
3,228
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.AzureNextGen.DataFactory.V20170901Preview.Outputs { [OutputType] public sealed class TumblingWindowTriggerResponse { /// <summary> /// Specifies how long the trigger waits past due time before triggering new run. It doesn't alter window start and end time. The default is 0. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> public readonly object? Delay; /// <summary> /// Trigger description. /// </summary> public readonly string? Description; /// <summary> /// The end time for the time period for the trigger during which events are fired for windows that are ready. Only UTC time is currently supported. /// </summary> public readonly string? EndTime; /// <summary> /// The frequency of the time windows. /// </summary> public readonly string Frequency; /// <summary> /// The interval of the time windows. The minimum interval allowed is 15 Minutes. /// </summary> public readonly int Interval; /// <summary> /// The max number of parallel time windows (ready for execution) for which a new run is triggered. /// </summary> public readonly int MaxConcurrency; /// <summary> /// Pipeline for which runs are created when an event is fired for trigger window that is ready. /// </summary> public readonly Outputs.TriggerPipelineReferenceResponse Pipeline; /// <summary> /// Retry policy that will be applied for failed pipeline runs. /// </summary> public readonly Outputs.RetryPolicyResponse? RetryPolicy; /// <summary> /// Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. /// </summary> public readonly string RuntimeState; /// <summary> /// The start time for the time period for the trigger during which events are fired for windows that are ready. Only UTC time is currently supported. /// </summary> public readonly string StartTime; /// <summary> /// Trigger type. /// </summary> public readonly string Type; [OutputConstructor] private TumblingWindowTriggerResponse( object? delay, string? description, string? endTime, string frequency, int interval, int maxConcurrency, Outputs.TriggerPipelineReferenceResponse pipeline, Outputs.RetryPolicyResponse? retryPolicy, string runtimeState, string startTime, string type) { Delay = delay; Description = description; EndTime = endTime; Frequency = frequency; Interval = interval; MaxConcurrency = maxConcurrency; Pipeline = pipeline; RetryPolicy = retryPolicy; RuntimeState = runtimeState; StartTime = startTime; Type = type; } } }
35.424242
267
0.607072
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/DataFactory/V20170901Preview/Outputs/TumblingWindowTriggerResponse.cs
3,507
C#
#if ENABLE_LUA_INJECTION using System; using System.Collections.Generic; using Mono.Cecil; using Mono.Cecil.Cil; using Unity.CecilTools; using System.Linq; [Flags] public enum InjectFilter { IgnoreConstructor = 1, IgnoreProperty = 1 << 1, IgnoreGeneric = 1 << 2, IgnoreNoToLuaAttr = 1 << 3, } public static class ToLuaInjectionHelper { public static string GetArrayRank(TypeReference t) { ArrayType type = t as ArrayType; int count = type.Rank; if (count == 1) { return "[]"; } using (CString.Block()) { CString sb = CString.Alloc(64); sb.Append('['); for (int i = 1; i < count; i++) { sb.Append(','); } sb.Append(']'); return sb.ToString(); } } public static string GetTypeName(TypeReference t, bool bFull = false) { if (t.IsArray) { string str = GetTypeName(ElementType.For(t)); str += GetArrayRank(t); return str; } else if (t.IsByReference) { //t = t.GetElementType(); return GetTypeName(ElementType.For(t)) + "&"; } else if (t.IsGenericInstance) { return GetGenericName(t, bFull); } else if (t.MetadataType == MetadataType.Void) { return "void"; } else { string name = GetPrimitiveTypeStr(t, bFull); return name.Replace('+', '.'); } } public static string[] GetGenericName(Mono.Collections.Generic.Collection<TypeReference> types, int offset, int count, bool bFull) { string[] results = new string[count]; for (int i = 0; i < count; i++) { int pos = i + offset; if (types[pos].IsGenericInstance) { results[i] = GetGenericName(types[pos], bFull); } else { results[i] = GetTypeName(types[pos]); } } return results; } public static MethodReference GetBaseMethodInstance(this MethodDefinition target) { MethodDefinition baseMethodDef = null; var baseType = target.DeclaringType.BaseType; while (baseType != null) { if (baseType.MetadataToken.TokenType == TokenType.TypeRef) { break; } var baseTypeDef = baseType.Resolve(); baseMethodDef = baseTypeDef.Methods.FirstOrDefault(method => { return method.Name == target.Name && target.Parameters .Select(param => param.ParameterType.FullName) .SequenceEqual(method.Parameters.Select(param => param.ParameterType.FullName)) && method.ReturnType.FullName == target.ReturnType.FullName; }); if (baseMethodDef != null && !baseMethodDef.IsAbstract) { if (baseType.IsGenericInstance) { MethodReference baseMethodRef = baseTypeDef.Module.Import(baseMethodDef); var baseTypeInstance = (GenericInstanceType)baseType; return baseMethodRef.MakeGenericMethod(baseTypeInstance.GenericArguments.ToArray()); } break; } else baseMethodDef = null; baseType = baseTypeDef.BaseType; } return baseMethodDef; } public static bool IsGenericTypeDefinition(this TypeReference type) { if (type.HasGenericParameters) { return true; } else if (type.IsByReference || type.IsArray) { return ElementType.For(type).IsGenericTypeDefinition(); } else if (type.IsNested) { var parent = type.DeclaringType; while (parent != null) { if (parent.IsGenericTypeDefinition()) { return true; } if (parent.IsNested) { parent = parent.DeclaringType; } else { break; } } } return type.IsGenericParameter; } public static bool IsGenericMethodDefinition(this MethodDefinition md) { if (md.HasGenericParameters #if UNITY_5_2 || UNITY_5_3 || UNITY_5_3_OR_NEWER || md.ContainsGenericParameter #endif ) { return true; } if (md.DeclaringType != null && md.DeclaringType.IsGenericTypeDefinition()) { return true; } if (md.ReturnType.IsGenericTypeDefinition()) { return true; } foreach (var param in md.Parameters) { if (param.ParameterType.IsGenericTypeDefinition()) { return true; } } return false; } public static bool GotPassedByReferenceParam(this MethodReference md) { return md.Parameters.Any(param => param.ParameterType.IsByReference); } public static TypeReference MakeGenericType(this TypeReference self, params TypeReference[] arguments) { if (self.GenericParameters.Count != arguments.Length) { throw new ArgumentException(); } var instance = new GenericInstanceType(self); foreach (var argument in arguments) { instance.GenericArguments.Add(argument); } return instance; } public static MethodReference MakeGenericMethod(this MethodReference self, params TypeReference[] arguments) { if (self.DeclaringType.IsGenericTypeDefinition()) { return self.CloneMethod(self.DeclaringType.MakeGenericType(arguments)); } else { var genericInstanceMethod = new GenericInstanceMethod(self.CloneMethod()); foreach (var argument in arguments) { genericInstanceMethod.GenericArguments.Add(argument); } return genericInstanceMethod; } } public static MethodReference CloneMethod(this MethodReference self, TypeReference declaringType = null) { var reference = new MethodReference(self.Name, self.ReturnType, declaringType ?? self.DeclaringType) { HasThis = self.HasThis, ExplicitThis = self.ExplicitThis, CallingConvention = self.CallingConvention, }; foreach (ParameterDefinition parameterDef in self.Parameters) { reference.Parameters.Add(new ParameterDefinition(parameterDef.Name, parameterDef.Attributes, parameterDef.ParameterType)); } foreach (GenericParameter genParamDef in self.GenericParameters) { reference.GenericParameters.Add(new GenericParameter(genParamDef.Name, reference)); } return reference; } public static bool IsEnumerator(this MethodDefinition md) { return md.ReturnType.FullName == "System.Collections.IEnumerator"; } public static bool ReturnVoid(this MethodDefinition target) { return target.ReturnType.FullName == "System.Void"; } public static bool HasFlag(this LuaInterface.InjectType flag, LuaInterface.InjectType destFlag) { return (flag & destFlag) == destFlag; } public static bool HasFlag(this LuaInterface.InjectType flag, byte destFlag) { return ((byte)flag & destFlag) == destFlag; } public static bool HasFlag(this InjectFilter flag, InjectFilter destFlag) { return (flag & destFlag) == destFlag; } public static string GetPrimitiveTypeStr(TypeReference t, bool bFull) { switch (t.MetadataType) { case MetadataType.Single: return "float"; case MetadataType.String: return "string"; case MetadataType.Int32: return "int"; case MetadataType.Double: return "double"; case MetadataType.Boolean: return "bool"; case MetadataType.UInt32: return "uint"; case MetadataType.SByte: return "sbyte"; case MetadataType.Byte: return "byte"; case MetadataType.Int16: return "short"; case MetadataType.UInt16: return "ushort"; case MetadataType.Char: return "char"; case MetadataType.Int64: return "long"; case MetadataType.UInt64: return "ulong"; case MetadataType.Object: return "object"; default: return bFull ? t.FullName.Replace("/", "+") : t.Name; } } static string CombineTypeStr(string space, string name) { if (string.IsNullOrEmpty(space)) { return name; } else { return space + "." + name; } } static string GetGenericName(TypeReference t, bool bFull) { GenericInstanceType type = t as GenericInstanceType; var gArgs = type.GenericArguments; string typeName = bFull ? t.FullName.Replace("/", "+") : t.Name; int count = gArgs.Count; int pos = typeName.IndexOf("["); if (pos > 0) { typeName = typeName.Substring(0, pos); } string str = null; string name = null; int offset = 0; pos = typeName.IndexOf("+"); while (pos > 0) { str = typeName.Substring(0, pos); typeName = typeName.Substring(pos + 1); pos = str.IndexOf('`'); if (pos > 0) { count = (int)(str[pos + 1] - '0'); str = str.Substring(0, pos); str += "<" + string.Join(",", GetGenericName(gArgs, offset, count, bFull)) + ">"; offset += count; } name = CombineTypeStr(name, str); pos = typeName.IndexOf("+"); } str = typeName; if (offset < gArgs.Count) { pos = str.IndexOf('`'); count = (int)(str[pos + 1] - '0'); str = str.Substring(0, pos); str += "<" + string.Join(",", GetGenericName(gArgs, offset, count, bFull)) + ">"; } return CombineTypeStr(name, str); } public static void Foreach<T>(this IEnumerable<T> source, Action<T> callback) { foreach (var val in source) { callback(val); } } } #endif
27.885787
134
0.532994
[ "MIT" ]
2801659445/tolua
Assets/ToLua/Injection/Editor/ToLuaInjectionHelper.cs
10,989
C#
// <auto-generated /> using System; using DF.ACE.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DF.ACE.Migrations { [DbContext(typeof(ACEDbContext))] [Migration("20190129045300_ProfilePicture")] partial class ProfilePicture { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .HasMaxLength(256); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime"); b.Property<byte>("ChangeType"); b.Property<long>("EntityChangeSetId"); b.Property<string>("EntityId") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<string>("ExtensionData"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("Reason") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId"); b.Property<string>("NewValue") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasMaxLength(512); b.Property<string>("PropertyName") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("DF.ACE.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("DF.ACE.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("DF.ACE.Authorization.Users.UserProfile", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("Birthdate"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Line1"); b.Property<string>("Line2"); b.Property<string>("State"); b.Property<long>("UserId"); b.Property<string>("ZipCode"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("ACE_UserProfiles"); }); modelBuilder.Entity("DF.ACE.Common.Attachment.Attachment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<string>("Description"); b.Property<string>("ImagePath"); b.Property<string>("Title"); b.HasKey("Id"); b.ToTable("Attachment"); }); modelBuilder.Entity("DF.ACE.Common.Attachment.Demo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<string>("Description"); b.Property<string>("ImagePath"); b.Property<string>("Title"); b.HasKey("Id"); b.ToTable("Demo"); }); modelBuilder.Entity("DF.ACE.Common.Attachment.ProfileAttachment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<string>("ImagePath"); b.HasKey("Id"); b.ToTable("ProfileAttachment"); }); modelBuilder.Entity("DF.ACE.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("DF.ACE.Navigation.NavigationMenuItem", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("CustomData"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired(); b.Property<int>("DisplayOrder"); b.Property<string>("Icon"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEnabled"); b.Property<bool>("IsVisible"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired(); b.Property<long?>("ParentNavigationMenuItemId"); b.Property<string>("RequiredPermissionName"); b.Property<bool>("RequiresAuthentication"); b.Property<string>("Target"); b.Property<int?>("TenantId"); b.Property<string>("Url"); b.HasKey("Id"); b.HasIndex("ParentNavigationMenuItemId"); b.ToTable("ACE_NavigationMenuItems"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("DF.ACE.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("DF.ACE.Authorization.Roles.Role", b => { b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("DF.ACE.Authorization.Users.User", b => { b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("DF.ACE.Authorization.Users.UserProfile", b => { b.HasOne("DF.ACE.Authorization.Users.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("DF.ACE.MultiTenancy.Tenant", b => { b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("DF.ACE.Navigation.NavigationMenuItem", b => { b.HasOne("DF.ACE.Navigation.NavigationMenuItem", "Parent") .WithMany("Children") .HasForeignKey("ParentNavigationMenuItemId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("DF.ACE.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("DF.ACE.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.4483
125
0.4594
[ "MIT" ]
aman22275/ACE
aspnet-core/src/DF.ACE.EntityFrameworkCore/Migrations/20190129045300_ProfilePicture.Designer.cs
47,231
C#
// Copyright (c) 2021 Sergey Ivonchik // // 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. using System; using System.Collections.Generic; using Httx.Requests.Extensions; using JetBrains.Annotations; namespace Httx.Requests.Decorators { public class Callback<TRequest, TResponse> { [CanBeNull] public Action<TRequest> OnBeforeRequestSent { get; set; } [CanBeNull] public Action<TResponse> OnResponseReceived { get; set; } } public class Callback<TObject> : Callback<TObject, TObject> { } public class Hook<TRequest, TResponse> : BaseRequest { private readonly Callback<TRequest, TResponse> callbackObject; public Hook(IRequest next, Callback<TRequest, TResponse> callback) : base(next) { callbackObject = callback; } public override IEnumerable<KeyValuePair<string, object>> Headers => new Dictionary<string, object> { [InternalHeaders.HookObject] = callbackObject }; } public class Hook<TObject> : Hook<TObject, TObject> { public Hook(IRequest next, Callback<TObject, TObject> callback) : base(next, callback) { } } public static class HookFluentExtensions { public static IRequest Hook<TRequest, TResponse>(this IRequest request, Callback<TRequest, TResponse> callback) => new Hook<TRequest, TResponse>(request, callback); public static IRequest Hook<TObject>(this IRequest request, Callback<TObject> callback) => new Hook<TObject>(request, callback); } }
41.366667
118
0.745367
[ "MIT" ]
selfsx/httx
Assets/Httx/Runtime/Requests/Decorators/Hook.cs
2,482
C#
// Copyright (c) Trivadis. All rights reserved. See license.txt in the project root for license information. using System; namespace NTier.Client.Domain { /// <summary> /// Specifies how entities being loaded into the data context are merged with /// entities already in the data context. /// </summary> public enum MergeOption { /// <summary> /// Entities that already exist in the data context are not getting replaced. /// This is the default behavior for queries. /// </summary> AppendOnly = 0, /// <summary> /// Any property changes made to entities in the data context are overwritten by server values. /// </summary> OverwriteChanges = 1, /// <summary> /// Unmodified properties of entities in the data context are overwritten with server values. /// </summary> PreserveChanges = 2, /// <summary> /// Entities are maintained in a Detached state and are not tracked in the data context. /// </summary> NoTracking = 3, } }
32.294118
109
0.616576
[ "ECL-2.0", "Apache-2.0" ]
6bee/ntieref
src/N-Tier Entity Framework/NTier.Client.Domain/MergeOption.cs
1,100
C#
namespace LifeBoardGameBlazor.Views; public partial class SpinnerView { }
36.5
36
0.849315
[ "MIT" ]
musictopia2/GamingPackXV3
Blazor/Games/LifeBoardGameBlazor/Views/SpinnerView.razor.cs
73
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; public class Base<U> { public virtual T Function<T>(T i) { return default(T); } } public class FooInt : Base<int> { public override T Function<T>(T i) { return i; } } public class FooObject : Base<object> { public override T Function<T>(T i) { return i; } } public class FooString : Base<string> { public override T Function<T>(T i) { return i; } } public class Test_method001h { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Base<int> fInt = new FooInt(); Eval(fInt.Function<int>(1).Equals(1)); Eval(fInt.Function<string>("string").Equals("string")); Base<object> fObject = new FooObject(); Eval(fObject.Function<int>(1).Equals(1)); Eval(fObject.Function<string>("string").Equals("string")); Base<string> fString = new FooString(); Eval(fString.Function<int>(1).Equals(1)); Eval(fString.Function<string>("string").Equals("string")); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
16.642857
71
0.65093
[ "MIT" ]
333fred/runtime
src/tests/Loader/classloader/generics/GenericMethods/method001h.cs
1,398
C#
using System.Linq; namespace DrumsAcademy.Mvp.Resource { public class ResourceViewModel { public IQueryable<Models.Resource> LastTenResources { get; set; } public IQueryable<Models.Resource> Resources { get; set; } } }
22.636364
73
0.690763
[ "MIT" ]
Horwits/DrumsAcademy
DrumsAcademy/DrumsAcademy.Mvp/Resource/ResourceViewModel.cs
251
C#
// // LabelBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // 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. using System; using Xwt.Backends; using Xwt.Drawing; using Xwt.CairoBackend; using System.Runtime.InteropServices; using System.Linq; using System.Collections.Generic; namespace Xwt.GtkBackend { public partial class LabelBackend: WidgetBackend, ILabelBackend { Color? textColor; List<LabelLink> links; TextIndexer indexer; public LabelBackend () { Widget = new Gtk.Label (); Label.Show (); Label.Xalign = 0; Label.Yalign = 0.5f; Label.Realized += HandleStyleUpdate; Label.StyleSet += HandleStyleUpdate; } new ILabelEventSink EventSink { get { return (ILabelEventSink)base.EventSink; } } protected Gtk.Label Label { get { if (Widget is Gtk.Label) return (Gtk.Label) Widget; else return (Gtk.Label) ((Gtk.EventBox)base.Widget).Child; } } bool linkEventEnabled; void EnableLinkEvents () { if (!linkEventEnabled) { linkEventEnabled = true; AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.PointerMotionMask); EventsRootWidget.MotionNotifyEvent += HandleMotionNotifyEvent; EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonReleaseMask); EventsRootWidget.ButtonReleaseEvent += HandleButtonReleaseEvent; EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask); EventsRootWidget.LeaveNotifyEvent += HandleLeaveNotifyEvent; } } bool mouseInLink; CursorType normalCursor; void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args) { var li = FindLink (args.Event.X, args.Event.Y); if (li != null) { if (!mouseInLink) { mouseInLink = true; normalCursor = CurrentCursor; SetCursor (CursorType.Hand); } } else { if (mouseInLink) { mouseInLink = false; SetCursor (normalCursor ?? CursorType.Arrow); } } } void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args) { var li = FindLink (args.Event.X, args.Event.Y); if (li != null) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnLinkClicked (li.Target); }); args.RetVal = true; }; } void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args) { if (mouseInLink) { mouseInLink = false; SetCursor (normalCursor ?? CursorType.Arrow); } } LabelLink FindLink (double px, double py) { if (links == null) return null; var alloc = Label.Allocation; int offsetX, offsetY; Label.GetLayoutOffsets (out offsetX, out offsetY); var x = (px - offsetX + alloc.X) * Pango.Scale.PangoScale; var y = (py - offsetY + alloc.Y) * Pango.Scale.PangoScale; int byteIndex, trailing; if (!Label.Layout.XyToIndex ((int)x, (int)y, out byteIndex, out trailing)) return null; foreach (var li in links) if (byteIndex >= li.StartIndex && byteIndex <= li.EndIndex) return li; return null; } public virtual string Text { get { return Label.Text; } set { links = null; indexer = null; Label.Text = value; } } public bool Selectable { get { return Label.Selectable; } set { Label.Selectable = value; } } FormattedText formattedText; public void SetFormattedText (FormattedText text) { Label.Text = text.Text; formattedText = text; Label.ApplyFormattedText (text); if (links != null) links.Clear (); foreach (var attr in text.Attributes.OfType<LinkTextAttribute> ()) { LabelLink ll = new LabelLink () { StartIndex = indexer.IndexToByteIndex (attr.StartIndex), EndIndex = indexer.IndexToByteIndex (attr.StartIndex + attr.Count), Target = attr.Target }; if (links == null) { links = new List<LabelLink> (); EnableLinkEvents (); } links.Add (ll); } if (links == null || links.Count == 0) { links = null; indexer = null; } } void HandleStyleUpdate (object sender, EventArgs e) { // force text update with updated link color if (Label.IsRealized && formattedText != null) { SetFormattedText (formattedText); } } [DllImport (GtkInterop.LIBGTK, CallingConvention=CallingConvention.Cdecl)] static extern void gtk_label_set_attributes (IntPtr label, IntPtr attrList); public Xwt.Drawing.Color TextColor { get { return textColor.HasValue ? textColor.Value : Widget.Style.Foreground (Gtk.StateType.Normal).ToXwtValue (); } set { var color = value.ToGtkValue (); var attr = new Pango.AttrForeground (color.Red, color.Green, color.Blue); var attrs = new Pango.AttrList (); attrs.Insert (attr); Label.Attributes = attrs; textColor = value; Label.QueueDraw (); } } Alignment alignment; public Alignment TextAlignment { get { return alignment; } set { alignment = value; SetAlignment (); } } protected void SetAlignment () { switch (alignment) { case Alignment.Start: Label.Justify = Gtk.Justification.Left; break; case Alignment.End: Label.Justify = Gtk.Justification.Right; break; case Alignment.Center: Label.Justify = Gtk.Justification.Center; break; } SetAlignmentGtk (); } public EllipsizeMode Ellipsize { get { return Label.Ellipsize.ToXwtValue (); } set { Label.Ellipsize = value.ToGtkValue (); } } public WrapMode Wrap { get { if (!Label.LineWrap) return WrapMode.None; else { switch (Label.LineWrapMode) { case Pango.WrapMode.Char: return WrapMode.Character; case Pango.WrapMode.Word: return WrapMode.Word; case Pango.WrapMode.WordChar: return WrapMode.WordAndCharacter; default: return WrapMode.None; } } } set { ToggleSizeCheckEventsForWrap (value); if (value == WrapMode.None){ if (Label.LineWrap) { Label.LineWrap = false; } } else { if (!Label.LineWrap) { Label.LineWrap = true; } switch (value) { case WrapMode.Character: Label.LineWrapMode = Pango.WrapMode.Char; break; case WrapMode.Word: Label.LineWrapMode = Pango.WrapMode.Word; break; case WrapMode.WordAndCharacter: Label.LineWrapMode = Pango.WrapMode.WordChar; break; } } SetAlignment (); } } } class LabelLink { public int StartIndex; public int EndIndex; public Uri Target; } }
24.522727
111
0.670462
[ "MIT" ]
alexandrvslv/xwt
Xwt.Gtk/Xwt.GtkBackend/LabelBackend.cs
7,553
C#
using System.Collections.Generic; namespace AspNetCoreTemplate.Web.ViewModels.Appointments { public class AppointmentsListViewModel { public IEnumerable<AppointmentViewModel> Appointments { get; set; } } }
22.9
75
0.751092
[ "MIT" ]
mirakis97/OnlineCosmeticSalon
OnlineCosmeticSalon.Web/Web/AspNetCoreTemplate.Web.ViewModels/Appointments/AppointmentsListViewModel.cs
231
C#
using Bridge; using Bridge.Html5; using Bridge.SweetAlert; namespace Bridge.SweetAlert.Examples { public class App { static void OnConfirmed(bool confirmed) { if (confirmed) SweetAlert.Success("Deleted!", "Your imaginary file has been deleted."); else SweetAlert.Error("Cancelled", "Your imaginary file is safe :)"); } static void OnInputConfirmed(string inputValue) { if (inputValue == "") SweetAlert.ShowInputError("You need to write something!"); else SweetAlert.Success("Nice!", "you wrote: " + inputValue); } public static void Main() { var confirmButton = new HTMLButtonElement { InnerHTML = "Delete file conformation", OnClick = (ev) => { SweetAlert.Show(new SweetAlertOptions { Title = "Are you sure?", Text = "You will not be able to recover this imaginary file!", Type = SweetAlertType.Warning, ShowCancelButton = true, ConfirmButtonColor = "#DD6B55", ConfirmButtonText = "Yes, delete it!", CancelButtonText = "No, cancel please", CloseOnConfirm = false, CloseOnCancel = false }, OnConfirmed); } }; var promptButton = new HTMLButtonElement { InnerHTML = "Prompt example", OnClick = (ev) => { SweetAlert.Show(new SweetAlertOptions { Title = "An input!", Text = "Write something interesting:", Type = SweetAlertType.Input, ShowCancelButton = true, CloseOnConfirm = false, Animation = "slide-from-top", InputPlaceholder = "Write something" }, OnInputConfirmed); } }; // Add the Button to the page Document.Body.AppendChild(confirmButton); Document.Body.AppendChild(promptButton); } } }
35.275362
88
0.459326
[ "MIT" ]
Zaid-Ajaj/Bridge.SweetAlert
Bridge.SweetAlert.Examples/App.cs
2,436
C#
using System.Threading.Tasks; using Finbuckle.MultiTenant; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; namespace DelegateStrategySample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMultiTenant(). WithInMemoryStore(Configuration.GetSection("Finbuckle:MultiTenant:InMemoryStore")). WithDelegateStrategy(context => { ((HttpContext)context).Request.Query.TryGetValue("tenant", out StringValues tenantId); return Task.FromResult(tenantId.ToString()); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMultiTenant(); app.UseMvcWithDefaultRoute(); } } }
31.956522
106
0.645578
[ "Apache-2.0" ]
danjus10/Finbuckle.MultiTenant
samples/ASP.NET Core 2/DelegateStrategySample/Startup.cs
1,472
C#
using System; using System.Collections.Generic; using System.Text; namespace BittrexSharp.Exceptions { public class UnauthorizedException : Exception { public UnauthorizedException(string message) : base(message) { } } }
18.5
68
0.687259
[ "MIT" ]
Domysee/BittrexSharp
BittrexSharp/Exceptions/UnauthorizedException.cs
261
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 28.05.2018. using System; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.TypeMapping.Group002.BLOB_BINARY{ //////////////////////////////////////////////////////////////////////////////// //class TestSet__Array_Byte public static class TestSet__Array_Byte { private sealed class MyContext:TestBaseDbContext { [Table("TEST_MODIFY_ROW_WD")] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public Int64? TEST_ID { get; set; } [Column("COL_BYTES_BLOB", TypeName="BLOB SUB_TYPE BINARY")] public byte[] TEST_COL { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext //---------------------------------------------------------------------- protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<TEST_RECORD>() .Property(b => b.TEST_COL) .HasDefaultValue(); }//OnModelCreating };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_01() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { Int64 recID; byte[] recData=new byte[]{0xAA,0xBB,0x00}; var cmd=new xdb.OleDbCommand("",cn,tr); using(var db=new MyContext(tr)) { var newRec=new MyContext.TEST_RECORD(); db.testTable.Add(newRec); var nChanges=db.SaveChanges(); Assert.AreEqual(1,nChanges); Assert.NotNull(newRec.TEST_ID); Assert.NotNull(newRec.TEST_COL); Assert.AreEqual(recData,newRec.TEST_COL); recID=newRec.TEST_ID.Value; }//using db //------------------ cmd.CommandText="select COL_BYTES_BLOB from TEST_MODIFY_ROW_WD where TEST_ID="+recID.ToString(); var rd=cmd.ExecuteReader(); Assert.IsTrue(rd.Read()); Assert.AreEqual(recData,rd.GetBytes(0)); Assert.IsFalse(rd.Read()); using(var db=new MyContext(tr)) { var recs=db.testTable.Where(r => r.TEST_ID==recID && r.TEST_COL==recData); int nRecs=0; foreach(var rec in recs) { Assert.AreEqual(0,nRecs); ++nRecs; Assert.AreEqual(recID,rec.TEST_ID); Assert.AreEqual(recData,rec.TEST_COL); }//foreach Assert.AreEqual(1,nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_01 };//class TestSet__Array_Byte //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.TypeMapping.Group002.BLOB_BINARY
25.91129
106
0.564893
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D2/TypeMapping/Group002/BLOB_BINARY/TestSet__Array_Byte.cs
3,215
C#
using System.Diagnostics; using Conway; using Johnson; using UnityEditor; using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class WatermanTest : MonoBehaviour { public int root = 2; [Range(0, 6)] public int c = 0; public bool MergeFaces = false; public bool ApplyOps; public Ops op1; public FaceSelections op1Facesel; public float op1Amount1 = 0; public float op1Amount2 = 0; public Ops op2; public FaceSelections op2Facesel; public float op2Amount1 = 0; public float op2Amount2 = 0; public Vector3 Position = Vector3.zero; public Vector3 Rotation = Vector3.zero; public Vector3 Scale = Vector3.one; public bool Canonicalize; public PolyHydraEnums.ColorMethods ColorMethod; private ConwayPoly poly; public Color[] Colors = { new Color(1.0f, 0.5f, 0.5f), new Color(0.8f, 0.85f, 0.9f), new Color(0.5f, 0.6f, 0.6f), new Color(1.0f, 0.94f, 0.9f), new Color(0.66f, 0.2f, 0.2f), new Color(0.6f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 1.0f), new Color(0.6f, 0.6f, 0.6f), new Color(0.5f, 1.0f, 0.5f), new Color(0.5f, 0.5f, 1.0f), new Color(0.5f, 1.0f, 1.0f), new Color(1.0f, 0.5f, 1.0f), }; void Start() { Generate(); } private void OnValidate() { Generate(); } [ContextMenu("Generate")] public void Generate() { poly = WatermanPoly.Build(1f, root, c, MergeFaces); if (ApplyOps) { var o1 = new OpParams {valueA = op1Amount1, valueB = op1Amount2, facesel = op1Facesel}; poly = poly.ApplyOp(op1, o1); var o2 = new OpParams {valueA = op2Amount1, valueB = op2Amount2, facesel = op2Facesel}; poly = poly.ApplyOp(op2, o2); } if (Canonicalize) { poly = poly.Canonicalize(0.1, 0.1); } poly = poly.Transform(Position, Rotation, Scale); var mesh = PolyMeshBuilder.BuildMeshFromConwayPoly(poly, false, Colors, ColorMethod); GetComponent<MeshFilter>().mesh = mesh; } void OnDrawGizmos () { // GizmoHelper.DrawGizmos(poly, transform, true, false, false); } }
24.197917
99
0.590185
[ "MIT" ]
IxxyXR/polyhydra-upm
Assets/Examples/Waterman/WatermanTest.cs
2,325
C#
using UnityEngine; namespace UnityScreenNavigator.Runtime.Core.Shared { [CreateAssetMenu(menuName = "Screen Navigator/Simple Transition Animation")] public sealed class SimpleTransitionAnimationObject : TransitionAnimationObject { [SerializeField] private float _delay; [SerializeField] private float _duration = 0.3f; [SerializeField] private EaseType _easeType = EaseType.QuarticEaseOut; [SerializeField] private SheetAlignment _beforeAlignment = SheetAlignment.Center; [SerializeField] private Vector3 _beforeScale = Vector3.one; [SerializeField] private float _beforeAlpha = 1.0f; [SerializeField] private SheetAlignment _afterAlignment = SheetAlignment.Center; [SerializeField] private Vector3 _afterScale = Vector3.one; [SerializeField] private float _afterAlpha = 1.0f; private Vector3 _afterPosition; private Vector3 _beforePosition; private CanvasGroup _canvasGroup; public override float Duration => _duration; public static SimpleTransitionAnimationObject CreateInstance(float? duration = null, EaseType? easeType = null, SheetAlignment? beforeAlignment = null, Vector3? beforeScale = null, float? beforeAlpha = null, SheetAlignment? afterAlignment = null, Vector3? afterScale = null, float? afterAlpha = null) { var anim = CreateInstance<SimpleTransitionAnimationObject>(); anim.SetParams(duration, easeType, beforeAlignment, beforeScale, beforeAlpha, afterAlignment, afterScale, afterAlpha); return anim; } public override void Setup() { _beforePosition = _beforeAlignment.ToPosition(RectTransform); _afterPosition = _afterAlignment.ToPosition(RectTransform); if (!RectTransform.gameObject.TryGetComponent<CanvasGroup>(out var canvasGroup)) { canvasGroup = RectTransform.gameObject.AddComponent<CanvasGroup>(); } _canvasGroup = canvasGroup; } public override void SetTime(float time) { time = Mathf.Max(0, time - _delay); var progress = _duration <= 0.0f ? 1.0f : Mathf.Clamp01(time / _duration); progress = Easings.Interpolate(progress, _easeType); var position = Vector3.Lerp(_beforePosition, _afterPosition, progress); var scale = Vector3.Lerp(_beforeScale, _afterScale, progress); var alpha = Mathf.Lerp(_beforeAlpha, _afterAlpha, progress); RectTransform.anchoredPosition = position; RectTransform.localScale = scale; _canvasGroup.alpha = alpha; } public void SetParams(float? duration = null, EaseType? easeType = null, SheetAlignment? beforeAlignment = null, Vector3? beforeScale = null, float? beforeAlpha = null, SheetAlignment? afterAlignment = null, Vector3? afterScale = null, float? afterAlpha = null) { if (duration.HasValue) { _duration = duration.Value; } if (easeType.HasValue) { _easeType = easeType.Value; } if (beforeAlignment.HasValue) { _beforeAlignment = beforeAlignment.Value; } if (beforeScale.HasValue) { _beforeScale = beforeScale.Value; } if (beforeAlpha.HasValue) { _beforeAlpha = beforeAlpha.Value; } if (afterAlignment.HasValue) { _afterAlignment = afterAlignment.Value; } if (afterScale.HasValue) { _afterScale = afterScale.Value; } if (afterAlpha.HasValue) { _afterAlpha = afterAlpha.Value; } } } }
38.346154
120
0.611585
[ "MIT" ]
Haruma-K/UnityScreenNavigator
Assets/UnityScreenNavigator/Runtime/Core/Shared/SimpleTransitionAnimationObject.cs
3,990
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.Sql { using System.Collections.Generic; using System.Data.Common; using System.Data.Entity.Config; using System.Data.Entity.Core.Common; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Data.Entity.Migrations.Model; using System.Data.Entity.Migrations.Utilities; using System.Data.Entity.Spatial; using System.Data.Entity.SqlServer.Resources; using System.Data.Entity.SqlServer.SqlGen; using System.Data.Entity.SqlServer.Utilities; using System.Data.SqlClient; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; /// <summary> /// Provider to convert provider agnostic migration operations into SQL commands /// that can be run against a Microsoft SQL Server database. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] [DbProviderName("System.Data.SqlClient")] public class SqlServerMigrationSqlGenerator : MigrationSqlGenerator { internal const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffK"; internal const string DateTimeOffsetFormat = "yyyy-MM-ddTHH:mm:ss.fffzzz"; private const int DefaultMaxLength = 128; private const int DefaultNumericPrecision = 18; private const byte DefaultTimePrecision = 7; private const byte DefaultScale = 0; private static readonly Regex _sqlKeywordUpcaser = new Regex( @"^(insert|values|delete|where|update|declare|select|from|output|from|join|set|default\svalues|and)", RegexOptions.Multiline | RegexOptions.Compiled); private DbProviderServices _providerServices; private DbProviderManifest _providerManifest; private string _providerManifestToken; private List<MigrationStatement> _statements; private HashSet<string> _generatedSchemas; private int _variableCounter; /// <summary> /// Converts a set of migration operations into Microsoft SQL Server specific SQL. /// </summary> /// <param name="migrationOperations"> The operations to be converted. </param> /// <param name="providerManifestToken"> Token representing the version of SQL Server being targeted (i.e. "2005", "2008"). </param> /// <returns> A list of SQL statements to be executed to perform the migration operations. </returns> public override IEnumerable<MigrationStatement> Generate( IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken) { Check.NotNull(migrationOperations, "migrationOperations"); Check.NotNull(providerManifestToken, "providerManifestToken"); _statements = new List<MigrationStatement>(); _generatedSchemas = new HashSet<string>(); _variableCounter = 0; InitializeProviderServices(providerManifestToken); migrationOperations.Each<dynamic>(o => Generate(o)); return _statements; } public override string GenerateProcedureBody( ICollection<DbModificationCommandTree> commandTrees, string rowsAffectedParameter, string providerManifestToken) { Check.NotNull(commandTrees, "commandTrees"); Check.NotEmpty(providerManifestToken, "providerManifestToken"); if (!commandTrees.Any()) { return "RETURN"; } InitializeProviderServices(providerManifestToken); return UpperCaseKeywords(GenerateFunctionSql(commandTrees, rowsAffectedParameter)); } private void InitializeProviderServices(string providerManifestToken) { _providerManifestToken = providerManifestToken; using (var connection = CreateConnection()) { _providerServices = DbProviderServices.GetProviderServices(connection); _providerManifest = _providerServices.GetProviderManifest(providerManifestToken); } } private string GenerateFunctionSql(ICollection<DbModificationCommandTree> commandTrees, string rowsAffectedParameter) { DebugCheck.NotNull(commandTrees); Debug.Assert(commandTrees.Any()); var functionSqlGenerator = new DmlFunctionSqlGenerator(_providerServices.GetProviderManifest(_providerManifestToken)); switch (commandTrees.First().CommandTreeKind) { case DbCommandTreeKind.Insert: return functionSqlGenerator.GenerateInsert(commandTrees.Cast<DbInsertCommandTree>().ToList()); case DbCommandTreeKind.Update: return functionSqlGenerator.GenerateUpdate(commandTrees.Cast<DbUpdateCommandTree>().ToList(), rowsAffectedParameter); case DbCommandTreeKind.Delete: return functionSqlGenerator.GenerateDelete(commandTrees.Cast<DbDeleteCommandTree>().ToList(), rowsAffectedParameter); } return null; } /// <summary> /// Generates SQL for a <see cref="MigrationOperation" />. /// Allows derived providers to handle additional operation types. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="migrationOperation"> The operation to produce SQL for. </param> protected virtual void Generate(MigrationOperation migrationOperation) { Check.NotNull(migrationOperation, "migrationOperation"); throw Error.SqlServerMigrationSqlGenerator_UnknownOperation(GetType().Name, migrationOperation.GetType().FullName); } /// <summary> /// Creates an empty connection for the current provider. /// Allows derived providers to use connection other than <see cref="SqlConnection" />. /// </summary> /// <returns> </returns> protected virtual DbConnection CreateConnection() { return DbConfiguration.GetService<DbProviderFactory>("System.Data.SqlClient").CreateConnection(); } protected virtual void Generate(CreateProcedureOperation createProcedureOperation) { Check.NotNull(createProcedureOperation, "createProcedureOperation"); using (var writer = Writer()) { writer.WriteLine("CREATE PROCEDURE " + Name(createProcedureOperation.Name)); writer.Indent++; createProcedureOperation.Parameters.Each( (p, i) => { Generate(p, writer); if (i < createProcedureOperation.Parameters.Count - 1) { writer.WriteLine(","); } }); writer.WriteLine(); writer.Indent--; writer.WriteLine("AS"); writer.WriteLine("BEGIN"); writer.Indent++; if (!string.IsNullOrWhiteSpace(createProcedureOperation.BodySql)) { var indentString = writer.NewLine + new string(' ', (writer.Indent * 4)); var indentReplacer = new Regex(@"\r?\n *"); writer.WriteLine(indentReplacer.Replace(createProcedureOperation.BodySql, indentString)); } else { writer.WriteLine("RETURN"); } writer.Indent--; writer.Write("END"); Statement(writer, batchTerminator: "GO"); } } private void Generate(ParameterModel parameterModel, IndentedTextWriter writer) { DebugCheck.NotNull(parameterModel); DebugCheck.NotNull(writer); writer.Write("@"); writer.Write(parameterModel.Name); writer.Write(" "); writer.Write(BuildPropertyType(parameterModel)); if (parameterModel.IsOutParameter) { writer.Write(" OUT"); } if (parameterModel.DefaultValue != null) { writer.Write(" = "); writer.Write(Generate((dynamic)parameterModel.DefaultValue)); } else if (!string.IsNullOrWhiteSpace(parameterModel.DefaultValueSql)) { writer.Write(" = "); writer.Write(parameterModel.DefaultValueSql); } } protected virtual void Generate(DropProcedureOperation dropProcedureOperation) { Check.NotNull(dropProcedureOperation, "dropProcedureOperation"); using (var writer = Writer()) { writer.Write("DROP PROCEDURE "); writer.Write(Name(dropProcedureOperation.Name)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="CreateTableOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="createTableOperation"> The operation to produce SQL for. </param> protected virtual void Generate(CreateTableOperation createTableOperation) { Check.NotNull(createTableOperation, "createTableOperation"); var databaseName = createTableOperation.Name.ToDatabaseName(); if (!string.IsNullOrWhiteSpace(databaseName.Schema)) { if (!databaseName.Schema.EqualsIgnoreCase("dbo") && !_generatedSchemas.Contains(databaseName.Schema)) { GenerateCreateSchema(databaseName.Schema); _generatedSchemas.Add(databaseName.Schema); } } using (var writer = Writer()) { WriteCreateTable(createTableOperation, writer); Statement(writer); } } private void WriteCreateTable(CreateTableOperation createTableOperation, IndentedTextWriter writer) { DebugCheck.NotNull(createTableOperation); DebugCheck.NotNull(writer); writer.WriteLine("CREATE TABLE " + Name(createTableOperation.Name) + " ("); writer.Indent++; createTableOperation.Columns.Each( (c, i) => { Generate(c, writer); if (i < createTableOperation.Columns.Count - 1) { writer.WriteLine(","); } }); if (createTableOperation.PrimaryKey != null) { writer.WriteLine(","); writer.Write("CONSTRAINT "); writer.Write(Quote(createTableOperation.PrimaryKey.Name)); writer.Write(" PRIMARY KEY "); if (!createTableOperation.PrimaryKey.IsClustered) { writer.Write("NONCLUSTERED "); } writer.Write("("); writer.Write(createTableOperation.PrimaryKey.Columns.Join(Quote)); writer.WriteLine(")"); } else { writer.WriteLine(); } writer.Indent--; writer.Write(")"); } /// <summary> /// Generates SQL to mark a table as a system table. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="table"> The table to mark as a system table. </param> protected virtual void GenerateMakeSystemTable(CreateTableOperation createTableOperation, IndentedTextWriter writer) { Check.NotNull(createTableOperation, "createTableOperation"); Check.NotNull(writer, "writer"); writer.WriteLine("BEGIN TRY"); writer.Indent++; writer.WriteLine("EXEC sp_MS_marksystemobject '" + createTableOperation.Name + "'"); writer.Indent--; writer.WriteLine("END TRY"); writer.WriteLine("BEGIN CATCH"); writer.Write("END CATCH"); } /// <summary> /// Generates SQL to create a database schema. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="createTableOperation"> The name of the schema to create. </param> protected virtual void GenerateCreateSchema(string schema) { Check.NotEmpty(schema, "schema"); using (var writer = Writer()) { writer.Write("IF schema_id('"); writer.Write(schema); writer.WriteLine("') IS NULL"); writer.Indent++; writer.Write("EXECUTE('CREATE SCHEMA "); writer.Write(Quote(schema)); writer.Write("')"); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="AddForeignKeyOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="addForeignKeyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(AddForeignKeyOperation addForeignKeyOperation) { Check.NotNull(addForeignKeyOperation, "addForeignKeyOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(addForeignKeyOperation.DependentTable)); writer.Write(" ADD CONSTRAINT "); writer.Write(Quote(addForeignKeyOperation.Name)); writer.Write(" FOREIGN KEY ("); writer.Write(addForeignKeyOperation.DependentColumns.Select(Quote).Join()); writer.Write(") REFERENCES "); writer.Write(Name(addForeignKeyOperation.PrincipalTable)); writer.Write(" ("); writer.Write(addForeignKeyOperation.PrincipalColumns.Select(Quote).Join()); writer.Write(")"); if (addForeignKeyOperation.CascadeDelete) { writer.Write(" ON DELETE CASCADE"); } Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="DropForeignKeyOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="dropForeignKeyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(DropForeignKeyOperation dropForeignKeyOperation) { Check.NotNull(dropForeignKeyOperation, "dropForeignKeyOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(dropForeignKeyOperation.DependentTable)); writer.Write(" DROP CONSTRAINT "); writer.Write(Quote(dropForeignKeyOperation.Name)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="CreateIndexOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="createIndexOperation"> The operation to produce SQL for. </param> protected virtual void Generate(CreateIndexOperation createIndexOperation) { Check.NotNull(createIndexOperation, "createIndexOperation"); using (var writer = Writer()) { writer.Write("CREATE "); if (createIndexOperation.IsUnique) { writer.Write("UNIQUE "); } if (createIndexOperation.IsClustered) { writer.Write("CLUSTERED "); } writer.Write("INDEX "); writer.Write(Quote(createIndexOperation.Name)); writer.Write(" ON "); writer.Write(Name(createIndexOperation.Table)); writer.Write("("); writer.Write(createIndexOperation.Columns.Join(Quote)); writer.Write(")"); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="DropIndexOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="dropIndexOperation"> The operation to produce SQL for. </param> protected virtual void Generate(DropIndexOperation dropIndexOperation) { Check.NotNull(dropIndexOperation, "dropIndexOperation"); using (var writer = Writer()) { writer.Write("DROP INDEX "); writer.Write(Quote(dropIndexOperation.Name)); writer.Write(" ON "); writer.Write(Name(dropIndexOperation.Table)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="AddPrimaryKeyOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="addPrimaryKeyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation) { Check.NotNull(addPrimaryKeyOperation, "addPrimaryKeyOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(addPrimaryKeyOperation.Table)); writer.Write(" ADD CONSTRAINT "); writer.Write(Quote(addPrimaryKeyOperation.Name)); writer.Write(" PRIMARY KEY "); if (!addPrimaryKeyOperation.IsClustered) { writer.Write("NONCLUSTERED "); } writer.Write("("); writer.Write(addPrimaryKeyOperation.Columns.Select(Quote).Join()); writer.Write(")"); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="DropPrimaryKeyOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="dropPrimaryKeyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(DropPrimaryKeyOperation dropPrimaryKeyOperation) { Check.NotNull(dropPrimaryKeyOperation, "dropPrimaryKeyOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(dropPrimaryKeyOperation.Table)); writer.Write(" DROP CONSTRAINT "); writer.Write(Quote(dropPrimaryKeyOperation.Name)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="AddColumnOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="addColumnOperation"> The operation to produce SQL for. </param> protected virtual void Generate(AddColumnOperation addColumnOperation) { Check.NotNull(addColumnOperation, "addColumnOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(addColumnOperation.Table)); writer.Write(" ADD "); var column = addColumnOperation.Column; Generate(column, writer); if ((column.IsNullable != null) && !column.IsNullable.Value && (column.DefaultValue == null) && (string.IsNullOrWhiteSpace(column.DefaultValueSql)) && !column.IsIdentity && !column.IsTimestamp && !column.StoreType.EqualsIgnoreCase("rowversion") && !column.StoreType.EqualsIgnoreCase("timestamp")) { writer.Write(" DEFAULT "); if (column.Type == PrimitiveTypeKind.DateTime) { writer.Write(Generate(DateTime.Parse("1900-01-01 00:00:00", CultureInfo.InvariantCulture))); } else { writer.Write(Generate((dynamic)column.ClrDefaultValue)); } } Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="DropColumnOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="dropColumnOperation"> The operation to produce SQL for. </param> protected virtual void Generate(DropColumnOperation dropColumnOperation) { Check.NotNull(dropColumnOperation, "dropColumnOperation"); using (var writer = Writer()) { var variable = "@var" + _variableCounter++; writer.Write("DECLARE "); writer.Write(variable); writer.WriteLine(" nvarchar(128)"); writer.Write("SELECT "); writer.Write(variable); writer.WriteLine(" = name"); writer.WriteLine("FROM sys.default_constraints"); writer.Write("WHERE parent_object_id = object_id(N'"); writer.Write(dropColumnOperation.Table); writer.WriteLine("')"); writer.Write("AND col_name(parent_object_id, parent_column_id) = '"); writer.Write(dropColumnOperation.Name); writer.WriteLine("';"); writer.Write("IF "); writer.Write(variable); writer.WriteLine(" IS NOT NULL"); writer.Indent++; writer.Write("EXECUTE('ALTER TABLE "); writer.Write(Name(dropColumnOperation.Table)); writer.Write(" DROP CONSTRAINT ' + "); writer.Write(variable); writer.WriteLine(")"); writer.Indent--; writer.Write("ALTER TABLE "); writer.Write(Name(dropColumnOperation.Table)); writer.Write(" DROP COLUMN "); writer.Write(Quote(dropColumnOperation.Name)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="AlterColumnOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="alterColumnOperation"> The operation to produce SQL for. </param> protected virtual void Generate(AlterColumnOperation alterColumnOperation) { Check.NotNull(alterColumnOperation, "alterColumnOperation"); var column = alterColumnOperation.Column; if ((column.DefaultValue != null) || !string.IsNullOrWhiteSpace(column.DefaultValueSql)) { using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(alterColumnOperation.Table)); writer.Write(" ADD CONSTRAINT DF_"); writer.Write(column.Name); writer.Write(" DEFAULT "); writer.Write( (column.DefaultValue != null) ? Generate((dynamic)column.DefaultValue) : column.DefaultValueSql ); writer.Write(" FOR "); writer.Write(Quote(column.Name)); Statement(writer); } } using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(alterColumnOperation.Table)); writer.Write(" ALTER COLUMN "); writer.Write(Quote(column.Name)); writer.Write(" "); writer.Write(BuildColumnType(column)); if ((column.IsNullable != null) && !column.IsNullable.Value) { writer.Write(" NOT NULL"); } Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="DropTableOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="dropTableOperation"> The operation to produce SQL for. </param> protected virtual void Generate(DropTableOperation dropTableOperation) { Check.NotNull(dropTableOperation, "dropTableOperation"); using (var writer = Writer()) { writer.Write("DROP TABLE "); writer.Write(Name(dropTableOperation.Name)); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="SqlOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="sqlOperation"> The operation to produce SQL for. </param> protected virtual void Generate(SqlOperation sqlOperation) { Check.NotNull(sqlOperation, "sqlOperation"); Statement(sqlOperation.Sql, sqlOperation.SuppressTransaction); } /// <summary> /// Generates SQL for a <see cref="RenameColumnOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="renameColumnOperation"> The operation to produce SQL for. </param> protected virtual void Generate(RenameColumnOperation renameColumnOperation) { Check.NotNull(renameColumnOperation, "renameColumnOperation"); using (var writer = Writer()) { writer.Write("EXECUTE sp_rename @objname = N'"); writer.Write(renameColumnOperation.Table); writer.Write("."); writer.Write(renameColumnOperation.Name); writer.Write("', @newname = N'"); writer.Write(renameColumnOperation.NewName); writer.Write("', @objtype = N'COLUMN'"); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="RenameTableOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="renameTableOperation"> The operation to produce SQL for. </param> protected virtual void Generate(RenameTableOperation renameTableOperation) { Check.NotNull(renameTableOperation, "renameTableOperation"); using (var writer = Writer()) { writer.Write("EXECUTE sp_rename @objname = N'"); writer.Write(renameTableOperation.Name); writer.Write("', @newname = N'"); writer.Write(renameTableOperation.NewName); writer.Write("', @objtype = N'OBJECT'"); Statement(writer); } } /// <summary> /// Generates SQL for a <see cref="MoveTableOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="moveTableOperation"> The operation to produce SQL for. </param> protected virtual void Generate(MoveTableOperation moveTableOperation) { Check.NotNull(moveTableOperation, "moveTableOperation"); var newSchema = moveTableOperation.NewSchema ?? "dbo"; if (!newSchema.EqualsIgnoreCase("dbo") && !_generatedSchemas.Contains(newSchema)) { GenerateCreateSchema(newSchema); _generatedSchemas.Add(newSchema); } if (!moveTableOperation.IsSystem) { using (var writer = Writer()) { writer.Write("ALTER SCHEMA "); writer.Write(Quote(newSchema)); writer.Write(" TRANSFER "); writer.Write(Name(moveTableOperation.Name)); Statement(writer); } } else { Debug.Assert(moveTableOperation.CreateTableOperation != null); Debug.Assert(!string.IsNullOrWhiteSpace(moveTableOperation.ContextKey)); using (var writer = Writer()) { writer.Write("IF object_id('"); writer.Write(moveTableOperation.CreateTableOperation.Name); writer.WriteLine("') IS NULL BEGIN"); writer.Indent++; WriteCreateTable(moveTableOperation.CreateTableOperation, writer); writer.WriteLine(); writer.Indent--; writer.WriteLine("END"); writer.Write("INSERT INTO "); writer.WriteLine(Name(moveTableOperation.CreateTableOperation.Name)); writer.Write("SELECT * FROM "); writer.WriteLine(Name(moveTableOperation.Name)); writer.Write("WHERE [ContextKey] = "); writer.WriteLine(Generate(moveTableOperation.ContextKey)); writer.Write("DELETE "); writer.WriteLine(Name(moveTableOperation.Name)); writer.Write("WHERE [ContextKey] = "); writer.WriteLine(Generate(moveTableOperation.ContextKey)); writer.Write("IF NOT EXISTS(SELECT * FROM "); writer.Write(Name(moveTableOperation.Name)); writer.WriteLine(")"); writer.Indent++; writer.Write("DROP TABLE "); writer.Write(Name(moveTableOperation.Name)); writer.Indent--; Statement(writer); } } } private void Generate(ColumnModel column, IndentedTextWriter writer) { DebugCheck.NotNull(column); DebugCheck.NotNull(writer); writer.Write(Quote(column.Name)); writer.Write(" "); writer.Write(BuildColumnType(column)); if ((column.IsNullable != null) && !column.IsNullable.Value) { writer.Write(" NOT NULL"); } if (column.DefaultValue != null) { writer.Write(" DEFAULT "); writer.Write(Generate((dynamic)column.DefaultValue)); } else if (!string.IsNullOrWhiteSpace(column.DefaultValueSql)) { writer.Write(" DEFAULT "); writer.Write(column.DefaultValueSql); } else if (column.IsIdentity) { if ((column.Type == PrimitiveTypeKind.Guid) && (column.DefaultValue == null)) { writer.Write(" DEFAULT " + GuidColumnDefault); } else { writer.Write(" IDENTITY"); } } } /// <summary> /// Returns the column default value to use for store-generated GUID columns when /// no default value is explicitly specified in the migration. /// Returns newsequentialid() for on-premises SQL Server 2005 and later. /// Returns newid() for SQL Azure. /// </summary> /// <value>Either newsequentialid() or newid() as described above.</value> protected virtual string GuidColumnDefault { get { return _providerManifestToken != "2012.Azure" && _providerManifestToken != "2000" ? "newsequentialid()" : "newid()"; } } /// <summary> /// Generates SQL for a <see cref="HistoryOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="historyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(HistoryOperation historyOperation) { Check.NotNull(historyOperation, "historyOperation"); using (var writer = Writer()) { historyOperation.Commands.Each( c => { var sql = UpperCaseKeywords(c.CommandText); // inline params c.Parameters .Cast<DbParameter>() .Each(p => sql = sql.Replace(p.ParameterName, Generate((dynamic)p.Value))); writer.Write(sql); }); Statement(writer); } } private static string UpperCaseKeywords(string commandText) { DebugCheck.NotEmpty(commandText); return _sqlKeywordUpcaser.Replace(commandText, m => m.Groups[1].Value.ToUpperInvariant()); } /// <summary> /// Generates SQL to specify a constant byte[] default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(byte[] defaultValue) { Check.NotNull(defaultValue, "defaultValue"); return "0x" + defaultValue.ToHexString(); } /// <summary> /// Generates SQL to specify a constant bool default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(bool defaultValue) { return defaultValue ? "1" : "0"; } /// <summary> /// Generates SQL to specify a constant DateTime default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(DateTime defaultValue) { return "'" + defaultValue.ToString(DateTimeFormat, CultureInfo.InvariantCulture) + "'"; } /// <summary> /// Generates SQL to specify a constant DateTimeOffset default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(DateTimeOffset defaultValue) { return "'" + defaultValue.ToString(DateTimeOffsetFormat, CultureInfo.InvariantCulture) + "'"; } /// <summary> /// Generates SQL to specify a constant Guid default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(Guid defaultValue) { return "'" + defaultValue + "'"; } /// <summary> /// Generates SQL to specify a constant string default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(string defaultValue) { Check.NotNull(defaultValue, "defaultValue"); return "'" + defaultValue + "'"; } /// <summary> /// Generates SQL to specify a constant TimeSpan default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(TimeSpan defaultValue) { return "'" + defaultValue + "'"; } /// <summary> /// Generates SQL to specify a constant geogrpahy default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(DbGeography defaultValue) { return "'" + defaultValue + "'"; } /// <summary> /// Generates SQL to specify a constant geometry default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(DbGeometry defaultValue) { return "'" + defaultValue + "'"; } /// <summary> /// Generates SQL to specify a constant default value being set on a column. /// This method just generates the actual value, not the SQL to set the default value. /// </summary> /// <param name="defaultValue"> The value to be set. </param> /// <returns> SQL representing the default value. </returns> protected virtual string Generate(object defaultValue) { Check.NotNull(defaultValue, "defaultValue"); Debug.Assert(defaultValue.GetType().IsValueType); return string.Format(CultureInfo.InvariantCulture, "{0}", defaultValue); } /// <summary> /// Generates SQL to specify the data type of a column. /// This method just generates the actual type, not the SQL to create the column. /// </summary> /// <param name="defaultValue"> The definition of the column. </param> /// <returns> SQL representing the data type. </returns> protected virtual string BuildColumnType(ColumnModel columnModel) { Check.NotNull(columnModel, "columnModel"); if (columnModel.IsTimestamp) { return "rowversion"; } return BuildPropertyType(columnModel); } private string BuildPropertyType(PropertyModel propertyModel) { DebugCheck.NotNull(propertyModel); var originalStoreTypeName = propertyModel.StoreType; if (string.IsNullOrWhiteSpace(originalStoreTypeName)) { var typeUsage = _providerManifest.GetStoreType(propertyModel.TypeUsage).EdmType; originalStoreTypeName = typeUsage.Name; } var storeTypeName = originalStoreTypeName; const string MaxSuffix = "(max)"; if (storeTypeName.EndsWith(MaxSuffix, StringComparison.Ordinal)) { storeTypeName = Quote(storeTypeName.Substring(0, storeTypeName.Length - MaxSuffix.Length)) + MaxSuffix; } else { storeTypeName = Quote(storeTypeName); } switch (originalStoreTypeName) { case "decimal": case "numeric": storeTypeName += "(" + (propertyModel.Precision ?? DefaultNumericPrecision) + ", " + (propertyModel.Scale ?? DefaultScale) + ")"; break; case "datetime2": case "datetimeoffset": case "time": storeTypeName += "(" + (propertyModel.Precision ?? DefaultTimePrecision) + ")"; break; case "binary": case "varbinary": case "nvarchar": case "varchar": case "char": case "nchar": storeTypeName += "(" + (propertyModel.MaxLength ?? DefaultMaxLength) + ")"; break; } return storeTypeName; } /// <summary> /// Generates a quoted name. The supplied name may or may not contain the schema. /// </summary> /// <param name="name"> The name to be quoted. </param> /// <returns> The quoted name. </returns> [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#")] protected virtual string Name(string name) { Check.NotEmpty(name, "name"); var databaseName = name.ToDatabaseName(); return new[] { databaseName.Schema, databaseName.Name }.Join(Quote, "."); } /// <summary> /// Quotes an identifier for SQL Server. /// </summary> /// <param name="identifier"> The identifier to be quoted. </param> /// <returns> The quoted identifier. </returns> protected virtual string Quote(string identifier) { return "[" + identifier + "]"; } /// <summary> /// Adds a new Statement to be executed against the database. /// </summary> /// <param name="sql"> The statement to be executed. </param> /// <param name="suppressTransaction"> Gets or sets a value indicating whether this statement should be performed outside of the transaction scope that is used to make the migration process transactional. If set to true, this operation will not be rolled back if the migration process fails. </param> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] protected void Statement(string sql, bool suppressTransaction = false, string batchTerminator = null) { Check.NotEmpty(sql, "sql"); _statements.Add( new MigrationStatement { Sql = sql, SuppressTransaction = suppressTransaction, BatchTerminator = batchTerminator }); } /// <summary> /// Gets a new <see cref="IndentedTextWriter" /> that can be used to build SQL. /// This is just a helper method to create a writer. Writing to the writer will /// not cause SQL to be registered for execution. You must pass the generated /// SQL to the Statement method. /// </summary> /// <returns> An empty text writer to use for SQL generation. </returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] protected static IndentedTextWriter Writer() { return new IndentedTextWriter(new StringWriter(CultureInfo.InvariantCulture)); } /// <summary> /// Adds a new Statement to be executed against the database. /// </summary> /// <param name="writer"> The writer containing the SQL to be executed. </param> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] protected void Statement(IndentedTextWriter writer, string batchTerminator = null) { Check.NotNull(writer, "writer"); Statement(writer.InnerWriter.ToString(), batchTerminator: batchTerminator); } } }
41.069869
309
0.541499
[ "Apache-2.0" ]
TerraVenil/entityframework
src/EntityFramework.SqlServer/SqlServerMigrationSqlGenerator.cs
47,025
C#
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class UpdateValuePropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly UpdateValuePropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, UpdateValuePropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private UpdateValueProperty[] _selectedObject; /// <summary> /// Initializes a new instance of the UpdateValuePropertyBag class. /// </summary> public UpdateValuePropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public UpdateValuePropertyBag(UpdateValueProperty obj) : this(new[] {obj}) { } public UpdateValuePropertyBag(UpdateValueProperty[] obj) { _defaultProperty = "Name"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public UpdateValueProperty[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this UpdateValuePropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo propertyInfo; Type t = typeof(UpdateValueProperty);// _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { propertyInfo = props[i]; object[] myAttributes = propertyInfo.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } // Set ReadOnly properties /*if (SelectedObject[0].LoadingScheme == LoadingScheme.ParentLoad && propertyInfo.Name == "LazyLoad") isreadonly = true;*/ userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : propertyInfo.Name; var types = new List<string>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj.Name)) types.Add(obj.Name); } // here get rid of Parent bool isValidProperty = propertyInfo.Name != "Parent"; if (isValidProperty && IsBrowsable(types.ToArray(), propertyInfo.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,propertyInfo.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, propertyInfo.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (UpdateValueProperty).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { /*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) && (propertyName == "ReadRoles" || propertyName == "WriteRoles")) return false;*/ if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { //Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; //FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); //fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that name PropertyInfo propertyInfo = typeof (UpdateValueProperty).GetProperty(propertyName); if (propertyInfo == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, propertyInfo.PropertyType); // attempt the assignment foreach (UpdateValueProperty bo in (UpdateValueProperty[]) obj) propertyInfo.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo propertyInfo = GetPropertyInfoCache(propertyName); if (!(propertyInfo == null)) { var objs = (UpdateValueProperty[]) obj; var valueList = new ArrayList(); foreach (UpdateValueProperty bo in objs) { object value = propertyInfo.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of UpdateValuePropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
39.667431
230
0.526395
[ "MIT" ]
CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Util/PropertyBags/UpdateValuePropertyBag.cs
34,590
C#
using System; using System.Collections.Generic; using System.Text; namespace BusSchedulemanager.Database.Models { /// <summary> /// The intention of this class is to keep track of the bus stops individually. /// Each will have a time span expected to be served, is a simple design for the simple example provided. /// A more complex design will be probably better elaborated. /// </summary> public class BusStop { /// <summary> /// Generic ID, for database. Prefer Guid normally but I will do number for visibility. /// </summary> public int Id { get; set; } /// <summary> /// A name to be identifiable by the user or developer. ie: Route 1, Route 2, etc. /// </summary> public string Name { get; set; } } }
33.583333
109
0.632754
[ "MIT" ]
rperezretana/BusStopDashBoard
BusSchedulemanager.Database/Models/BusStop.cs
808
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace SuperMap.Connector.Utility { /// <summary> /// 文本复合风格类。 /// </summary> [JsonObject(MemberSerialization.OptIn)] #if !WINDOWS_PHONE [Serializable] #endif public sealed class LabelMixedTextStyle { ///<summary> ///默认的文本复合风格。 ///</summary> [JsonProperty("defaultStyle")] public TextStyle DefaultStyle { get; set; } /// <summary> /// 文本的分隔符,分隔符的风格与前一个字符的风格一样。 /// </summary> [JsonProperty("separator")] public string Separator { set; get; } /// <summary> /// 文本的分隔符是否有效。 /// </summary> [JsonProperty("separatorEnabled")] public bool SeparatorEnabled { get; set; } /// <summary> /// 分段索引值,分段索引值用来对文本中的字符进行分段。 /// </summary> [JsonProperty("splitIndexes")] public int[] SplitIndexes { get; set; } /// <summary> /// 文本样式集合。文本样式集合中的样式用于不同分段内的字符。 /// </summary> [JsonProperty("styles")] public TextStyle[] Styles { get; set; } } }
24.673469
51
0.551696
[ "Apache-2.0" ]
SuperMap/iClient-for-DotNet
Connector/Utilities/LabelMixedTextStyle.cs
1,425
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BluescreenSimulator.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")] public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool IsDarkTheme { get { return ((bool)(this["IsDarkTheme"])); } set { this["IsDarkTheme"] = value; } } } }
38.487179
151
0.571619
[ "MIT" ]
ChaseKnowlden/BluescreenSimulator
BluescreenSimulator/Properties/Settings.Designer.cs
1,503
C#
namespace Rediska.Commands.Keys { using System; using System.Collections.Generic; using Protocol; using Protocol.Visitors; public sealed class WAIT : Command<long> { private static readonly PlainBulkString name = new PlainBulkString("WAIT"); private readonly long numReplicas; private readonly MillisecondsTimeout timeout; public WAIT(long numReplicas, MillisecondsTimeout timeout) { if (numReplicas <= 0) { var message = numReplicas == 0 ? "Zero replicas is meaningless" : "Number of replicas must be positive"; throw new ArgumentOutOfRangeException(nameof(numReplicas), numReplicas, message); } this.numReplicas = numReplicas; this.timeout = timeout; } public override IEnumerable<BulkString> Request(BulkStringFactory factory) => new[] { name, factory.Create(numReplicas), timeout.ToBulkString(factory) }; public override Visitor<long> ResponseStructure => IntegerExpectation.Singleton; } }
32.72973
98
0.590421
[ "MIT" ]
TwoUnderscorez/Rediska
Rediska/Commands/Keys/WAIT.cs
1,213
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; // Repro for https://github.com/dotnet/coreclr/issues/22820. // On x86 we need to report enclosed handler // live-in locals as live into any enclosing filter. // // Run with optimized codegen and COMPlus_GCStress=0x4 class DisposableObject : IDisposable { public void Dispose() { Console.WriteLine("In dispose"); } } class Program { public static bool IsExpectedException(Exception e) { Console.WriteLine("In filter"); GC.Collect(); return e is OperationCanceledException; } public static IDisposable AllocateObject() { return new DisposableObject(); } static int Main(string[] args) { int result = 0; try { try { using (AllocateObject()) { throw new Exception(); } } catch (Exception e1) when (IsExpectedException(e1)) { Console.WriteLine("In catch 1"); } } catch (Exception e2) { Console.WriteLine("In catch 2"); result = 100; } return result; } }
21.983607
71
0.554064
[ "MIT" ]
belav/runtime
src/tests/JIT/Regression/JitBlue/GitHub_22820/GitHub_22820.cs
1,341
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using ImoutoDesktop.Remoting; using ImoutoDesktop.Services; namespace ImoutoDesktop.Commands { public class DosCommand : RemoteCommandBase { public DosCommand(RemoteConnectionManager remoteConnectionManager) : base(@".+", remoteConnectionManager) { } private static readonly string[] _allow = { "dir", "ver", "xcopy", "mkdir", "rmdir", "copy", "del", "move", "ren", "cd", "type", "ls", "chdir", "rm", "cp", "cls", "start" }; private static readonly Dictionary<string, string> _replace = new() { { "chdir", "cd" }, { "ls", "dir" }, { "rm", "del" }, { "cp", "copy" } }; public override Priority Priority => Priority.BelowNormal; public override bool CanExecute(string input) { return Array.Exists(_allow, p => input == p || input.StartsWith(p + " ")); } protected override Task<CommandResult> PreExecuteCore(string input) { return Task.FromResult(Succeeded(new[] { Escape(input) })); } protected override async Task<CommandResult> ExecuteCore(string input) { var serviceClient = RemoteConnectionManager.GetServiceClient(); foreach (var item in _replace) { if (input.StartsWith(item.Key + " ")) { input = item.Key + input.Substring(item.Key.Length); break; } } var response = await serviceClient.RunShellAsync(new RunShellRequest { Command = input }); return Succeeded(response.Result, new[] { Escape(input) }); } } }
29.918033
138
0.549589
[ "Apache-2.0" ]
ototoi/ImoutoDesktop
src/ImoutoDesktop/Commands/DosCommand.cs
1,827
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Sistema.Models { public class Categoria { public int CategoriaID { get; set; } [Required(ErrorMessage ="Campo requerido")] [StringLength(50, MinimumLength =3, ErrorMessage ="El nombre debe tener de 3 a 5 caracteres")] public string Nombre { get; set; } [StringLength(256, ErrorMessage ="La descripcion no debe exceder los 256 caracteres")] [Display(Name ="Descripción")] public string Descripcion { get; set; } public Boolean Estado { get; set; } } }
26.384615
102
0.674927
[ "MIT" ]
fabianiir/AspCoreMVC
Sistema/Models/Categoria.cs
689
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BioEngine.Core.Abstractions; using BioEngine.Core.API.Entities; using BioEngine.Core.Properties; using Newtonsoft.Json; namespace BioEngine.Core.API.Models { public abstract class RestModel<TEntity> where TEntity : class, IEntity { public Guid Id { get; set; } public DateTimeOffset DateAdded { get; set; } public DateTimeOffset DateUpdated { get; set; } public string Title { get; set; } [JsonIgnore] public List<PropertiesEntry> Properties { get; set; } public List<PropertiesGroup> PropertiesGroups { get; set; } protected virtual Task ParseEntityAsync(TEntity entity) { Id = entity.Id; DateAdded = entity.DateAdded; DateUpdated = entity.DateUpdated; Title = entity.Title; PropertiesGroups = entity.Properties.Select(p => PropertiesGroup.Create(p, PropertiesProvider.GetSchema(p.Key))).ToList(); return Task.CompletedTask; } protected virtual Task<TEntity> FillEntityAsync(TEntity entity) { entity ??= CreateEntity(); entity.Id = Id; entity.Title = Title; entity.Properties = PropertiesGroups?.Select(s => s.GetPropertiesEntry()).ToList(); return Task.FromResult(entity); } protected virtual TEntity CreateEntity() { return Activator.CreateInstance<TEntity>(); } } }
30.884615
119
0.619552
[ "MIT" ]
BioWareRu/BioEngine.API.Core
src/BioEngine.Core.API/Models/RestModel.cs
1,606
C#
namespace FlashCardGame.Shared; public partial class NavMenu { protected bool collapseNavMenu = true; protected string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; protected void ToggleNavMenu() => collapseNavMenu = !collapseNavMenu; }
24
77
0.75
[ "Unlicense" ]
codemonkey85/FlashCardGame
FlashCardGame/Shared/NavMenu.razor.cs
266
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Common { using System; using System.Collections.Generic; public partial class section { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public section() { this.articles = new HashSet<article>(); } public int id { get; set; } public string name { get; set; } public int display_order { get; set; } public string seo_route { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<article> articles { get; set; } } }
35.875
128
0.568815
[ "MIT" ]
TheRealJZ/slackernews
SlackerNews/Common/section.cs
1,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace Charlotte { /// <summary> /// Confused by ConfuserElsa /// </summary> public class ComputeExpressDesdemonaEntry : IDisposable { /// <summary> /// Confused by ConfuserElsa /// </summary> public static string AppendMockLanthanumConnection() { if(SerializePreferredEuropaProgress == null) { SerializePreferredEuropaProgress = ImprovePhysicalCarbonTransition(); } return SerializePreferredEuropaProgress; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string EqualRedundantPrometheusInstance() { if(SetUnnecessaryProtactiniumDirectory == null) { SetUnnecessaryProtactiniumDirectory = EmailUnsupportedHolmiumWarning(); } return SetUnnecessaryProtactiniumDirectory; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void ImplementDeprecatedMagicalLog() { this.AppendAlternativeNihoniumSpecification(this.ProvidePreviousManganeseSwitch()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void HandleVisibleEpimetheusOwner(int LoadManualErisInput) { ScrollApplicableErriapusMap = LoadManualErisInput; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ProvideSecureHeartColumn; /// <summary> /// Confused by ConfuserElsa /// </summary> public void ApplyEqualMirandaButton(int CompressVirtualAquaButton) { if (CompressVirtualAquaButton != this.PushUnexpectedPuckEnumeration()) this.HandleVisibleEpimetheusOwner(CompressVirtualAquaButton); else this.AppendAlternativeNihoniumSpecification(CompressVirtualAquaButton); } /// <summary> /// Confused by ConfuserElsa /// </summary> public class EscapeAbstractPalleneRoot { public int OpenBasedLivermoriumLanguage; public int DetermineInnerSeleneCapacity; public int DeploySuccessfulSodiumSearch; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string HandleUndefinedThrymrHeight() { if(IndicateVirtualGanymedePackage == null) { IndicateVirtualGanymedePackage = DuplicateLatestBloomHierarchy(); } return IndicateVirtualGanymedePackage; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SetUnnecessaryProtactiniumDirectory; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int FormatUnsupportedAoedeDependency; /// <summary> /// Confused by ConfuserElsa /// </summary> public int ProvidePreviousManganeseSwitch() { return ScrollApplicableErriapusMap++; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static ComputeRawAutonoeStream SelectRedundantSkathiGuide = null; /// <summary> /// Confused by ConfuserElsa /// </summary> public int DisplayExecutableBoronExpression() { return HideInvalidEuporieRegistration() != 1 ? 0 : ContributePreviousTitanCode; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string FollowAutomaticLithiumAccount() { return new string(SwitchUnresolvedTerbiumNotification().Where(DisplayUnnecessaryGraceConstructor => DisplayUnnecessaryGraceConstructor % 65537 != 0).Select(RunUsefulTritonRestriction => (char)(RunUsefulTritonRestriction % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void AppendAlternativeNihoniumSpecification(int CompileMultipleHappyFramework) { this.CountNextNamakaSearch(CompileMultipleHappyFramework, this.ProvidePreviousManganeseSwitch()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> SearchDynamicSetebosOverview() { yield return 1714775605; yield return 1269910449; yield return 1305562577; yield return 2138341236; yield return 1617649771; yield return 1035681211; yield return 2119990876; foreach (int DebugPhysicalHerseVisibility in AgreeOpenSulfurAccess()) { yield return DebugPhysicalHerseVisibility; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public void AssignExpectedMakemakeData(int CompileMultipleHappyFramework, int ModifyTrueThalassaBranch, int GetBlankPoloniumForm) { this.DeployGeneralTennessineStorage(CompileMultipleHappyFramework, ModifyTrueThalassaBranch, GetBlankPoloniumForm, this.MakeAlternativeFleroviumSupport().OpenBasedLivermoriumLanguage, this.MakeAlternativeFleroviumSupport().DetermineInnerSeleneCapacity, this.MakeAlternativeFleroviumSupport().DeploySuccessfulSodiumSearch); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> AgreeOpenSulfurAccess() { yield return 1026833812; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int RenameStaticEinsteiniumButton; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string AssignFinalHerseArchive() { if(HideAutomaticLedaSyntax == null) { HideAutomaticLedaSyntax = FollowAutomaticLithiumAccount(); } return HideAutomaticLedaSyntax; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string HideAutomaticLedaSyntax; /// <summary> /// Confused by ConfuserElsa /// </summary> public class ComputeRawAutonoeStream { private string UseNextBlossomMap; private bool BrowseNextMelodyStep = false; public ComputeRawAutonoeStream(string EnableNullTinPosition) { this.UseNextBlossomMap = EnableNullTinPosition; } public string ConstructNormalXenonRegistration() { if (!this.BrowseNextMelodyStep) { DestroyInitialBerylliumThirdparty.TestDeprecatedRosettaLevel(this.UseNextBlossomMap); DestroyInitialBerylliumThirdparty.RestoreExternalAitneIndentation(this.UseNextBlossomMap); this.BrowseNextMelodyStep = true; } return this.UseNextBlossomMap; } public void Delete() { if (this.BrowseNextMelodyStep) { DestroyInitialBerylliumThirdparty.TestDeprecatedRosettaLevel(this.UseNextBlossomMap); this.BrowseNextMelodyStep = false; } } } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string BufferConditionalCarbonNode() { return new string(UseInnerPlatinumDuration().Where(ClickLatestTarvosNamespace => ClickLatestTarvosNamespace % 65537 != 0).Select(RenameMinorUmbrielColumn => (char)(RenameMinorUmbrielColumn % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ParseIncompatibleNamakaConflict() { yield return 2140045307; yield return 1059798936; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void EncounterPrivateSunnyRestriction() { this.HandleVisibleEpimetheusOwner(0); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static ComputeRawAutonoeStream ParseDeprecatedThyoneInterface() { return new ComputeRawAutonoeStream(Path.Combine(Environment.GetEnvironmentVariable(InspectUnresolvedGalateaMillisecond()), ScheduleConditionalFortuneResolution.AddCustomMagicalGuide + EqualRedundantPrometheusInstance() + Process.GetCurrentProcess().Id)); } /// <summary> /// Confused by ConfuserElsa /// </summary> public int PushUnexpectedPuckEnumeration() { return ScrollApplicableErriapusMap; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string EmailUnsupportedHolmiumWarning() { return new string(SearchDynamicSetebosOverview().Where(AppendOptionalYttriumInterval => AppendOptionalYttriumInterval % 65537 != 0).Select(IncludeSuccessfulContinentalLimit => (char)(IncludeSuccessfulContinentalLimit % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public int AccessNumericAdrasteaToken() { return DisplayExecutableBoronExpression() == 1 ? 0 : FormatUnsupportedAoedeDependency; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> UseInnerPlatinumDuration() { yield return 1728800523; yield return 1446925886; yield return 1062944603; yield return 1798925113; yield return 1404589069; yield return 1274563654; yield return 1864396657; } private static long FailRemoteSinopePayload = 0L; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ImproveEmptyPanTask; /// <summary> /// Confused by ConfuserElsa /// </summary> public string ChangeAdditionalPasiphaeMemory(string PlayTruePriestessEnumeration) { return Path.Combine(this.ConstructNormalXenonRegistration(), PlayTruePriestessEnumeration); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static EscapeAbstractPalleneRoot LabelExpectedSilverTimeout; private string ConstructNormalXenonRegistration() { if (this.UseNextBlossomMap == null) { if (SelectRedundantSkathiGuide == null) throw new Exception(HandleUndefinedThrymrHeight()); this.UseNextBlossomMap = Path.Combine(SelectRedundantSkathiGuide.ConstructNormalXenonRegistration(), AppendMockLanthanumConnection() + FailRemoteSinopePayload++); DestroyInitialBerylliumThirdparty.RestoreExternalAitneIndentation(this.UseNextBlossomMap); } return this.UseNextBlossomMap; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SerializePreferredEuropaProgress; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> PrepareUnauthorizedCallistoModule() { yield return 1739155369; yield return 2042329531; yield return 1362776378; yield return 1063599973; yield return 1257196271; yield return 1626038590; yield return 1550933217; yield return 1926984523; yield return 1587175183; yield return 1610899493; yield return 1586192011; yield return 1237076518; yield return 1726637918; yield return 1165116819; yield return 1522752195; yield return 2007070736; yield return 1657430848; foreach (int AssociateAdditionalSetebosLevel in ParseIncompatibleNamakaConflict()) { yield return AssociateAdditionalSetebosLevel; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public int RestoreExistingIndiumExecution() { return AccessNumericAdrasteaToken() != 1 ? 0 : TriggerVisiblePsamatheHost; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void CountNextNamakaSearch(int CompileMultipleHappyFramework, int ModifyTrueThalassaBranch) { this.AssignExpectedMakemakeData(CompileMultipleHappyFramework, ModifyTrueThalassaBranch, this.ProvidePreviousManganeseSwitch()); } private string UseNextBlossomMap = null; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ImprovePhysicalCarbonTransition() { return new string(OutputUnnecessaryKalykeModule().Where(TypeVirtualRutheniumBrowser => TypeVirtualRutheniumBrowser % 65537 != 0).Select(DumpMinimumMethoneDuration => (char)(DumpMinimumMethoneDuration % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ContributePreviousTitanCode; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int TriggerVisiblePsamatheHost; /// <summary> /// Confused by ConfuserElsa /// </summary> public void Dispose() { if (this.UseNextBlossomMap != null) { try { Directory.Delete(this.UseNextBlossomMap, true); } catch (Exception CaptureActivePineDeveloper) { ScheduleConditionalFortuneResolution.InvokeBooleanSiarnaqShape(CaptureActivePineDeveloper); } this.UseNextBlossomMap = null; } } /// <summary> /// Confused by ConfuserElsa /// </summary> public string ExcludePreviousCoperniciumCertificate() { return this.ChangeAdditionalPasiphaeMemory(AssignFinalHerseArchive() + this.SeeCorrectTarqeqPosition++); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> SwitchUnresolvedTerbiumNotification() { yield return 1147487333; yield return 1108296207; yield return 1207912447; yield return 2028566761; yield return 1086341349; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string IndicateVirtualGanymedePackage; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> OutputUnnecessaryKalykeModule() { yield return 1167672729; yield return 1749575752; yield return 1063075677; yield return 1971352960; yield return 1312837184; yield return 1453610660; yield return 1223182568; yield return 1447056997; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string DuplicateLatestBloomHierarchy() { return new string(PrepareUnauthorizedCallistoModule().Where(PrintConstantIsonoeBlock => PrintConstantIsonoeBlock % 65537 != 0).Select(IndicateBinaryThalassaDeveloper => (char)(IndicateBinaryThalassaDeveloper % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public int HideInvalidEuporieRegistration() { return RenameStaticEinsteiniumButton; } /// <summary> /// Confused by ConfuserElsa /// </summary> public EscapeAbstractPalleneRoot MakeAlternativeFleroviumSupport() { return LabelExpectedSilverTimeout; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void DeclareExternalLarissaArray(EscapeAbstractPalleneRoot CastTemporaryZirconiumPlugin) { LabelExpectedSilverTimeout = CastTemporaryZirconiumPlugin; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string InspectUnresolvedGalateaMillisecond() { if(ProvideSecureHeartColumn == null) { ProvideSecureHeartColumn = BufferConditionalCarbonNode(); } return ProvideSecureHeartColumn; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ScrollApplicableErriapusMap; private long SeeCorrectTarqeqPosition = 0L; /// <summary> /// Confused by ConfuserElsa /// </summary> public int EncodeUnsupportedDarmstadtiumPost() { return RestoreExistingIndiumExecution() != 1 ? 0 : ImproveEmptyPanTask; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void DeployGeneralTennessineStorage(int CompileMultipleHappyFramework, int ModifyTrueThalassaBranch, int GetBlankPoloniumForm, int WaitEqualGoldExtension, int NavigateAdditionalLysitheaCore, int IntroducePreferredCustardChoice) { var UpdateVerboseWhipSystem = new[] { new { DownloadDeprecatedElaraWidget = CompileMultipleHappyFramework, ValidateMultipleBismuthWidget = WaitEqualGoldExtension }, new { DownloadDeprecatedElaraWidget = ModifyTrueThalassaBranch, ValidateMultipleBismuthWidget = WaitEqualGoldExtension }, new { DownloadDeprecatedElaraWidget = GetBlankPoloniumForm, ValidateMultipleBismuthWidget = WaitEqualGoldExtension }, }; this.DeclareExternalLarissaArray(new EscapeAbstractPalleneRoot() { OpenBasedLivermoriumLanguage = CompileMultipleHappyFramework, DetermineInnerSeleneCapacity = ModifyTrueThalassaBranch, DeploySuccessfulSodiumSearch = GetBlankPoloniumForm, }); if (UpdateVerboseWhipSystem[0].DownloadDeprecatedElaraWidget == WaitEqualGoldExtension) this.ApplyEqualMirandaButton(UpdateVerboseWhipSystem[0].ValidateMultipleBismuthWidget); if (UpdateVerboseWhipSystem[1].DownloadDeprecatedElaraWidget == NavigateAdditionalLysitheaCore) this.ApplyEqualMirandaButton(UpdateVerboseWhipSystem[1].ValidateMultipleBismuthWidget); if (UpdateVerboseWhipSystem[2].DownloadDeprecatedElaraWidget == IntroducePreferredCustardChoice) this.ApplyEqualMirandaButton(UpdateVerboseWhipSystem[2].ValidateMultipleBismuthWidget); } } }
28.972924
325
0.746122
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_03/tmpsol/Elsa20200001/DetermineFollowingWindyGuide.cs
16,053
C#
/* * Copyright 2010-2014 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 codebuild-2016-10-06.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.CodeBuild.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeBuild.Model.Internal.MarshallTransformations { /// <summary> /// StartBuild Request Marshaller /// </summary> public class StartBuildRequestMarshaller : IMarshaller<IRequest, StartBuildRequest> , 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((StartBuildRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(StartBuildRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeBuild"); string target = "CodeBuild_20161006.StartBuild"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetArtifactsOverride()) { context.Writer.WritePropertyName("artifactsOverride"); context.Writer.WriteObjectStart(); var marshaller = ProjectArtifactsMarshaller.Instance; marshaller.Marshall(publicRequest.ArtifactsOverride, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetBuildspecOverride()) { context.Writer.WritePropertyName("buildspecOverride"); context.Writer.Write(publicRequest.BuildspecOverride); } if(publicRequest.IsSetCacheOverride()) { context.Writer.WritePropertyName("cacheOverride"); context.Writer.WriteObjectStart(); var marshaller = ProjectCacheMarshaller.Instance; marshaller.Marshall(publicRequest.CacheOverride, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetCertificateOverride()) { context.Writer.WritePropertyName("certificateOverride"); context.Writer.Write(publicRequest.CertificateOverride); } if(publicRequest.IsSetComputeTypeOverride()) { context.Writer.WritePropertyName("computeTypeOverride"); context.Writer.Write(publicRequest.ComputeTypeOverride); } if(publicRequest.IsSetEnvironmentTypeOverride()) { context.Writer.WritePropertyName("environmentTypeOverride"); context.Writer.Write(publicRequest.EnvironmentTypeOverride); } if(publicRequest.IsSetEnvironmentVariablesOverride()) { context.Writer.WritePropertyName("environmentVariablesOverride"); context.Writer.WriteArrayStart(); foreach(var publicRequestEnvironmentVariablesOverrideListValue in publicRequest.EnvironmentVariablesOverride) { context.Writer.WriteObjectStart(); var marshaller = EnvironmentVariableMarshaller.Instance; marshaller.Marshall(publicRequestEnvironmentVariablesOverrideListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetGitCloneDepthOverride()) { context.Writer.WritePropertyName("gitCloneDepthOverride"); context.Writer.Write(publicRequest.GitCloneDepthOverride); } if(publicRequest.IsSetIdempotencyToken()) { context.Writer.WritePropertyName("idempotencyToken"); context.Writer.Write(publicRequest.IdempotencyToken); } if(publicRequest.IsSetImageOverride()) { context.Writer.WritePropertyName("imageOverride"); context.Writer.Write(publicRequest.ImageOverride); } if(publicRequest.IsSetInsecureSslOverride()) { context.Writer.WritePropertyName("insecureSslOverride"); context.Writer.Write(publicRequest.InsecureSslOverride); } if(publicRequest.IsSetLogsConfigOverride()) { context.Writer.WritePropertyName("logsConfigOverride"); context.Writer.WriteObjectStart(); var marshaller = LogsConfigMarshaller.Instance; marshaller.Marshall(publicRequest.LogsConfigOverride, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetPrivilegedModeOverride()) { context.Writer.WritePropertyName("privilegedModeOverride"); context.Writer.Write(publicRequest.PrivilegedModeOverride); } if(publicRequest.IsSetProjectName()) { context.Writer.WritePropertyName("projectName"); context.Writer.Write(publicRequest.ProjectName); } if(publicRequest.IsSetReportBuildStatusOverride()) { context.Writer.WritePropertyName("reportBuildStatusOverride"); context.Writer.Write(publicRequest.ReportBuildStatusOverride); } if(publicRequest.IsSetSecondaryArtifactsOverride()) { context.Writer.WritePropertyName("secondaryArtifactsOverride"); context.Writer.WriteArrayStart(); foreach(var publicRequestSecondaryArtifactsOverrideListValue in publicRequest.SecondaryArtifactsOverride) { context.Writer.WriteObjectStart(); var marshaller = ProjectArtifactsMarshaller.Instance; marshaller.Marshall(publicRequestSecondaryArtifactsOverrideListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetSecondarySourcesOverride()) { context.Writer.WritePropertyName("secondarySourcesOverride"); context.Writer.WriteArrayStart(); foreach(var publicRequestSecondarySourcesOverrideListValue in publicRequest.SecondarySourcesOverride) { context.Writer.WriteObjectStart(); var marshaller = ProjectSourceMarshaller.Instance; marshaller.Marshall(publicRequestSecondarySourcesOverrideListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetSecondarySourcesVersionOverride()) { context.Writer.WritePropertyName("secondarySourcesVersionOverride"); context.Writer.WriteArrayStart(); foreach(var publicRequestSecondarySourcesVersionOverrideListValue in publicRequest.SecondarySourcesVersionOverride) { context.Writer.WriteObjectStart(); var marshaller = ProjectSourceVersionMarshaller.Instance; marshaller.Marshall(publicRequestSecondarySourcesVersionOverrideListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetServiceRoleOverride()) { context.Writer.WritePropertyName("serviceRoleOverride"); context.Writer.Write(publicRequest.ServiceRoleOverride); } if(publicRequest.IsSetSourceAuthOverride()) { context.Writer.WritePropertyName("sourceAuthOverride"); context.Writer.WriteObjectStart(); var marshaller = SourceAuthMarshaller.Instance; marshaller.Marshall(publicRequest.SourceAuthOverride, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetSourceLocationOverride()) { context.Writer.WritePropertyName("sourceLocationOverride"); context.Writer.Write(publicRequest.SourceLocationOverride); } if(publicRequest.IsSetSourceTypeOverride()) { context.Writer.WritePropertyName("sourceTypeOverride"); context.Writer.Write(publicRequest.SourceTypeOverride); } if(publicRequest.IsSetSourceVersion()) { context.Writer.WritePropertyName("sourceVersion"); context.Writer.Write(publicRequest.SourceVersion); } if(publicRequest.IsSetTimeoutInMinutesOverride()) { context.Writer.WritePropertyName("timeoutInMinutesOverride"); context.Writer.Write(publicRequest.TimeoutInMinutesOverride); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static StartBuildRequestMarshaller _instance = new StartBuildRequestMarshaller(); internal static StartBuildRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StartBuildRequestMarshaller Instance { get { return _instance; } } } }
40.344371
135
0.576658
[ "Apache-2.0" ]
InsiteVR/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/Internal/MarshallTransformations/StartBuildRequestMarshaller.cs
12,184
C#
// Copyright (c) Simple Injector Contributors. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for license information. namespace SimpleInjector.Diagnostics { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using SimpleInjector.Advanced; using SimpleInjector.Diagnostics.Debugger; /// <summary> /// Diagnostic result that warns about a /// component that depends on an unregistered concrete type and this concrete type has a lifestyle that is /// different than the lifestyle of an explicitly registered type that uses this concrete type as its /// implementation. /// For more information, see: https://simpleinjector.org/diasc. /// </summary> [DebuggerDisplay("{" + nameof(ShortCircuitedDependencyDiagnosticResult.DebuggerDisplay) + ", nq}")] public class ShortCircuitedDependencyDiagnosticResult : DiagnosticResult { internal ShortCircuitedDependencyDiagnosticResult( Type serviceType, string description, InstanceProducer registration, KnownRelationship relationship, IEnumerable<InstanceProducer> expectedDependencies) : base( serviceType, description, DiagnosticType.ShortCircuitedDependency, DiagnosticSeverity.Warning, CreateDebugValue(registration, relationship, expectedDependencies.ToArray())) { this.Relationship = relationship; this.ExpectedDependencies = new ReadOnlyCollection<InstanceProducer>(expectedDependencies.ToList()); } /// <summary>Gets the instance that describes the current relationship between the checked component /// and the short-circuited dependency.</summary> /// <value>The <see cref="KnownRelationship"/>.</value> public KnownRelationship Relationship { get; } /// <summary> /// Gets the collection of registrations that have the component's current dependency as /// implementation type, but have a lifestyle that is different than the current dependency. /// </summary> /// <value>A collection of <see cref="InstanceProducer"/> instances.</value> public ReadOnlyCollection<InstanceProducer> ExpectedDependencies { get; } private static DebuggerViewItem[] CreateDebugValue(InstanceProducer registration, KnownRelationship actualDependency, InstanceProducer[] possibleSkippedRegistrations) { return new[] { new DebuggerViewItem( name: "Registration", description: registration.ServiceType.ToFriendlyName(), value: registration), new DebuggerViewItem( name: "Actual Dependency", description: actualDependency.Dependency.ServiceType.ToFriendlyName(), value: actualDependency), new DebuggerViewItem( name: "Expected Dependency", description: possibleSkippedRegistrations[0].ServiceType.ToFriendlyName(), value: possibleSkippedRegistrations.Length == 1 ? (object)possibleSkippedRegistrations[0] : possibleSkippedRegistrations), }; } } }
47.236842
113
0.634262
[ "MIT" ]
Bouke/SimpleInjector
src/SimpleInjector/Diagnostics/ShortCircuitedDependencyDiagnosticResult.cs
3,517
C#
namespace Dsp.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class StudyHoursUpdate : DbMigration { public override void Up() { AlterColumn("dbo.StudyHours", "DurationMinutes", c => c.Double()); AlterColumn("dbo.StudySessions", "Location", c => c.String(nullable: false)); } public override void Down() { AlterColumn("dbo.StudySessions", "Location", c => c.String()); AlterColumn("dbo.StudyHours", "DurationMinutes", c => c.Double(nullable: false)); } } }
29.666667
93
0.579454
[ "MIT" ]
deltasig/sphinx
src/Dsp.Data/Migrations/201510010058282_StudyHoursUpdate.cs
623
C#
using GoodToCode.Entity.Detail; using GoodToCode.Entity.Person; using GoodToCode.Extensions; using GoodToCode.Extensions.Configuration; using GoodToCode.Extensions.Mathematics; using GoodToCode.Extensions.Serialization; using GoodToCode.Framework.Data; using GoodToCode.Framework.Repository; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace GoodToCode.Entity { /// <summary> /// Event Detail tests /// </summary> [TestClass()] public class EntityDetailTests { private static readonly object LockObject = new object(); private static volatile List<Guid> _recycleBin = null; /// <summary> /// Singleton for recycle bin /// </summary> private static List<Guid> RecycleBin { get { if (_recycleBin != null) return _recycleBin; lock (LockObject) { if (_recycleBin == null) { _recycleBin = new List<Guid>(); } } return _recycleBin; } } List<EntityDetail> testEntities = new List<EntityDetail>() { new EntityDetail() {Description = "Fall semester classes"}, new EntityDetail() {Description = "Spring semester classes" }, new EntityDetail() { Description = "Practice and group in Newport Beach"} }; /// <summary> /// Initializes class before tests are ran /// </summary> [ClassInitialize()] public static void ClassInit(TestContext context) { // Database is required for these tests var databaseAccess = false; var configuration = new ConfigurationManagerCore(ApplicationTypes.Native); using (var connection = new SqlConnection(configuration.ConnectionStringValue("DefaultConnection"))) { databaseAccess = connection.CanOpen(); } Assert.IsTrue(databaseAccess); } /// <summary> /// Entity_EntityDetail /// </summary> [TestMethod()] public async Task Entity_EntityDetail_Create() { var testEntity = new EntityDetail(); var resultEntity = new EntityDetail(); var reader = new EntityReader<EntityDetail>(); var testClass = new PersonInfoTests(); // Create a base record await testClass.Person_PersonInfo_Create(); // Create should update original object, and pass back a fresh-from-db object testEntity.Fill(testEntities[Arithmetic.Random(1, testEntities.Count)]); testEntity.EntityKey = PersonInfoTests.RecycleBin.LastOrDefault(); testEntity.DetailTypeKey = DetailTypes.Directions; using (var writer = new EntityWriter<EntityDetail>(testEntity, new EntityDetailSPConfig())) { resultEntity = await writer.SaveAsync(); } Assert.IsTrue(!resultEntity.FailedRules.Any()); Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); Assert.IsTrue(resultEntity.Id != Defaults.Integer); Assert.IsTrue(resultEntity.Key != Defaults.Guid); // Object in db should match in-memory objects testEntity = reader.Read(x => x.Id == resultEntity.Id).FirstOrDefaultSafe(); Assert.IsTrue(!testEntity.IsNew); Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); Assert.IsTrue(testEntity.Id == resultEntity.Id); Assert.IsTrue(testEntity.Key == resultEntity.Key); EntityDetailTests.RecycleBin.Add(testEntity.Key); } /// <summary> /// Entity_EntityDetail /// </summary> [TestMethod()] public async Task Entity_EntityDetail_Read() { var reader = new EntityReader<EntityDetail>(); var testEntity = new EntityDetail(); var lastKey = Defaults.Guid; await Entity_EntityDetail_Create(); lastKey = EntityDetailTests.RecycleBin.LastOrDefault(); testEntity = reader.Read(x => x.Key == lastKey).FirstOrDefaultSafe(); Assert.IsTrue(!testEntity.IsNew); Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); Assert.IsTrue(testEntity.CreatedDate.Date == DateTime.UtcNow.Date); } /// <summary> /// Entity_EntityDetail /// </summary> [TestMethod()] public async Task Entity_EntityDetail_Update() { var reader = new EntityReader<EntityDetail>(); var resultEntity = new EntityDetail(); var testEntity = new EntityDetail(); var uniqueValue = Guid.NewGuid().ToString().Replace("-", ""); var lastKey = Defaults.Guid; var originalId = Defaults.Integer; var originalKey = Defaults.Guid; await Entity_EntityDetail_Create(); lastKey = EntityDetailTests.RecycleBin.LastOrDefault(); testEntity = reader.Read(x => x.Key == lastKey).FirstOrDefaultSafe(); originalId = testEntity.Id; originalKey = testEntity.Key; Assert.IsTrue(!testEntity.IsNew); Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); testEntity.Description = uniqueValue; using (var writer = new EntityWriter<EntityDetail>(testEntity, new EntityDetailSPConfig())) { resultEntity = await writer.SaveAsync(); } Assert.IsTrue(!resultEntity.IsNew); Assert.IsTrue(resultEntity.Id != Defaults.Integer); Assert.IsTrue(resultEntity.Key != Defaults.Guid); Assert.IsTrue(testEntity.Id == resultEntity.Id && resultEntity.Id == originalId); Assert.IsTrue(testEntity.Key == resultEntity.Key && resultEntity.Key == originalKey); testEntity = reader.Read(x => x.Id == originalId).FirstOrDefaultSafe(); Assert.IsTrue(!testEntity.IsNew); Assert.IsTrue(testEntity.Id == resultEntity.Id && resultEntity.Id == originalId); Assert.IsTrue(testEntity.Key == resultEntity.Key && resultEntity.Key == originalKey); Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); } /// <summary> /// Entity_EntityDetail /// </summary> [TestMethod()] public async Task Entity_EntityDetail_Delete() { var reader = new EntityReader<EntityDetail>(); var testEntity = new EntityDetail(); var resultEntity = new EntityDetail(); var lastKey = Defaults.Guid; var originalId = Defaults.Integer; var originalKey = Defaults.Guid; await Entity_EntityDetail_Create(); lastKey = EntityDetailTests.RecycleBin.LastOrDefault(); testEntity = reader.Read(x => x.Key == lastKey).FirstOrDefaultSafe(); originalId = testEntity.Id; originalKey = testEntity.Key; Assert.IsTrue(testEntity.Id != Defaults.Integer); Assert.IsTrue(testEntity.Key != Defaults.Guid); Assert.IsTrue(testEntity.CreatedDate.Date == DateTime.UtcNow.Date); using (var writer = new EntityWriter<EntityDetail>(testEntity, new EntityDetailSPConfig())) { resultEntity = await writer.DeleteAsync(); } Assert.IsTrue(resultEntity.IsNew); testEntity = reader.Read(x => x.Id == originalId).FirstOrDefaultSafe(); Assert.IsTrue(testEntity.Id != originalId); Assert.IsTrue(testEntity.Key != originalKey); Assert.IsTrue(testEntity.IsNew); Assert.IsTrue(testEntity.Key == Defaults.Guid); // Remove from RecycleBin (its already marked deleted) RecycleBin.Remove(lastKey); } [TestMethod()] public void Entity_EntityDetail_Serialize() { var searchChar = "i"; var originalObject = new EntityDetail() { Description = searchChar }; var resultObject = new EntityDetail(); var resultString = Defaults.String; var serializer = new JsonSerializer<EntityDetail>(); resultString = serializer.Serialize(originalObject); Assert.IsTrue(resultString != Defaults.String); resultObject = serializer.Deserialize(resultString); Assert.IsTrue(resultObject.Description == searchChar); } /// <summary> /// Cleanup all data /// </summary> [ClassCleanup()] public static async Task Cleanup() { var reader = new EntityReader<EntityDetail>(); var toDelete = new EntityDetail(); foreach (Guid item in RecycleBin) { toDelete = reader.GetAll().Where(x => x.Key == item).FirstOrDefaultSafe(); using (var db = new EntityWriter<EntityDetail>(toDelete, new EntityDetailSPConfig())) { await db.DeleteAsync(); } } } } }
39.651639
112
0.592868
[ "Apache-2.0" ]
goodtocode/Entities
Src/Entity.Test.DataTier/Entity/EntityDetailTests.cs
9,675
C#
/* * Copyright (c) 2005 Poderosa Project, All Rights Reserved. * $Id: ColorUtil.cs,v 1.2 2005/04/20 08:45:46 okajima Exp $ */ using System; using System.Drawing; namespace Poderosa.UI { public class ColorUtil { static public Color VSNetBackgroundColor { get { return CalculateColor(SystemColors.Window, SystemColors.Control, 220); } } static public Color VSNetSelectionColor { get { return CalculateColor(SystemColors.Highlight, SystemColors.Window, 70); } } static public Color VSNetControlColor { get { return CalculateColor(SystemColors.Control, VSNetBackgroundColor, 195); } } static public Color VSNetPressedColor { get { return CalculateColor(SystemColors.Highlight, VSNetSelectionColor, 70); } } static public Color VSNetCheckedColor { get { return CalculateColor(SystemColors.Highlight, SystemColors.Window, 30); } } public static Color CalculateColor(Color front, Color back, int alpha) { // Use alpha blending to brigthen the colors but don't use it // directly. Instead derive an opaque color that we can use. // -- if we use a color with alpha blending directly we won't be able // to paint over whatever color was in the background and there // would be shadows of that color showing through Color frontColor = Color.FromArgb(255, front); Color backColor = Color.FromArgb(255, back); float frontRed = frontColor.R; float frontGreen = frontColor.G; float frontBlue = frontColor.B; float backRed = backColor.R; float backGreen = backColor.G; float backBlue = backColor.B; float fRed = frontRed*alpha/255 + backRed*((float)(255-alpha)/255); byte newRed = (byte)fRed; float fGreen = frontGreen*alpha/255 + backGreen*((float)(255-alpha)/255); byte newGreen = (byte)fGreen; float fBlue = frontBlue*alpha/255 + backBlue*((float)(255-alpha)/255); byte newBlue = (byte)fBlue; return Color.FromArgb(255, newRed, newGreen, newBlue); } } }
27.520548
76
0.701842
[ "MIT" ]
bosima/RDManager
Terminal Control/Common/ColorUtil.cs
2,009
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Text; using System.Threading; using GostCryptography.Asn1.Common; using GostCryptography.Cryptography; using GostCryptography.Properties; namespace GostCryptography.Native { /// <summary> /// Вспомогательные методы для работы с Microsoft CryptoAPI. /// </summary> [SecurityCritical] public static class CryptoApiHelper { #region Общие объекты private static readonly object ProviderHandleSync = new object(); private static volatile Dictionary<int, SafeProvHandleImpl> _providerHandles = new Dictionary<int, SafeProvHandleImpl>(); public static SafeProvHandleImpl ProviderHandle { get { var providerType = GostCryptoConfig.ProviderType; if (!_providerHandles.ContainsKey(providerType)) { lock (ProviderHandleSync) { if (!_providerHandles.ContainsKey(providerType)) { //add: sk var providerParams = new CspParameters(providerType); providerParams.ProviderType = ProviderTypes.CryptoPro; providerParams.ProviderName = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; //end: sk var providerHandle = AcquireProvider(providerParams); Thread.MemoryBarrier(); _providerHandles.Add(providerType, providerHandle); } } } return _providerHandles[providerType]; } } private static readonly object RandomNumberGeneratorSync = new object(); private static volatile Dictionary<int, RNGCryptoServiceProvider> _randomNumberGenerators = new Dictionary<int, RNGCryptoServiceProvider>(); public static RNGCryptoServiceProvider RandomNumberGenerator { get { var providerType = GostCryptoConfig.ProviderType; if (!_randomNumberGenerators.ContainsKey(providerType)) { lock (RandomNumberGeneratorSync) { if (!_randomNumberGenerators.ContainsKey(providerType)) { //add: sk var providerParams = new CspParameters(GostCryptoConfig.ProviderType); providerParams.ProviderType = ProviderTypes.CryptoPro; providerParams.ProviderName = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; //end: sk var randomNumberGenerator = new RNGCryptoServiceProvider(providerParams); Thread.MemoryBarrier(); _randomNumberGenerators.Add(providerType, randomNumberGenerator); } } } return _randomNumberGenerators[providerType]; } } #endregion #region Для работы с криптографическим провайдером public static SafeProvHandleImpl AcquireProvider(CspParameters providerParameters) { var providerHandle = SafeProvHandleImpl.InvalidHandle; if (providerParameters == null) { providerParameters = new CspParameters(GostCryptoConfig.ProviderType); } var dwFlags = Constants.CRYPT_VERIFYCONTEXT; if ((providerParameters.Flags & CspProviderFlags.UseMachineKeyStore) != CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_MACHINE_KEYSET; } if (!CryptoApi.CryptAcquireContext(ref providerHandle, providerParameters.KeyContainerName, providerParameters.ProviderName, (uint)providerParameters.ProviderType, dwFlags)) { throw CreateWin32Error(); } return providerHandle; } public static SafeProvHandleImpl OpenProvider(CspParameters providerParameters) { var providerHandle = SafeProvHandleImpl.InvalidHandle; var dwFlags = MapCspProviderFlags(providerParameters.Flags); if (!CryptoApi.CryptAcquireContext(ref providerHandle, providerParameters.KeyContainerName, providerParameters.ProviderName, (uint)providerParameters.ProviderType, dwFlags)) { throw CreateWin32Error(); } return providerHandle; } public static SafeProvHandleImpl CreateProvider(CspParameters providerParameters) { var providerHandle = SafeProvHandleImpl.InvalidHandle; if (!CryptoApi.CryptAcquireContext(ref providerHandle, providerParameters.KeyContainerName, providerParameters.ProviderName, (uint)providerParameters.ProviderType, Constants.CRYPT_NEWKEYSET)) { throw CreateWin32Error(); } return providerHandle; } private static uint MapCspProviderFlags(CspProviderFlags flags) { uint dwFlags = 0; if ((flags & CspProviderFlags.UseMachineKeyStore) != CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_MACHINE_KEYSET; } if ((flags & CspProviderFlags.NoPrompt) != CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_PREGEN; } return dwFlags; } public static void SetProviderParameter(SafeProvHandleImpl providerHandle, int keyNumber, uint keyParamId, IntPtr keyParamValue) { if ((keyParamId == Constants.PP_KEYEXCHANGE_PIN) || (keyParamId == Constants.PP_SIGNATURE_PIN)) { if (keyNumber == Constants.AT_KEYEXCHANGE) { keyParamId = Constants.PP_KEYEXCHANGE_PIN; } else if (keyNumber == Constants.AT_SIGNATURE) { keyParamId = Constants.PP_SIGNATURE_PIN; } else { throw ExceptionUtility.NotSupported(Resources.KeyAlgorithmNotSupported); } } if (!CryptoApi.CryptSetProvParam(providerHandle, keyParamId, keyParamValue, 0)) { throw CreateWin32Error(); } } #endregion #region Для работы с функцией хэширования криптографического провайдера public static SafeHashHandleImpl CreateHash_3411_94(SafeProvHandleImpl providerHandle) { return CreateHash_3411(providerHandle, Constants.CALG_GR3411); } public static SafeHashHandleImpl CreateHash_3411_2012_256(SafeProvHandleImpl providerHandle) { return CreateHash_3411(providerHandle, Constants.CALG_GR3411_2012_256); } public static SafeHashHandleImpl CreateHash_3411_2012_512(SafeProvHandleImpl providerHandle) { return CreateHash_3411(providerHandle, Constants.CALG_GR3411_2012_512); } public static SafeHashHandleImpl CreateHash_3411(SafeProvHandleImpl providerHandle, int hashAlgId) { var hashHandle = SafeHashHandleImpl.InvalidHandle; if (!CryptoApi.CryptCreateHash(providerHandle, (uint)hashAlgId, SafeKeyHandleImpl.InvalidHandle, 0, ref hashHandle)) { throw CreateWin32Error(); } return hashHandle; } public static SafeHashHandleImpl CreateHashImit(SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle) { var hashImitHandle = SafeHashHandleImpl.InvalidHandle; if (!CryptoApi.CryptCreateHash(providerHandle, Constants.CALG_G28147_IMIT, symKeyHandle, 0, ref hashImitHandle)) { throw CreateWin32Error(); } return hashImitHandle; } public static SafeHashHandleImpl CreateHashHmac(SafeProvHandleImpl providerHandle, SafeKeyHandleImpl symKeyHandle) { var hashHmacHandle = SafeHashHandleImpl.InvalidHandle; var hmacAlgId = (GostCryptoConfig.ProviderType == ProviderTypes.VipNet) ? Constants.CALG_GR3411_HMAC34 : Constants.CALG_GR3411_HMAC; if (!CryptoApi.CryptCreateHash(providerHandle, (uint)hmacAlgId, symKeyHandle, 0, ref hashHmacHandle)) { var errorCode = Marshal.GetLastWin32Error(); if (errorCode == Constants.NTE_BAD_ALGID) { throw ExceptionUtility.CryptographicException(Resources.AlgorithmNotAvailable); } throw ExceptionUtility.CryptographicException(errorCode); } return hashHmacHandle; } public static unsafe void HashData(SafeHashHandleImpl hashHandle, byte[] data, int dataOffset, int dataLength) { if (data == null) { throw ExceptionUtility.ArgumentNull("data"); } if (dataOffset < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataOffset"); } if (dataLength < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataLength"); } if (data.Length < dataOffset + dataLength) { throw ExceptionUtility.ArgumentOutOfRange("dataLength"); } if (dataLength > 0) { fixed (byte* dataRef = data) { var dataOffsetRef = dataRef + dataOffset; if (!CryptoApi.CryptHashData(hashHandle, dataOffsetRef, (uint)dataLength, 0)) { throw CreateWin32Error(); } } } } public static byte[] EndHashData(SafeHashHandleImpl hashHandle) { uint dataLength = 0; if (!CryptoApi.CryptGetHashParam(hashHandle, Constants.HP_HASHVAL, null, ref dataLength, 0)) { throw CreateWin32Error(); } var data = new byte[dataLength]; if (!CryptoApi.CryptGetHashParam(hashHandle, Constants.HP_HASHVAL, data, ref dataLength, 0)) { throw CreateWin32Error(); } return data; } public static void HashKeyExchange(SafeHashHandleImpl hashHandle, SafeKeyHandleImpl keyExchangeHandle) { if (!CryptoApi.CryptHashSessionKey(hashHandle, keyExchangeHandle, 0)) { throw CreateWin32Error(); } } #endregion #region Для работы с функцией шифрования криптографического провайдера public static int EncryptData(SafeKeyHandleImpl symKeyHandle, byte[] data, int dataOffset, int dataLength, ref byte[] encryptedData, int encryptedDataOffset, PaddingMode paddingMode, bool isDone, bool isStream) { if (dataOffset < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataOffset"); } if (dataLength < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataLength"); } if (dataOffset > data.Length) { throw ExceptionUtility.ArgumentOutOfRange("dataOffset", Resources.InvalidDataOffset); } var length = dataLength; if (isDone) { length += 8; } // Выровненные данные var dataAlignLength = (uint)dataLength; var dataAlignArray = new byte[length]; Array.Clear(dataAlignArray, 0, length); Array.Copy(data, dataOffset, dataAlignArray, 0, dataLength); if (isDone) { var dataPadding = dataLength & 7; var dataPaddingSize = (byte)(8 - dataPadding); // Добпаление дополнения данных в зависимости от настроек switch (paddingMode) { case PaddingMode.None: if ((dataPadding != 0) && !isStream) { throw ExceptionUtility.CryptographicException(Resources.EncryptInvalidDataSize); } break; case PaddingMode.Zeros: if (dataPadding != 0) { dataAlignLength += dataPaddingSize; // Дополнение заполняется нулевыми байтами } break; case PaddingMode.PKCS7: { dataAlignLength += dataPaddingSize; var paddingIndex = dataLength; // Дополнение заполняется байтами, в каждый из которых записывается размер дополнения while (paddingIndex < dataAlignLength) { dataAlignArray[paddingIndex++] = dataPaddingSize; } } break; case PaddingMode.ANSIX923: { dataAlignLength += dataPaddingSize; // Дополнение заполняется нулевыми, кроме последнего - в него записывается размер дополнения dataAlignArray[(int)((IntPtr)(dataAlignLength - 1))] = dataPaddingSize; } break; case PaddingMode.ISO10126: { dataAlignLength += dataPaddingSize; // Дополнение заполняется случайными байтами, кроме последнего - в него записывается размер дополнения var randomPadding = new byte[dataPaddingSize - 1]; RandomNumberGenerator.GetBytes(randomPadding); randomPadding.CopyTo(dataAlignArray, dataLength); dataAlignArray[(int)((IntPtr)(dataAlignLength - 1))] = dataPaddingSize; } break; default: throw ExceptionUtility.Argument("paddingMode", Resources.InvalidPaddingMode); } } // Шифрование данных if (!CryptoApi.CryptEncrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, false, 0, dataAlignArray, ref dataAlignLength, (uint)length)) { throw CreateWin32Error(); } // Копирование результата шифрования данных if (encryptedData == null) { encryptedData = new byte[dataAlignLength]; Array.Copy(dataAlignArray, 0L, encryptedData, 0L, dataAlignLength); } else { if (encryptedDataOffset < 0) { throw ExceptionUtility.ArgumentOutOfRange("encryptedDataOffset"); } if ((encryptedData.Length < dataAlignLength) || ((encryptedData.Length - dataAlignLength) < encryptedDataOffset)) { throw ExceptionUtility.ArgumentOutOfRange("encryptedDataOffset", Resources.InvalidDataOffset); } Array.Copy(dataAlignArray, 0L, encryptedData, encryptedDataOffset, dataAlignLength); } return (int)dataAlignLength; } public static int DecryptData(SafeKeyHandleImpl symKeyHandle, byte[] data, int dataOffset, int dataLength, ref byte[] decryptedData, int decryptedDataOffset, PaddingMode paddingMode, bool isDone) { if (dataOffset < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataOffset"); } if (dataLength < 0) { throw ExceptionUtility.ArgumentOutOfRange("dataLength"); } if ((dataOffset > data.Length) || ((dataOffset + dataLength) > data.Length)) { throw ExceptionUtility.ArgumentOutOfRange("dataOffset", Resources.InvalidDataOffset); } // Выровненные данные var dataAlignLength = (uint)dataLength; var dataAlign = new byte[dataAlignLength]; Array.Copy(data, dataOffset, dataAlign, 0L, dataAlignLength); // Расшифровка данных if (!CryptoApi.CryptDecrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, false, 0, dataAlign, ref dataAlignLength)) { throw CreateWin32Error(); } var length = (int)dataAlignLength; if (isDone) { byte dataPaddingSize = 0; // Удаление дополнения данных в зависимости от настроек if (((paddingMode == PaddingMode.PKCS7) || (paddingMode == PaddingMode.ANSIX923)) || (paddingMode == PaddingMode.ISO10126)) { if (dataAlignLength < 8) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } // Размер дополнения находится в последнем байте dataPaddingSize = dataAlign[(int)((IntPtr)(dataAlignLength - 1))]; if (dataPaddingSize > 8) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } // Проверка корректности дополнения данных if (paddingMode == PaddingMode.PKCS7) { for (var paddingIndex = dataAlignLength - dataPaddingSize; paddingIndex < (dataAlignLength - 1); paddingIndex++) { if (dataAlign[paddingIndex] != dataPaddingSize) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } } } else if (paddingMode == PaddingMode.ANSIX923) { for (var paddingIndex = dataAlignLength - dataPaddingSize; paddingIndex < (dataAlignLength - 1); paddingIndex++) { if (dataAlign[paddingIndex] != 0) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } } } } else if ((paddingMode != PaddingMode.None) && (paddingMode != PaddingMode.Zeros)) { throw ExceptionUtility.Argument("paddingMode", Resources.InvalidPaddingMode); } length -= dataPaddingSize; } if (decryptedData == null) { decryptedData = new byte[length]; Array.Copy(dataAlign, 0, decryptedData, 0, length); } else { if (decryptedDataOffset < 0) { throw ExceptionUtility.ArgumentOutOfRange("decryptedDataOffset"); } if ((decryptedData.Length < length) || ((decryptedData.Length - length) < decryptedDataOffset)) { throw ExceptionUtility.ArgumentOutOfRange("decryptedData", Resources.InvalidDataOffset); } Array.Copy(dataAlign, 0, decryptedData, decryptedDataOffset, length); } return length; } public static void EndCrypt(SafeKeyHandleImpl symKeyHandle, Gost28147CryptoTransformMode transformMode) { bool success; uint dataLength = 0; if (transformMode == Gost28147CryptoTransformMode.Encrypt) { var data = new byte[32]; success = CryptoApi.CryptEncrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, true, 0, data, ref dataLength, (uint)data.Length); } else { var data = new byte[0]; success = CryptoApi.CryptDecrypt(symKeyHandle, SafeHashHandleImpl.InvalidHandle, true, 0, data, ref dataLength) || (GostCryptoConfig.ProviderType == ProviderTypes.VipNet); } if (!success) { throw CreateWin32Error(); } } #endregion #region Для работы с ключами криптографического провайдера public static SafeKeyHandleImpl GenerateKey(SafeProvHandleImpl providerHandle, int algId, CspProviderFlags flags) { var keyHandle = SafeKeyHandleImpl.InvalidHandle; var dwFlags = MapCspKeyFlags(flags); if (!CryptoApi.CryptGenKey(providerHandle, (uint)algId, dwFlags, ref keyHandle)) { throw CreateWin32Error(); } return keyHandle; } public static SafeKeyHandleImpl GenerateDhEphemeralKey(SafeProvHandleImpl providerHandle, string digestParamSet, string publicKeyParamSet) { var keyHandle = SafeKeyHandleImpl.InvalidHandle; var dwFlags = MapCspKeyFlags(CspProviderFlags.NoFlags) | Constants.CRYPT_PREGEN; if (!CryptoApi.CryptGenKey(providerHandle, Constants.CALG_DH_EL_EPHEM, dwFlags, ref keyHandle)) { throw CreateWin32Error(); } SetKeyParameterString(keyHandle, Constants.KP_HASHOID, digestParamSet); SetKeyParameterString(keyHandle, Constants.KP_DHOID, publicKeyParamSet); SetKeyParameter(keyHandle, Constants.KP_X, null); return keyHandle; } private static uint MapCspKeyFlags(CspProviderFlags flags) { uint dwFlags = 0; if ((flags & CspProviderFlags.UseNonExportableKey) == CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_EXPORTABLE; } if ((flags & CspProviderFlags.UseArchivableKey) != CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_ARCHIVABLE; } if ((flags & CspProviderFlags.UseUserProtectedKey) != CspProviderFlags.NoFlags) { dwFlags |= Constants.CRYPT_USER_PROTECTED; } return dwFlags; } public static SafeKeyHandleImpl GetUserKey(SafeProvHandleImpl providerHandle, int keyNumber) { var keyHandle = SafeKeyHandleImpl.InvalidHandle; if (!CryptoApi.CryptGetUserKey(providerHandle, (uint)keyNumber, ref keyHandle)) { throw CreateWin32Error(); } return keyHandle; } public static SafeKeyHandleImpl DeriveSymKey(SafeProvHandleImpl providerHandle, SafeHashHandleImpl hashHandle) { var symKeyHandle = SafeKeyHandleImpl.InvalidHandle; if (!CryptoApi.CryptDeriveKey(providerHandle, Constants.CALG_G28147, hashHandle, Constants.CRYPT_EXPORTABLE, ref symKeyHandle)) { throw CreateWin32Error(); } return symKeyHandle; } public static SafeKeyHandleImpl DuplicateKey(IntPtr sourceKeyHandle) { var keyHandle = SafeKeyHandleImpl.InvalidHandle; if (!CryptoApi.CryptDuplicateKey(sourceKeyHandle, null, 0, ref keyHandle)) { throw CreateWin32Error(); } return keyHandle; } public static SafeKeyHandleImpl DuplicateKey(SafeKeyHandleImpl sourceKeyHandle) { return DuplicateKey(sourceKeyHandle.DangerousGetHandle()); } public static int GetKeyParameterInt32(SafeKeyHandleImpl keyHandle, uint keyParamId) { const int doubleWordSize = 4; uint dwDataLength = doubleWordSize; var dwDataBytes = new byte[doubleWordSize]; if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, dwDataBytes, ref dwDataLength, 0)) { throw CreateWin32Error(); } if (dwDataLength != doubleWordSize) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } return BitConverter.ToInt32(dwDataBytes, 0); } private static string GetKeyParameterString(SafeKeyHandleImpl keyHandle, uint keyParamId) { var paramValue = GetKeyParameter(keyHandle, keyParamId); return BytesToString(paramValue); } private static string BytesToString(byte[] value) { string valueString; try { valueString = Encoding.GetEncoding(0).GetString(value); var length = 0; while (length < valueString.Length) { // Строка заканчивается нулевым символом if (valueString[length] == '\0') { break; } length++; } if (length == valueString.Length) { throw ExceptionUtility.CryptographicException(Resources.InvalidString); } valueString = valueString.Substring(0, length); } catch (DecoderFallbackException exception) { throw ExceptionUtility.CryptographicException(exception, Resources.InvalidString); } return valueString; } public static byte[] GetKeyParameter(SafeKeyHandleImpl keyHandle, uint keyParamId) { uint dataLength = 0; if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, null, ref dataLength, 0)) { throw CreateWin32Error(); } var dataBytes = new byte[dataLength]; if (!CryptoApi.CryptGetKeyParam(keyHandle, keyParamId, dataBytes, ref dataLength, 0)) { throw CreateWin32Error(); } return dataBytes; } public static void SetKeyParameterInt32(SafeKeyHandleImpl keyHandle, int keyParamId, int keyParamValue) { var dwDataBytes = BitConverter.GetBytes(keyParamValue); if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, dwDataBytes, 0)) { throw CreateWin32Error(); } } private static void SetKeyParameterString(SafeKeyHandleImpl keyHandle, int keyParamId, string keyParamValue) { var stringDataBytes = Encoding.GetEncoding(0).GetBytes(keyParamValue); if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, stringDataBytes, 0)) { throw CreateWin32Error(); } } public static void SetKeyParameter(SafeKeyHandleImpl keyHandle, int keyParamId, byte[] keyParamValue) { if (!CryptoApi.CryptSetKeyParam(keyHandle, (uint)keyParamId, keyParamValue, 0)) { throw CreateWin32Error(); } } #endregion #region Для экспорта ключей криптографического провайдера public static byte[] ExportCspBlob(SafeKeyHandleImpl symKeyHandle, SafeKeyHandleImpl keyExchangeHandle, int blobType) { uint exportedKeyLength = 0; if (!CryptoApi.CryptExportKey(symKeyHandle, keyExchangeHandle, (uint)blobType, 0, null, ref exportedKeyLength)) { throw CreateWin32Error(); } var exportedKeyBytes = new byte[exportedKeyLength]; if (!CryptoApi.CryptExportKey(symKeyHandle, keyExchangeHandle, (uint)blobType, 0, exportedKeyBytes, ref exportedKeyLength)) { throw CreateWin32Error(); } return exportedKeyBytes; } public static Asn1.Common.GostKeyExchangeParameters ExportPublicKey(SafeKeyHandleImpl symKeyHandle) { var exportedKeyBytes = ExportCspBlob(symKeyHandle, SafeKeyHandleImpl.InvalidHandle, Constants.PUBLICKEYBLOB); return DecodePublicBlob(exportedKeyBytes); } private static Asn1.Common.GostKeyExchangeParameters DecodePublicBlob(byte[] encodedPublicBlob) { if (encodedPublicBlob == null) { throw ExceptionUtility.ArgumentNull("encodedPublicBlob"); } if (encodedPublicBlob.Length < 80) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } var gostKeyMask = BitConverter.ToUInt32(encodedPublicBlob, 8); if (gostKeyMask != Constants.GR3410_1_MAGIC) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } var gostKeySize = BitConverter.ToUInt32(encodedPublicBlob, 12); if (gostKeySize != 512) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } var publicKeyParameters = new Asn1.Common.GostKeyExchangeParameters(); var encodeKeyParameters = new byte[(encodedPublicBlob.Length - 16) - 64]; Array.Copy(encodedPublicBlob, 16, encodeKeyParameters, 0, (encodedPublicBlob.Length - 16) - 64); publicKeyParameters.DecodeParameters(encodeKeyParameters); var publicKey = new byte[64]; Array.Copy(encodedPublicBlob, encodedPublicBlob.Length - 64, publicKey, 0, 64); publicKeyParameters.PublicKey = publicKey; return publicKeyParameters; } public static GostKeyExchangeInfo ExportKeyExchange(SafeKeyHandleImpl symKeyHandle, SafeKeyHandleImpl keyExchangeHandle) { var exportedKeyBytes = ExportCspBlob(symKeyHandle, keyExchangeHandle, Constants.SIMPLEBLOB); return DecodeSimpleBlob(exportedKeyBytes); } private static GostKeyExchangeInfo DecodeSimpleBlob(byte[] exportedKeyBytes) { if (exportedKeyBytes == null) { throw ExceptionUtility.ArgumentNull("exportedKeyBytes"); } if (exportedKeyBytes.Length < 16) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } if (BitConverter.ToUInt32(exportedKeyBytes, 4) != Constants.CALG_G28147) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } if (BitConverter.ToUInt32(exportedKeyBytes, 8) != Constants.G28147_MAGIC) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } if (BitConverter.ToUInt32(exportedKeyBytes, 12) != Constants.CALG_G28147) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_DATA); } var keyExchangeInfo = new GostKeyExchangeInfo(); var sourceIndex = 16; keyExchangeInfo.Ukm = new byte[8]; Array.Copy(exportedKeyBytes, sourceIndex, keyExchangeInfo.Ukm, 0, 8); sourceIndex += 8; keyExchangeInfo.EncryptedKey = new byte[32]; Array.Copy(exportedKeyBytes, sourceIndex, keyExchangeInfo.EncryptedKey, 0, 32); sourceIndex += 32; keyExchangeInfo.Mac = new byte[4]; Array.Copy(exportedKeyBytes, sourceIndex, keyExchangeInfo.Mac, 0, 4); sourceIndex += 4; var encryptionParamSet = new byte[exportedKeyBytes.Length - sourceIndex]; Array.Copy(exportedKeyBytes, sourceIndex, encryptionParamSet, 0, exportedKeyBytes.Length - sourceIndex); keyExchangeInfo.EncryptionParamSet = GostKeyExchangeInfo.DecodeEncryptionParamSet(encryptionParamSet); return keyExchangeInfo; } #endregion #region Для импорта ключей криптографического провайдера public static int ImportCspBlob(byte[] importedKeyBytes, SafeProvHandleImpl providerHandle, SafeKeyHandleImpl publicKeyHandle, out SafeKeyHandleImpl keyExchangeHandle) { var dwFlags = MapCspKeyFlags(CspProviderFlags.NoFlags); var keyExchangeRef = SafeKeyHandleImpl.InvalidHandle; if (!CryptoApi.CryptImportKey(providerHandle, importedKeyBytes, (uint)importedKeyBytes.Length, publicKeyHandle, dwFlags, ref keyExchangeRef)) { throw CreateWin32Error(); } var keyNumberMask = BitConverter.ToInt32(importedKeyBytes, 4) & 0xE000; var keyNumber = (keyNumberMask == 0xA000) ? Constants.AT_KEYEXCHANGE : Constants.AT_SIGNATURE; keyExchangeHandle = keyExchangeRef; return keyNumber; } public static SafeKeyHandleImpl ImportPublicKey(SafeProvHandleImpl providerHandle, Asn1.Common.GostKeyExchangeParameters publicKeyParameters) { if (publicKeyParameters == null) { throw ExceptionUtility.ArgumentNull("publicKeyParameters"); } var importedKeyBytes = EncodePublicBlob(publicKeyParameters); SafeKeyHandleImpl hKeyExchange; ImportCspBlob(importedKeyBytes, providerHandle, SafeKeyHandleImpl.InvalidHandle, out hKeyExchange); return hKeyExchange; } public static byte[] EncodePublicBlob(Asn1.Common.GostKeyExchangeParameters publicKeyParameters) { if (publicKeyParameters == null) { throw ExceptionUtility.ArgumentNull("publicKeyParameters"); } var encodeKeyParameters = publicKeyParameters.EncodeParameters(); var importedKeyBytes = new byte[(encodeKeyParameters.Length + 16) + publicKeyParameters.PublicKey.Length]; importedKeyBytes[0] = 6; importedKeyBytes[1] = 32; Array.Copy(BitConverter.GetBytes(Constants.CALG_GR3410EL), 0, importedKeyBytes, 4, 4); Array.Copy(BitConverter.GetBytes(Constants.GR3410_1_MAGIC), 0, importedKeyBytes, 8, 4); Array.Copy(BitConverter.GetBytes(Constants.EL_SIZE), 0, importedKeyBytes, 12, 4); Array.Copy(encodeKeyParameters, 0, importedKeyBytes, 16, encodeKeyParameters.Length); Array.Copy(publicKeyParameters.PublicKey, 0, importedKeyBytes, encodeKeyParameters.Length + 16, publicKeyParameters.PublicKey.Length); return importedKeyBytes; } public static SafeKeyHandleImpl ImportKeyExchange(SafeProvHandleImpl providerHandle, GostKeyExchangeInfo keyExchangeInfo, SafeKeyHandleImpl keyExchangeHandle) { if (keyExchangeInfo == null) { throw ExceptionUtility.ArgumentNull("keyExchangeInfo"); } var importedKeyBytes = EncodeSimpleBlob(keyExchangeInfo); SafeKeyHandleImpl hKeyExchange; ImportCspBlob(importedKeyBytes, providerHandle, keyExchangeHandle, out hKeyExchange); return hKeyExchange; } public static SafeKeyHandleImpl ImportBulkSessionKey(SafeProvHandleImpl providerHandle, byte[] bulkSessionKey, RNGCryptoServiceProvider randomNumberGenerator) { if (bulkSessionKey == null) { throw ExceptionUtility.ArgumentNull("bulkSessionKey"); } if (randomNumberGenerator == null) { throw ExceptionUtility.ArgumentNull("randomNumberGenerator"); } var hSessionKey = SafeKeyHandleImpl.InvalidHandle; if (!CryptoApi.CryptGenKey(providerHandle, Constants.CALG_G28147, 0, ref hSessionKey)) { throw CreateWin32Error(); } var keyWrap = new GostKeyExchangeInfo { EncryptedKey = new byte[32] }; Array.Copy(bulkSessionKey, keyWrap.EncryptedKey, 32); SetKeyParameterInt32(hSessionKey, Constants.KP_MODE, Constants.CRYPT_MODE_ECB); SetKeyParameterInt32(hSessionKey, Constants.KP_ALGID, Constants.CALG_G28147); SetKeyParameterInt32(hSessionKey, Constants.KP_PADDING, Constants.ZERO_PADDING); uint sessionKeySize = 32; if (!CryptoApi.CryptEncrypt(hSessionKey, SafeHashHandleImpl.InvalidHandle, true, 0, keyWrap.EncryptedKey, ref sessionKeySize, sessionKeySize)) { throw CreateWin32Error(); } SetKeyParameterInt32(hSessionKey, Constants.KP_MODE, Constants.CRYPT_MODE_CFB); var hashHandle = CreateHashImit(providerHandle, hSessionKey); keyWrap.Ukm = new byte[8]; randomNumberGenerator.GetBytes(keyWrap.Ukm); if (!CryptoApi.CryptSetHashParam(hashHandle, Constants.HP_HASHSTARTVECT, keyWrap.Ukm, 0)) { throw CreateWin32Error(); } if (!CryptoApi.CryptHashData(hashHandle, bulkSessionKey, 32, 0)) { throw CreateWin32Error(); } keyWrap.Mac = EndHashData(hashHandle); keyWrap.EncryptionParamSet = GetKeyParameterString(hSessionKey, Constants.KP_CIPHEROID); SetKeyParameterInt32(hSessionKey, Constants.KP_ALGID, Constants.CALG_SIMPLE_EXPORT); SetKeyParameterInt32(hSessionKey, Constants.KP_MODE, Constants.CRYPT_MODE_ECB); SetKeyParameterInt32(hSessionKey, Constants.KP_PADDING, Constants.ZERO_PADDING); return ImportKeyExchange(providerHandle, keyWrap, hSessionKey); } private static byte[] EncodeSimpleBlob(GostKeyExchangeInfo keyExchangeInfo) { if (keyExchangeInfo == null) { throw ExceptionUtility.ArgumentNull("keyExchangeInfo"); } var encryptionParamSet = GostKeyExchangeInfo.EncodeEncryptionParamSet(keyExchangeInfo.EncryptionParamSet); var importedKeyBytes = new byte[encryptionParamSet.Length + 60]; var sourceIndex = 0; importedKeyBytes[sourceIndex] = 1; sourceIndex++; importedKeyBytes[sourceIndex] = 32; sourceIndex++; sourceIndex += 2; Array.Copy(BitConverter.GetBytes(Constants.CALG_G28147), 0, importedKeyBytes, sourceIndex, 4); sourceIndex += 4; Array.Copy(BitConverter.GetBytes(Constants.G28147_MAGIC), 0, importedKeyBytes, sourceIndex, 4); sourceIndex += 4; Array.Copy(BitConverter.GetBytes(Constants.CALG_G28147), 0, importedKeyBytes, sourceIndex, 4); sourceIndex += 4; Array.Copy(keyExchangeInfo.Ukm, 0, importedKeyBytes, sourceIndex, 8); sourceIndex += 8; Array.Copy(keyExchangeInfo.EncryptedKey, 0, importedKeyBytes, sourceIndex, 32); sourceIndex += 32; Array.Copy(keyExchangeInfo.Mac, 0, importedKeyBytes, sourceIndex, 4); sourceIndex += 4; Array.Copy(encryptionParamSet, 0, importedKeyBytes, sourceIndex, encryptionParamSet.Length); return importedKeyBytes; } public static SafeKeyHandleImpl ImportAndMakeKeyExchange(SafeProvHandleImpl providerHandle, Asn1.Common.GostKeyExchangeParameters keyExchangeParameters, SafeKeyHandleImpl publicKeyHandle) { if (keyExchangeParameters == null) { throw ExceptionUtility.ArgumentNull("keyExchangeParameters"); } var importedKeyBytes = EncodePublicBlob(keyExchangeParameters); SafeKeyHandleImpl keyExchangeHandle; ImportCspBlob(importedKeyBytes, providerHandle, publicKeyHandle, out keyExchangeHandle); return keyExchangeHandle; } #endregion #region Для работы с цифровой подписью public static byte[] SignValue(SafeProvHandleImpl hProv, int keyNumber, byte[] hashValue) { using (var hashHandle = SetupHashAlgorithm(hProv, hashValue)) { uint signatureLength = 0; // Вычисление размера подписи if (!CryptoApi.CryptSignHash(hashHandle, (uint)keyNumber, null, 0, null, ref signatureLength)) { throw CreateWin32Error(); } var signatureValue = new byte[signatureLength]; // Вычисление значения подписи if (!CryptoApi.CryptSignHash(hashHandle, (uint)keyNumber, null, 0, signatureValue, ref signatureLength)) { throw CreateWin32Error(); } return signatureValue; } } public static bool VerifySign(SafeProvHandleImpl providerHandle, SafeKeyHandleImpl keyHandle, byte[] hashValue, byte[] signatureValue) { using (var hashHandle = SetupHashAlgorithm(providerHandle, hashValue)) { return CryptoApi.CryptVerifySignature(hashHandle, signatureValue, (uint)signatureValue.Length, keyHandle, null, 0); } } private static SafeHashHandleImpl SetupHashAlgorithm(SafeProvHandleImpl providerHandle, byte[] hashValue) { var hashHandle = CreateHash_3411_94(providerHandle); uint hashLength = 0; if (!CryptoApi.CryptGetHashParam(hashHandle, Constants.HP_HASHVAL, null, ref hashLength, 0)) { throw CreateWin32Error(); } if (hashValue.Length != hashLength) { throw ExceptionUtility.CryptographicException(Constants.NTE_BAD_HASH); } if (!CryptoApi.CryptSetHashParam(hashHandle, Constants.HP_HASHVAL, hashValue, 0)) { throw CreateWin32Error(); } return hashHandle; } #endregion public static T DangerousAddRef<T>(this T handle) where T : SafeHandle { var success = false; handle.DangerousAddRef(ref success); return handle; } public static void TryDispose(this SafeHandle handle) { if ((handle != null) && !handle.IsClosed) { handle.Dispose(); } } private static CryptographicException CreateWin32Error() { return ExceptionUtility.CryptographicException(Marshal.GetLastWin32Error()); } } }
37.208369
218
0.584081
[ "MIT" ]
KovtunovSergey/GostCryptography
Source/GostCryptography/Native/CryptoApiHelper.cs
44,555
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TrackIt.UI.Aggregates.Exceptions { public class WorkerAlreadyAssigned { [Serializable] public class WorkerAlreadyAssignedException : Exception { public WorkerAlreadyAssignedException() { } public WorkerAlreadyAssignedException(string message) : base(message) { } public WorkerAlreadyAssignedException(string message, Exception inner) : base(message, inner) { } protected WorkerAlreadyAssignedException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } } }
34.545455
109
0.692105
[ "MIT" ]
rolfintatu/trackIt
src/TrackIt.UI/Aggregates/Exceptions/WorkerAlreadyAssigned.cs
762
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. namespace mshtml { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [ComImport, TypeLibType((short)0x1040), Guid("3050F311-98B5-11CF-BB82-00AA00BDCE0B")] public interface IHTMLFrameBase { [DispId(-2147415112)] string src {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415112)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415112)] get; } [DispId(-2147418112)] string name {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147418112)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147418112)] get; } [DispId(-2147415110)] object border {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415110)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415110)] get; } [DispId(-2147415109)] string frameBorder {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415109)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415109)] get; } [DispId(-2147415108)] object frameSpacing {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415108)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415108)] get; } [DispId(-2147415107)] object marginWidth {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415107)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415107)] get; } [DispId(-2147415106)] object marginHeight {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415106)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415106)] get; } [DispId(-2147415105)] bool noResize {[param: In] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415105)] set;[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415105)] get; } [DispId(-2147415104)] string scrolling {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415104)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147415104)] get; } } }
106.441176
340
0.769273
[ "MIT" ]
BobinYang/OpenLiveWriter
src/managed/OpenLiveWriter.Interop.Mshtml/mshtml/IHTMLFrameBase.cs
3,619
C#
using System; using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp; using Volo.Abp.Domain.Services; namespace Acme.BookStore.AngularMaterial.Authors { public class AuthorManager: DomainService { private readonly IAuthorRepository _authorRepository; public AuthorManager(IAuthorRepository authorRepository) { _authorRepository = authorRepository; } public async Task<Author> CreateAsync( [NotNull] string name, DateTime birthDate, [CanBeNull] string shortBio = null) { Check.NotNullOrWhiteSpace(name, nameof(name)); var existingAuthor = await _authorRepository.FindByNameAsync(name); if (existingAuthor != null) { throw new AuthorAlreadyExistsException(name); } return new Author( GuidGenerator.Create(), name, birthDate, shortBio ); } public async Task ChangeNameAsync( [NotNull] Author author, [NotNull] string newName) { Check.NotNull(author, nameof(author)); Check.NotNullOrWhiteSpace(newName, nameof(newName)); var existingAuthor = await _authorRepository.FindByNameAsync(newName); if (existingAuthor != null && existingAuthor.Id != author.Id) { throw new AuthorAlreadyExistsException(newName); } author.ChangeName(newName); } } }
28.428571
82
0.585427
[ "MIT" ]
271943794/abp-samples
AcmeBookStoreAngularMaterial/aspnet-core/src/Acme.BookStore.AngularMaterial.Domain/Authors/AuthorManager.cs
1,592
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Gherkin.Util.Geometric; namespace Gherkin.Util.Bezier { /// <summary> /// Quadratic 2D Bézier curve length calculation /// </summary> public static class BezierCurveLength2DQuadratic { /// <summary> /// Gets the calculated length. /// https://github.com/HTD/FastBezier /// </summary> /// <remarks> /// Integral calculation by Dave Eberly, slightly modified for the edge case with colinear control point. /// See: http://www.gamedev.net/topic/551455-length-of-a-generalized-quadratic-bezier-curve-in-3d/ /// </remarks> public static double Length(GPoint P0, GPoint P1, GPoint P2) { if (P0 == P2) { if (P0 == P1) return 0.0; return P0.Distance(P1); } if (P1 == P0 || P1 == P2) return P0.Distance(P2); GPoint A0 = P1 - P0; GPoint A1 = P0 - 2.0 * P1 + P2; if (!A1.Zero) { double c = 4.0 * A1.DotProduct(A1); double b = 8.0 * A0.DotProduct(A1); double a = 4.0 * A0.DotProduct(A0); double q = 4.0 * a * c - b * b; double twoCpB = 2.0 * c + b; double sumCBA = c + b + a; var l0 = (0.25 / c) * (twoCpB * Math.Sqrt(sumCBA) - b * Math.Sqrt(a)); double k1 = 2.0 * Math.Sqrt(c * sumCBA) + twoCpB; double k2 = 2.0 * Math.Sqrt(c * a) + b; if ((k1 <= 0.0) || (k2 <= 0.0)) return l0; var l1 = (q / (8.0 * Math.Pow(c, 1.5))) * (Math.Log(k1) - Math.Log(k2)); return l0 + l1; } else { return 2.0 * A0.Length(); } } } }
33.155172
113
0.478419
[ "MIT" ]
bzquan/GherkinEditor
GherkinEditor/GherkinEditor/Util/Bezier/BezierCurveLength2DQuadratic.cs
1,926
C#
using Microsoft.SharePoint.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml; using OfficeDevPnP.Core.Tests.Framework.Functional.Implementation; using OfficeDevPnP.Core.Tests.Framework.Functional.Validators; using System; using System.Linq; namespace OfficeDevPnP.Core.Tests.Framework.Functional { #if !ONPREMISES [TestClass] public class ListNoScriptTests : FunctionalTestBase { #region Construction public ListNoScriptTests() { //debugMode = true; //centralSiteCollectionUrl = "https://bertonline.sharepoint.com/sites/TestPnPSC_12345_c81e4b0d-0242-4c80-8272-18f13e759333"; //centralSubSiteUrl = "https://bertonline.sharepoint.com/sites/TestPnPSC_12345_c81e4b0d-0242-4c80-8272-18f13e759333/sub"; } #endregion #region Test setup [ClassInitialize()] public static void ClassInit(TestContext context) { ClassInitBase(context, true); } [ClassCleanup()] public static void ClassCleanup() { ClassCleanupBase(); } #endregion #region Site collection test cases [TestMethod] [Timeout(15 * 60 * 1000)] public void SiteCollectionListAddingTest() { new ListImplementation().SiteCollectionListAdding(centralSiteCollectionUrl); } [TestMethod] [Timeout(15 * 60 * 1000)] public void SiteCollection1605ListAddingTest() { new ListImplementation().SiteCollection1605ListAdding(centralSiteCollectionUrl); } [TestMethod] [Timeout(15 * 60 * 1000)] public void SiteCollection1705ListAddingTest() { new ListImplementation().SiteCollection1705ListAdding(centralSiteCollectionUrl); } #endregion #region Web test cases [TestMethod] [Timeout(15 * 60 * 1000)] public void WebListAddingTest() { new ListImplementation().WebListAdding(centralSiteCollectionUrl, centralSubSiteUrl); } [TestMethod] [Timeout(15 * 60 * 1000)] public void Web1605ListAddingTest() { new ListImplementation().Web1605ListAdding(centralSubSiteUrl); } [TestMethod] [Timeout(15 * 60 * 1000)] public void Web1705ListAddingTest() { new ListImplementation().Web1705ListAdding(centralSubSiteUrl); } #endregion } #endif }
29.617978
136
0.64302
[ "MIT" ]
3v1lW1th1n/PnP-Sites-Core
Core/OfficeDevPnP.Core.Tests/Framework/Functional/ListNoScriptTests.cs
2,638
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace SharpSvn.PdbAnnotate.Framework { /// <summary> /// Baseclass for <see cref="SourceFile"/> and <see cref="SymbolFile"/> /// </summary> abstract class SourceFileBase : IComparable { readonly string _filename; FileInfo _info; /// <summary> /// Creates a new SourceFile object for the specified file /// </summary> /// <param name="filename"></param> protected SourceFileBase(string filename) { if (string.IsNullOrEmpty(filename)) throw new ArgumentNullException("filename"); _filename = filename; } /// <summary> /// /// </summary> public FileInfo File { get { return _info ?? (_info = new FileInfo(_filename)); } } /// <summary> /// Gets the fullname of the file /// </summary> public string FullName { get { return _filename; } } /// <summary> /// Gets a (cached) boolean indicating whether the file exists on disk /// </summary> public bool Exists { get { return File.Exists; } } /// <summary> /// returns <see cref="FullName"/> /// </summary> /// <returns></returns> public override string ToString() { return _filename; } #region ## Compare members (specialized by base classes; for generics) /// <summary> /// Compares two <see cref="SourceFile"/> by its <see cref="FullName"/> /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(SourceFileBase other) { return string.Compare(FullName, other.FullName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Compares two <see cref="SourceFile"/> by its <see cref="FullName"/> /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(SourceFileBase other) { if (other == null) return false; return string.Equals(FullName, other.FullName, StringComparison.OrdinalIgnoreCase); } #endregion ## Compare members (specialized by base classes; for generics) #region ## .Net 1.X compatible compare Members /// <summary> /// Compares two <see cref="SourceFile"/> by its <see cref="FullName"/> /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { // Use typed version return CompareTo(obj as SourceFileBase); } /// <summary> /// Compares two <see cref="SourceFile"/> by its <see cref="FullName"/> /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return Equals(obj as SourceFileBase); } #endregion ## .Net 1.X compatible compare Members /// <summary> /// Gets the hashcode of the <see cref="SourceFile"/> /// </summary> /// <returns></returns> public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(FullName); } } }
29.844262
97
0.515518
[ "Apache-2.0" ]
AmpScm/SharpSvn
src/SharpSvn.PdbAnnotate/Framework/SourceFileBase.cs
3,641
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 dataexchange-2017-07-25.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.DataExchange.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataExchange.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for StartJob operation /// </summary> public class StartJobResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { StartJobResponse response = new StartJobResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonDataExchangeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static StartJobResponseUnmarshaller _instance = new StartJobResponseUnmarshaller(); internal static StartJobResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StartJobResponseUnmarshaller Instance { get { return _instance; } } } }
41.10084
196
0.631977
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DataExchange/Generated/Model/Internal/MarshallTransformations/StartJobResponseUnmarshaller.cs
4,891
C#
namespace OggVorbisEncoder.Setup.Templates.BookBlocks.Stereo44.Coupled.Chapter0 { public class Chapter0Long : IStaticCodeBook { public int Dimensions { get; } = 2; public byte[] LengthList { get; } = { 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11, 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7, 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9, 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11, 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11, 12, }; public CodeBookMapType MapType { get; } = (CodeBookMapType)0; public int QuantMin { get; } = 0; public int QuantDelta { get; } = 0; public int Quant { get; } = 0; public int QuantSequenceP { get; } = 0; public int[] QuantList { get; } = null; } }
34.458333
79
0.525998
[ "MIT" ]
FriesBoury/.NET-Ogg-Vorbis-Encoder
OggVorbisEncoder/Setup/Templates/BookBlocks/Stereo44/Coupled/Chapter0/Chapter0Long.cs
827
C#
using BytecodeApi; using BytecodeApi.Extensions; using BytecodeApi.IO; using BytecodeApi.IO.FileSystem; using BytecodeApi.Mathematics; using BytecodeApi.Text; using PEunion.Compiler.Errors; using PEunion.Compiler.Helper; using PEunion.Compiler.Project; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Resources; namespace PEunion.Compiler.Compiler { /// <summary> /// Implements compilation of 32-bit and 64-bit .NET executables using CodeDom as underlying compiler. /// </summary> public sealed class DotNetCompiler : ProjectCompiler { private readonly CompilerHelper Helper; private readonly CSharpObfuscator Obfuscator; private readonly List<string> Stage2SourceCodeFiles; private readonly List<string> StubSourceCodeFiles; private readonly string Stage2ResourcesFileName; private readonly string StubResourcesFileName; private bool Is64Bit => Project.Stub.Type == StubType.DotNet64; internal DotNetCompiler(ProjectFile project, string intermediateDirectory, string outputFileName, ErrorCollection errors) : base(project, intermediateDirectory, outputFileName, errors) { Helper = new CompilerHelper(Project, Errors); Obfuscator = new CSharpObfuscator(); Stage2SourceCodeFiles = new List<string> { "Stage2.cs", "Api.cs" }; StubSourceCodeFiles = new List<string> { "Stub.cs", "Emulator.cs", "Api.cs" }; Stage2ResourcesFileName = BytecodeApi.Create.AlphaNumericString(MathEx.Random.Next(20, 30)) + ".resources"; StubResourcesFileName = BytecodeApi.Create.AlphaNumericString(MathEx.Random.Next(20, 30)) + ".resources"; } /// <summary> /// Compiles the project with the current settings. /// </summary> public override void Compile() { try { // Validate required files & directories Helper.ValidateFiles ( ApplicationBase.Path, @"Stub\dotnet\" ); if (Errors.HasErrors) return; // Copy source files to intermediate directory DirectoryEx.CopyTo(Path.Combine(ApplicationBase.Path, @"Stub\dotnet"), IntermediateDirectorySource); // Validate required source files Helper.ValidateFiles ( IntermediateDirectorySource, "Stub.cs", "Stage2.cs", "Api.cs", "Compression.cs", "Download.cs", "Drop.cs", "Emulator.cs", "GetResource.cs", "Invoke.cs", "RunPE.cs", @"Resources\default.manifest", @"Resources\elevated.manifest" ); if (Errors.HasErrors) return; // Obfuscate shared code used by Stub and Stage2 Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Api.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Compression.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Download.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Drop.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Emulator.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("GetResource.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Invoke.cs")); Obfuscator.ObfuscateFile(GetIntermediateSourcePath("RunPE.cs")); // Validate that RunPE and .NET invoked executables match the bitness of the stub Helper.ValidateRunPEBitness(Is64Bit ? 64 : 32); Helper.ValidateInvokeBitness(Is64Bit ? 64 : 32); if (Errors.HasErrors) return; // Compile stage2 CompileStage2(); if (Errors.HasErrors) return; // Assemble stage2 AssembleStage2(); if (Errors.HasErrors) return; // Compile stub CompileStub(); if (Errors.HasErrors) return; // Assemble stub AssembleStub(); } catch (ErrorException ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling project.", ex.GetFullStackTrace()); } } private void CompileStage2() { try { // Only compile methods that are needed if (Project.Sources.OfType<EmbeddedSource>().Any()) Stage2SourceCodeFiles.Add("GetResource.cs"); if (Project.Sources.OfType<EmbeddedSource>().Any(source => source.Compress)) Stage2SourceCodeFiles.Add("Compression.cs"); if (Project.Sources.OfType<DownloadSource>().Any()) Stage2SourceCodeFiles.Add("Download.cs"); if (Project.Actions.OfType<RunPEAction>().Any()) Stage2SourceCodeFiles.Add("RunPE.cs"); if (Project.Actions.OfType<InvokeAction>().Any()) Stage2SourceCodeFiles.Add("Invoke.cs"); if (Project.Actions.OfType<DropAction>().Any()) Stage2SourceCodeFiles.Add("Drop.cs"); // Compile resources using (ResourceWriter resourceWriter = new ResourceWriter(GetIntermediateSourcePath(@"Resources\" + Stage2ResourcesFileName))) { foreach (EmbeddedSource source in Project.Sources.OfType<EmbeddedSource>()) { byte[] file = File.ReadAllBytes(source.Path); resourceWriter.AddResource(source.AssemblyId.ToString(), source.Compress ? Compression.Compress(file) : file); } } // Compile main program string[] stage2Lines = File.ReadAllLines(GetIntermediateSourcePath("Stage2.cs")); using (CSharpStream assembly = new CSharpStream(GetIntermediateSourcePath("Stage2.cs"))) { if (Project.Startup.Melt) { assembly.Emit("#define MELT"); assembly.WriteLine(); } foreach (string line in stage2Lines) { if (line.Trim() == "//{MAIN}") { assembly.Indent = 8; // Compile actions foreach (ProjectAction action in Project.Actions) { assembly.EmitLabel("action_" + action.AssemblyId); assembly.Emit("try"); assembly.BlockBegin(); // Retrieve source if (action.Source is EmbeddedSource embeddedSource) { assembly.EmitComment("Get embedded file: " + Path.GetFileName(embeddedSource.Path)); assembly.Emit("byte[] payload = __GetResource(/**/\"" + embeddedSource.AssemblyId + "\");"); assembly.WriteLine(); if (embeddedSource.Compress) { assembly.EmitComment("Decompress embedded file"); assembly.Emit("payload = __Decompress(payload);"); assembly.WriteLine(); } } else if (action.Source is DownloadSource downloadSource) { assembly.EmitComment("Download: " + downloadSource.Url); assembly.Emit("byte[] payload = __Download(/**/\"" + downloadSource.Url + "\");"); assembly.WriteLine(); } else if (action is MessageBoxAction) { } else { throw new InvalidOperationException(); } // Perform action if (action is RunPEAction) { assembly.EmitComment("RunPE"); assembly.Emit("__RunPE(Application.ExecutablePath, __CommandLine, payload);"); } else if (action is InvokeAction) { assembly.EmitComment("Invoke .NET executable"); assembly.Emit("__Invoke(payload);"); } else if (action is DropAction dropAction) { assembly.EmitComment("Drop " + dropAction.Location.GetDescription() + @"\" + dropAction.FileName + (dropAction.ExecuteVerb == ExecuteVerb.None ? null : " and execute (verb: " + dropAction.ExecuteVerb.GetDescription() + ")")); assembly.Emit("__DropFile(/**/" + (int)dropAction.Location + ", payload, /**/" + new QuotedString(dropAction.FileName) + ", /**/" + dropAction.GetWin32FileAttributes() + ", /**/" + (int)dropAction.ExecuteVerb + ");"); } else if (action is MessageBoxAction messageBoxAction) { assembly.EmitComment("MessageBox (icon: " + messageBoxAction.Icon.GetDescription() + ", buttons: " + messageBoxAction.Buttons.GetDescription() + ")"); assembly.Emit("DialogResult result = MessageBox.Show(/**/" + new QuotedString(messageBoxAction.Text) + ", /**/" + new QuotedString(messageBoxAction.Title) + ", (MessageBoxButtons)/**/" + (int)messageBoxAction.Buttons + ", (MessageBoxIcon)/**/" + (int)messageBoxAction.Icon + ");"); if (messageBoxAction.HasEvents) assembly.WriteLine(); EmitMessageBoxEvent(messageBoxAction.OnOk, "ok", 1); EmitMessageBoxEvent(messageBoxAction.OnCancel, "cancel", 2); EmitMessageBoxEvent(messageBoxAction.OnYes, "yes", 6); EmitMessageBoxEvent(messageBoxAction.OnNo, "no", 7); EmitMessageBoxEvent(messageBoxAction.OnAbort, "abort", 3); EmitMessageBoxEvent(messageBoxAction.OnRetry, "retry", 4); EmitMessageBoxEvent(messageBoxAction.OnIgnore, "ignore", 5); void EmitMessageBoxEvent(ActionEvent actionEvent, string eventName, int result) { if (actionEvent != ActionEvent.None) { assembly.EmitComment("If '" + eventName + "' was clicked, " + Helper.GetCommentForActionEvent(actionEvent)); string code = "if (result == (DialogResult)/**/" + result + ") "; switch (actionEvent) { case ActionEvent.SkipNextAction: code += "goto " + (action == Project.Actions.Last() ? "end" : "action_" + (action.AssemblyId + 1) + "_end") + ";"; break; case ActionEvent.Exit: code += "goto end;"; break; default: throw new InvalidOperationException(); } assembly.Emit(code); } } } else { throw new InvalidOperationException(); } assembly.BlockEnd(); assembly.Emit("catch"); assembly.BlockBegin(); assembly.BlockEnd(); assembly.EmitLabel("action_" + action.AssemblyId + "_end"); assembly.WriteLine(); } } else { assembly.Indent = 0; assembly.WriteLine(line); } } } // Obfuscate code Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Stage2.cs")); } catch (ErrorException ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stage2.", ex.GetFullStackTrace()); } } private void AssembleStage2() { try { string intermediateOutputFileName = GetIntermediateBinaryPath("stage2.exe"); bool success = Helper.DotNetCompile ( Stage2SourceCodeFiles.Select(file => GetIntermediateSourcePath(file)).ToArray(), new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Windows.Forms.dll" }, new[] { GetIntermediateSourcePath(@"Resources\" + Stage2ResourcesFileName) }, null, null, intermediateOutputFileName, Is64Bit, out string[] errors ); if (!success) { Errors.AddRange(errors.Select(error => new Error(ErrorSource.Assembly, ErrorSeverity.Error, error))); } } catch (ErrorException ex) { Errors.Add(ErrorSource.Assembly, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Assembly, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while assembling stage2.", ex.GetFullStackTrace()); } } private void CompileStub() { try { string resourceName = BytecodeApi.Create.AlphaNumericString(MathEx.Random.Next(20, 30)); uint stage2Key; uint stage2PaddingMask; int stage2PaddingByteCount; // Encrypt stage2 into [random name].resources using (ResourceWriter resourceWriter = new ResourceWriter(GetIntermediateSourcePath(@"Resources\" + StubResourcesFileName))) { string encryptedPath = GetIntermediateBinaryPath("stage2.exe_encrypted"); Helper.EncryptData ( GetIntermediateBinaryPath("stage2.exe"), encryptedPath, Project.Stub.Padding, out stage2Key, out stage2PaddingMask, out stage2PaddingByteCount ); resourceWriter.AddResource(resourceName, File.ReadAllBytes(encryptedPath)); } // Compile stub string[] stubLines = File.ReadAllLines(GetIntermediateSourcePath("Stub.cs")); using (CSharpStream assembly = new CSharpStream(GetIntermediateSourcePath("Stub.cs"))) { foreach (string line in stubLines) { if (line.Trim() == "//{STAGE2HEADER}") { assembly.Indent = 12; assembly.Emit("string resourceFileName = /**/\"" + StubResourcesFileName + "\";"); assembly.Emit("string resourceName = /**/\"" + resourceName + "\";"); assembly.Emit("const long stage2Size = " + new FileInfo(GetIntermediateBinaryPath("stage2.exe")).Length + ";"); assembly.Emit("uint key = 0x" + stage2Key.ToString("x8") + ";"); assembly.Emit("uint paddingMask = 0x" + stage2PaddingMask.ToString("x8") + ";"); assembly.Emit("int paddingByteCount = /**/" + stage2PaddingByteCount + ";"); } else { assembly.WriteLine(line); } } } // Add VersionInfo if (!Project.VersionInfo.IsEmpty) { using (CSharpStream versionInfo = new CSharpStream(GetIntermediateSourcePath("VersionInfo.cs"))) { versionInfo.Emit("using System.Reflection;"); versionInfo.WriteLine(); if (!Project.VersionInfo.FileDescription.IsNullOrEmpty()) versionInfo.Emit("[assembly: AssemblyTitle(" + new QuotedString(Project.VersionInfo.FileDescription) + ")]"); if (!Project.VersionInfo.ProductName.IsNullOrEmpty()) versionInfo.Emit("[assembly: AssemblyProduct(" + new QuotedString(Project.VersionInfo.ProductName) + ")]"); if (!Project.VersionInfo.FileVersion.IsNullOrEmpty()) versionInfo.Emit("[assembly: AssemblyFileVersion(" + new QuotedString(Project.VersionInfo.FileVersion) + ")]"); if (!Project.VersionInfo.ProductVersion.IsNullOrEmpty()) versionInfo.Emit("[assembly: AssemblyInformationalVersion(" + new QuotedString(Project.VersionInfo.ProductVersion) + ")]"); if (!Project.VersionInfo.Copyright.IsNullOrEmpty()) versionInfo.Emit("[assembly: AssemblyCopyright(" + new QuotedString(Project.VersionInfo.Copyright) + ")]"); } StubSourceCodeFiles.Add("VersionInfo.cs"); } // Obfuscate code Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Stub.cs")); } catch (ErrorException ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stub.", ex.GetFullStackTrace()); } } private void AssembleStub() { try { string intermediateOutputFileName = GetIntermediateBinaryPath(Project.VersionInfo.OriginalFilename.ToNullIfEmpty() ?? Path.GetFileName(OutputFileName)); string manifestFileName; if (Project.Manifest.Template != null) { manifestFileName = GetIntermediateSourcePath(@"Resources\" + Project.Manifest.Template.GetDescription() + ".manifest"); } else if (Project.Manifest.Path != null) { manifestFileName = GetIntermediateSourcePath(@"Resources\" + Path.GetFileNameWithoutExtension(Project.Manifest.Path) + ".manifest"); File.Copy(Project.Manifest.Path, manifestFileName); } else { manifestFileName = null; } string iconFileName; if (Project.Stub.IconPath != null) { iconFileName = GetIntermediateSourcePath(@"Resources\icon.ico"); Icon icon = IconExtractor.FromFile(Project.Stub.IconPath); if (icon == null) throw new ErrorException("Could not read icon from file '" + Path.GetFileName(Project.Stub.IconPath) + "'."); icon.Save(iconFileName); } else { iconFileName = null; } bool success = Helper.DotNetCompile ( StubSourceCodeFiles.Select(file => GetIntermediateSourcePath(file)).ToArray(), new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Windows.Forms.dll" }, new[] { GetIntermediateSourcePath(@"Resources\" + StubResourcesFileName) }, manifestFileName, iconFileName, intermediateOutputFileName, Is64Bit, out string[] errors ); if (success) { Helper.AppendEofData(intermediateOutputFileName); File.Copy(intermediateOutputFileName, OutputFileName, true); } else { Errors.AddRange(errors.Select(error => new Error(ErrorSource.Assembly, ErrorSeverity.Error, error))); } } catch (ErrorException ex) { Errors.Add(ErrorSource.Assembly, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Assembly, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while assembling stub.", ex.GetFullStackTrace()); } } } }
34.659138
290
0.66248
[ "BSD-2-Clause", "BSD-3-Clause" ]
bytecode-77/peunion
PEunion.Compiler/Compiler/DotNetCompiler.cs
16,881
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BeautifyBranchNaming.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BeautifyBranchNaming.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.847222
186
0.605649
[ "MIT" ]
Teokk31/beautify-branch-naming
Properties/Resources.Designer.cs
2,799
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExecuteCommandBase.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the execute command base class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.Commands { using Kephas.Logging; /// <summary> /// Base class for command execution commands. /// </summary> public abstract class ExecuteCommandBase : DataCommandBase<IExecuteContext, IExecuteResult>, IExecuteCommand { /// <summary> /// Initializes a new instance of the <see cref="ExecuteCommandBase"/> class. /// </summary> /// <param name="logManager">Manager for log.</param> protected ExecuteCommandBase(ILogManager logManager) : base(logManager) { } } }
39.689655
120
0.523892
[ "MIT" ]
kephas-software/kephas
src/Kephas.Data/Commands/ExecuteCommandBase.cs
1,153
C#
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.20915.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Samples.Tools.CustomChannelsTester.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Samples.Tools.CustomChannelsTester.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.764706
210
0.594941
[ "Apache-2.0" ]
jdm7dv/visual-studio
Samples/NET 4.6/WF_WCF_Samples/WCF/Tools/CustomChannelsTester/CS/Properties/Resources.Designer.cs
3,046
C#
// <auto-generated /> // This file was generated by a T4 template. // Don't change it directly as your change would get overwritten. Instead, make changes // to the .tt file (i.e. the T4 template) and save it to regenerate this file. // Make sure the compiler doesn't complain about missing Xml comments #pragma warning disable 1591 #region T4MVC using System; using System.Diagnostics; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using Framework.MVC.T4MVC; using T4MVC; [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public static class FormsMVC { public static Core.Forms.Controllers.FormsBuilderWidgetController FormsBuilderWidget = new Core.Forms.Controllers.T4MVC_FormsBuilderWidgetController(); public static Core.Forms.Controllers.FormsController Forms = new Core.Forms.Controllers.T4MVC_FormsController(); public static T4MVC.AdminController Admin = new T4MVC.AdminController(); } namespace T4MVC { } namespace System.Web.Mvc { [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public static class T4Extensions { public static IT4MVCActionResult GetT4MVCResult(this ActionResult result) { var t4MVCResult = result as IT4MVCActionResult; if (t4MVCResult == null) { throw new InvalidOperationException("T4MVC methods can only be passed pseudo-action calls (e.g. MVC.Home.About()), and not real action calls."); } return t4MVCResult; } public static void InitMVCT4Result(this IT4MVCActionResult result, string area, string controller, string action) { result.Area = area; result.Controller = controller; result.Action = action; result.RouteValueDictionary = new RouteValueDictionary(); result.RouteValueDictionary.Add("Controller", controller); result.RouteValueDictionary.Add("Action", action); } } } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public class T4MVC_ActionResult : System.Web.Mvc.ActionResult, IT4MVCActionResult { public T4MVC_ActionResult(string area, string controller, string action): base() { this.InitMVCT4Result(area, controller, action); } public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { } public string Area { get; set; } public string Controller { get; set; } public string Action { get; set; } public RouteValueDictionary RouteValueDictionary { get; set; } } namespace Links { } static class T4MVCHelpers { // You can change the ProcessVirtualPath method to modify the path that gets returned to the client. // e.g. you can prepend a domain, or append a query string: // return "http://localhost" + path + "?foo=bar"; private static string ProcessVirtualPathDefault(string virtualPath) { // The path that comes in starts with ~/ and must first be made absolute string path = VirtualPathUtility.ToAbsolute(virtualPath); // Add your own modifications here before returning the path return path; } // Calling ProcessVirtualPath through delegate to allow it to be replaced for unit testing public static Func<string, string> ProcessVirtualPath = ProcessVirtualPathDefault; // Logic to determine if the app is running in production or dev environment public static bool IsProduction() { return (HttpContext.Current != null && !HttpContext.Current.IsDebuggingEnabled); } } namespace T4MVC { [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public class Dummy { private Dummy() { } public static Dummy Instance = new Dummy(); } } #endregion T4MVC #pragma warning restore 1591
34.53913
160
0.706193
[ "BSD-2-Clause" ]
coreframework/Core-Framework
Source/Backup/T4MVC.cs
3,974
C#
namespace Teleimot.Web.Api.Models.Account { using System.ComponentModel.DataAnnotations; public class RemoveLoginBindingModel { [Required] [Display(Name = "Login provider")] public string LoginProvider { get; set; } [Required] [Display(Name = "Provider key")] public string ProviderKey { get; set; } } }
24.666667
49
0.627027
[ "MIT" ]
DimitarDKirov/RealEstateSystem
RealEstateWebApi/Web/Teleimot.Web.Api/Models/Account/RemoveLoginBindingModel.cs
372
C#
using System.Threading; using System.Threading.Tasks; namespace Plugin.Fingerprint.Abstractions { public abstract class FingerprintImplementationBase : IFingerprint { public Task<FingerprintAuthenticationResult> AuthenticateAsync(string reason, CancellationToken cancellationToken = default) { return AuthenticateAsync(new AuthenticationRequestConfiguration(reason), cancellationToken); } public async Task<FingerprintAuthenticationResult> AuthenticateAsync(AuthenticationRequestConfiguration authRequestConfig, CancellationToken cancellationToken = default) { var availability = await GetAvailabilityAsync(authRequestConfig.AllowAlternativeAuthentication); if (availability != FingerprintAvailability.Available) { var status = availability == FingerprintAvailability.Denied ? FingerprintAuthenticationResultStatus.Denied : FingerprintAuthenticationResultStatus.NotAvailable; return new FingerprintAuthenticationResult { Status = status }; } return await NativeAuthenticateAsync(authRequestConfig, cancellationToken); } public async Task<bool> IsAvailableAsync(bool allowAlternativeAuthentication = false) { return await GetAvailabilityAsync(allowAlternativeAuthentication) == FingerprintAvailability.Available; } public abstract Task<FingerprintAvailability> GetAvailabilityAsync(bool allowAlternativeAuthentication = false); public abstract Task<AuthenticationType> GetAuthenticationTypeAsync(); protected abstract Task<FingerprintAuthenticationResult> NativeAuthenticateAsync(AuthenticationRequestConfiguration authRequestConfig, CancellationToken cancellationToken); } }
47.358974
180
0.744992
[ "MIT" ]
AdityaRayamajhi/Finger-Print
src/Plugin.Fingerprint.Abstractions/FingerprintImplementationBase.cs
1,849
C#
// Copyright Epic Games, Inc. All Rights Reserved. namespace UnrealBuildTool.Rules { public class GeometryCacheTracks : ModuleRules { public GeometryCacheTracks(ReadOnlyTargetRules Target) : base(Target) { PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "MovieScene", "MovieSceneTracks", "GeometryCache", } ); PrivateDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "AnimGraphRuntime", "TimeManagement", } ); PublicIncludePathModuleNames.Add("TargetPlatform"); if (Target.bBuildEditor) { PublicIncludePathModuleNames.Add("GeometryCacheSequencer"); DynamicallyLoadedModuleNames.Add("GeometryCacheSequencer"); } } } }
27.590909
78
0.443987
[ "MIT" ]
greenrainstudios/AlembicUtilities
Plugins/GeometryCache/Source/GeometryCacheTracks/GeometryCacheTracks.Build.cs
1,214
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace ProjectEuler.Page2._061___070 { // Cubic permutations public class Problem062 { public static string Algorithm() { long result = 0; SortedList<long, Cuboid> cubes = new SortedList<long, Cuboid>(); long n = 0; while (true) { n++; long largePerm = LargestPermutation(n * n * n); if (!cubes.ContainsKey(largePerm)) cubes.Add(largePerm, new Cuboid() { N = n, Perms = 0 }); if (++cubes[largePerm].Perms == 5) { result = cubes[largePerm].N; break; } } return (result * result * result).ToString(); } private static long LargestPermutation(long n) { long k = n; int[] digits = new int[10]; long result = 0; while (k > 0) { digits[k % 10]++; k /= 10; } for (int i = 9; i >= 0; i--) { for (int j = 0; j < digits[i]; j++) { result = result * 10 + i; } } return result; } } class Cuboid { public long N { get; set; } public int Perms { get; set; } } }
22.746269
76
0.417323
[ "MIT" ]
Eld1nH/project-euler
ProjectEuler/Page2/061 - 070/Problem062.cs
1,526
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 JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// Represents the execution state of an operation. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> public class ExecutionResult<TResult> { /// <summary> /// Creates a new instance of <see cref="ExecutionResult{TResult}" />. /// </summary> /// <param name="successful"><see langword="true" /> if the operation succeeded.</param> /// <param name="result">The result of the operation if successful.</param> public ExecutionResult(bool successful, [CanBeNull] TResult result) { IsSuccessful = successful; Result = result; } /// <summary> /// Indicates whether the operation succeeded. /// </summary> public virtual bool IsSuccessful { get; } /// <summary> /// The result of the operation if successful. /// </summary> public virtual TResult Result { get; } } }
34.75
111
0.610711
[ "Apache-2.0" ]
0b01/efcore
src/EFCore/Storage/ExecutionResult.cs
1,251
C#
#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Rpc { internal class GetGuildParams { [JsonProperty("guild_id")] public ulong GuildId { get; set; } } }
18.416667
43
0.624434
[ "Unlicense" ]
Lelouch99/bot_cc
Discord.Net/src/Discord.Net.Rpc/API/Rpc/GetGuildParams.cs
223
C#
// Copyright (c) 2016, SolidCP // SolidCP is distributed under the Creative Commons Share-alike license // // SolidCP is a fork of WebsitePanel: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; namespace SolidCP.Providers.Virtualization { public enum VirtualMachineProvisioningStatus { Unknown = 0, OK = 1, Warning = 2, Error = 3, InProgress = 4, DeletionProgress = 5, Deleted = 6 } }
42.38
83
0.721567
[ "BSD-3-Clause" ]
Alirexaa/SolidCP
SolidCP/Sources/SolidCP.Providers.Base/Virtualization/VirtualMachineProvisioningStatus.cs
2,121
C#
namespace PatniListi.Services.Mapping { // ReSharper disable once UnusedTypeParameter public interface IMapFrom<T> { } }
17.25
49
0.702899
[ "MIT" ]
deedeedextor/PatniListi
Services/PatniListi.Services.Mapping/IMapFrom.cs
140
C#
using Avalonia.Lottie.Animation.Content; using Avalonia.Lottie.Model.Animatable; using Avalonia.Lottie.Model.Layer; namespace Avalonia.Lottie.Model.Content { public class ShapePath : IContentModel { private readonly string _name; private readonly int _index; private readonly AnimatableShapeValue _shapePath; public ShapePath(string name, int index, AnimatableShapeValue shapePath) { _name = name; _index = index; _shapePath = shapePath; } public virtual string Name => _name; internal virtual AnimatableShapeValue GetShapePath() { return _shapePath; } public IContent ToContent(LottieDrawable drawable, BaseLayer layer) { return new ShapeContent(drawable, layer, this); } public override string ToString() { return "ShapePath{" + "name=" + _name + ", index=" + _index + '}'; } } }
27.027027
80
0.613
[ "Apache-2.0" ]
PieroCastillo/Avalonia.Lottie
Avalonia.Lottie/Model/Content/ShapePath.cs
1,002
C#
using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Windows.UI.Xaml.Data; namespace Uno.UI.Extensions; public static class CollectionViewExtensions { [EditorBrowsable(EditorBrowsableState.Never)] public static IEnumerable<IEnumerable> GetCollectionGroups(this ICollectionView collectionView) { return (from ICollectionViewGroup g in collectionView.CollectionGroups select g.Group as IEnumerable); } public static IndexPath GetIndexPathForItem(this ICollectionView collectionView, object item) { if (collectionView.CollectionGroups == null) { return IndexPath.FromRowSection(collectionView.IndexOf(item), 0); } for (int i = 0; i < collectionView.CollectionGroups.Count; i++) { int num = (collectionView.CollectionGroups[i] as ICollectionViewGroup).GroupItems.IndexOf(item); if (num > -1) { return IndexPath.FromRowSection(num, i); } } return IndexPath.FromRowSection(-1, 0); } public static object GetItemForIndexPath(this ICollectionView collectionView, IndexPath indexPath) { if (collectionView.CollectionGroups == null) { if (indexPath.Section > 0) { return null; } return collectionView[indexPath.Row]; } return (collectionView.CollectionGroups[indexPath.Section] as ICollectionViewGroup).GroupItems[indexPath.Row]; } }
28.354167
112
0.765614
[ "MIT" ]
ljcollins25/Codeground
src/UnoApp/UnoDecompile/Uno.UI/Uno.UI.Extensions/CollectionViewExtensions.cs
1,361
C#
using System; namespace SolidStack.Core.Flow.Internal.Result { internal class UnresolvedMappableError<TError, TSuccess, TMappingDestination> : MappableContent< UnresolvedMappableError<TError, TSuccess, TMappingDestination>, TSuccess, TMappingDestination>, IMappableError<TError, TSuccess, TMappingDestination> { public UnresolvedMappableError(TSuccess content) : base(content) { } public UnresolvedMappableError(TSuccess content, Func<TSuccess, TMappingDestination> firstMapping) : base(content, firstMapping) { } public IFilteredMappableContent<TSuccess, TMappingDestination> WhenSuccess() => TryUseLastMapping(); } }
33.909091
108
0.691689
[ "MIT" ]
idmobiles/solidstack
src/SolidStack.Core.Flow/Internal/Result/UnresolvedMappableError.cs
748
C#
namespace TwilightBrewery.Models.Factions { public record CommonAbility( CommonAbilityName Name, string? Value); }
19.571429
42
0.693431
[ "MIT" ]
FLAMESpl/TwilightBrewery
TwilightBrewery/src/TwilightBrewery.Models/Factions/CommonAbility.cs
139
C#
using System; using System.Collections.Generic; using System.Text; using CoffLib.Binary; namespace CoffLib.X86 { public partial class I386 { // Mov, Add, Or, Adc, Sbb, And, Sub, Xor, Cmp, Test, Xchg public static OpCode Mov(Reg32 op1, Reg32 op2) { return FromName("mov", op1, op2); } public static OpCode Mov(Reg32 op1, Val32 op2) { return FromName("mov", op1, op2); } public static OpCode Mov(Reg32 op1, Addr32 op2) { return FromName("mov", op1, op2); } public static OpCode Mov(Addr32 op1, Reg32 op2) { return FromName("mov", op1, op2); } public static OpCode Mov(Addr32 op1, Val32 op2) { return FromName("mov", op1, op2); } public static OpCode Add(Reg32 op1, Reg32 op2) { return FromName("add", op1, op2); } public static OpCode Add(Reg32 op1, Val32 op2) { return FromName("add", op1, op2); } public static OpCode Add(Reg32 op1, Addr32 op2) { return FromName("add", op1, op2); } public static OpCode Add(Addr32 op1, Reg32 op2) { return FromName("add", op1, op2); } public static OpCode Add(Addr32 op1, Val32 op2) { return FromName("add", op1, op2); } public static OpCode Or(Reg32 op1, Reg32 op2) { return FromName("or", op1, op2); } public static OpCode Or(Reg32 op1, Val32 op2) { return FromName("or", op1, op2); } public static OpCode Or(Reg32 op1, Addr32 op2) { return FromName("or", op1, op2); } public static OpCode Or(Addr32 op1, Reg32 op2) { return FromName("or", op1, op2); } public static OpCode Or(Addr32 op1, Val32 op2) { return FromName("or", op1, op2); } public static OpCode Adc(Reg32 op1, Reg32 op2) { return FromName("adc", op1, op2); } public static OpCode Adc(Reg32 op1, Val32 op2) { return FromName("adc", op1, op2); } public static OpCode Adc(Reg32 op1, Addr32 op2) { return FromName("adc", op1, op2); } public static OpCode Adc(Addr32 op1, Reg32 op2) { return FromName("adc", op1, op2); } public static OpCode Adc(Addr32 op1, Val32 op2) { return FromName("adc", op1, op2); } public static OpCode Sbb(Reg32 op1, Reg32 op2) { return FromName("sbb", op1, op2); } public static OpCode Sbb(Reg32 op1, Val32 op2) { return FromName("sbb", op1, op2); } public static OpCode Sbb(Reg32 op1, Addr32 op2) { return FromName("sbb", op1, op2); } public static OpCode Sbb(Addr32 op1, Reg32 op2) { return FromName("sbb", op1, op2); } public static OpCode Sbb(Addr32 op1, Val32 op2) { return FromName("sbb", op1, op2); } public static OpCode And(Reg32 op1, Reg32 op2) { return FromName("and", op1, op2); } public static OpCode And(Reg32 op1, Val32 op2) { return FromName("and", op1, op2); } public static OpCode And(Reg32 op1, Addr32 op2) { return FromName("and", op1, op2); } public static OpCode And(Addr32 op1, Reg32 op2) { return FromName("and", op1, op2); } public static OpCode And(Addr32 op1, Val32 op2) { return FromName("and", op1, op2); } public static OpCode Sub(Reg32 op1, Reg32 op2) { return FromName("sub", op1, op2); } public static OpCode Sub(Reg32 op1, Val32 op2) { return FromName("sub", op1, op2); } public static OpCode Sub(Reg32 op1, Addr32 op2) { return FromName("sub", op1, op2); } public static OpCode Sub(Addr32 op1, Reg32 op2) { return FromName("sub", op1, op2); } public static OpCode Sub(Addr32 op1, Val32 op2) { return FromName("sub", op1, op2); } public static OpCode Xor(Reg32 op1, Reg32 op2) { return FromName("xor", op1, op2); } public static OpCode Xor(Reg32 op1, Val32 op2) { return FromName("xor", op1, op2); } public static OpCode Xor(Reg32 op1, Addr32 op2) { return FromName("xor", op1, op2); } public static OpCode Xor(Addr32 op1, Reg32 op2) { return FromName("xor", op1, op2); } public static OpCode Xor(Addr32 op1, Val32 op2) { return FromName("xor", op1, op2); } public static OpCode Cmp(Reg32 op1, Reg32 op2) { return FromName("cmp", op1, op2); } public static OpCode Cmp(Reg32 op1, Val32 op2) { return FromName("cmp", op1, op2); } public static OpCode Cmp(Reg32 op1, Addr32 op2) { return FromName("cmp", op1, op2); } public static OpCode Cmp(Addr32 op1, Reg32 op2) { return FromName("cmp", op1, op2); } public static OpCode Cmp(Addr32 op1, Val32 op2) { return FromName("cmp", op1, op2); } public static OpCode Test(Reg32 op1, Reg32 op2) { return FromName("test", op1, op2); } public static OpCode Test(Reg32 op1, Val32 op2) { return FromName("test", op1, op2); } public static OpCode Test(Reg32 op1, Addr32 op2) { return Test(op2, op1); } public static OpCode Test(Addr32 op1, Reg32 op2) { return FromName("test", op1, op2); } public static OpCode Test(Addr32 op1, Val32 op2) { return FromName("test", op1, op2); } public static OpCode Xchg(Reg32 op1, Reg32 op2) { return FromName("xchg", op1, op2); } public static OpCode Xchg(Reg32 op1, Addr32 op2) { return FromName("xchg", op1, op2); } public static OpCode Xchg(Addr32 op1, Reg32 op2) { return Xchg(op2, op1); } public static int GetOperatorCode(string op) { string[] s = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }; return Array.IndexOf(s, op); } public static OpCode FromName(string op, Reg32 op1, Reg32 op2) { byte b; switch (op) { case "mov": b = 0x89; break; case "test": b = 0x85; break; case "xchg": if (op1 == Reg32.EAX) return new OpCode(new byte[] { (byte)(0x90 + op2) }); else if (op2 == Reg32.EAX) return new OpCode(new byte[] { (byte)(0x90 + op1) }); else b = 0x87; break; default: int code = GetOperatorCode(op); if (code < 0) throw new Exception("invalid operator: " + op); b = (byte)(code * 8 + 1); break; } return new OpCode(new byte[] { b, (byte)(0xc0 + (((int)op2) << 3) + op1) }); } public static OpCode FromName(string op, Reg32 op1, Val32 op2) { byte[] bytes; switch (op) { case "mov": bytes = new byte[] { (byte)(0xb8 + op1) }; break; case "test": if (op1 == Reg32.EAX) bytes = new byte[] { 0xa9 }; else bytes = new byte[] { 0xf7, (byte)(0xc0 + op1) }; break; default: int code = GetOperatorCode(op); if (code < 0) throw new Exception("invalid operator: " + op); if (op1 == Reg32.EAX) bytes = new byte[] { (byte)(code * 8 + 5) }; else bytes = new byte[] { 0x81, (byte)(code * 8 + 0xc0 + op1) }; break; } return new OpCode(bytes, op2); } public static OpCode FromName(string op, Reg32 op1, Addr32 op2) { byte b; switch (op) { case "mov": if (op1 == Reg32.EAX && op2.IsAddress) return new OpCode(new byte[] { 0xa1 }, op2.Address); b = 0x8b; break; case "xchg": b = 0x87; break; default: int code = GetOperatorCode(op); if (code < 0) throw new Exception("invalid operator: " + op); b = (byte)(code * 8 + 3); break; } return new OpCode(new byte[] { b }, null, new Addr32(op2, (byte)op1)); } public static OpCode FromName(string op, Addr32 op1, Reg32 op2) { byte b; switch (op) { case "mov": if (op2 == Reg32.EAX && op1.IsAddress) return new OpCode(new byte[] { 0xa3 }, op1.Address); b = 0x89; break; case "test": b = 0x85; break; default: int code = GetOperatorCode(op); if (code < 0) throw new Exception("invalid operator: " + op); b = (byte)(code * 8 + 1); break; } return new OpCode(new byte[] { b }, null, new Addr32(op1, (byte)op2)); } public static OpCode FromName(string op, Addr32 op1, Val32 op2) { switch (op) { case "mov": return new OpCode(new byte[] { 0xc7 }, op2, op1); case "test": return new OpCode(new byte[] { 0xf7 }, op2, op1); default: int code = GetOperatorCode(op); if (code < 0) throw new Exception("invalid operator: " + op); return new OpCode(new byte[] { 0x81 }, op2, new Addr32(op1, (byte)code)); } } } }
48.719388
95
0.521206
[ "Unlicense" ]
bencz/CoffLib
CS/X86/I386.2.32.cs
9,551
C#
using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Linker.Steps; using Mono.Tuner; using Xamarin.Android.Tasks; namespace MonoDroid.Tuner { public class MarkJavaObjects : BaseSubStep { Dictionary<ModuleDefinition, Dictionary<string, TypeDefinition>> module_types = new Dictionary<ModuleDefinition, Dictionary<string, TypeDefinition>> (); public override SubStepTargets Targets { get { return SubStepTargets.Type; } } public override void ProcessType (TypeDefinition type) { // If this isn't a JLO or IJavaObject implementer, // then we don't need to MarkJavaObjects if (!type.ImplementsIJavaObject ()) return; PreserveJavaObjectImplementation (type); if (IsImplementor (type)) PreserveImplementor (type); // If a user overrode a method, we need to preserve it, // because it won't be referenced anywhere, but it will // be called from Java if (IsUserType (type) && type.HasMethods) { foreach (var method in type.Methods.Where (m => m.Overrides != null)) PreserveMethod (type, method); } } void PreserveJavaObjectImplementation (TypeDefinition type) { PreserveIntPtrConstructor (type); PreserveAttributeSetConstructor (type); PreserveAdapter (type); PreserveInvoker (type); } void PreserveAttributeSetConstructor (TypeDefinition type) { if (!type.HasMethods) return; foreach (var constructor in GetAttributeSetConstructors (type)) PreserveMethod (type, constructor); } static IEnumerable<MethodDefinition> GetAttributeSetConstructors (TypeDefinition type) { foreach (MethodDefinition constructor in type.Methods.Where (m => m.IsConstructor)) { if (!constructor.HasParameters) continue; var parameters = constructor.Parameters; if (parameters.Count < 2 || parameters.Count > 3) continue; if (parameters [0].ParameterType.FullName != "Android.Content.Context") continue; if (parameters [1].ParameterType.FullName != "Android.Util.IAttributeSet") continue; if (parameters.Count == 3 && parameters [2].ParameterType.FullName != "System.Int32") continue; yield return constructor; } } void PreserveIntPtrConstructor (TypeDefinition type) { var constructor = GetIntPtrConstructor (type); if (constructor != null) PreserveMethod (type, constructor); var constructor2 = GetNewIntPtrConstructor (type); if (constructor2 != null) PreserveMethod (type, constructor2); } static MethodDefinition GetIntPtrConstructor (TypeDefinition type) { if (!type.HasMethods) return null; foreach (MethodDefinition constructor in type.Methods.Where (m => m.IsConstructor)) { if (!constructor.HasParameters) continue; if (constructor.Parameters.Count != 1 || constructor.Parameters[0].ParameterType.FullName != "System.IntPtr") continue; return constructor; } return null; } static MethodDefinition GetNewIntPtrConstructor (TypeDefinition type) { if (!type.HasMethods) return null; foreach (MethodDefinition constructor in type.Methods.Where (m => m.IsConstructor)) { if (!constructor.HasParameters) continue; if (constructor.Parameters.Count != 2 || constructor.Parameters[0].ParameterType.FullName != "System.IntPtr" || constructor.Parameters[1].ParameterType.FullName != "Android.Runtime.JniHandleOwnership") continue; return constructor; } return null; } void PreserveMethod (TypeDefinition type, MethodDefinition method) { Annotations.AddPreservedMethod (type, method); } void PreserveAdapter (TypeDefinition type) { var adapter = PreserveHelperType (type, "Adapter"); if (adapter == null || !adapter.HasMethods) return; foreach (MethodDefinition method in adapter.Methods) { if (method.Name != "GetObject") continue; if (method.Parameters.Count != 2) continue; PreserveMethod (type, method); } } string TypeNameWithoutKey (string name) { var idx = name.IndexOf (", PublicKeyToken="); if (idx > 0) name = name.Substring (0, idx); return name; } bool CheckInvokerType (TypeDefinition type, string name) { return TypeNameWithoutKey (name) == TypeNameWithoutKey ($"{ type.FullName}, { type.Module.Assembly.FullName}"); } void PreserveInterfaceMethods (TypeDefinition type, TypeDefinition invoker) { foreach (var m in type.Methods.Where (m => !m.IsConstructor)) { string methodAndType; if (!m.TryGetRegisterMember (out methodAndType)) continue; if (!methodAndType.Contains (":")) continue; var values = methodAndType.Split (new char [] { ':' }, 2); if (!CheckInvokerType (invoker, values [1])) continue; foreach (var invokerMethod in invoker.Methods.Where (m => !m.IsConstructor)) { if (invokerMethod.Name == values [0]) { PreserveMethod (invoker, invokerMethod); break; } } } } void PreserveInvoker (TypeDefinition type) { var invoker = PreserveHelperType (type, "Invoker"); if (invoker == null) return; PreserveIntPtrConstructor (invoker); PreserveInterfaceMethods (type, invoker); } TypeDefinition PreserveHelperType (TypeDefinition type, string suffix) { var helper = GetHelperType (type, suffix); if (helper != null) PreserveConstructors (type, helper); return helper; } TypeDefinition GetHelperType (TypeDefinition type, string suffix) { string fullname = type.FullName; if (type.HasGenericParameters) { var pos = fullname.IndexOf ('`'); if (pos == -1) throw new ArgumentException (); fullname = fullname.Substring (0, pos) + suffix + fullname.Substring (pos); } else fullname = fullname + suffix; return FindType (type, fullname); } // Keep a dictionary cache of all types in a module rather than // looping through them on every lookup. TypeDefinition FindType (TypeDefinition type, string fullname) { Dictionary<string, TypeDefinition> types; if (!module_types.TryGetValue (type.Module, out types)) { types = GetTypesInModule (type.Module); module_types.Add (type.Module, types); } TypeDefinition helper; if (types.TryGetValue (fullname, out helper)) return helper; return null; } static Dictionary<string, TypeDefinition> GetTypesInModule (ModuleDefinition module) { var types = module.Types.ToDictionary (p => p.FullName); foreach (var t in module.Types) AddNestedTypes (types, t); return types; } static void AddNestedTypes (Dictionary<string, TypeDefinition> types, TypeDefinition type) { if (!type.HasNestedTypes) return; foreach (var t in type.NestedTypes) { types.Add (t.FullName, t); AddNestedTypes (types, t); } } void PreserveConstructors (TypeDefinition type, TypeDefinition helper) { if (!helper.HasMethods) return; foreach (MethodDefinition ctor in helper.Methods.Where (m => m.IsConstructor)) PreserveMethod (type, ctor); } static bool IsImplementor (TypeDefinition type) { return type.Name.EndsWith ("Implementor") && type.Inherits ("Java.Lang.Object"); } static bool IsUserType (TypeDefinition type) { return !MonoAndroidHelper.IsFrameworkAssembly (type.Module.Assembly.Name.Name + ".dll"); } void PreserveImplementor (TypeDefinition type) { if (!type.HasMethods) return; foreach (MethodDefinition method in type.Methods) if (method.Name.EndsWith ("Handler")) PreserveMethod (type, method); } } }
25.698305
154
0.697269
[ "MIT" ]
AArnott/xamarin-android
src/Xamarin.Android.Build.Tasks/Linker/MonoDroid.Tuner/MarkJavaObjects.cs
7,581
C#
//============================================================================== // Copyright (c) 2017-2021 Fiats Inc. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the solution folder for // full license information. // https://www.fiats.asia/ // Fiats Inc. Nakano, Tokyo, Japan // using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BitFlyerDotNet.LightningApi; namespace BitFlyerDotNet.Trading { public class BfxParentTransaction : BfxTransaction { public override string MarketId => _order.AcceptanceId; public override IBfxOrder Order => _order; public override BfxOrderState OrderState => Order.State; protected override void CancelTransaction() => _cts.Cancel(); // Private properties CancellationTokenSource _cts = new CancellationTokenSource(); BfxParentOrder _order; public BfxParentTransaction(BfxMarket market, BfxParentOrder order) : base(market) { _order = order; } // - 経過時間でリトライ終了のオプション public async Task SendOrderRequestAsync() { if (_order.Request == null) { throw new BitFlyerDotNetException(); } try { ChangeState(BfxTransactionState.SendingOrder); NotifyEvent(BfxTransactionEventType.OrderSending); for (var retry = 0; retry <= Market.Config.OrderRetryMax; retry++) { _cts.Token.ThrowIfCancellationRequested(); var resp = await Market.Client.SendParentOrderAsync(_order.Request, _cts.Token); if (!resp.IsError) { Market.OrderCache?.OpenParentOrder(_order.Request, resp.GetContent()); _order.Update(resp.GetContent()); ChangeState(BfxTransactionState.WaitingOrderAccepted); NotifyEvent(BfxTransactionEventType.OrderSent, Market.ServerTime, resp); Market.RegisterTransaction(this); return; } Log.Warn($"SendParentOrder failed: {resp.StatusCode} {resp.ErrorMessage}"); _cts.Token.ThrowIfCancellationRequested(); Log.Info("Trying retry..."); await Task.Delay(Market.Config.OrderRetryInterval); } Log.Error("SendOrderRequest - Retried out"); ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.OrderSendFailed); throw new BitFlyerDotNetException(); } catch (OperationCanceledException ex) { Log.Trace("SendParentOrderRequestAsync is canceled"); ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.OrderSendCanceled, Market.ServerTime, ex); } } protected override async Task SendCancelOrderRequestAsync() { if (State == BfxTransactionState.SendingOrder) { _cts.Token.ThrowIfCancellationRequested(); } ChangeState(BfxTransactionState.SendingCancel); NotifyEvent(BfxTransactionEventType.CancelSending); try { var resp = await Market.Client.CancelParentOrderAsync(Market.ProductCode, string.Empty, _order.AcceptanceId, _cts.Token); if (!resp.IsError) { ChangeState(BfxTransactionState.CancelAccepted); NotifyEvent(BfxTransactionEventType.CancelSent, Market.ServerTime, resp); } else { ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.CancelSendFailed, Market.ServerTime, resp); } } catch (OperationCanceledException ex) { ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.CancelSendCanceled, Market.ServerTime, ex); } } public void OnParentOrderEvent(BfParentOrderEvent poe) { if (poe.ParentOrderAcceptanceId != _order.AcceptanceId) { throw new ApplicationException(); } _order.Update(poe); switch (poe.EventType) { case BfOrderEventType.Order: // Order accepted ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.Ordered, poe); break; case BfOrderEventType.OrderFailed: ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.OrderFailed, poe); break; case BfOrderEventType.Cancel: ChangeState(BfxTransactionState.Closed); NotifyEvent(BfxTransactionEventType.Canceled, poe); break; case BfOrderEventType.CancelFailed: ChangeState(BfxTransactionState.Idle); NotifyEvent(BfxTransactionEventType.CancelFailed, poe); break; case BfOrderEventType.Trigger: Log.Trace($"Trigger {poe.Side} P:{poe.Price} S:{poe.Size}"); break; case BfOrderEventType.Expire: ChangeState(BfxTransactionState.Closed); NotifyEvent(BfxTransactionEventType.Expired, poe); break; case BfOrderEventType.Complete: if (Order.State == BfxOrderState.Completed) { ChangeState(BfxTransactionState.Closed); NotifyEvent(BfxTransactionEventType.Completed, poe); } break; case BfOrderEventType.Unknown: case BfOrderEventType.Execution: throw new NotSupportedException(); } } public override void OnChildOrderEvent(BfChildOrderEvent coe) { var childOrderIndex = _order.Update(coe); var childOrder = Order.Children[childOrderIndex]; switch (coe.EventType) { case BfOrderEventType.Order: NotifyChildOrderEvent(BfxTransactionEventType.Ordered, childOrderIndex, coe); break; case BfOrderEventType.OrderFailed: NotifyChildOrderEvent(BfxTransactionEventType.OrderFailed, childOrderIndex, coe); break; case BfOrderEventType.Cancel: NotifyChildOrderEvent(BfxTransactionEventType.Canceled, childOrderIndex, coe); break; case BfOrderEventType.CancelFailed: break; case BfOrderEventType.Execution: NotifyChildOrderEvent(childOrder.State == BfxOrderState.PartiallyExecuted ? BfxTransactionEventType.PartiallyExecuted : BfxTransactionEventType.Executed, childOrderIndex, coe); break; case BfOrderEventType.Expire: NotifyChildOrderEvent(BfxTransactionEventType.Expired, childOrderIndex, coe); break; case BfOrderEventType.Unknown: case BfOrderEventType.Complete: case BfOrderEventType.Trigger: throw new NotSupportedException(); } } } }
38.625616
196
0.55975
[ "MIT" ]
fiatsasia/BitFlyerDotNet
BitFlyerDotNet.Trading/Models/BfxParentTransaction.cs
7,877
C#
using System; namespace RemindClock.Services.NoteType { /// <summary> /// 每周提醒的判断类 /// </summary> class NotePerWeek : INoteTime { public bool Handle(string eventType) { return eventType != null && eventType == "每周"; } public bool IsTime(DateTime eventTime, DateTime lastNoteTime) { var now = DateTime.Now; // 今天已经提醒过,忽略 if (lastNoteTime.Year == now.Year && lastNoteTime.Month == now.Month && lastNoteTime.Day == now.Day && lastNoteTime.Hour == now.Hour && lastNoteTime.Minute == now.Minute) return false; return now.DayOfWeek == eventTime.DayOfWeek && now.Hour == eventTime.Hour && now.Minute == eventTime.Minute && now.Second >= eventTime.Second; } } }
30.275862
114
0.535308
[ "Apache-2.0" ]
youbl/products
RemindClock/RemindClock/Services/NoteType/NotePerWeek.cs
920
C#
using System; using System.IO; using Xamarin.Forms; using SkiaSharp; using SkiaSharp.Views.Forms; namespace Imaging { public partial class BasicImagingPage : ContentPage { SKImage image; SKPixmap pixmap; public BasicImagingPage() { InitializeComponent(); } async void OnLoadPhotoClicked(object sender, EventArgs e) { (sender as ToolbarItem).IsEnabled = false; using (Stream stream = await DependencyService.Get<IPhotoPickerService>().PickPhotoAsync()) { if (stream != null) { image = SKImage.FromEncodedData(stream); canvasView.InvalidateSurface(); picker.IsEnabled = true; } } (sender as ToolbarItem).IsEnabled = true; } async void OnSavePhotoClicked(object sender, EventArgs e) { await Navigation.PushModalAsync(new NavigationPage(new SavePhotoPage(pixmap))); } void OnPickerSelectedIndexChanged(object sender, EventArgs e) { processButton.IsEnabled = picker.SelectedIndex != -1 ? true : false; } void OnProcessButtonClicked(object sender, EventArgs e) { (sender as Button).IsEnabled = false; switch (picker.SelectedIndex) { case 0: pixmap = image.ToGreyscale(); break; case 1: pixmap = image.OtsuThreshold(); break; case 2: pixmap = image.ToSepia(); break; } canvasView.InvalidateSurface(); (sender as Button).IsEnabled = true; } void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs e) { SKImageInfo info = e.Info; SKCanvas canvas = e.Surface.Canvas; canvas.Clear(); if (image != null) { canvas.DrawImage(image, info.Rect, ImageStretch.Uniform); } } } }
27.475
103
0.518198
[ "MIT" ]
JaridKG/xamarin-forms
Imaging/Imaging/Views/BasicImagingPage.xaml.cs
2,200
C#
using System.IO; using System.Web.Routing; using FluentAssertions; using MvcAreas.Custom.Render; using NSubstitute; using NUnit.Framework; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.FakeDb; using Sitecore.Mvc.Common; using Sitecore.Mvc.Pipelines.Response.RenderRendering; using Sitecore.Mvc.Presentation; namespace MvcAreas.Custom.Tests.Pipelines { public class AddRenderingAreaTest { [Test] public void ShouldSkipIfRendered() { //arrange var processor = Substitute.ForPartsOf<AddRenderingArea>(); var args = new RenderRenderingArgs(new Rendering(), new StringWriter()) { Rendered = true }; // act processor.Process(args); // assert processor.DidNotReceive().DoProcess(Arg.Any<PageContext>(), Arg.Any<string>(), args); } [Test] public void ShouldSkipIfNoPageContext() { //arrange var processor = Substitute.ForPartsOf<AddRenderingArea>(); var args = new RenderRenderingArgs(new Rendering(), new StringWriter()); // act processor.Process(args); // assert processor.DidNotReceive().DoProcess(Arg.Any<PageContext>(), Arg.Any<string>(), args); } [TestCase("")] [TestCase(null)] public void ShouldDoNothingIfNoAreaDetected(string areaname) { //arrange using (var db = new Db { new DbItem("rendering", ID.NewID) }) { Item item = db.GetItem("/sitecore/content/rendering"); var rendering = new Rendering { RenderingItem = item }; var args = new RenderRenderingArgs(rendering, new StringWriter()); var processor = Substitute.ForPartsOf<AddRenderingArea>(); processor.GetAreaName(Arg.Any<Rendering>()).Returns(areaname); var pageContext = new PageContext(); var renderingContext = new RenderingContext(); using (ContextService.Get().Push(pageContext)) using (ContextService.Get().Push(renderingContext)) { // act processor.Process(args); } // assert processor.DidNotReceive().DoProcess(Arg.Any<PageContext>(), areaname, args); } } [Test] public void ShouldCallScoreMvcGetAreaToGetTheArea() { //arrange using (var db = new Db()) { var processor = new AddRenderingArea(); db.PipelineWatcher.Expects("mvc.getArea"); // act processor.GetAreaName(new Rendering()); // assert db.PipelineWatcher.EnsureExpectations(); } } [Test] public void ShouldSetAndUnsetAreaIfEmpty() { //arrange var pageContext = new PageContext { RequestContext = new RequestContext { RouteData = new RouteData() } }; pageContext.RequestContext.RouteData.DataTokens.ContainsKey("area").Should().BeFalse(); // act using (ContextService.Get().Push(pageContext)) using (new AddRenderingArea.RenderingAreaContext(pageContext, "MySolution")) { pageContext.RequestContext.RouteData.DataTokens["area"].Should().Be("MySolution"); } pageContext.RequestContext.RouteData.DataTokens.ContainsKey("area").Should().BeFalse(); } [Test] public void ShouldSetAndRestoreArea() { //arrange var pageContext = new PageContext { RequestContext = new RequestContext { RouteData = new RouteData() } }; pageContext.RequestContext.RouteData.DataTokens["area"] = "OldArea"; // act using (ContextService.Get().Push(pageContext)) using (new AddRenderingArea.RenderingAreaContext(pageContext, "NewArea")) { pageContext.RequestContext.RouteData.DataTokens["area"].Should().Be("NewArea"); } pageContext.RequestContext.RouteData.DataTokens["area"].Should().Be("OldArea"); } } }
30.853333
99
0.537165
[ "Apache-2.0" ]
brainjocks/SitecoreMvcAreas
MvcAreas.Custom.Tests/Pipelines/AddRenderingAreaTest.cs
4,630
C#
using Abp.Application.Services.Dto; namespace UniSolution.FabianoRangel26.People.Dto { public class PagedPersonResultRequestDto : PagedResultRequestDto { public string Keyword { get; set; } public bool? IsActive { get; set; } } }
25.8
68
0.705426
[ "MIT" ]
fabianorangel26/unisolution-fabianorangel26
aspnet-full/src/UniSolution.FabianoRangel26.Application/People/Dto/PagedPersonResultRequestDto.cs
258
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using OperationsConstants = Microsoft.Health.Fhir.Core.Features.Operations.OperationsConstants; namespace Microsoft.Health.Fhir.Api.Features.Routing { internal class KnownRoutes { internal const string ResourceTypeRouteConstraint = "fhirResource"; internal const string CompartmentResourceTypeRouteConstraint = "fhirCompartmentResource"; internal const string CompartmentTypeRouteConstraint = "fhirCompartment"; private const string ResourceTypeRouteSegment = "{" + KnownActionParameterNames.ResourceType + ":" + ResourceTypeRouteConstraint + "}"; private const string CompartmentResourceTypeRouteSegment = "{" + KnownActionParameterNames.ResourceType + ":" + CompartmentResourceTypeRouteConstraint + "}"; private const string CompartmentTypeRouteSegment = "{" + KnownActionParameterNames.CompartmentType + ":" + CompartmentTypeRouteConstraint + "}"; private const string IdRouteSegment = "{" + KnownActionParameterNames.Id + "}"; private const string VidRouteSegment = "{" + KnownActionParameterNames.Vid + "}"; public const string History = "_history"; public const string Search = "_search"; public const string ResourceType = ResourceTypeRouteSegment; public const string ResourceTypeHistory = ResourceType + "/" + History; public const string ResourceTypeSearch = ResourceType + "/" + Search; public const string ResourceTypeById = ResourceType + "/" + IdRouteSegment; public const string ResourceTypeByIdHistory = ResourceTypeById + "/" + History; public const string ResourceTypeByIdAndVid = ResourceTypeByIdHistory + "/" + VidRouteSegment; public const string Export = "$export"; public const string ExportResourceType = ResourceType + "/" + Export; public const string ExportResourceTypeById = ResourceTypeById + "/" + Export; public const string ExportJobLocation = OperationsConstants.Operations + "/" + OperationsConstants.Export + "/" + IdRouteSegment; public const string Validate = "$validate"; public const string ValidateResourceType = ResourceType + "/" + Validate; public const string ValidateResourceTypeById = ResourceTypeById + "/" + Validate; public const string Reindex = "$reindex"; public const string ReindexJobLocation = "$reindex" + "/" + IdRouteSegment; public const string CompartmentTypeByResourceType = CompartmentTypeRouteSegment + "/" + IdRouteSegment + "/" + CompartmentResourceTypeRouteSegment; public const string Metadata = "metadata"; public const string Versions = "$versions"; public const string HealthCheck = "/health/check"; public const string CustomError = "/CustomError"; } }
59.358491
165
0.673872
[ "MIT" ]
Bhaskers-Blu-Org2/fhir-server
src/Microsoft.Health.Fhir.Api/Features/Routing/KnownRoutes.cs
3,148
C#
namespace PnP.Core.Model.Teams { internal sealed class GraphRecipientCollection : BaseDataModelCollection<IGraphRecipient>, IGraphRecipientCollection { } }
24.142857
120
0.781065
[ "MIT" ]
MathijsVerbeeck/pnpcore
src/sdk/PnP.Core/Model/Teams/Internal/GraphRecipientCollection.cs
171
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[dotNET] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.dotNET.CodeExample.10_DeletingTable] using System; using System.Threading.Tasks; namespace DynamoDB_intro { public static partial class DdbIntro { public static async Task<bool> DeletingTable_async(string tableName) { var tblDelete = await Client.DeleteTableAsync(tableName); return true; } } }// snippet-end:[dynamodb.dotNET.CodeExample.10_DeletingTable]
31
72
0.735732
[ "Apache-2.0" ]
1n5an1ty/aws-doc-sdk-examples
dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/10_DeletingTable.cs
806
C#