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 Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace NotificationServiceAPI.Hubs { public class PhotoTyeHub : Hub { public Task JoinGroup(string groupName) { return Groups.AddToGroupAsync(Context.ConnectionId, groupName); } } }
20.133333
75
0.678808
[ "Unlicense" ]
johnnyruz/ProjectTyeDemo
NotificationServiceAPI/Hubs/PhotoTyeHub.cs
304
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; using Shouldly; using Xunit; #nullable disable namespace Microsoft.Build.Tasks.UnitTests { public class RoslynCodeTaskFactory_Tests { private const string TaskName = "MyInlineTask"; [Fact] public void RoslynCodeTaskFactory_ReuseCompilation() { string text1 = $@" <Project> <UsingTask TaskName=""Custom1"" TaskFactory=""RoslynCodeTaskFactory"" AssemblyFile=""$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll"" > <ParameterGroup> <SayHi ParameterType=""System.String"" Required=""true"" /> </ParameterGroup> <Task> <Reference Include=""{typeof(Enumerable).Assembly.Location}"" /> <Code Type=""Fragment"" Language=""cs""> Log.LogMessage(SayHi); </Code> </Task> </UsingTask> <Target Name=""Build""> <MSBuild Projects=""p2.proj"" Targets=""Build"" /> <Custom1 SayHi=""hello1"" /> <Custom1 SayHi=""hello2"" /> </Target> </Project>"; var text2 = $@" <Project> <UsingTask TaskName=""Custom1"" TaskFactory=""RoslynCodeTaskFactory"" AssemblyFile=""$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll"" > <ParameterGroup> <SayHi ParameterType=""System.String"" Required=""true"" /> </ParameterGroup> <Task> <Reference Include=""{typeof(Enumerable).Assembly.Location}"" /> <Code Type=""Fragment"" Language=""cs""> Log.LogMessage(SayHi); </Code> </Task> </UsingTask> <Target Name=""Build""> <Custom1 SayHi=""hello1"" /> <Custom1 SayHi=""hello2"" /> </Target> </Project>"; using var env = TestEnvironment.Create(); var p2 = env.CreateTestProjectWithFiles("p2.proj", text2); text1 = text1.Replace("p2.proj", p2.ProjectFile); var p1 = env.CreateTestProjectWithFiles("p1.proj", text1); var logger = p1.BuildProjectExpectSuccess(); var messages = logger .BuildMessageEvents .Where(m => m.Message == "Compiling task source code") .ToArray(); // with broken cache we get two Compiling messages // as we fail to reuse the first assembly messages.Count().ShouldBe(1); } [Fact] public void VisualBasicFragment() { const string fragment = "Dim x = 0"; string expectedSourceCode = $@"'------------------------------------------------------------------------------ ' <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> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports Microsoft.Build.Framework Imports Microsoft.Build.Utilities Imports System Imports System.Collections Imports System.Collections.Generic Imports System.IO Imports System.Linq Imports System.Text Namespace InlineCode Public Class {TaskName} Inherits Microsoft.Build.Utilities.Task Private _Success As Boolean = true Public Overridable Property Success() As Boolean Get Return _Success End Get Set _Success = value End Set End Property Public Overrides Function Execute() As Boolean {fragment} Return Success End Function End Class End Namespace "; TryLoadTaskBodyAndExpectSuccess( taskBody: $"<Code Language=\"VB\">{fragment}</Code>", expectedCodeLanguage: "VB", expectedSourceCode: expectedSourceCode, expectedCodeType: RoslynCodeTaskFactoryCodeType.Fragment); } [Fact] public void VisualBasicFragmentWithProperties() { ICollection<TaskPropertyInfo> parameters = new List<TaskPropertyInfo> { new TaskPropertyInfo("Parameter1", typeof(string), output: false, required: true), new TaskPropertyInfo("Parameter2", typeof(string), output: true, required: false), new TaskPropertyInfo("Parameter3", typeof(string), output: true, required: true), new TaskPropertyInfo("Parameter4", typeof(ITaskItem), output: false, required: false), new TaskPropertyInfo("Parameter5", typeof(ITaskItem[]), output: false, required: false), }; const string fragment = @"Dim x = 0"; string expectedSourceCode = $@"'------------------------------------------------------------------------------ ' <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> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports Microsoft.Build.Framework Imports Microsoft.Build.Utilities Imports System Imports System.Collections Imports System.Collections.Generic Imports System.IO Imports System.Linq Imports System.Text Namespace InlineCode Public Class {TaskName} Inherits Microsoft.Build.Utilities.Task Private _Parameter1 As String Public Overridable Property Parameter1() As String Get Return _Parameter1 End Get Set _Parameter1 = value End Set End Property Private _Parameter2 As String Public Overridable Property Parameter2() As String Get Return _Parameter2 End Get Set _Parameter2 = value End Set End Property Private _Parameter3 As String Public Overridable Property Parameter3() As String Get Return _Parameter3 End Get Set _Parameter3 = value End Set End Property Private _Parameter4 As Microsoft.Build.Framework.ITaskItem Public Overridable Property Parameter4() As Microsoft.Build.Framework.ITaskItem Get Return _Parameter4 End Get Set _Parameter4 = value End Set End Property Private _Parameter5() As Microsoft.Build.Framework.ITaskItem Public Overridable Property Parameter5() As Microsoft.Build.Framework.ITaskItem() Get Return _Parameter5 End Get Set _Parameter5 = value End Set End Property Private _Success As Boolean = true Public Overridable Property Success() As Boolean Get Return _Success End Get Set _Success = value End Set End Property Public Overrides Function Execute() As Boolean {fragment} Return Success End Function End Class End Namespace "; TryLoadTaskBodyAndExpectSuccess( taskBody: $"<Code Language=\"VB\">{fragment}</Code>", expectedCodeLanguage: "VB", expectedSourceCode: expectedSourceCode, expectedCodeType: RoslynCodeTaskFactoryCodeType.Fragment, parameters: parameters); } [Fact] public void VisualBasicMethod() { const string method = @"Public Overrides Function Execute() As Boolean Dim x = 0 Return True End Function"; string expectedSourceCode = $@"'------------------------------------------------------------------------------ ' <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> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports Microsoft.Build.Framework Imports Microsoft.Build.Utilities Imports System Imports System.Collections Imports System.Collections.Generic Imports System.IO Imports System.Linq Imports System.Text Namespace InlineCode Public Class {TaskName} Inherits Microsoft.Build.Utilities.Task {method} End Class End Namespace "; TryLoadTaskBodyAndExpectSuccess( taskBody: $"<Code Language=\"VB\" Type=\"Method\">{method}</Code>", expectedCodeLanguage: "VB", expectedSourceCode: expectedSourceCode, expectedCodeType: RoslynCodeTaskFactoryCodeType.Method); } [Fact] public void CodeLanguageFromTaskBody() { TryLoadTaskBodyAndExpectSuccess("<Code Language=\"CS\">code</Code>", expectedCodeLanguage: "CS"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"cs\">code</Code>", expectedCodeLanguage: "CS"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"csharp\">code</Code>", expectedCodeLanguage: "CS"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"c#\">code</Code>", expectedCodeLanguage: "CS"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"VB\">code</Code>", expectedCodeLanguage: "VB"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"vb\">code</Code>", expectedCodeLanguage: "VB"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"visualbasic\">code</Code>", expectedCodeLanguage: "VB"); TryLoadTaskBodyAndExpectSuccess("<Code Language=\"ViSuAl BaSic\">code</Code>", expectedCodeLanguage: "VB"); } [Fact] public void CodeTypeFromTaskBody() { foreach (RoslynCodeTaskFactoryCodeType codeType in Enum.GetValues(typeof(RoslynCodeTaskFactoryCodeType)).Cast<RoslynCodeTaskFactoryCodeType>()) { TryLoadTaskBodyAndExpectSuccess($"<Code Type=\"{codeType}\">code</Code>", expectedCodeType: codeType); } using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFile file = testEnvironment.CreateFile(fileName: "236D48CE30064161B31B55DBF088C8B2", contents: "6159BD98607A460AA4F11D2FA92E5436"); TryLoadTaskBodyAndExpectSuccess($"<Code Source=\"{file.Path}\"/>", expectedCodeType: RoslynCodeTaskFactoryCodeType.Class); } } [Fact] public void CSharpFragment() { const string fragment = "int x = 0;"; string expectedSourceCode = $@"//------------------------------------------------------------------------------ // <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 InlineCode {{ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; public class {TaskName} : Microsoft.Build.Utilities.Task {{ private bool _Success = true; public virtual bool Success {{ get {{ return _Success; }} set {{ _Success = value; }} }} public override bool Execute() {{ {fragment} return Success; }} }} }} "; TryLoadTaskBodyAndExpectSuccess(taskBody: $"<Code>{fragment}</Code>", expectedSourceCode: expectedSourceCode); } [Fact] public void CSharpFragmentWithProperties() { ICollection<TaskPropertyInfo> parameters = new List<TaskPropertyInfo> { new TaskPropertyInfo("Parameter1", typeof(string), output: false, required: true), new TaskPropertyInfo("Parameter2", typeof(string), output: true, required: false), new TaskPropertyInfo("Parameter3", typeof(string), output: true, required: true), new TaskPropertyInfo("Parameter4", typeof(ITaskItem), output: false, required: false), new TaskPropertyInfo("Parameter5", typeof(ITaskItem[]), output: false, required: false), }; const string fragment = @"int x = 0;"; string expectedSourceCode = $@"//------------------------------------------------------------------------------ // <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 InlineCode {{ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; public class {TaskName} : Microsoft.Build.Utilities.Task {{ private string _Parameter1; public virtual string Parameter1 {{ get {{ return _Parameter1; }} set {{ _Parameter1 = value; }} }} private string _Parameter2; public virtual string Parameter2 {{ get {{ return _Parameter2; }} set {{ _Parameter2 = value; }} }} private string _Parameter3; public virtual string Parameter3 {{ get {{ return _Parameter3; }} set {{ _Parameter3 = value; }} }} private Microsoft.Build.Framework.ITaskItem _Parameter4; public virtual Microsoft.Build.Framework.ITaskItem Parameter4 {{ get {{ return _Parameter4; }} set {{ _Parameter4 = value; }} }} private Microsoft.Build.Framework.ITaskItem[] _Parameter5; public virtual Microsoft.Build.Framework.ITaskItem[] Parameter5 {{ get {{ return _Parameter5; }} set {{ _Parameter5 = value; }} }} private bool _Success = true; public virtual bool Success {{ get {{ return _Success; }} set {{ _Success = value; }} }} public override bool Execute() {{ {fragment} return Success; }} }} }} "; TryLoadTaskBodyAndExpectSuccess( taskBody: $"<Code>{fragment}</Code>", expectedSourceCode: expectedSourceCode, expectedCodeType: RoslynCodeTaskFactoryCodeType.Fragment, parameters: parameters); } [Fact] public void CSharpMethod() { const string method = @"public override bool Execute() { int x = 0; return true; }"; string expectedSourceCode = $@"//------------------------------------------------------------------------------ // <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 InlineCode {{ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; public class MyInlineTask : Microsoft.Build.Utilities.Task {{ {method} }} }} "; TryLoadTaskBodyAndExpectSuccess( taskBody: $"<Code Type=\"Method\">{method}</Code>", expectedSourceCode: expectedSourceCode, expectedCodeType: RoslynCodeTaskFactoryCodeType.Method); } [Fact] public void EmptyCodeElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code />", expectedErrorMessage: "You must specify source code within the Code element or a path to a file containing source code."); } [Fact] public void EmptyIncludeAttributeOnReferenceElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Reference Include=\"\" />", expectedErrorMessage: "The \"Include\" attribute of the <Reference> element has been set but is empty. If the \"Include\" attribute is set it must not be empty."); } [Fact] public void EmptyLanguageAttributeOnCodeElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Language=\"\" />", expectedErrorMessage: "The \"Language\" attribute of the <Code> element has been set but is empty. If the \"Language\" attribute is set it must not be empty."); } [Fact] public void EmptyNamespaceAttributeOnUsingElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Using Namespace=\"\" />", expectedErrorMessage: "The \"Namespace\" attribute of the <Using> element has been set but is empty. If the \"Namespace\" attribute is set it must not be empty."); } [Fact] public void EmptySourceAttributeOnCodeElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Source=\"\" />", expectedErrorMessage: "The \"Source\" attribute of the <Code> element has been set but is empty. If the \"Source\" attribute is set it must not be empty."); } [Fact] public void EmptyTypeAttributeOnCodeElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Type=\"\" />", expectedErrorMessage: "The \"Type\" attribute of the <Code> element has been set but is empty. If the \"Type\" attribute is set it must not be empty."); } [Fact] public void IgnoreTaskCommentsAndWhiteSpace() { TryLoadTaskBodyAndExpectSuccess("<!-- Comment --><Code>code</Code>"); TryLoadTaskBodyAndExpectSuccess(" <Code>code</Code>"); } [Fact] public void InvalidCodeElementAttribute() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Invalid=\"Attribute\" />", expectedErrorMessage: "The attribute \"Invalid\" is not valid for the <Code> element. Valid attributes are \"Language\", \"Source\", and \"Type\"."); } [Fact] public void InvalidCodeLanguage() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Language=\"Invalid\" />", expectedErrorMessage: "The specified code language \"Invalid\" is invalid. The supported code languages are \"CS, VB\"."); } [Fact] public void InvalidCodeType() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code Type=\"Invalid\" />", expectedErrorMessage: "The specified code type \"Invalid\" is invalid. The supported code types are \"Fragment, Method, Class\"."); } [Fact] public void InvalidTaskChildElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Invalid />", expectedErrorMessage: "The element <Invalid> is not a valid child of the <Task> element. Valid child elements are <Code>, <Reference>, and <Using>."); TryLoadTaskBodyAndExpectFailure( taskBody: "invalid<Code>code</Code>", expectedErrorMessage: "The element <Text> is not a valid child of the <Task> element. Valid child elements are <Code>, <Reference>, and <Using>."); } [Fact] public void InvalidTaskXml() { TryLoadTaskBodyAndExpectFailure( taskBody: "<invalid xml", expectedErrorMessage: "The specified task XML is invalid. '<' is an unexpected token. The expected token is '='. Line 1, position 19."); } [Fact] public void MissingCodeElement() { TryLoadTaskBodyAndExpectFailure( taskBody: "", expectedErrorMessage: $"The <Code> element is missing for the \"{TaskName}\" task. This element is required."); } [Fact] public void MultipleCodeNodes() { TryLoadTaskBodyAndExpectFailure( taskBody: "<Code><![CDATA[]]></Code><Code></Code>", expectedErrorMessage: "Only one <Code> element can be specified."); } [Fact] public void NamespacesFromTaskBody() { const string taskBody = @" <Using Namespace=""namespace.A"" /> <Using Namespace="" namespace.B "" /> <Using Namespace=""namespace.C""></Using> <Code>code</Code>"; TryLoadTaskBodyAndExpectSuccess( taskBody, expectedNamespaces: new HashSet<string> { "namespace.A", "namespace.B", "namespace.C", }); } [Fact] public void ReferencesFromTaskBody() { const string taskBody = @" <Reference Include=""AssemblyA"" /> <Reference Include="" AssemblyB "" /> <Reference Include=""AssemblyC""></Reference> <Reference Include=""C:\Program Files(x86)\Common Files\Microsoft\AssemblyD.dll"" /> <Code>code</Code>"; TryLoadTaskBodyAndExpectSuccess( taskBody, expectedReferences: new HashSet<string> { "AssemblyA", "AssemblyB", "AssemblyC", @"C:\Program Files(x86)\Common Files\Microsoft\AssemblyD.dll" }); } [Fact] public void SourceCodeFromFile() { const string sourceCodeFileContents = @" 1F214E27A13F432B9397F1733BC55929 9111DC29B0064E6994A68CFE465404D4"; using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFile file = testEnvironment.CreateFile(fileName: "CB3096DA4A454768AA9C0C4D422FC188.tmp", contents: sourceCodeFileContents); TryLoadTaskBodyAndExpectSuccess( $"<Code Source=\"{file.Path}\"/>", expectedSourceCode: sourceCodeFileContents, expectedCodeType: RoslynCodeTaskFactoryCodeType.Class); } } private void TryLoadTaskBodyAndExpectFailure(string taskBody, string expectedErrorMessage) { if (expectedErrorMessage == null) { throw new ArgumentNullException(nameof(expectedErrorMessage)); } MockEngine buildEngine = new MockEngine(); TaskLoggingHelper log = new TaskLoggingHelper(buildEngine, TaskName) { TaskResources = Shared.AssemblyResources.PrimaryResources }; bool success = RoslynCodeTaskFactory.TryLoadTaskBody(log, TaskName, taskBody, new List<TaskPropertyInfo>(), out RoslynCodeTaskFactoryTaskInfo _); success.ShouldBeFalse(); buildEngine.Errors.ShouldBe(1); buildEngine.Log.ShouldContain(expectedErrorMessage, () => buildEngine.Log); } private void TryLoadTaskBodyAndExpectSuccess( string taskBody, ICollection<TaskPropertyInfo> parameters = null, ISet<string> expectedReferences = null, ISet<string> expectedNamespaces = null, string expectedCodeLanguage = null, RoslynCodeTaskFactoryCodeType? expectedCodeType = null, string expectedSourceCode = null, IReadOnlyList<string> expectedWarningMessages = null) { MockEngine buildEngine = new MockEngine(); TaskLoggingHelper log = new TaskLoggingHelper(buildEngine, TaskName) { TaskResources = Shared.AssemblyResources.PrimaryResources }; bool success = RoslynCodeTaskFactory.TryLoadTaskBody(log, TaskName, taskBody, parameters ?? new List<TaskPropertyInfo>(), out RoslynCodeTaskFactoryTaskInfo taskInfo); buildEngine.Errors.ShouldBe(0, buildEngine.Log); if (expectedWarningMessages == null) { buildEngine.Warnings.ShouldBe(0); } else { string output = buildEngine.Log; foreach (string expectedWarningMessage in expectedWarningMessages) { output.ShouldContain(expectedWarningMessage, () => output); } } success.ShouldBeTrue(); if (expectedReferences != null) { taskInfo.References.ShouldBe(expectedReferences); } if (expectedNamespaces != null) { taskInfo.Namespaces.ShouldBe(expectedNamespaces); } if (expectedCodeLanguage != null) { taskInfo.CodeLanguage.ShouldBe(expectedCodeLanguage); } if (expectedCodeType != null) { taskInfo.CodeType.ShouldBe(expectedCodeType.Value); } if (expectedSourceCode != null) { NormalizeRuntime(taskInfo.SourceCode) .ShouldBe(NormalizeRuntime(expectedSourceCode), StringCompareShould.IgnoreLineEndings); } } private static readonly Regex RuntimeVersionLine = new Regex("Runtime Version:.*"); private static string NormalizeRuntime(string input) { return RuntimeVersionLine.Replace(input, "Runtime Version:SOMETHING"); } } }
33.551095
179
0.56068
[ "MIT" ]
MarcoRossignoli/msbuild
src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs
27,581
C#
using FreeSql.Internal; using FreeSql.Internal.Model; using FreeSql.Internal.ObjectPool; using System; using System.Collections; using System.Data.Common; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading; namespace FreeSql.MsAccess { class MsAccessAdo : FreeSql.Internal.CommonProvider.AdoProvider { public MsAccessAdo() : base(DataType.MsAccess, null, null) { } public MsAccessAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings, Func<DbConnection> connectionFactory) : base(DataType.MsAccess, masterConnectionString, slaveConnectionStrings) { base._util = util; if (connectionFactory != null) { MasterPool = new FreeSql.Internal.CommonProvider.DbConnectionPool(DataType.MsAccess, connectionFactory); return; } if (!string.IsNullOrEmpty(masterConnectionString)) MasterPool = new MsAccessConnectionPool("主库", masterConnectionString, null, null); if (slaveConnectionStrings != null) { foreach (var slaveConnectionString in slaveConnectionStrings) { var slavePool = new MsAccessConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); SlavePools.Add(slavePool); } } } public override object AddslashesProcessParam(object param, Type mapType, ColumnInfo mapColumn) { if (param == null) return "NULL"; if (mapType != null && mapType != param.GetType() && (param is IEnumerable == false)) param = Utils.GetDataReaderValue(mapType, param); if (param is bool || param is bool?) return (bool)param ? -1 : 0; else if (param is string || param is char) return string.Concat("'", param.ToString().Replace("'", "''"), "'"); else if (param is Enum) return ((Enum)param).ToInt64(); else if (decimal.TryParse(string.Concat(param), out var trydec)) return param; else if (param is DateTime || param is DateTime?) { if (param.Equals(DateTime.MinValue) == true) param = new DateTime(1970, 1, 1); return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss"), "'"); } else if (param is TimeSpan || param is TimeSpan?) return ((TimeSpan)param).TotalSeconds; else if (param is byte[]) return $"0x{CommonUtils.BytesSqlRaw(param as byte[])}"; else if (param is IEnumerable) return AddslashesIEnumerable(param, mapType, mapColumn); return string.Concat("'", param.ToString().Replace("'", "''"), "'"); } protected override DbCommand CreateCommand() { return new OleDbCommand(); } protected override void ReturnConnection(IObjectPool<DbConnection> pool, Object<DbConnection> conn, Exception ex) { var rawPool = pool as MsAccessConnectionPool; if (rawPool != null) rawPool.Return(conn, ex); else pool.Return(conn); } protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); } }
44.2875
220
0.605701
[ "MIT" ]
damoson/FreeSql
Providers/FreeSql.Provider.MsAccess/MsAccessAdo/MsAccessAdo.cs
3,553
C#
// <auto-generated> // This code was partially generated by a tool. // </auto-generated> namespace YoutubeDLSharp.Options { public partial class OptionSet { private Option<string> username = new Option<string>("-u", "--username"); private Option<string> password = new Option<string>("-p", "--password"); private Option<string> twofactor = new Option<string>("-2", "--twofactor"); private Option<bool> netrc = new Option<bool>("-n", "--netrc"); private Option<string> videoPassword = new Option<string>("--video-password"); /// <summary> /// Login with this account ID /// </summary> public string Username { get => username.Value; set => username.Value = value; } /// <summary> /// Account password. If this option is /// left out, youtube-dl will ask /// interactively. /// </summary> public string Password { get => password.Value; set => password.Value = value; } /// <summary> /// Two-factor authentication code /// </summary> public string TwoFactor { get => twofactor.Value; set => twofactor.Value = value; } /// <summary> /// Use .netrc authentication data /// </summary> public bool Netrc { get => netrc.Value; set => netrc.Value = value; } /// <summary> /// Video password (vimeo, youku) /// </summary> public string VideoPassword { get => videoPassword.Value; set => videoPassword.Value = value; } } }
39.589744
103
0.582902
[ "BSD-3-Clause" ]
2b-creator/YoutubeDLSharp
YoutubeDLSharp/Options/OptionSet.Authentication.cs
1,546
C#
using NUnit.Framework; using Rebus.Tests.Contracts.Activation; namespace Rebus.DryIoc.Tests { [TestFixture] public class DryIocRealContainerTests : RealContainerTests<DryIocContainerAdapterFactory> { } }
20.181818
93
0.77027
[ "MIT" ]
lucasantarelli/rebus
Rebus.DryIoc.Tests/DryIocRealContainerTests.cs
224
C#
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Diagnostics; using System.Windows.Forms; namespace MLifter.AudioTools.Codecs { /// <summary> /// Provides a list of codecs. /// </summary> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public class Codecs : List<Codec>, ICloneable { /// <summary> /// Initializes a new instance of the <see cref="Codecs"/> class. /// </summary> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public Codecs() { this.XMLString = Codecs.DefaultXML; } /// <summary> /// Gets or sets the serialized class as XML string. /// </summary> /// <value>The XML string.</value> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public string XMLString { get { XmlSerializer ser = new XmlSerializer(typeof(List<Codec>)); MemoryStream stream = new MemoryStream(); ser.Serialize(stream, this); byte[] xmlbyte = stream.GetBuffer(); return System.Text.Encoding.Default.GetString(xmlbyte); } set { if (!string.IsNullOrEmpty(value)) { XmlSerializer ser = new XmlSerializer(typeof(List<Codec>)); MemoryStream stream = new MemoryStream(); byte[] xmlbyte = System.Text.Encoding.Default.GetBytes(value); stream.Write(xmlbyte, 0, xmlbyte.Length); stream.Position = 0; List<Codec> codecs = (List<Codec>)ser.Deserialize(stream); this.Clear(); this.AddRange(codecs); } } } /// <summary> /// Gets the codecs which support encoding, sorted by their file extension. /// </summary> /// <value>The encode codecs.</value> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public Dictionary<string, Codec> encodeCodecs { get { Dictionary<string, Codec> codecs = new Dictionary<string, Codec>(); foreach (Codec codec in this) if (codec.CanEncode) codecs.Add(codec.extension.ToLowerInvariant(), codec); return codecs; } } /// <summary> /// Gets the codecs which support decoding, sorted by their file extension. /// </summary> /// <value>The decode codecs.</value> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public Dictionary<string, Codec> decodeCodecs { get { Dictionary<string, Codec> codecs = new Dictionary<string, Codec>(); foreach (Codec codec in this) if (codec.CanDecode) codecs.Add(codec.extension.ToLowerInvariant(), codec); return codecs; } } #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public object Clone() { Codecs clone = new Codecs(); clone.Clear(); foreach (Codec codec in this) clone.Add((Codec)codec.Clone()); return clone; } #endregion /// <summary> /// Gets the default XML. /// </summary> /// <value>The default XML.</value> /// <remarks>Documented by Dev02, 2008-04-15</remarks> public static string DefaultXML { get { return MLifterAudioTools.Properties.Resources.DEFAULT_CODECS_XML; } } } /// <summary> /// This class describes the encoding / decoding facilities required for a defined file format. /// </summary> /// <remarks>Documented by Dev02, 2008-04-10</remarks> [Serializable] public class Codec : ICloneable { /// <summary> /// The file extension, with a leading dot. /// </summary> public string extension; /// <summary> /// The name of this format. /// </summary> public string name; /// <summary> /// The encoding application. /// </summary> public string EncodeApp; /// <summary> /// The arguments for the encoding application. /// </summary> public string EncodeArgs; /// <summary> /// The decoding application. /// </summary> public string DecodeApp; /// <summary> /// The arguments for the decoding application. /// </summary> public string DecodeArgs; /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </returns> /// <remarks>Documented by Dev02, 2008-04-10</remarks> public override string ToString() { return string.Format("{0} (*{1})", this.name, this.extension); } /// <summary> /// Gets a value indicating whether this instance can encode. /// </summary> /// <value> /// <c>true</c> if this instance can encode; otherwise, <c>false</c>. /// </value> /// <remarks>Documented by Dev02, 2008-04-10</remarks> public bool CanEncode { get { return EncodeError == string.Empty; } } /// <summary> /// Sets a value indicating whether this instance can decode. /// </summary> /// <value> /// <c>true</c> if this instance can decode; otherwise, <c>false</c>. /// </value> /// <remarks>Documented by Dev02, 2008-04-10</remarks> public bool CanDecode { get { return DecodeError == string.Empty; } } /// <summary> /// Validates the supplied values. /// </summary> /// <param name="application">The application.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// An error message when invalid or an empty string when valid. /// </returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> private string Validate(string application, string arguments) { string error = string.Empty; bool appvalid = CheckExecutablePath(application); bool argvalid = arguments.Contains("{0}") && arguments.Contains("{1}"); if (!appvalid) error += "Application path not found. "; if (!argvalid) error += "Arguments: Both placeholders are required. "; return error; } /// <summary> /// Validates the encoding values. /// </summary> /// <returns>An error message when invalid or an empty string when valid.</returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public string EncodeError { get { return Validate(EncodeApp, EncodeArgs); } } /// <summary> /// Validates the decoding values. /// </summary> /// <returns>An error message when invalid or an empty string when valid.</returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public string DecodeError { get { return Validate(DecodeApp, DecodeArgs); } } /// <summary> /// Decodes the compressed file to a wavefile. /// </summary> /// <param name="sourcefile">The sourcefile.</param> /// <param name="tempfolder">The tempfolder.</param> /// <param name="showwindow">if set to <c>true</c> [showwindow].</param> /// <param name="minimizewindow">if set to <c>true</c> [minimizewindow].</param> /// <returns>The generated file.</returns> /// <remarks>Documented by Dev02, 2008-03-17</remarks> public FileInfo Decode(FileInfo sourcefile, DirectoryInfo tempfolder, bool showwindow, bool minimizewindow) { FileInfo destfile = new FileInfo(Path.ChangeExtension(Path.Combine(tempfolder.FullName, sourcefile.Name), MLifterAudioTools.Properties.Resources.AUDIO_WAVE_EXTENSION)); return Decode(sourcefile, destfile, showwindow, minimizewindow); } /// <summary> /// Decodes the compressed file to a wavefile. /// </summary> /// <param name="sourcefile">The sourcefile.</param> /// <param name="destfile">The destfile.</param> /// <param name="showwindow">if set to <c>true</c> [showwindow].</param> /// <param name="minimizewindow">if set to <c>true</c> [minimizewindow].</param> /// <returns>The generated file.</returns> /// <remarks>Documented by Dev02, 2008-03-17</remarks> public FileInfo Decode(FileInfo sourcefile, FileInfo destfile, bool showwindow, bool minimizewindow) { StartExternalExe(this.DecodeApp, String.Format(this.DecodeArgs, '"' + sourcefile.FullName + '"', '"' + destfile.FullName + '"'), showwindow, minimizewindow); destfile.Refresh(); if (destfile.Exists) return destfile; else return null; } /// <summary> /// Encodes the wavefile to a compressed file. /// </summary> /// <param name="sourcefile">The sourcefile.</param> /// <param name="tempfolder">The tempfolder.</param> /// <returns>The generated file.</returns> /// <remarks>Documented by Dev02, 2008-03-17</remarks> public FileInfo Encode(FileInfo sourcefile, DirectoryInfo tempfolder, bool showwindow, bool minimizewindow) { FileInfo destfile = new FileInfo(Path.ChangeExtension(Path.Combine(tempfolder.FullName, sourcefile.Name), this.extension)); return Encode(sourcefile, destfile, showwindow, minimizewindow); } /// <summary> /// Encodes the wavefile to a compressed file. /// </summary> /// <param name="sourcefile">The sourcefile.</param> /// <param name="destfile">The destfile.</param> /// <param name="showwindow">if set to <c>true</c> [showwindow].</param> /// <param name="minimizewindow">if set to <c>true</c> [minimizewindow].</param> /// <returns>The generated file.</returns> /// <remarks>Documented by Dev02, 2008-03-17</remarks> public FileInfo Encode(FileInfo sourcefile, FileInfo destfile, bool showwindow, bool minimizewindow) { StartExternalExe(this.EncodeApp, String.Format(this.EncodeArgs, '"' + sourcefile.FullName + '"', '"' + destfile.FullName + '"'), showwindow, minimizewindow); destfile.Refresh(); if (destfile.Exists) return destfile; else return null; } /// <summary> /// Starts an external executable. /// </summary> /// <param name="executable">The executable.</param> /// <param name="parameters">The parameters.</param> /// <param name="showwindow">if set to <c>true</c> [showwindow].</param> /// <param name="minimizewindow">if set to <c>true</c> [minimizewindow].</param> /// <remarks>Documented by Dev02, 2008-03-17</remarks> private static void StartExternalExe(string executable, string parameters, bool showwindow, bool minimizewindow) { FileInfo exe = GetExecutablePath(executable); if (exe != null) { ProcessStartInfo pi = new ProcessStartInfo(); pi.FileName = exe.FullName; pi.WorkingDirectory = exe.Directory.FullName; pi.Arguments = parameters; pi.WindowStyle = showwindow ? (minimizewindow ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal) : ProcessWindowStyle.Hidden; Process externalprocess = Process.Start(pi); externalprocess.WaitForExit(); } } /// <summary> /// Checks the executable path. /// </summary> /// <param name="executable">The executable.</param> /// <returns>The FileInfo, if it is valid, else null.</returns> /// <remarks>Documented by Dev02, 2008-04-10</remarks> private static FileInfo GetExecutablePath(string executable) { if (string.IsNullOrEmpty(executable)) return null; FileInfo exefile; if (Path.IsPathRooted(executable)) exefile = new FileInfo(executable); else exefile = new FileInfo(Path.Combine(Application.StartupPath, executable)); if (!exefile.Exists) exefile = null; return exefile; } /// <summary> /// Checks the executable path. /// </summary> /// <param name="executable">The executable.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-04-10</remarks> public static bool CheckExecutablePath(string executable) { return GetExecutablePath(executable) != null; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false. /// </returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Codec)) return false; return this.Equals((Codec)obj); } /// <summary> /// Equalses the specified codec. /// </summary> /// <param name="codec">The codec.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public bool Equals(Codec codec) { if (codec == null) return false; return this.GetHashCode() == codec.GetHashCode(); } /// <summary> /// Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"></see>. /// </returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public override int GetHashCode() { return this.ToString().GetHashCode(); } #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> /// <remarks>Documented by Dev02, 2008-04-11</remarks> public object Clone() { Codec codec = new Codec(); codec.name = this.name; codec.extension = this.extension; codec.EncodeApp = this.EncodeApp; codec.EncodeArgs = this.EncodeArgs; codec.DecodeApp = this.DecodeApp; codec.DecodeArgs = this.DecodeArgs; return codec; } #endregion } }
39.975057
188
0.552442
[ "MIT" ]
hmehr/OSS
MemoryLifter/Development/Current/MLifter.AudioTools/Codecs/Codec.cs
17,629
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("2PrintCompanyInformation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Toshiba")] [assembly: AssemblyProduct("2PrintCompanyInformation")] [assembly: AssemblyCopyright("Copyright © Toshiba 2015")] [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("0e334bff-b1e0-4f7e-b00d-4bd50707f35c")] // 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")]
38.783784
84
0.751916
[ "MIT" ]
GoranGit/CSharp
Homework/4-Console-In-and-Out/2PrintCompanyInformation/Properties/AssemblyInfo.cs
1,438
C#
using Amazon.CDK; using Amazon.CDK.AWS.IAM; using System.Collections.Generic; namespace MyApp.Modules { public sealed class LambdaBatchExecutionRole: Construct { Construct scope = null; string id = ""; public Role Role {get;set;} public LambdaBatchExecutionRole(Construct scope, string id): base(scope, id) { this.scope = scope; this.id = id; this.Role = GetRole( this, id+"-role", Utilities.ServiceBuilder.GetLambdaBatchExecutionRoleManagedPolicyARNs(), new string[]{ Constants.LAMBDA_BATCH_ROLE_SERVICE }, Constants.LAMBDA_BATCH_POLICY_NAME, new string[]{ "sts:AssumeRole" }, "*" ); } public Role GetRole(Construct scope, string roleId, string[] ManagedPolicyArns, string[] PrincipalServices, string PolicyName, string[] Actions, string resources){ var roleProps = new RoleProps{ Path = "/", AssumedBy = new ServicePrincipal(PrincipalServices[0]) }; if(PrincipalServices.Length > 0){ List<PrincipalBase> principalBases = new List<PrincipalBase>(); foreach(string service in PrincipalServices){ PrincipalBase principalBase = new ServicePrincipal(service); principalBases.Add(principalBase); } var compositePrincipal = new CompositePrincipal(principalBases.ToArray()); roleProps = new RoleProps{ Path = "/", AssumedBy = compositePrincipal }; } var iamRole = new Role(scope, roleId, roleProps); foreach(string arn in ManagedPolicyArns){ iamRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn)); } PolicyStatement policyStatement = new PolicyStatement(new PolicyStatementProps{ Actions = Actions, Resources = new string[]{resources}, Effect = Effect.ALLOW }); iamRole.AddToPolicy(policyStatement); return iamRole; } } }
33.486111
91
0.532974
[ "MIT-0" ]
aws-samples/aws-netcore-app-using-batch
src/MyApp/SourceCode/Modules/LambdaBatchExecutionRole.cs
2,411
C#
using UnityEngine; using System.Collections; public class MyAgent : MonoBehaviour { public GameObject particle; protected UnityEngine.AI.NavMeshAgent agent; protected Animator animator; protected MyLocomotion locomotion; protected Object particleClone; void Start () { agent = GetComponent<UnityEngine.AI.NavMeshAgent>(); agent.updateRotation = false; animator = GetComponent<Animator>(); locomotion = new MyLocomotion(animator); particleClone = null; } protected void SetDestination() { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { // 如果粒子特效实例已经存在,则先销毁之 if (particleClone != null) { GameObject.Destroy(particleClone); particleClone = null; } Quaternion q = new Quaternion(); q.SetLookRotation(hit.normal, Vector3.forward); particleClone = Instantiate(particle, hit.point, q); agent.destination = hit.point; } } protected bool AgentStopping() { return agent.remainingDistance <= agent.stoppingDistance; } protected bool AgentDone() { return !agent.pathPending && AgentStopping(); } void OnAnimatorMove() { agent.velocity = animator.deltaPosition / Time.deltaTime; transform.rotation = animator.rootRotation; } protected void SetupAgentLocomotion() { if (AgentDone()) { locomotion.Do(0, 0); if (particleClone != null) { GameObject.Destroy(particleClone); particleClone = null; } } else { float speed = agent.desiredVelocity.magnitude; Vector3 velocity = Quaternion.Inverse(transform.rotation) * agent.desiredVelocity; float angle = Mathf.Atan2(velocity.x, velocity.z) * Mathf.Rad2Deg; locomotion.Do(speed, angle); } } void Update () { if (Input.GetButtonDown ("Fire1")) SetDestination(); SetupAgentLocomotion(); } void OnGUI() { GUILayout.Label("按鼠标左键选择目标点,然后Teddy熊会寻找过去。"); } }
20.242105
85
0.703068
[ "MIT" ]
Altoid76/Unity3DTraining
MacanimSystem/Macanim_Training/Assets/_Scripts/NavAgent/MyAgent.cs
2,001
C#
using UnityEngine; using XMonoNode; namespace XMonoNode { [CreateNodeMenu("Float/Abs", -189)] [NodeWidth(160)] public class FloatAbs : MonoNode { [Input] public float x; [Output] public float result; private NodePort portX; protected override void Init() { base.Init(); portX = GetInputPort(nameof(x)); GetOutputPort(nameof(result)).label = "|X|"; } public override object GetValue(NodePort port) { return Mathf.Abs(portX.GetInputValue(x)); } } }
21.142857
56
0.5625
[ "MIT" ]
ArtemBelaev-ural/MonoNode
Scripts/FlowNodes/Nodes/Math/Float/FloatAbs.cs
594
C#
namespace NuGetPackageManager.Web { using Catel.Logging; using NuGet.Protocol.Core.Types; using System; using System.Net; public class FatalProtocolExceptionHandler : IHttpExceptionHandler<FatalProtocolException> { private static readonly ILog Log = LogManager.GetCurrentClassLogger(); private static readonly IHttpExceptionHandler<WebException> webExceptionHandler = new HttpWebExceptionHandler(); public FeedVerificationResult HandleException(FatalProtocolException exception, string source) { try { var innerException = exception.InnerException; if (innerException == null) { //handle based on protocol error messages if (exception.HidesUnauthorizedError()) { return FeedVerificationResult.AuthenticationRequired; } if (exception.HidesForbiddenError()) { return FeedVerificationResult.AuthorizationRequired; } } else { if (innerException is WebException) { webExceptionHandler.HandleException(innerException as WebException, source); } } } catch (Exception ex) { Log.Debug(ex, "Failed to verify feed '{0}'", source); } return FeedVerificationResult.Invalid; } } }
32.52
120
0.537515
[ "MIT" ]
Averus-a/NuGetPackageManager
src/NuGetPackageManager/Web/FatalProtocolExceptionHandler.cs
1,628
C#
// Copyright 2016, 2017, 2018 TRUMPF Werkzeugmaschinen GmbH + Co. KG. // // 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. namespace Trumpf.Coparoo.Web { /// <summary> /// Internal interface for root object nodes. /// </summary> internal interface ITabObjectNodeInternal { /// <summary> /// Gets the node locator. /// </summary> INodeLocator NodeLocator { get; } } }
34.518519
75
0.685622
[ "Apache-2.0" ]
NilsEngelbach/Trumpf.Coparoo.Web
Trumpf.Coparoo.Web/Root/TabObject/ITabObjectNodeInternal.cs
934
C#
using System; namespace vlko.core.web.ValidationAtribute { /// <summary> /// Use this attribute to prevent any changes to text. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class AntiXssIgnoreAttribute : Attribute { } }
28
113
0.702381
[ "MIT" ]
vlko/vlko
vlko.core.web/ValidationAtribute/AntiXssIgnoreAttribute.cs
338
C#
using System.Collections.Generic; using Core.Extensions; using NUnit.Framework; namespace Tests.ExtensionTests { [TestFixture] public class ListExtensionTests { [Test] public void CheckEmptyList() { var ints = new List<int>(); ints.NotEmpty().ShouldBeFalse(); ints.Add(12); ints.NotEmpty().ShouldBeTrue(); } } }
21.052632
44
0.595
[ "Apache-2.0" ]
VioletTape/Jackal
Tests/ExtensionTests/ListExtensionTests.cs
402
C#
// // ISkillInfo.cs // // Copyright (c) František Boháček. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using NosSmooth.Data.Abstractions.Enums; using NosSmooth.Data.Abstractions.Language; namespace NosSmooth.Data.Abstractions.Infos; /// <summary> /// The NosTale skill information. /// </summary> public interface ISkillInfo : IVNumInfo { /// <summary> /// Gets the translatable name of the skill. /// </summary> TranslatableString Name { get; } /// <summary> /// Gets the tile range of the skill. /// </summary> short Range { get; } /// <summary> /// Gets the zone tiles range. /// </summary> short ZoneRange { get; } /// <summary> /// Gets the time it takes to cast this skill. Units UNKNOWN TODO. /// </summary> int CastTime { get; } /// <summary> /// Gets the time of the cooldown. Units UNKNOWN TODO. /// </summary> int Cooldown { get; } /// <summary> /// Gets the type of the skill. /// </summary> SkillType SkillType { get; } /// <summary> /// Gets the mana points the skill cast costs. /// </summary> int MpCost { get; } /// <summary> /// Gets the cast id of the skill used in u_s, su packets. /// </summary> short CastId { get; } /// <summary> /// Gets the type of the target. /// </summary> TargetType TargetType { get; } /// <summary> /// Gets the hit type of the skill. /// </summary> HitType HitType { get; } }
23.909091
102
0.597592
[ "MIT" ]
Rutherther/NosSmooth
Data/NosSmooth.Data.Abstractions/Infos/ISkillInfo.cs
1,583
C#
using UnityEngine; public class Singleton<T> : MonoBehaviour where T : Singleton<T> { public static T Instance { get { if (instance == null) { T[] managers = Object.FindObjectsOfType(typeof(T)) as T[]; if (managers.Length != 0) { if (managers.Length == 1) { instance = managers[0]; instance.gameObject.name = typeof(T).Name; return instance; } else { Debug.LogError("Class " + typeof(T).Name + " exists multiple times in violation of singleton pattern. Destroying all copies"); foreach (T manager in managers) { Destroy(manager.gameObject); } } } var go = new GameObject(typeof(T).Name, typeof(T)); instance = go.GetComponent<T>(); DontDestroyOnLoad(go); } return instance; } set { instance = value as T; } } private static T instance; }
20.880952
132
0.599772
[ "MIT" ]
MarcoElz/unity-object-pool
Assets/Scripts/Singleton.cs
877
C#
using System; using System.Collections.Generic; using UIKit; using Foundation; namespace Phoneword_iOS { public partial class ViewController : UIViewController { // translatedNumber was moved here from ViewDidLoad () string translatedNumber = ""; public List<String> PhoneNumbers { get; set; } public ViewController (IntPtr handle) : base (handle) { PhoneNumbers = new List<String> (); } public override void ViewDidLoad () { base.ViewDidLoad (); TranslateButton.TouchUpInside += (object sender, EventArgs e) => { // Convert the phone number with text to a number // using PhoneTranslator.cs translatedNumber = PhonewordTranslator.ToNumber( PhoneNumberText.Text); // Dismiss the keyboard if text field was tapped PhoneNumberText.ResignFirstResponder (); if (translatedNumber == "") { CallButton.SetTitle ("Call ", UIControlState.Normal); CallButton.Enabled = false; } else { CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal); CallButton.Enabled = true; } }; CallButton.TouchUpInside += (object sender, EventArgs e) => { //Store the phone number that we're dialing in PhoneNumbers PhoneNumbers.Add (translatedNumber); var url = new NSUrl ("tel:" + translatedNumber); // Use URL handler with tel: prefix to invoke Apple's Phone app, // otherwise show an alert dialog if (!UIApplication.SharedApplication.OpenUrl (url)) { var alert = UIAlertController.Create ("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert); alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); PresentViewController (alert, true, null); } }; // // Nativation without Segues // - if the segue was deleted from the storyboard, this code would enable the button to open the second view controller // // CallHistoryButton.TouchUpInside += (object sender, EventArgs e) => { // // Launches a new instance of CallHistoryController // CallHistoryController callHistory = this.Storyboard.InstantiateViewController ("CallHistoryController") as CallHistoryController; // if (callHistory != null) { // callHistory.PhoneNumbers = PhoneNumbers; // this.NavigationController.PushViewController (callHistory, true); // } // }; } // // Navigation with Segues // - there is already a segue defined in the storyboard, we use this method to populate it with phone numbers // public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); // set the View Controller that’s powering the screen we’re // transitioning to var callHistoryController = segue.DestinationViewController as CallHistoryController; //set the Table View Controller’s list of phone numbers to the // list of dialed phone numbers if (callHistoryController != null) { callHistoryController.PhoneNumbers = PhoneNumbers; } } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } }
30.980769
139
0.70298
[ "MIT" ]
Art-Lav/ios-samples
Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/ViewController.cs
3,230
C#
/*************************************************************************** * * QuMESHS (Quantum Mesoscopic Electronic Semiconductor Heterostructure * Solver) for calculating electron and hole densities and electrostatic * potentials using self-consistent Poisson-Schroedinger solutions in * layered semiconductors * * Copyright(C) 2015 E. T. Owen and C. H. W. Barnes * * The MIT License (MIT) * * 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. * * For additional information, please contact eto24@cam.ac.uk or visit * <http://www.qumeshs.org> * **************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Solver_Bases; using Solver_Bases.Layers; using System.IO; using CenterSpace.NMath.Core; namespace Solver_GUI { public partial class Solver_GUI : Form { int dimension = 2; Band_Data chem_pot; Band_Data val_pot; SpinResolved_Data car_dens; SpinResolved_Data dop_dens; IExperiment exp1d; Dictionary<string, object> inputs = new Dictionary<string,object>(); public Solver_GUI() { InitializeComponent(); this.dimensionality.SelectedIndex = 1; Update_BandStructure(); this.bandstructureCombo.SelectedIndex = 0; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void dimensionality_SelectedIndexChanged(object sender, EventArgs e) { this.Text = "Solver - " + this.dimensionality.SelectedItem.ToString(); this.dimension = this.dimensionality.SelectedIndex + 1; // check dimensionality to alter inputs if (dimension == 1) { this.nx1Dval.Enabled = false; this.ny1Dval.Enabled = false; } else if (dimension == 2) { this.nx1Dval.Enabled = false; this.ny1Dval.Enabled = true; } else { this.nx1Dval.Enabled = true; this.ny1Dval.Enabled = true; } } private void dftCheck_CheckedChanged(object sender, EventArgs e) { if (!dft1DCheck.Checked) { this.dftnz1Dval.Enabled = false; this.dftzmin1Dval.Enabled = false; } else { this.dftnz1Dval.Enabled = true; this.dftzmin1Dval.Enabled = true; } } private void step_button_Click(object sender, EventArgs e) { dimension = 1; conduction_band.Series["conduction_band_data"].Points.Clear(); conduction_band.Series["valence_band_data"].Points.Clear(); conduction_band.Series["x_data"].Points.Clear(); density.Series["car_dens_data"].Points.Clear(); density.Series["dop_dens_data"].Points.Clear(); density.Series["gphi_data"].Points.Clear(); int nz; int i = int.Parse(count_no_label.Text); if (!int.TryParse(nz1Dval.Text, out nz)) { MessageBox.Show("Format of Nz for dopent potential is invalid"); return; } // initialise dopent experiment if the count is zero if (i == 0) { exp1d = new OneD_ThomasFermiPoisson.Experiment(); car_dens = new SpinResolved_Data(nz); dop_dens = new SpinResolved_Data(nz); Dictionary<string, object> inputs_tmp = Create_Dictionary(); foreach (KeyValuePair<string, object> option in inputs_tmp) inputs.Add(option.Key.Replace("_1d", ""), option.Value); inputs["surface_charge"] = 0.0; inputs["max_iterations"] = 0.0; exp1d.Initialise(inputs); } converged = exp1d.Run(); ILayer[] layers = exp1d.Layers; double dz = exp1d.Dz_Pot; double zmin = exp1d.Zmin_Pot; car_dens = exp1d.Carrier_Density; dop_dens = exp1d.Dopent_Density; Band_Data x = Physics_Base.q_e * exp1d.X; Band_Data gphi = exp1d.GPhi; chem_pot = (Input_Band_Structure.Get_BandStructure_Grid(layers, dz, nz, zmin) - exp1d.Chemical_Potential);// + x); val_pot = (-1.0 * Input_Band_Structure.Get_BandStructure_Grid(layers, dz, nz, zmin) - exp1d.Chemical_Potential);// + x); for (int j = 0; j < chem_pot.Length; j++) { double pos = zmin + dz * j; conduction_band.Series["conduction_band_data"].Points.AddXY(pos, chem_pot[j]); conduction_band.Series["valence_band_data"].Points.AddXY(pos, val_pot[j]); conduction_band.Series["x_data"].Points.AddXY(pos, x[j]); density.Series["car_dens_data"].Points.AddXY(pos, car_dens.Spin_Summed_Data[j]); density.Series["dop_dens_data"].Points.AddXY(pos, dop_dens.Spin_Summed_Data[j]); density.Series["gphi_data"].Points.AddXY(pos, gphi[j]); } Set_Plot_Axes(dens_xmin_val.Text, dens_xmax_val.Text, density.ChartAreas["ChartArea1"].AxisX); Set_Plot_Axes(dens_ymin_val.Text, dens_ymax_val.Text, density.ChartAreas["ChartArea1"].AxisY); Set_Plot_Axes(pot_xmin_val.Text, pot_xmax_val.Text, conduction_band.ChartAreas["ChartArea1"].AxisX); Set_Plot_Axes(pot_ymin_val.Text, pot_ymax_val.Text, conduction_band.ChartAreas["ChartArea1"].AxisY); conduction_band.Refresh(); density.Refresh(); this.count_no_label.Text = (i + 1).ToString(); this.temperature_val_label.Text = exp1d.Current_Temperature.ToString() + " K"; this.carrier_dopent_density_Text.Text = (from val in car_dens.Spin_Summed_Data.vec where val < 0.0 select -1.0e14 * val * dz / Physics_Base.q_e).ToArray().Sum().ToString("e3"); } private void Set_Plot_Axes(string min, string max, System.Windows.Forms.DataVisualization.Charting.Axis axis) { double min_val, max_val; if (min != "") if (!double.TryParse(min, out min_val)) { MessageBox.Show("Error - " + min + " is not a valid format for axis plotting"); } else axis.Minimum = min_val; else axis.Minimum = double.NaN; if (max != "") if (!double.TryParse(max, out max_val)) { MessageBox.Show("Error - " + max + " is not a valid format for axis plotting"); } else axis.Maximum = max_val; else axis.Maximum = double.NaN; } private void refresh_button_Click(object sender, EventArgs e) { inputs = new Dictionary<string, object>(); conduction_band.Series["conduction_band_data"].Points.Clear(); conduction_band.Series["valence_band_data"].Points.Clear(); conduction_band.Series["x_data"].Points.Clear(); density.Series["car_dens_data"].Points.Clear(); density.Series["dop_dens_data"].Points.Clear(); density.Series["gphi_data"].Points.Clear(); System.IO.File.Delete("restart.flag"); count_no_label.Text = "0"; temperature_val_label.Text = "N/A"; } bool converged = false; private void run_button_Click(object sender, EventArgs e) { converged = false; while (!converged) { step_button_Click(sender, e); count_no_label.Refresh(); temperature_val_label.Refresh(); } } private Dictionary<string, object> Create_Dictionary() { Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("nz_1d", double.Parse(nz1Dval.Text)); result.Add("dz_1d", double.Parse(dz1Dval.Text)); result.Add("no_dft_1d", !dft1DCheck.Checked); result.Add("nz_dens_1d", double.Parse(dftnz1Dval.Text)); result.Add("dz_dens_1d", (double)result["dz_1d"]); result.Add("zmin_dens_1d", double.Parse(dftzmin1Dval.Text)); result.Add("T_1d", double.Parse(temperature1Dval.Text)); result.Add("top_V_1d", double.Parse(topV1Dval.Text)); result.Add("bottom_V_1d", double.Parse(bottomV1Dval.Text)); result.Add("tolerance_1d", double.Parse(tolerance1Dval.Text)); result.Add("max_iterations_1d", double.Parse(max_iterations1d_val.Text)); result.Add("use_FlexPDE_1d", false); result.Add("BandStructure_File", bandstructurefilename.Text); return result; } private void addlayer_Button_Click(object sender, EventArgs e) { if (material_combo.SelectedItem == null) return; ListViewItem new_layer = new ListViewItem(new string[] { (string)material_combo.SelectedItem, newlayer_thicknessval.Text, newlayer_xval.Text, newlayer_ndval.Text, newlayer_naval.Text}, -1); // insert layer into listview bandstructure_list.Items.Insert(bandstructureCombo.SelectedIndex + 1, new_layer); Update_BandStructure(); } private void Update_BandStructure() { double thickness = 0.0; // update bandstructure combo list bandstructureCombo.Items.Clear(); for (int i = 0; i < bandstructure_list.Items.Count; i++) { bandstructureCombo.Items.Add(i.ToString() + " " + bandstructure_list.Items[i].Text); if (bandstructure_list.Items[i].SubItems[1].Text != "") thickness += double.Parse(bandstructure_list.Items[i].SubItems[1].Text); } total_thickness_val.Text = thickness.ToString(); dz1Dval.Text = (thickness / double.Parse(nz1Dval.Text)).ToString(); } private void material_combo_SelectedIndexChanged(object sender, EventArgs e) { if ((string)material_combo.SelectedItem == "AlGaAs" || (string)material_combo.SelectedItem == "InGaAs" || (string)material_combo.SelectedItem == "InAlAs") { newlayer_xval.Enabled = true; newlayer_xval.Text = "0.33"; } else { newlayer_xval.Enabled = false; newlayer_xval.Text = ""; } } private void deleteLayer_Button_Click(object sender, EventArgs e) { if ((string)bandstructureCombo.SelectedItem == "surface" || (string)bandstructureCombo.SelectedItem == "substrate") return; bandstructure_list.Items.RemoveAt(bandstructureCombo.SelectedIndex); Update_BandStructure(); } private void editLayer_Button_Click(object sender, EventArgs e) { if (material_combo.SelectedItem == null || bandstructureCombo.SelectedIndex == -1) return; ListViewItem new_layer = new ListViewItem(new string[] { (string)material_combo.SelectedItem, newlayer_thicknessval.Text, newlayer_xval.Text, newlayer_ndval.Text, newlayer_naval.Text}, -1); // insert layer into listview bandstructure_list.Items.Insert(bandstructureCombo.SelectedIndex + 1, new_layer); bandstructure_list.Items.RemoveAt(bandstructureCombo.SelectedIndex); Update_BandStructure(); } private void bandstructure_create_button_Click(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(bandstructurefilename.Text); // create band structure file for (int i = 0; i < bandstructure_list.Items.Count; i++) { string layerstring; ListViewItem item = bandstructure_list.Items[i]; if (bandstructure_list.Items[i].Text == "surface") { sw.WriteLine("surface=true"); continue; } // add material property to layer layerstring = "mat=" + item.SubItems[0].Text; if (item.SubItems[0].Text != "substrate" && item.SubItems[1].Text == "") { MessageBox.Show("Error - thickness of layer " + i.ToString() + " is undefined"); sw.Close(); File.Delete(bandstructurefilename.Text); return; } else if (item.SubItems[0].Text != "substrate") // add thickness to layer layerstring += " t=" + item.SubItems[1].Text; // add alloy composition to layer if (item.SubItems[2].Text != "") layerstring += " x=" + item.SubItems[2].Text; // add donors to layer if (item.SubItems[3].Text != "") layerstring += " Nd=" + item.SubItems[3].Text; // add acceptors to layer if (item.SubItems[4].Text != "") layerstring += " Na=" + item.SubItems[4].Text; sw.WriteLine(layerstring); } sw.Close(); } private void mnuOpenBandStructure_Click(object sender, EventArgs e) { // load the band data from a given file openFileDialog1.InitialDirectory = Environment.CurrentDirectory; openFileDialog1.FileName = bandstructurefilename.Text; openFileDialog1.ShowDialog(); // read data from input file (discarding comment lines and white space) string[] bandstructure = (from line in File.ReadAllLines(openFileDialog1.FileName) where !line.StartsWith("#") && line.Trim().Length != 0 select line).ToArray(); bandstructure_list.Items.Clear(); for (int i = 0; i < bandstructure.Length; i++) { // get the layer data and put it into a dictionary string[] layer_data = bandstructure[i].Split(); Dictionary<string, string> layer_dict = new Dictionary<string, string>(); for (int j = 0; j < layer_data.Length; j++) layer_dict.Add(layer_data[j].Split('=')[0], layer_data[j].Split('=')[1]); string mat = ""; string t = ""; string x = ""; string nd = ""; string na = ""; ListViewItem layer; // check if it is the surface if (layer_dict.ContainsKey("surface")) { layer = new ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "surface", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))))}, -1); layer.UseItemStyleForSubItems = false; } else if (layer_dict["mat"] == "substrate") { if (layer_dict.ContainsKey("Na")) na = layer_dict["Na"]; if (layer_dict.ContainsKey("Nd")) nd = layer_dict["Nd"]; layer = new ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "substrate"), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Control, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)))), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, nd), new System.Windows.Forms.ListViewItem.ListViewSubItem(null, na)}, -1); layer.UseItemStyleForSubItems = false; } else { mat = layer_dict["mat"]; t = layer_dict["t"]; if (layer_dict.ContainsKey("x")) x = layer_dict["x"]; if (layer_dict.ContainsKey("Na")) na = layer_dict["Na"]; if (layer_dict.ContainsKey("Nd")) nd = layer_dict["Nd"]; // or the substrate layer = new ListViewItem(new string[] { mat, t, x, nd, na }); } bandstructure_list.Items.Add(layer); } bandstructure_list.Refresh(); Update_BandStructure(); } } }
45.6875
298
0.553705
[ "MIT" ]
EdmundOwen/QuMESHS
Solver_GUI/Form1.cs
21,201
C#
using System; namespace Neo.VM { [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] internal class OperandSizeAttribute : Attribute { public int Size { get; set; } public int SizePrefix { get; set; } } }
20.833333
67
0.656
[ "MIT" ]
NewEconoLab/neo-devpack-dotnet
src/Neo.SmartContract.Framework/OperandSizeAttribute.cs
250
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace Erato.Model { /// <summary> /// HEF洗净类 /// </summary> [CollectionName("hef")] public class HEF : MongoEntity { /// <summary> /// LotNo /// </summary> [Required] [Display(Name = "LOTNO")] [BsonElement("lotNo")] public string LotNo { get; set; } /// <summary> /// 录入时间 /// </summary> [Display(Name = "录入时间")] [BsonDateTimeOptions(Kind = DateTimeKind.Local)] [BsonElement("operationTime")] public DateTime OperationTime { get; set; } /// <summary> /// 录入人工号 /// </summary> [Display(Name = "录入人工号")] [BsonElement("operator")] public string Operator { get; set; } } }
23.595238
56
0.568113
[ "MIT" ]
robertzml/Erato
Erato.Model/HEF.cs
1,035
C#
namespace CyberCAT.Core.DumpedEnums { public enum gameinteractionsELootVisualiserControlOperation { Locked = 1 } }
15
60
0.8
[ "MIT" ]
Deweh/CyberCAT
CyberCAT.Core/Enums/Dumped Enums/gameinteractionsELootVisualiserControlOperation.cs
120
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Python.Runtime; using System; using System.Collections.Generic; using System.Linq; using NodaTime; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Util; using QuantConnect.Python; namespace QuantConnect.Data { /// <summary> /// Enumerable Subscription Management Class /// </summary> public class SubscriptionManager { private IAlgorithmSubscriptionManager _subscriptionManager; /// <summary> /// Instance that implements <see cref="ISubscriptionDataConfigService" /> /// </summary> public ISubscriptionDataConfigService SubscriptionDataConfigService => _subscriptionManager; /// <summary> /// Returns an IEnumerable of Subscriptions /// </summary> /// <remarks>Will not return internal subscriptions</remarks> public IEnumerable<SubscriptionDataConfig> Subscriptions => _subscriptionManager.SubscriptionManagerSubscriptions.Where(config => !config.IsInternalFeed); /// <summary> /// The different <see cref="TickType" /> each <see cref="SecurityType" /> supports /// </summary> public Dictionary<SecurityType, List<TickType>> AvailableDataTypes => _subscriptionManager.AvailableDataTypes; /// <summary> /// Get the count of assets: /// </summary> public int Count => _subscriptionManager.SubscriptionManagerCount(); /// <summary> /// Add Market Data Required (Overloaded method for backwards compatibility). /// </summary> /// <param name="symbol">Symbol of the asset we're like</param> /// <param name="resolution">Resolution of Asset Required</param> /// <param name="timeZone">The time zone the subscription's data is time stamped in</param> /// <param name="exchangeTimeZone"> /// Specifies the time zone of the exchange for the security this subscription is for. This /// is this output time zone, that is, the time zone that will be used on BaseData instances /// </param> /// <param name="isCustomData">True if this is custom user supplied data, false for normal QC data</param> /// <param name="fillDataForward">when there is no data pass the last tradebar forward</param> /// <param name="extendedMarketHours">Request premarket data as well when true </param> /// <returns> /// The newly created <see cref="SubscriptionDataConfig" /> or existing instance if it already existed /// </returns> public SubscriptionDataConfig Add( Symbol symbol, Resolution resolution, DateTimeZone timeZone, DateTimeZone exchangeTimeZone, bool isCustomData = false, bool fillDataForward = true, bool extendedMarketHours = false ) { //Set the type: market data only comes in two forms -- ticks(trade by trade) or tradebar(time summaries) var dataType = typeof(TradeBar); if (resolution == Resolution.Tick) { dataType = typeof(Tick); } var tickType = LeanData.GetCommonTickTypeForCommonDataTypes(dataType, symbol.SecurityType); return Add(dataType, tickType, symbol, resolution, timeZone, exchangeTimeZone, isCustomData, fillDataForward, extendedMarketHours); } /// <summary> /// Add Market Data Required - generic data typing support as long as Type implements BaseData. /// </summary> /// <param name="dataType">Set the type of the data we're subscribing to.</param> /// <param name="tickType">Tick type for the subscription.</param> /// <param name="symbol">Symbol of the asset we're like</param> /// <param name="resolution">Resolution of Asset Required</param> /// <param name="dataTimeZone">The time zone the subscription's data is time stamped in</param> /// <param name="exchangeTimeZone"> /// Specifies the time zone of the exchange for the security this subscription is for. This /// is this output time zone, that is, the time zone that will be used on BaseData instances /// </param> /// <param name="isCustomData">True if this is custom user supplied data, false for normal QC data</param> /// <param name="fillDataForward">when there is no data pass the last tradebar forward</param> /// <param name="extendedMarketHours">Request premarket data as well when true </param> /// <param name="isInternalFeed"> /// Set to true to prevent data from this subscription from being sent into the algorithm's /// OnData events /// </param> /// <param name="isFilteredSubscription"> /// True if this subscription should have filters applied to it (market hours/user /// filters from security), false otherwise /// </param> /// <param name="dataNormalizationMode">Define how data is normalized</param> /// <returns> /// The newly created <see cref="SubscriptionDataConfig" /> or existing instance if it already existed /// </returns> public SubscriptionDataConfig Add( Type dataType, TickType tickType, Symbol symbol, Resolution resolution, DateTimeZone dataTimeZone, DateTimeZone exchangeTimeZone, bool isCustomData, bool fillDataForward = true, bool extendedMarketHours = false, bool isInternalFeed = false, bool isFilteredSubscription = true, DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted ) { return SubscriptionDataConfigService.Add(symbol, resolution, fillDataForward, extendedMarketHours, isFilteredSubscription, isInternalFeed, isCustomData, new List<Tuple<Type, TickType>> {new Tuple<Type, TickType>(dataType, tickType)}, dataNormalizationMode).First(); } /// <summary> /// Add a consolidator for the symbol /// </summary> /// <param name="symbol">Symbol of the asset to consolidate</param> /// <param name="consolidator">The consolidator</param> public void AddConsolidator(Symbol symbol, IDataConsolidator consolidator) { // Find the right subscription and add the consolidator to it var subscriptions = Subscriptions.Where(x => x.Symbol == symbol).ToList(); if (subscriptions.Count == 0) { // If we made it here it is because we never found the symbol in the subscription list throw new ArgumentException("Please subscribe to this symbol before adding a consolidator for it. Symbol: " + symbol.Value); } foreach (var subscription in subscriptions) { // we need to be able to pipe data directly from the data feed into the consolidator if (IsSubscriptionValidForConsolidator(subscription, consolidator)) { subscription.Consolidators.Add(consolidator); return; } } throw new ArgumentException("Type mismatch found between consolidator and symbol. " + $"Symbol: {symbol.Value} does not support input type: {consolidator.InputType.Name}. " + $"Supported types: {string.Join(",", subscriptions.Select(x => x.Type.Name))}."); } /// <summary> /// Add a custom python consolidator for the symbol /// </summary> /// <param name="symbol">Symbol of the asset to consolidate</param> /// <param name="pyConsolidator">The custom python consolidator</param> public void AddConsolidator(Symbol symbol, PyObject pyConsolidator) { IDataConsolidator consolidator = new DataConsolidatorPythonWrapper(pyConsolidator); AddConsolidator(symbol, consolidator); } /// <summary> /// Removes the specified consolidator for the symbol /// </summary> /// <param name="symbol">The symbol the consolidator is receiving data from</param> /// <param name="consolidator">The consolidator instance to be removed</param> public void RemoveConsolidator(Symbol symbol, IDataConsolidator consolidator) { // remove consolidator from each subscription foreach (var subscription in _subscriptionManager.GetSubscriptionDataConfigs(symbol)) { subscription.Consolidators.Remove(consolidator); } // dispose of the consolidator to remove any remaining event handlers consolidator.DisposeSafely(); } /// <summary> /// Hard code the set of default available data feeds /// </summary> public static Dictionary<SecurityType, List<TickType>> DefaultDataTypes() { return new Dictionary<SecurityType, List<TickType>> { {SecurityType.Base, new List<TickType> {TickType.Trade}}, {SecurityType.Index, new List<TickType> {TickType.Trade}}, {SecurityType.Forex, new List<TickType> {TickType.Quote}}, {SecurityType.Equity, new List<TickType> {TickType.Trade, TickType.Quote}}, {SecurityType.Option, new List<TickType> {TickType.Quote, TickType.Trade, TickType.OpenInterest}}, {SecurityType.FutureOption, new List<TickType> {TickType.Quote, TickType.Trade, TickType.OpenInterest}}, {SecurityType.IndexOption, new List<TickType> {TickType.Quote, TickType.Trade, TickType.OpenInterest}}, {SecurityType.Cfd, new List<TickType> {TickType.Quote}}, {SecurityType.Future, new List<TickType> {TickType.Quote, TickType.Trade, TickType.OpenInterest}}, {SecurityType.Commodity, new List<TickType> {TickType.Trade}}, {SecurityType.Crypto, new List<TickType> {TickType.Trade, TickType.Quote}} }; } /// <summary> /// Get the available data types for a security /// </summary> public IReadOnlyList<TickType> GetDataTypesForSecurity(SecurityType securityType) { return AvailableDataTypes[securityType]; } /// <summary> /// Get the data feed types for a given <see cref="SecurityType" /> <see cref="Resolution" /> /// </summary> /// <param name="symbolSecurityType">The <see cref="SecurityType" /> used to determine the types</param> /// <param name="resolution">The resolution of the data requested</param> /// <param name="isCanonical">Indicates whether the security is Canonical (future and options)</param> /// <returns>Types that should be added to the <see cref="SubscriptionDataConfig" /></returns> public List<Tuple<Type, TickType>> LookupSubscriptionConfigDataTypes( SecurityType symbolSecurityType, Resolution resolution, bool isCanonical ) { return _subscriptionManager.LookupSubscriptionConfigDataTypes(symbolSecurityType, resolution, isCanonical); } /// <summary> /// Sets the Subscription Manager /// </summary> public void SetDataManager(IAlgorithmSubscriptionManager subscriptionManager) { _subscriptionManager = subscriptionManager; } /// <summary> /// Checks if the subscription is valid for the consolidator /// </summary> /// <param name="subscription">The subscription configuration</param> /// <param name="consolidator">The consolidator</param> /// <returns>true if the subscription is valid for the consolidator</returns> public static bool IsSubscriptionValidForConsolidator(SubscriptionDataConfig subscription, IDataConsolidator consolidator) { if (subscription.Type == typeof(Tick) && LeanData.IsCommonLeanDataType(consolidator.OutputType)) { var tickType = LeanData.GetCommonTickTypeForCommonDataTypes( consolidator.OutputType, subscription.Symbol.SecurityType); return subscription.TickType == tickType; } return consolidator.InputType.IsAssignableFrom(subscription.Type); } /// <summary> /// Returns true if the provided data is the default data type associated with it's <see cref="SecurityType"/>. /// This is useful to determine if a data point should be used/cached in an environment where consumers will not provider a data type and we want to preserve /// determinism and backwards compatibility when there are multiple data types available per <see cref="SecurityType"/> or new ones added. /// </summary> /// <remarks>Temporary until we have a dictionary for the default data type per security type see GH issue 4196. /// Internal so it's only accessible from this assembly.</remarks> internal static bool IsDefaultDataType(BaseData data) { switch (data.Symbol.SecurityType) { case SecurityType.Equity: if (data.DataType == MarketDataType.QuoteBar || data.DataType == MarketDataType.Tick && (data as Tick).TickType == TickType.Quote) { return false; } break; } return true; } } }
48.78
165
0.631338
[ "Apache-2.0" ]
3ai-co/Lean
Common/Data/SubscriptionManager.cs
14,634
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; namespace System.Xml.Xsl.Qil { /// <summary> /// View over a Qil StrConcat operator. /// </summary> /// <remarks> /// Don't construct QIL nodes directly; instead, use the <see cref="QilFactory">QilFactory</see>. /// </remarks> internal sealed class QilStrConcat : QilBinary { //----------------------------------------------- // Constructor //----------------------------------------------- /// <summary> /// Construct a new node /// </summary> public QilStrConcat(QilNodeType nodeType, QilNode delimiter, QilNode values) : base(nodeType, delimiter, values) { } //----------------------------------------------- // QilStrConcat methods //----------------------------------------------- /// <summary> /// A string delimiter to insert between successive values of the concatenation /// </summary> public QilNode Delimiter { get { return Left; } set { Left = value; } } /// <summary> /// List of values to concatenate /// </summary> public QilNode Values { get { return Right; } set { Right = value; } } } }
29.2
101
0.476712
[ "MIT" ]
belav/runtime
src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs
1,460
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 shield-2016-06-02.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.Shield.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Shield.Model.Internal.MarshallTransformations { /// <summary> /// DescribeDRTAccess Request Marshaller /// </summary> public class DescribeDRTAccessRequestMarshaller : IMarshaller<IRequest, DescribeDRTAccessRequest> , 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((DescribeDRTAccessRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeDRTAccessRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Shield"); string target = "AWSShield_20160616.DescribeDRTAccess"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-06-02"; request.HttpMethod = "POST"; request.ResourcePath = "/"; var content = "{}"; request.Content = System.Text.Encoding.UTF8.GetBytes(content); return request; } private static DescribeDRTAccessRequestMarshaller _instance = new DescribeDRTAccessRequestMarshaller(); internal static DescribeDRTAccessRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeDRTAccessRequestMarshaller Instance { get { return _instance; } } } }
34.067416
149
0.651055
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Shield/Generated/Model/Internal/MarshallTransformations/DescribeDRTAccessRequestMarshaller.cs
3,032
C#
using SpeedDate.Logging; using SpeedDate.Packets.Rooms; namespace SpeedDate.ClientPlugins.Peer.Room { /// <summary> /// Base class for connectors. /// Connectors should provide means for client to connect /// to game server /// </summary> public abstract class RoomConnector { /// <summary> /// Latest access data. When switching scenes, if this is set, /// connector should most likely try to use this data to connect to game server /// (if the scene is right) /// </summary> private static RoomAccessPacket _accessData; /// <summary> /// Connector instance /// </summary> public static RoomConnector Instance; protected virtual void Awake() { Instance = this; } protected virtual void OnDestroy() { Instance = null; } /// <summary> /// Should try to connect to game server with data, provided /// in the access packet /// </summary> /// <param name="access"></param> public abstract void ConnectToGame(RoomAccessPacket access); #region Static /// <summary> /// Publicly accessible method, which clients should use to connect /// to game servers /// </summary> /// <param name="packet"></param> public static void Connect(RoomAccessPacket packet) { if (Instance == null) { Logs.Error("Failed to connect to game server. No Game Connector was found in the scene"); return; } // Save the access data _accessData = packet; Instance.ConnectToGame(packet); } #endregion } }
27.878788
105
0.543478
[ "MIT" ]
proepkes/SpeedDate
SpeedDate.ClientPlugins.Peer/Room/RoomConnector.cs
1,842
C#
using FluentValidation; using MediatR; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WrldcHrIs.Application.Common.Interfaces; using WrldcHrIs.Core.Entities; namespace WrldcHrIs.Application.CanteenOrders.Queries.GetCanteenOrders { public class GetCanteenOrdersQuery : IRequest<List<CanteenOrder>> { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public class GetCanteenOrdersQueryHandler : IRequestHandler<GetCanteenOrdersQuery, List<CanteenOrder>> { private readonly IAppDbContext _context; public GetCanteenOrdersQueryHandler(IAppDbContext context) { _context = context; } public async Task<List<CanteenOrder>> Handle(GetCanteenOrdersQuery request, CancellationToken cancellationToken) { List<CanteenOrder> res = await _context.CanteenOrders .Where(co => co.OrderDate >= request.StartDate && co.OrderDate <= request.EndDate) .Include(co => co.Customer) .ToListAsync(cancellationToken: cancellationToken); return res; } } } }
35.675
130
0.628591
[ "MIT" ]
nagasudhirpulla/wrldc_hris
src/WrldcHrIs.Application/CanteenOrders/Queries/GetCanteenOrders/GetCanteenOrdersQuery.cs
1,429
C#
using System; using System.Web.Mvc; using System.Web.Routing; using Castle.Windsor; namespace Itaparica.Web.Infra.Container { /// <summary> /// Customização de Controller Factory para tornar o Castle Windsor responsável pelo ciclo de vida de um Controller da aplicação. /// </summary> public class WindsorControllerFactory: DefaultControllerFactory { public IWindsorContainer Container { get; protected set; } public WindsorControllerFactory(IWindsorContainer container) { if (container == null) { throw new ArgumentNullException("Container não configurado."); } Container = container; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { return null; } return Container.Resolve(controllerType) as IController; } public override void ReleaseController(IController controller) { var disposableController = controller as IDisposable; disposableController?.Dispose(); Container.Release(controller); } } }
28.727273
133
0.631329
[ "Unlicense" ]
ricardoborges/Itaparica
src/Itaparica.Web/Infra/Container/WindsorControllerFactory.cs
1,272
C#
// Copyright (c) 2011-2020 Roland Pheasant. All rights reserved. // Roland Pheasant licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; namespace DynamicData.List.Internal { internal sealed class BufferIf<T> { private readonly bool _initialPauseState; private readonly IObservable<bool> _pauseIfTrueSelector; private readonly IScheduler _scheduler; private readonly IObservable<IChangeSet<T>> _source; private readonly TimeSpan _timeOut; public BufferIf(IObservable<IChangeSet<T>> source, IObservable<bool> pauseIfTrueSelector, bool initialPauseState = false, TimeSpan? timeOut = null, IScheduler? scheduler = null) { _source = source ?? throw new ArgumentNullException(nameof(source)); _pauseIfTrueSelector = pauseIfTrueSelector ?? throw new ArgumentNullException(nameof(pauseIfTrueSelector)); _initialPauseState = initialPauseState; _timeOut = timeOut ?? TimeSpan.Zero; _scheduler = scheduler ?? Scheduler.Default; } public IObservable<IChangeSet<T>> Run() { return Observable.Create<IChangeSet<T>>( observer => { var locker = new object(); var paused = _initialPauseState; var buffer = new ChangeSet<T>(); var timeoutSubscriber = new SerialDisposable(); var timeoutSubject = new Subject<bool>(); var bufferSelector = Observable.Return(_initialPauseState).Concat(_pauseIfTrueSelector.Merge(timeoutSubject)).ObserveOn(_scheduler).Synchronize(locker).Publish(); var pause = bufferSelector.Where(state => state).Subscribe( _ => { paused = true; // add pause timeout if required if (_timeOut != TimeSpan.Zero) { timeoutSubscriber.Disposable = Observable.Timer(_timeOut, _scheduler).Select(_ => false).SubscribeSafe(timeoutSubject); } }); var resume = bufferSelector.Where(state => !state).Subscribe( _ => { paused = false; // publish changes and clear buffer if (buffer.Count == 0) { return; } observer.OnNext(buffer); buffer = new ChangeSet<T>(); // kill off timeout if required timeoutSubscriber.Disposable = Disposable.Empty; }); var updateSubscriber = _source.Synchronize(locker).Subscribe( updates => { if (paused) { buffer.AddRange(updates); } else { observer.OnNext(updates); } }); var connected = bufferSelector.Connect(); return Disposable.Create( () => { connected.Dispose(); pause.Dispose(); resume.Dispose(); updateSubscriber.Dispose(); timeoutSubject.OnCompleted(); timeoutSubscriber.Dispose(); }); }); } } }
42.933333
186
0.437001
[ "MIT" ]
1R053/DynamicData
src/DynamicData/List/Internal/BufferIf.cs
4,508
C#
// <auto-generated /> using System; using Clean_Architecture_Task.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Clean_Architecture_Task.Infrastructure.Persistence.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20191024194629_Todos")] partial class Todos { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Clean_Architecture_Task.Domain.Entities.TodoItem", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("Created") .HasColumnType("datetime2"); b.Property<string>("CreatedBy") .HasColumnType("nvarchar(max)"); b.Property<bool>("Done") .HasColumnType("bit"); b.Property<DateTime?>("LastModified") .HasColumnType("datetime2"); b.Property<string>("LastModifiedBy") .HasColumnType("nvarchar(max)"); b.Property<int>("ListId") .HasColumnType("int"); b.Property<string>("Note") .HasColumnType("nvarchar(max)"); b.Property<int>("Priority") .HasColumnType("int"); b.Property<DateTime?>("Reminder") .HasColumnType("datetime2"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("ListId"); b.ToTable("TodoItems"); }); modelBuilder.Entity("Clean_Architecture_Task.Domain.Entities.TodoList", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Colour") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Created") .HasColumnType("datetime2"); b.Property<string>("CreatedBy") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("LastModified") .HasColumnType("datetime2"); b.Property<string>("LastModifiedBy") .HasColumnType("nvarchar(max)"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("TodoLists"); }); modelBuilder.Entity("Clean_Architecture_Task.Infrastructure.Identity.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => { b.Property<string>("UserCode") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("UserCode"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.ToTable("DeviceCodes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("PersistedGrants"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Clean_Architecture_Task.Domain.Entities.TodoItem", b => { b.HasOne("Clean_Architecture_Task.Domain.Entities.TodoList", "List") .WithMany("Items") .HasForeignKey("ListId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Clean_Architecture_Task.Infrastructure.Identity.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Clean_Architecture_Task.Infrastructure.Identity.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Clean_Architecture_Task.Infrastructure.Identity.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Clean_Architecture_Task.Infrastructure.Identity.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.548098
125
0.45883
[ "MIT" ]
zlazel/Clean-Architecture-Task
src/Infrastructure/Persistence/Migrations/20191024194629_Todos.Designer.cs
16,786
C#
using Context.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Context { public class Service { private IDataContextFactory Factory { get; set; } public Service(IDataContextFactory factory) { Factory = factory; } public int AddProduct(string name, decimal price, string category, int stockId) { using (var context = Factory.CreateContext()) { var product = context.Products.Add(new Product { Name = name, Category = category, Price = price, StockId = stockId }); context.SaveChanges(); return product.Id; } } public void DeleteProduct(int id) { using (var context = Factory.CreateContext()) { var product = context.Products.Find(id); context.Products.Remove(product); context.SaveChanges(); } } } }
26.9
88
0.555762
[ "MIT" ]
SlavaUtesinov/EffortInPractice
Context/Service.cs
1,078
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Regression algorithm showcasing adding two futures with the same ticker for different market, related to PR 4328 /// </summary> public class FutureSharingTickerRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 08); SetEndDate(2013, 10, 10); var gold = AddFuture(Futures.Metals.Gold, market: Market.COMEX); gold.SetFilter(0, 182); // this future does not exist just added as an example var gold2 = AddFuture(Futures.Metals.Gold, market: Market.NYMEX); gold2.SetFilter(0, 182); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { foreach (var chain in data.FutureChains) { // find the front contract expiring no earlier than in 90 days var contract = ( from futuresContract in chain.Value.OrderBy(x => x.Expiry) where futuresContract.Expiry > Time.Date.AddDays(90) select futuresContract ).FirstOrDefault(); if (contract != null) { MarketOrder(contract.Symbol, 1); } } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// Data Points count of all timeslices of algorithm /// </summary> public long DataPoints => 135885; /// <summary> /// Data Points count of the algorithm history /// </summary> public int AlgorithmHistoryDataPoints => 0; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "-98.645%"}, {"Drawdown", "5.400%"}, {"Expectancy", "0"}, {"Net Profit", "-3.474%"}, {"Sharpe Ratio", "-68.954"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-1.896"}, {"Beta", "0.058"}, {"Annual Standard Deviation", "0.014"}, {"Annual Variance", "0"}, {"Information Ratio", "-75.062"}, {"Tracking Error", "0.229"}, {"Treynor Ratio", "-16.736"}, {"Total Fees", "$1.85"}, {"Estimated Strategy Capacity", "$93000000.00"}, {"Lowest Capacity Asset", "GC VOFJUCDY9XNH"}, {"Fitness Score", "0.005"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-10.938"}, {"Return Over Maximum Drawdown", "-25.528"}, {"Portfolio Turnover", "0.445"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "c627a8c7156e3ab378f2ab13d21b5737"} }; } }
41.271429
149
0.565247
[ "Apache-2.0" ]
AsquaredXIV/Lean
Algorithm.CSharp/FutureSharingTickerRegressionAlgorithm.cs
5,778
C#
using System; using System.Collections.Generic; using System.Text; namespace fmacias.Components.MVPVMModule { /// <summary> /// Data Access Layer /// </summary> public abstract class DAL : IDAL { protected readonly IDomainModels domainModels; protected readonly IDomainModelFactory domainModelFactory; protected DAL(IDomainModels domainModels, IDomainModelFactory domainModelFactory) { this.domainModels = domainModels; this.domainModelFactory = domainModelFactory; } public IDomainModels DomainModels => domainModels; public IDomainModelFactory DomainModelFactory => domainModelFactory; public IDAL AddModel(IDomainModel Model) { domainModels.Models.Add(Model); return this; } } }
26.25
89
0.666667
[ "BSD-3-Clause" ]
fmacias/FIFO-Task-Queue
Components/MVPVMModule/netstandard2.1/MVPVMModule/DAL.cs
842
C#
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { [PublicAPI] public class TeamCityArtifactDependency : TeamCityDependency { public TeamCityBuildType BuildType { get; set; } public string[] ArtifactRules { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock($"artifacts({BuildType.Id})")) { writer.WriteArray("artifactRules", ArtifactRules); } } } }
26.888889
67
0.662534
[ "MIT" ]
ChaseFlorell/nuke
source/Nuke.Common/CI/TeamCity/Configuration/TeamCityArtifactDependency.cs
726
C#
 namespace CRUD { partial class criar_turma { /// <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(criar_turma)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtNomeT = new System.Windows.Forms.TextBox(); this.cbCurso = new System.Windows.Forms.ComboBox(); this.cbHorario = new System.Windows.Forms.ComboBox(); this.cbMax = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.cbEstado = new System.Windows.Forms.ComboBox(); this.button2 = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.cbDocentes = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label1.Location = new System.Drawing.Point(100, 42); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 20); this.label1.TabIndex = 0; this.label1.Text = "Curso:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label2.Location = new System.Drawing.Point(89, 81); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(70, 20); this.label2.TabIndex = 1; this.label2.Text = "Horario:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label3.Location = new System.Drawing.Point(101, 176); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 20); this.label3.TabIndex = 2; this.label3.Text = "Nome:"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label4.Location = new System.Drawing.Point(8, 117); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(151, 20); this.label4.TabIndex = 3; this.label4.Text = "Máximo de Alunos:"; // // txtNomeT // this.txtNomeT.Enabled = false; this.txtNomeT.Location = new System.Drawing.Point(165, 176); this.txtNomeT.Name = "txtNomeT"; this.txtNomeT.Size = new System.Drawing.Size(177, 20); this.txtNomeT.TabIndex = 4; // // cbCurso // this.cbCurso.FormattingEnabled = true; this.cbCurso.Location = new System.Drawing.Point(165, 44); this.cbCurso.Name = "cbCurso"; this.cbCurso.Size = new System.Drawing.Size(177, 21); this.cbCurso.TabIndex = 5; this.cbCurso.SelectedIndexChanged += new System.EventHandler(this.cbCurso_SelectedIndexChanged); // // cbHorario // this.cbHorario.FormattingEnabled = true; this.cbHorario.Location = new System.Drawing.Point(165, 80); this.cbHorario.Name = "cbHorario"; this.cbHorario.Size = new System.Drawing.Size(177, 21); this.cbHorario.TabIndex = 6; // // cbMax // this.cbMax.FormattingEnabled = true; this.cbMax.Location = new System.Drawing.Point(165, 116); this.cbMax.Name = "cbMax"; this.cbMax.Size = new System.Drawing.Size(68, 21); this.cbMax.TabIndex = 7; // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.button1.Location = new System.Drawing.Point(117, 257); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(88, 37); this.button1.TabIndex = 8; this.button1.Text = "Criar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label5.Location = new System.Drawing.Point(93, 147); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(66, 20); this.label5.TabIndex = 9; this.label5.Text = "Estado:"; // // cbEstado // this.cbEstado.FormattingEnabled = true; this.cbEstado.Location = new System.Drawing.Point(165, 149); this.cbEstado.Name = "cbEstado"; this.cbEstado.Size = new System.Drawing.Size(177, 21); this.cbEstado.TabIndex = 10; // // button2 // this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.button2.Location = new System.Drawing.Point(258, 257); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(88, 37); this.button2.TabIndex = 11; this.button2.Text = "Sair"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.label6.Location = new System.Drawing.Point(82, 203); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(77, 20); this.label6.TabIndex = 12; this.label6.Text = "Docente:"; // // cbDocentes // this.cbDocentes.FormattingEnabled = true; this.cbDocentes.Location = new System.Drawing.Point(165, 202); this.cbDocentes.Name = "cbDocentes"; this.cbDocentes.Size = new System.Drawing.Size(177, 21); this.cbDocentes.TabIndex = 13; // // criar_turma // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(427, 306); this.Controls.Add(this.cbDocentes); this.Controls.Add(this.label6); this.Controls.Add(this.button2); this.Controls.Add(this.cbEstado); this.Controls.Add(this.label5); this.Controls.Add(this.button1); this.Controls.Add(this.cbMax); this.Controls.Add(this.cbHorario); this.Controls.Add(this.cbCurso); this.Controls.Add(this.txtNomeT); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "criar_turma"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "SpaceTech"; this.Load += new System.EventHandler(this.criar_turma_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtNomeT; private System.Windows.Forms.ComboBox cbCurso; private System.Windows.Forms.ComboBox cbHorario; private System.Windows.Forms.ComboBox cbMax; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cbEstado; private System.Windows.Forms.Button button2; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cbDocentes; } }
43.753304
143
0.565546
[ "MIT" ]
ArieleMartins/windows_forms
CRUD/CRUD/criar_turma.designer.cs
9,935
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.TrafficManager.Models; using Microsoft.Azure.Commands.TrafficManager.Utilities; using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources; namespace Microsoft.Azure.Commands.TrafficManager { [Cmdlet(VerbsCommon.Set, "AzureRmTrafficManagerProfile"), OutputType(typeof(TrafficManagerProfile))] public class SetAzureTrafficManagerProfile : TrafficManagerBaseCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The profile.")] [ValidateNotNullOrEmpty] public TrafficManagerProfile TrafficManagerProfile { get; set; } public override void ExecuteCmdlet() { TrafficManagerProfile profile = this.TrafficManagerClient.SetTrafficManagerProfile(this.TrafficManagerProfile); this.WriteVerbose(ProjectResources.Success); this.WriteObject(profile); } } }
45.205128
124
0.667045
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/TrafficManager/Commands.TrafficManager2/Profile/SetAzureTrafficManagerProfile.cs
1,727
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("Exercise")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Exercise")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("8a775f21-ee92-49cd-b93f-a53a995cfec2")] // 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.405405
84
0.746387
[ "MIT" ]
BorisLechev/Programming-Basics
Documents/Github/Programming-Fundamentals/Exams/09.07.2017FundamentalsExam/Exercise/Properties/AssemblyInfo.cs
1,387
C#
/** * Copyright (c) 2001-2017 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/epl-v10.html */ using System; using System.Drawing; using Robocode; using Robocode.Util; namespace SampleCs { /// <summary> /// Interactive - a sample robot by Flemming N. Larsen. /// <p/> /// This is a robot that is controlled using the arrow keys and mouse only. /// <p/> /// Keys: /// - Arrow up: Move forward /// - Arrow down: Move backward /// - Arrow right: Turn right /// - Arrow left: Turn left /// Mouse: /// - Moving: Moves the aim, which the gun will follow /// - Wheel up: Move forward /// - Wheel down: Move backward /// - Button 1: Fire a bullet with power = 1 /// - Button 2: Fire a bullet with power = 2 /// - Button 3: Fire a bullet with power = 3 /// <p/> /// The bullet color depends on the Fire power: /// - Power = 1: Yellow /// - Power = 2: Orange /// - Power = 3: Red /// <p/> /// Note that the robot will continue firing as long as the mouse button is /// pressed down. /// <p/> /// By enabling the "Paint" button on the robot console window for this robot, /// a cross hair will be painted for the robots current aim (controlled by the /// mouse). /// </summary> public class Interactive : AdvancedRobot { // Move direction: 1 = move forward, 0 = stand still, -1 = move backward private int moveDirection; // Turn direction: 1 = turn right, 0 = no turning, -1 = turn left private int turnDirection; // Amount of pixels/units to move private double moveAmount; // The coordinate of the aim (x,y) private int aimX, aimY; // Fire power, where 0 = don't Fire private int firePower; // Called when the robot must run public override void Run() { // Sets the colors of the robot // body = black, gun = white, radar = red SetColors(Color.Black, Color.White, Color.Red); // Loop forever for (;;) { // Sets the robot to move forward, backward or stop moving depending // on the move direction and amount of pixels to move SetAhead(moveAmount*moveDirection); // Decrement the amount of pixels to move until we reach 0 pixels // This way the robot will automatically stop if the mouse wheel // has stopped it's rotation moveAmount = Math.Max(0, moveAmount - 1); // Sets the robot to turn right or turn left (at maximum speed) or // stop turning depending on the turn direction SetTurnRight(45*turnDirection); // degrees // Turns the gun toward the current aim coordinate (x,y) controlled by // the current mouse coordinate double angle = Utils.NormalAbsoluteAngle(Math.Atan2(aimX - X, aimY - Y)); SetTurnGunRightRadians(Utils.NormalRelativeAngle(angle - GunHeadingRadians)); // Fire the gun with the specified Fire power, unless the Fire power = 0 if (firePower > 0) { SetFire(firePower); } // Execute all pending set-statements Execute(); // Next turn is processed in this loop.. } } // Called when a key has been pressed public override void OnKeyPressed(KeyEvent e) { switch (e.KeyCode) { case Keys.VK_UP: // Arrow up key: move direction = forward (infinitely) moveDirection = 1; moveAmount = Double.PositiveInfinity; break; case Keys.VK_DOWN: // Arrow down key: move direction = backward (infinitely) moveDirection = -1; moveAmount = Double.PositiveInfinity; break; case Keys.VK_RIGHT: // Arrow right key: turn direction = right turnDirection = 1; break; case Keys.VK_LEFT: // Arrow left key: turn direction = left turnDirection = -1; break; } } // Called when a key has been released (after being pressed) public override void OnKeyReleased(KeyEvent e) { switch (e.KeyCode) { case Keys.VK_UP: case Keys.VK_DOWN: // Arrow up and down keys: move direction = stand still moveDirection = 0; moveAmount = 0; break; case Keys.VK_RIGHT: case Keys.VK_LEFT: // Arrow right and left keys: turn direction = stop turning turnDirection = 0; break; } } // Called when the mouse wheel is rotated public override void OnMouseWheelMoved(MouseWheelMovedEvent e) { // If the wheel rotation is negative it means that it is moved forward. // Set move direction = forward, if wheel is moved forward. // Otherwise, set move direction = backward moveDirection = (e.WheelRotation < 0) ? 1 : -1; // Set the amount to move = absolute wheel rotation amount * 5 (speed) // Here 5 means 5 pixels per wheel rotation step. The higher value, the // more speed moveAmount += Math.Abs(e.WheelRotation)*5; } // Called when the mouse has been moved public override void OnMouseMoved(MouseEvent e) { // Set the aim coordinate = the mouse pointer coordinate aimX = e.X; aimY = e.Y; } // Called when a mouse button has been pressed public override void OnMousePressed(MouseEvent e) { if (e.Button == Keys.BUTTON3) { // Button 3: Fire power = 3 energy points, bullet color = red firePower = 3; BulletColor = (Color.Red); } else if (e.Button == Keys.BUTTON2) { // Button 2: Fire power = 2 energy points, bullet color = orange firePower = 2; BulletColor = (Color.Orange); } else { // Button 1 or unknown button: // Fire power = 1 energy points, bullet color = yellow firePower = 1; BulletColor = (Color.Yellow); } } // Called when a mouse button has been released (after being pressed) public override void OnMouseReleased(MouseEvent e) { // Fire power = 0, which means "don't Fire" firePower = 0; } // Called in order to paint graphics for this robot. // "Paint" button on the robot console window for this robot must be // enabled in order to see the paintings. public override void OnPaint(IGraphics g) { // Draw a red cross hair with the center at the current aim // coordinate (x,y) g.DrawEllipse(Pens.Red, aimX - 15, aimY - 15, 30, 30); g.DrawLine(Pens.Red, aimX, aimY - 4, aimX, aimY + 4); g.DrawLine(Pens.Red, aimX - 4, aimY, aimX + 4, aimY); } } }
36.394495
93
0.531258
[ "Apache-2.0" ]
WernerStruis/Naval-Robocode-Source
plugins/dotnet/robocode.dotnet.samples/src/SampleCs/Interactive.cs
7,934
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Threading; using System.Threading.Tasks; using MasterPatientIndex.Structures; using Serilog; using Serilog.Core; namespace MasterPatientIndex.ProbabilisticMPI { public class MatchEngine { private static IMpiConfiguration _mpiConfiguration; private readonly bool _mpiTraceEnabled = false; protected static readonly Logger Logger = new LoggerConfiguration().CreateLogger(); protected static readonly Logger MPIMatchLogger = new LoggerConfiguration().CreateLogger(/*"MPIMatchLogger"*/); protected static readonly Logger MPINoMatchLogger = new LoggerConfiguration().CreateLogger(/*"MPINoMatchLogger"*/); public MatchEngine(IMpiConfiguration configurationEngine) { _mpiConfiguration = configurationEngine; } public List<MPIMatchRecord> FindMatches (SearchVector searchVector, IList<SearchVector> candidates) { if (_mpiTraceEnabled) MPIMatchLogger.Verbose("Compared {0} candidates to {1}", candidates.Count, Describe(searchVector)); //setup parallelism var maxDegreeOfParallelism = 1; ThreadPool.SetMinThreads(maxDegreeOfParallelism, maxDegreeOfParallelism); var options = new ParallelOptions{MaxDegreeOfParallelism = maxDegreeOfParallelism}; //compare search vector against each candidate vector and calculate match score for each candidate var allMatchRecords = candidates.AsParallel() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .WithDegreeOfParallelism(options.MaxDegreeOfParallelism) .Select(c => GetCandidateMatchRecord(searchVector, c)) .ToList(); allMatchRecords = SetConfidenceLevels(allMatchRecords); //consider only medium and high confidence matches var matchResults = allMatchRecords.Where(m => m.MatchConfidenceLevel != MPIConfidenceLevelLookup.Low).ToList(); if (matchResults.Any()) { if (!_mpiTraceEnabled) return matchResults; var highMatches = allMatchRecords.Where(r => r.MatchConfidenceLevel != MPIConfidenceLevelLookup.High).ToList(); MPIMatchLogger.Information("{0} High confidence matches:", highMatches.Count); foreach (var hm in highMatches) { MPIMatchLogger.Information("TotalScore: {0}, IdentifierScores: {1}", hm.TotalMatchScore, Describe(hm.MatchVector)); } var mediumMatches = allMatchRecords.Where(r => r.MatchConfidenceLevel != MPIConfidenceLevelLookup.Medium).ToList(); MPIMatchLogger.Information("{0} Medium confidence matches:", mediumMatches.Count); foreach (var mm in mediumMatches) { MPIMatchLogger.Information("TotalScore: {0}, IdentifierScores: {1}", mm.TotalMatchScore,Describe(mm.MatchVector)); } return matchResults; } if (_mpiTraceEnabled) MPINoMatchLogger.Verbose(Describe(searchVector), searchVector); return matchResults; } private static MPIMatchRecord GetCandidateMatchRecord(SearchVector searchVector, SearchVector candidateVector) { //get list of identifier values for candidate //compare every element search vector to corresponding element in candidate vector var candidateMatchScores = searchVector.Identifiers.Select(sve => GetIdentifierScore(sve, candidateVector.GetIdentifierByName(sve.IdentifierName))) .ToList(); return new MPIMatchRecord { //TODO: MatchedAcuperaId = candidate.AcuperaId, MatchType = "Probabilistic", MatchVector = candidateMatchScores, }; } private static MPIIdentifier GetIdentifierScore (MPIIdentifier incoming, MPIIdentifier existing) { Contract.Requires(_mpiConfiguration != null && incoming != null && existing != null); if (IsNullEmptyOrUnknown(incoming.Value) || IsNullEmptyOrUnknown(existing.Value)) { //can't compare so return 0 (identifier has no bearing on match score) return new MPIIdentifier { IdentifierName = existing.IdentifierName, Score = 0, Value = existing.Value, }; } //get weights for this identifier //TODO: var weightRecord = _mpiConfiguration.IdentifierMatchWeights.First(w => w.Key.Equals(incoming.Identifier)).Value; var weightRecord = new MPIIdentifierWeight { Identifier = incoming.IdentifierName, MatchWeight = 1, NonMatchWeight = -1, }; //default to no match double identifierScore; //use fuzzy matching to determine how similar search vector is to candidate vector var similarityScore = GetSimilarityScore(incoming.IdentifierName, incoming, existing); if (similarityScore == 0) { identifierScore = weightRecord.NonMatchWeight; } else if (similarityScore == 1) { identifierScore = weightRecord.MatchWeight; } else { //if strings are neither identical nor different, adjust match weight by degree of similarity (0 to 1) identifierScore = weightRecord.MatchWeight * similarityScore; } return new MPIIdentifier { IdentifierName = existing.IdentifierName, Value = existing.Value, Score = identifierScore }; } private static bool IsNullEmptyOrUnknown(object identifierValue) { return (identifierValue == null || string.IsNullOrEmpty(identifierValue.ToString()) || identifierValue.ToString().Equals("Unknown", StringComparison.OrdinalIgnoreCase)); } //Min: 0 Max: 1 private static double GetSimilarityScore(string identifier, MPIIdentifier incoming, MPIIdentifier existing) { var incomingValue = incoming.Value; var existingValue = existing.Value; // if either vector elements have null values, treat as non match if (incomingValue == null || existingValue == null) return 0; switch (incoming.MatchType) { case MatchType.StringMatchUsingJaroDistance: return CompareStringsUsingJaro(incomingValue, existingValue); case MatchType.DateMatch: return CompareDates(incomingValue, existingValue); case MatchType.GenderMatch: return CompareGenders(incomingValue, existingValue); } return 0; } private static double CompareGenders(object incomingValue, object existingValue) { Contract.Requires(incomingValue != null & existingValue != null); var incomingGender = (GenderLookup) Enum.Parse(typeof (GenderLookup), incomingValue.ToString(), true); var existingGender = (GenderLookup) Enum.Parse(typeof (GenderLookup), existingValue.ToString(), true); return incomingGender == existingGender ? 1 : 0; } private static double CompareStringsUsingJaro(object incoming, object existing) { //if either value is empty, we can't determine match or non-match var incomingStr = ((string) incoming); var existingStr = ((string) existing); if (string.IsNullOrEmpty(incomingStr) || string.IsNullOrEmpty(existingStr)) return 0; //return Convert.Todouble(GetSimilarityFromDistance(incomingStr.ToUpper(), existingStr.ToUpper())); return Convert.ToDouble(incomingStr.JaroDistance(existingStr)); } private static double CompareDates(object incoming, object existing) { DateTime incomingDate; DateTime existingDate; if (!DateTime.TryParse(incoming.ToString(), out incomingDate) || !DateTime.TryParse(existing.ToString(), out existingDate)) return 0; //TODO: check for transpositions in birth month and day //what other type of "fuzzy" checks can be done on dates? return DateTime.Compare(incomingDate, existingDate) == 0 ? 1 : 0; } private static List<MPIMatchRecord> SetConfidenceLevels(List<MPIMatchRecord> matchResults) { var updatedResults = matchResults; foreach (var matchRecord in updatedResults) { if (matchRecord.TotalMatchScore > _mpiConfiguration.HighConfidenceMatchThreshold) matchRecord.MatchConfidenceLevel = MPIConfidenceLevelLookup.High; else if (matchRecord.TotalMatchScore > _mpiConfiguration.MediumConfidenceMatchThreshold) matchRecord.MatchConfidenceLevel = MPIConfidenceLevelLookup.Medium; else matchRecord.MatchConfidenceLevel = MPIConfidenceLevelLookup.Low; } if (updatedResults.Count(r => r.MatchConfidenceLevel == MPIConfidenceLevelLookup.High) <= 1) return updatedResults; //if we get multiple matches with HIGH confidence, //make them all MEDIUM since we can't auto-merge in that case foreach (var mr in updatedResults.Where(r => r.MatchConfidenceLevel == MPIConfidenceLevelLookup.High)) { mr.MatchConfidenceLevel = MPIConfidenceLevelLookup.Medium; } return updatedResults; } #if(false) private static double GetSimilarityFromDistance(string incoming, string existing) { if ((incoming.Any(char.IsLetter) && !(existing.Any(char.IsLetter))) || (existing.Any(char.IsLetter) && !(incoming.Any(char.IsLetter)))) return 0; var distance = incoming.LevenshteinDistance(existing); if (distance == 0) return 1; var maxDistance = incoming.Length >= existing.Length ? incoming.Length : existing.Length; var normalizedDistance = (double)distance / maxDistance; var similarity = 1 - normalizedDistance; return similarity; } #endif private object Describe(List<MPIIdentifier> hmMatchVector) { return string.Empty; } private static string Describe(SearchVector vector) { return string.Empty; // TODO: return vector.Aggregate(string.Empty, (current, ve) => current + $"{ve.Identifier}, {ve.Value}, {ve.Score}"); } public double TestJaroWinkler(string incoming, string existing) { return Convert.ToDouble(incoming.JaroDistance(existing)); } public double TestJaro(string incoming, string existing) { return Convert.ToDouble(incoming.JaroDistance(existing)); } #if(false) public double TestLevenshtein(string incoming, string existing) { return Convert.Todouble(incoming.LevenshteinDistance(existing)); } public double TestNormalizedLevenshtein(string incoming, string existing) { var distance = incoming.LevenshteinDistance(existing); if (distance == 0) return 1; var hammingDistance = incoming.HammingDistance(existing); var distanceNormalized = distance/hammingDistance; var similarity = 1 - distanceNormalized; return Convert.Todouble(similarity); } #endif } public class MPIIdentifierWeight { public string Identifier { get; set; } public double MatchWeight { get; set; } public double NonMatchWeight { get; set; } } }
43.110727
135
0.616984
[ "Apache-2.0" ]
HealthCatalyst/Fabric.MasterPatientIndex
MasterPatientIndex/ProbabilisticMPI/MatchEngine.cs
12,461
C#
/* MIT License Copyright (c) 2018 Jacques Kang Copyright (c) 2021 Pierre Sprimont 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 Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace WinCopies.IPCService.Hosting { public sealed class BackgroundService : Microsoft.Extensions.Hosting.BackgroundService { private readonly IEnumerable<IEndpoint> _endpoints; private readonly ILogger<BackgroundService> _logger; public BackgroundService(IEnumerable<IEndpoint> endpoints, ILogger<BackgroundService> logger) { _endpoints = endpoints ?? throw new System.ArgumentNullException(nameof(endpoints)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); } protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.WhenAll(_endpoints.Select(x => x.ExecuteAsync(stoppingToken))); public override void Dispose() { foreach (IEndpoint endpoint in _endpoints) endpoint.Dispose(); base.Dispose(); _logger.LogInformation(Properties.Resources.IPCBackgroundServiceDisposed); } } }
39.508772
149
0.752664
[ "MIT" ]
pierresprim/IpcServiceFramework
src/WinCopies.IPCService.Hosting/BackgroundService.cs
2,254
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; using Olo42.SAROM.WebApp.Models; namespace Olo42.SAROM.WebApp.Controllers { public class UnitsController : Controller { private readonly OperationContext _context; public UnitsController(OperationContext context) { _context = context; } // GET: Units public async Task<IActionResult> Index(string id) { ViewBag.OperationId = id; return View(await _context.Unit .OrderBy(u => u.Name) .Where(u => u.OperationId == id) .ToListAsync()); } // GET: Units/Details/5 public async Task<IActionResult> Details(string id) { if (id == null) { return NotFound(); } var unit = await _context.Unit .FirstOrDefaultAsync(m => m.Id == id); if (unit == null) { return NotFound(); } ViewBag.OperationId = unit.OperationId; return View(unit); } // GET: Units/Create public IActionResult Create(string id) { ViewBag.OperationId = id; return View(); } // POST: Units/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Name,GroupLeader,PagerNumber,OperationId,AreaSeeker,DebrisSearcher,WaterLocators,Mantrailer,Helpers")] Unit unit) { if (ModelState.IsValid) { _context.Add(unit); await _context.SaveChangesAsync(); OperationActionsController operationActionsController = new OperationActionsController(_context); await operationActionsController.Create(unit.OperationId, "Einheit eingetroffen / erfasst", unit.Name); // TODO: I18n return RedirectToAction(nameof(Index), new { id = unit.OperationId }); } return View(unit); } // GET: Units/Edit/5 public async Task<IActionResult> Edit(string id) { if (id == null) { return NotFound(); } var unit = await _context.Unit.FindAsync(id); if (unit == null) { return NotFound(); } ViewBag.OperationId = unit.OperationId; return View(unit); } // POST: Units/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(string id, [Bind("GroupLeader,Id,OperationId,Name,PagerNumber,AreaSeeker,DebrisSearcher,WaterLocators,Mantrailer,Helpers")] Unit unit) { if (id != unit.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(unit); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UnitExists(unit.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index), new { id = unit.OperationId }); } return View(unit); } // GET: Units/Delete/5 public async Task<IActionResult> Delete(string id) { if (id == null) { return NotFound(); } var unit = await _context.Unit .FirstOrDefaultAsync(m => m.Id == id); if (unit == null) { return NotFound(); } return View(unit); } // POST: Units/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(string id) { var unit = await _context.Unit.FindAsync(id); _context.Unit.Remove(unit); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool UnitExists(string id) { return _context.Unit.Any(e => e.Id == id); } } }
25.402439
176
0.609217
[ "MIT" ]
olo42/SAROM
WebApp/Controllers/UnitsController.cs
4,168
C#
namespace Stripe.Sigma { using System; using Newtonsoft.Json; using Stripe.Infrastructure; public class ScheduledQueryRun : StripeEntity<ScheduledQueryRun>, IHasId, IHasObject { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object’s type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } /// <summary> /// Time at which the object was created. Measured in seconds since the Unix epoch. /// </summary> [JsonProperty("created")] [JsonConverter(typeof(DateTimeConverter))] public DateTime Created { get; set; } /// <summary> /// When the query was run, Sigma contained a snapshot of your Stripe data at this time. /// </summary> [JsonProperty("data_load_time")] [JsonConverter(typeof(DateTimeConverter))] public DateTime DataLoadTime { get; set; } /// <summary> /// If the query run was not successful, this field contains information about the failure. /// </summary> [JsonProperty("error")] public ScheduledQueryRunError Error { get; set; } /// <summary> /// The file object representing the results of the query. /// </summary> [JsonProperty("file")] public File File { get; set; } /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value /// <c>false</c> if the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// Time at which the result expires and is no longer available for download. /// </summary> [JsonProperty("result_available_until")] [JsonConverter(typeof(DateTimeConverter))] public DateTime ResultAvailableUntil { get; set; } /// <summary> /// SQL for the query. /// </summary> [JsonProperty("sql")] public string Sql { get; set; } /// <summary> /// The query’s execution status, which will be <c>completed</c> for successful runs, and /// <c>canceled</c>, <c>failed</c>, or <c>timed_out</c> otherwise. /// </summary> [JsonProperty("status")] public string Status { get; set; } /// <summary> /// Title of the query. /// </summary> [JsonProperty("title")] public string Title { get; set; } } }
33.506173
99
0.569639
[ "Apache-2.0" ]
Loyalar/stripe-dotnet
src/Stripe.net/Entities/Sigma/ScheduledQueryRuns/ScheduledQueryRun.cs
2,718
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; namespace Dapplo.Confluence.Query { /// <summary> /// A clause for content identifying values like ancestor, content, id and parent /// </summary> internal class ContentClause : IContentClause { private readonly Fields[] _allowedFields = { Fields.Ancestor, Fields.Content, Fields.Id, Fields.Parent }; private readonly Clause _clause; private bool _negate; internal ContentClause(Fields contentField) { if (_allowedFields.All(field => contentField != field)) { throw new InvalidOperationException($"Can't add function for the field {contentField}"); } _clause = new Clause { Field = contentField }; } /// <inheritDoc /> public IContentClause Not { get { _negate = !_negate; return this; } } /// <inheritDoc /> public IFinalClause Is(long value) { _clause.Operator = Operators.EqualTo; _clause.Value = value.ToString(); if (_negate) { _clause.Negate(); } return _clause; } /// <inheritDoc /> public IFinalClause InRecentlyViewedContent(int limit, int offset = 0) { _clause.Operator = Operators.In; var skip = offset != 0 ? $",{offset}" : ""; _clause.Value = $"recentlyViewedContent({limit}{skip})"; if (_negate) { _clause.Negate(); } return _clause; } /// <inheritDoc /> public IFinalClause In(params long[] values) { _clause.Operator = Operators.In; _clause.Value = "(" + string.Join(", ", values) + ")"; if (_negate) { _clause.Negate(); } return _clause; } } }
28.101266
113
0.50991
[ "MIT" ]
DannySotzny/Dapplo.Confluence
src/Dapplo.Confluence/Query/ContentClause.cs
2,222
C#
//------------------------------------------------------------------------------ // <auto-generated> // Generated by the MSBuild WriteCodeFragment class. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Milka")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Milka")] [assembly: System.Reflection.AssemblyTitleAttribute("Milka")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
45.647059
80
0.632732
[ "MIT" ]
Jankowsky/.NetCoreMvc_Blog
Milka/obj/Release/netcoreapp2.1/Milka.AssemblyInfo.cs
776
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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Globalization { internal sealed partial class CultureData { // Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned // data as either and Int or string. internal static unsafe string? GetLocaleInfoEx(string localeName, uint field) { // REVIEW: Determine the maximum size for the buffer const int BUFFER_SIZE = 530; char* pBuffer = stackalloc char[BUFFER_SIZE]; int resultCode = GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE); if (resultCode > 0) { return new string(pBuffer); } return null; } internal static unsafe int GetLocaleInfoExInt(string localeName, uint field) { field |= Interop.Kernel32.LOCALE_RETURN_NUMBER; int value = 0; GetLocaleInfoEx(localeName, field, (char*)&value, sizeof(int)); return value; } internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData); } private string NlsGetLocaleInfo(LocaleStringData type) { Debug.Assert(ShouldUseUserOverrideNlsData); Debug.Assert(_sRealName != null, "[CultureData.DoGetLocaleInfo] Expected _sRealName to be populated by already"); return NlsGetLocaleInfo(_sRealName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string NlsGetLocaleInfo(string localeName, LocaleStringData type) { Debug.Assert(ShouldUseUserOverrideNlsData); uint lctype = (uint)type; return GetLocaleInfoFromLCType(localeName, lctype, _bUseOverrides); } private int NlsGetLocaleInfo(LocaleNumberData type) { Debug.Assert(IsWin32Installed); uint lctype = (uint)type; // Fix lctype if we don't want overrides if (!_bUseOverrides) { lctype |= Interop.Kernel32.LOCALE_NOUSEROVERRIDE; } // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. Debug.Assert(_sRealName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sRealName to be populated by already"); return GetLocaleInfoExInt(_sRealName, lctype); } private int[] NlsGetLocaleInfo(LocaleGroupingData type) { Debug.Assert(ShouldUseUserOverrideNlsData); Debug.Assert(_sRealName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sRealName to be populated by already"); return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sRealName, (uint)type, _bUseOverrides)); } internal static bool NlsIsEnsurePredefinedLocaleName(string name) { Debug.Assert(GlobalizationMode.UseNls); return CultureData.GetLocaleInfoExInt(name, Interop.Kernel32.LOCALE_ICONSTRUCTEDLOCALE) != 1; } private string? NlsGetTimeFormatString() { Debug.Assert(ShouldUseUserOverrideNlsData); Debug.Assert(_sRealName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sRealName to be populated by already"); return ReescapeWin32String(GetLocaleInfoFromLCType(_sRealName, Interop.Kernel32.LOCALE_STIMEFORMAT, _bUseOverrides)); } private int NlsGetFirstDayOfWeek() { Debug.Assert(ShouldUseUserOverrideNlsData); Debug.Assert(_sRealName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sRealName to be populated by already"); int result = GetLocaleInfoExInt(_sRealName, Interop.Kernel32.LOCALE_IFIRSTDAYOFWEEK | (!_bUseOverrides ? Interop.Kernel32.LOCALE_NOUSEROVERRIDE : 0)); // Win32 and .NET disagree on the numbering for days of the week, so we have to convert. return ConvertFirstDayOfWeekMonToSun(result); } // Enumerate all system cultures and then try to find out which culture has // region name match the requested region name private static CultureData? NlsGetCultureDataFromRegionName(string regionName) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); Debug.Assert(regionName != null); EnumLocaleData context; context.cultureName = null; context.regionName = regionName; unsafe { Interop.Kernel32.EnumSystemLocalesEx(&EnumSystemLocalesProc, Interop.Kernel32.LOCALE_SPECIFICDATA | Interop.Kernel32.LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero); } if (context.cultureName != null) { // we got a matched culture return GetCultureData(context.cultureName, true); } return null; } private string NlsGetLanguageDisplayName(string cultureName) { Debug.Assert(GlobalizationMode.UseNls); // Usually the UI culture shouldn't be different than what we got from WinRT except // if DefaultThreadCurrentUICulture was set CultureInfo? ci; if (CultureInfo.DefaultThreadCurrentUICulture != null && ((ci = CultureInfo.GetUserDefaultCulture()) != null) && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name)) { return NativeName; } else { return NlsGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } } private string NlsGetRegionDisplayName() { Debug.Assert(GlobalizationMode.UseNls); // If the current UI culture matching the OS UI language, we'll get the display name from the OS. // otherwise, we use the native name as we don't carry resources for the region display names anyway. if (CultureInfo.CurrentUICulture.Name.Equals(CultureInfo.UserDefaultUICulture.Name)) { return NlsGetLocaleInfo(LocaleStringData.LocalizedCountryName); } return NativeCountryName; } // PAL methods end here. private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOverride) { Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); // Fix lctype if we don't want overrides if (!useUserOverride) { lctype |= Interop.Kernel32.LOCALE_NOUSEROVERRIDE; } // Ask OS for data // Failed? Just use empty string return GetLocaleInfoEx(localeName, lctype) ?? string.Empty; } /// <summary> /// Reescape a Win32 style quote string as a NLS+ style quoted string /// /// This is also the escaping style used by custom culture data files /// /// NLS+ uses \ to escape the next character, whether in a quoted string or /// not, so we always have to change \ to \\. /// /// NLS+ uses \' to escape a quote inside a quoted string so we have to change /// '' to \' (if inside a quoted string) /// /// We don't build the stringbuilder unless we find something to change /// </summary> [return: NotNullIfNotNull("str")] internal static string? ReescapeWin32String(string? str) { // If we don't have data, then don't try anything if (str == null) { return null; } StringBuilder? result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder result ??= new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder result ??= new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character result?.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } [return: NotNullIfNotNull("array")] internal static string[]? ReescapeWin32Strings(string[]? array) { if (array != null) { for (int i = 0; i < array.Length; i++) { array[i] = ReescapeWin32String(array[i]); } } return array; } // If we get a group from windows, then its in 3;0 format with the 0 backwards // of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa) // EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning. private static int[] ConvertWin32GroupString(string win32Str) { // None of these cases make any sense if (string.IsNullOrEmpty(win32Str)) { return new int[] { 3 }; } if (win32Str.StartsWith('0')) { return new int[] { 0 }; } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str.EndsWith('0')) { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[win32Str.Length / 2]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[^1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (!char.IsBetween(win32Str[i], '1', '9')) return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return values; } private static int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } // Context for EnumCalendarInfoExEx callback. private struct EnumLocaleData { public string regionName; public string? cultureName; } // EnumSystemLocaleEx callback. [UnmanagedCallersOnly] private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle); try { string cultureName = new string(lpLocaleString); string? regionName = GetLocaleInfoEx(cultureName, Interop.Kernel32.LOCALE_SISO3166CTRYNAME); if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) { context.cultureName = cultureName; return Interop.BOOL.FALSE; // we found a match, then stop the enumeration } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // EnumSystemLocaleEx callback. [UnmanagedCallersOnly] private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle); try { context.strings.Add(new string(lpLocaleString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } // Context for EnumTimeFormatsEx callback. private struct EnumData { public List<string> strings; } // EnumTimeFormatsEx callback itself. [UnmanagedCallersOnly] private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { context.strings.Add(new string(lpTimeFormatString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe string[]? nativeEnumTimeFormats(string localeName, uint dwFlags, bool useUserOverride) { EnumData data = default; data.strings = new List<string>(); // Now call the enumeration API. Work is done by our callback function Interop.Kernel32.EnumTimeFormatsEx(&EnumTimeCallback, localeName, dwFlags, Unsafe.AsPointer(ref data)); if (data.strings.Count > 0) { // Now we need to allocate our stringarray and populate it string[] results = data.strings.ToArray(); if (!useUserOverride && data.strings.Count > 1) { // Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override // The override is the first entry if it is overriden. // We can check if we have overrides by checking the GetLocaleInfo with no override // If we do have an override, we don't know if it is a user defined override or if the // user has just selected one of the predefined formats so we can't just remove it // but we can move it down. uint lcType = (dwFlags == Interop.Kernel32.TIME_NOSECONDS) ? Interop.Kernel32.LOCALE_SSHORTTIME : Interop.Kernel32.LOCALE_STIMEFORMAT; string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride); if (timeFormatNoUserOverride != "") { string firstTimeFormat = results[0]; if (timeFormatNoUserOverride != firstTimeFormat) { results[0] = results[1]; results[1] = firstTimeFormat; } } } return results; } return null; } private static int NlsLocaleNameToLCID(string cultureName) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.LocaleNameToLCID(cultureName, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES); } private string NlsGetThreeLetterWindowsLanguageName(string cultureName) { Debug.Assert(GlobalizationMode.UseNls); return NlsGetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName); } private static CultureInfo[] NlsEnumCultures(CultureTypes types) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); uint flags = 0; #pragma warning disable 618 if ((types & (CultureTypes.FrameworkCultures | CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures)) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA | Interop.Kernel32.LOCALE_SPECIFICDATA; } #pragma warning restore 618 if ((types & CultureTypes.NeutralCultures) != 0) { flags |= Interop.Kernel32.LOCALE_NEUTRALDATA; } if ((types & CultureTypes.SpecificCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SPECIFICDATA; } if ((types & CultureTypes.UserCustomCulture) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } if ((types & CultureTypes.ReplacementCultures) != 0) { flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL; } EnumData context = default; context.strings = new List<string>(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(&EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero); } CultureInfo[] cultures = new CultureInfo[context.strings.Count]; for (int i = 0; i < cultures.Length; i++) { cultures[i] = new CultureInfo(context.strings[i]); } return cultures; } private string NlsGetConsoleFallbackName(string cultureName) { Debug.Assert(GlobalizationMode.UseNls); return NlsGetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName); } internal bool NlsIsReplacementCulture { get { Debug.Assert(GlobalizationMode.UseNls); EnumData context = default; context.strings = new List<string>(); unsafe { Interop.Kernel32.EnumSystemLocalesEx(&EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero); } for (int i = 0; i < context.strings.Count; i++) { if (string.Equals(context.strings[i], _sRealName, StringComparison.OrdinalIgnoreCase)) return true; } return false; } } } }
38.177449
198
0.554517
[ "MIT" ]
ChaseKnowlden/runtime
src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs
20,654
C#
using System; using System.Collections.Generic; using System.IO; using DotXxlJob.Core; using DotXxlJob.Core.Model; using Newtonsoft.Json; namespace HessianReader { class Program { static void Main(string[] args) { /* */ byte[] myBinary = File.ReadAllBytes("run.dat"); foreach (var i in myBinary) { Console.Write("0x"); Console.Write(i.ToString("x2")); Console.Write(","); } Console.WriteLine(Environment.NewLine); Console.WriteLine("---------------------------------------------------------------"); /* byte[] myBinary; var callbackParamList = new List<HandleCallbackParam> { new HandleCallbackParam { LogId = 11, LogDateTime = 1547819469000L, ExecuteResult =new ReturnT { Code = 200,Content ="acd3323",Msg ="1bc" } }, new HandleCallbackParam { LogId = 22, LogDateTime = 1547819469000L, ExecuteResult =new ReturnT { Code = 500,Content ="cac",Msg ="aad" } } }; var request = new RpcRequest { RequestId ="e24123be4a76417ca6f41f227532b235", CreateMillisTime = 1547819469003L, AccessToken = "", ClassName = "com.xxl.job.core.biz.AdminBiz", MethodName = "callback", ParameterTypes = new List<object> {new JavaClass {Name = "java.util.List"}}, Parameters = new List<object> {callbackParamList} }; using (var stream = new MemoryStream()) { HessianSerializer.SerializeRequest(stream,request); myBinary = stream.ToArray(); } */ using (var stream1 = new MemoryStream(myBinary)) { var s1 = HessianSerializer.DeserializeRequest(stream1); Console.WriteLine("{0}={1}",s1.GetType(),JsonConvert.SerializeObject(s1)); /* var s = new Deserializer(stream1); while ( s.CanRead()) { var o = s.ReadValue(); Console.WriteLine("{0}={1}",o.GetType(),JsonConvert.SerializeObject(o)); Console.WriteLine("------------------------------------------------------------"); } */ } Console.WriteLine("------------------------------------------------------------"); Console.ReadKey(); /** * * Console.WriteLine("---------------------------------------------------------------"); RpcRequest req = new RpcRequest { RequestId = "71565f61-94e8-4dcf-9760-f2fb73a6886a", CreateMillisTime = 1547621183585, AccessToken = "", ClassName = "com.xxl.job.core.biz.ExecutorBiz", MethodName = "run", ParameterTypes = new List<object> {new JavaClass{ Name = "com.xxl.job.core.biz.model.TriggerParam"}}, Version = null, Parameters = new List<object>() }; var p =new TriggerParam { JobId=1, ExecutorHandler="demoJobHandler", ExecutorParams="111", ExecutorBlockStrategy="SERIAL_EXECUTION", ExecutorTimeout=0, LogId=5, LogDateTime=1547621183414L, GlueType="BEAN", GlueSource="", GlueUpdateTime=1541254891000, BroadcastIndex=0, BroadcastTotal=1 }; req.Parameters.Add(p); using (var stream2 = new MemoryStream()) { var serializer = new Serializer(stream2); serializer.WriteObject(req); Console.WriteLine("-----------------------------序列化成功---{0}-------------------------------",stream2.Length); stream2.Position = 0; var s2 = HessianSerializer.DeserializeRequest(stream2); Console.WriteLine(JsonConvert.SerializeObject(s2)); } * [{"Item1":"requestId","Item2":"71565f61-94e8-4dcf-9760-f2fb73a6886a"},{"Item1":"createMillisTime","Item2":1432957289},{"Item1":"accessToken","Item2":""},{"Item1":"className","Item2":"com.xxl.job.core.biz.ExecutorBiz"},{"Item1":"methodName","Item2":"run"},{"Item1":"version","Item2":null},{"Item1":"parameterT ypes","Item2":[{"Name":"java.lang.Class","Fields":["name"]}]},{"Item1":"parameters","Item2":[{"Item1":"name","Item2":"com.xxl.job.core.biz.model.TriggerParam"}]}] System.Collections.Generic.List`1[System.Object] [{"Name":"com.xxl.job.core.biz.model.TriggerParam","Fields":["jobId","executorHandler","executorParams","executorBlockStrategy","executorTimeout","logId","logDateTim","glueType","glueSource","glueUpdatetime","broadcastIndex","broadcastTotal"]}] Hessian.HessianObject [{"Item1":"jobId","Item2":1},{"Item1":"executorHandler","Item2":"demoJobHandler"},{"Item1":"executorParams","Item2":"111"},{"Item1":"executorBlockStrategy","Item2":"SERIAL_EXECUTION"},{"Item1":"executorTimeout","Item2":0},{"Item1":"logId","Item2":5},{"Item1":"logDateTim","Item2":1432956926},{"Item1":"glueTy pe","Item2":"BEAN"},{"Item1":"glueSource","Item2":""},{"Item1":"glueUpdatetime","Item2":-638368258},{"Item1":"broadcastIndex","Item2":0},{"Item1":"broadcastTotal","Item2":1}] * requestId='71565f61-94e8-4dcf-9760-f2fb73a6886a', * createMillisTime=1547621183585, * accessToken='', * className='com.xxl.job.core.biz.ExecutorBiz', * methodName='run', * parameterTypes=[class com.xxl.job.core.biz.model.TriggerParam], * parameters=[ * TriggerParam{ * jobId=1, * executorHandler='demoJobHandler', * executorParams='111', * executorBlockStrategy='SERIAL_EXECUTION', * executorTimeout=0, * logId=5, * logDateTim=1547621183414, * glueType='BEAN', * glueSource='', * glueUpdatetime=1541254891000, * broadcastIndex=0, * broadcastTotal=1 * } * ], version='null' * */ } } }
42.702532
323
0.490144
[ "MIT" ]
yang-dw/DotXxlJob
samples/HessianReader/Program.cs
6,759
C#
using MarkPad.FileSystem.Data; using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media.Imaging; namespace MarkPad { [ValueConversion(typeof(DataItem), typeof(BitmapImage))] public class HeaderToImageConverter : IValueConverter { public static HeaderToImageConverter Instance = new HeaderToImageConverter(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var image = "Images/icons8-file-40.png"; switch ((DataType)value) { case DataType.Drive: image = "Images/icons8-hdd-48.png"; break; case DataType.FolderClosed: image = "Images/icons8-folder-50.png"; break; case DataType.FolderOpened: image = "Images/icons8-open-50.png"; break; case DataType.Empty: return null; } return new BitmapImage(new Uri($"pack://application:,,,/{image}")); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
31.428571
103
0.575
[ "MIT" ]
mihaitudor17/MarkPad
MarkPad/MarkPad/HeaderToImageConverter.cs
1,322
C#
using System; using System.Linq; namespace T02.TheLift { class Program { static void Main(string[] args) { int people = int.Parse(Console.ReadLine()); int[] lift = Console.ReadLine().Split().Select(int.Parse).ToArray(); int currentWagon = 0; while (people >= 0 && currentWagon < lift.Length) { int currentFreespace = 4 - lift[currentWagon]; if (currentFreespace <= people) { lift[currentWagon++] += currentFreespace; } else { lift[currentWagon++] += people; } people -= currentFreespace; } if (people < 0) { Console.WriteLine("The lift has empty spots!"); } else if (people > 0) { Console.WriteLine($"There isn't enough space! {people} people in a queue!"); } Console.WriteLine(String.Join(" ", lift)); } } }
28.307692
92
0.44837
[ "MIT" ]
akdimitrov/CSharp-Fundamentals
ExamPreparation/01.Exam Prep - PF MidExamRetake/T02.TheLift/Program.cs
1,106
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IssueTracker.Model; using System.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using Dapper; using IssueTracker.Model.ViewModel; namespace IssueTracker.Service { public class Issue : Interface.IIssue { private string _cnstring; #region ctor public Issue(string cn) { _cnstring = Connection.Get(cn); } #endregion public string Add(Model.Issue data) { try { using (var sql = new SqlConnection(_cnstring)) sql.Execute("IssueAdd", data, commandType: CommandType.StoredProcedure); } catch (SqlException ex) { return ex.InnerException?.Message ?? ex.Message; } return null; } public string AssignTo(int id, string userId, string description) { try { using (var sql = new SqlConnection(_cnstring)) sql.Execute( "IssueAssignTo", new { @Id = id, @AssignedTo = userId, @Description = description }, commandType: CommandType.StoredProcedure ); } catch (SqlException ex) { return ex.InnerException?.Message ?? ex.Message; } return null; } public string Close(int id) { try { using (var sql = new SqlConnection(_cnstring)) sql.Execute("IssueSetStatusClosed", new { @Id = id }, commandType: CommandType.StoredProcedure); } catch (SqlException ex) { return ex.InnerException?.Message ?? ex.Message; } return null; } public string Delete(int id) { try { using (var sql = new SqlConnection(_cnstring)) sql.Execute("IssueDelete", new { @Id = id }, commandType: CommandType.StoredProcedure); } catch (SqlException ex) { return ex.InnerException?.Message ?? ex.Message; } return null; } public Model.Issue GetById(int id) { using (var sql = new SqlConnection(_cnstring)) return sql.Query<IssueViewModel>( "IssueById", new { @id = id }, commandType: CommandType.StoredProcedure).FirstOrDefault(); } public IEnumerable<IssueViewModel> GetLatest() { using (var sql = new SqlConnection(_cnstring)) return sql.Query<IssueViewModel>( "IssueLatest", commandType: CommandType.StoredProcedure); } public IEnumerable<IssueViewModel> GetList(string accountId, string filter) { using (var sql = new SqlConnection(_cnstring)) return sql.Query<IssueViewModel>( "IssueList", new { @AccountId = accountId, @filter = filter }, commandType: CommandType.StoredProcedure); } public IEnumerable<IssueStatusStat> GetStatusStats() { using (var sql = new SqlConnection(_cnstring)) return sql.Query<IssueStatusStat>( "IssueStatistics", commandType: CommandType.StoredProcedure); } public string Update(Model.Issue data) { try { using (var sql = new SqlConnection(_cnstring)) sql.Execute("IssueUpdate", data, commandType: CommandType.StoredProcedure); } catch (SqlException ex) { return ex.InnerException?.Message ?? ex.Message; } return null; } } }
30.28777
116
0.503325
[ "MIT" ]
whebz/IssueTracker
IssueTracker.Service/Issue.cs
4,212
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IF.Lastfm.Core.Api.Commands.User; using IF.Lastfm.Core.Api.Enums; using IF.Lastfm.Core.Api.Helpers; using IF.Lastfm.Core.Objects; using IF.Lastfm.Core.Tests.Resources; using NUnit.Framework; namespace IF.Lastfm.Core.Tests.Api.Commands { public class UserGetTopArtistsCommandTests : CommandTestsBase { private const string USER = "Aurvandil"; private const LastStatsTimeSpan SPAN = LastStatsTimeSpan.Overall; [Test] public void ParametersCorrect() { var expected = new Dictionary<string, string> { {"user", USER}, {"period", SPAN.GetApiName()}, {"page", "5"}, {"limit", "10"} }; var command = new GetTopArtistsCommand(MAuth.Object, USER, SPAN) { Page = 5, Count = 10 }; command.SetParameters(); command.Parameters.Remove("disablecachetoken"); TestHelper.AssertSerialiseEqual(expected, command.Parameters); } [Test] public async Task HandleResponseSingle() { var command = new GetTopArtistsCommand(MAuth.Object, USER, SPAN) { Page = 1, Count = 1 }; command.SetParameters(); var expectedArtist = new LastArtist { Name = "Anathema", PlayCount = 5216, Mbid = "20aa23e3-3532-42ca-acf6-e8c2e9df2688", Url = new Uri("http://www.last.fm/music/Anathema"), MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/12571597.jpg", "http://userserve-ak.last.fm/serve/64/12571597.jpg", "http://userserve-ak.last.fm/serve/126/12571597.jpg", "http://userserve-ak.last.fm/serve/252/12571597.jpg", "http://userserve-ak.last.fm/serve/_/12571597/Anathema+Judgement+promo.jpg") }; var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetTopArtistsSingle)); var parsed = await command.HandleResponse(response); Assert.IsTrue(parsed.Success); Assert.AreEqual(1, parsed.Page); Assert.AreEqual(1, parsed.PageSize); Assert.AreEqual(1124, parsed.TotalItems); Assert.AreEqual(1124, parsed.TotalPages); Assert.AreEqual(1, parsed.Content.Count); var actualArtist = parsed.Content.First(); TestHelper.AssertSerialiseEqual(expectedArtist, actualArtist); } [Test] public async Task HandleResponseMultiple() { var command = new GetTopArtistsCommand(MAuth.Object, USER, SPAN) { Page = 1, Count = 2 }; command.SetParameters(); var expectedArtists = new List<LastArtist> { new LastArtist { Name = "Anathema", PlayCount = 5216, Mbid = "20aa23e3-3532-42ca-acf6-e8c2e9df2688", Url = new Uri("http://www.last.fm/music/Anathema"), MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/12571597.jpg", "http://userserve-ak.last.fm/serve/64/12571597.jpg", "http://userserve-ak.last.fm/serve/126/12571597.jpg", "http://userserve-ak.last.fm/serve/252/12571597.jpg", "http://userserve-ak.last.fm/serve/_/12571597/Anathema+Judgement+promo.jpg") }, new LastArtist { Name = "Insomnium", PlayCount = 4670, Mbid = "c1f8e226-75ea-4fe6-83ce-59c122bcbca4", Url = new Uri("http://www.last.fm/music/Insomnium"), MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/70409268.jpg", "http://userserve-ak.last.fm/serve/64/70409268.jpg", "http://userserve-ak.last.fm/serve/126/70409268.jpg", "http://userserve-ak.last.fm/serve/252/70409268.jpg", "http://userserve-ak.last.fm/serve/500/70409268/Insomnium.jpg") }, }; var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetTopArtistsMultiple)); var parsed = await command.HandleResponse(response); Assert.IsTrue(parsed.Success); Assert.AreEqual(1, parsed.Page); Assert.AreEqual(2, parsed.PageSize); Assert.AreEqual(1124, parsed.TotalItems); Assert.AreEqual(562, parsed.TotalPages); Assert.AreEqual(2, parsed.Content.Count); var actualArtists = parsed.Content; TestHelper.AssertSerialiseEqual(expectedArtists, actualArtists); } [Test] public async Task HandleResponseEmpty() { const string USER_WITH_NO_PLAYS = "e"; var command = new GetTopArtistsCommand(MAuth.Object, USER_WITH_NO_PLAYS, SPAN) { Page = 1, Count = 1 }; command.SetParameters(); var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetTopArtistsEmpty)); var parsed = await command.HandleResponse(response); Assert.IsTrue(parsed.Success); Assert.AreEqual(1, parsed.Page); Assert.AreEqual(0, parsed.PageSize); Assert.AreEqual(0, parsed.TotalItems); Assert.AreEqual(1, parsed.TotalPages); Assert.AreEqual(0, parsed.Content.Count); } [Test] public async Task HandleResponseError() { var command = new GetTopArtistsCommand(MAuth.Object, USER, SPAN) { Page = 1, Count = 1 }; command.SetParameters(); var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetTopArtistsError)); var parsed = await command.HandleResponse(response); Assert.IsFalse(parsed.Success); Assert.AreEqual(1, parsed.Page); Assert.AreEqual(0, parsed.PageSize); Assert.AreEqual(0, parsed.TotalItems); Assert.AreEqual(1, parsed.TotalPages); Assert.AreEqual(0, parsed.Content.Count); Assert.AreEqual(LastResponseStatus.MissingParameters, parsed.Status); } } }
37.510753
118
0.549377
[ "MIT" ]
c-d/lastfm
src/IF.Lastfm.Core.Tests/Api/Commands/UserGetTopArtistsCommandTests.cs
6,979
C#
using Terraria.Localization; using Terraria.ModLoader; namespace MagicStorageExtra { public partial class MagicStorageExtra { private void AddTranslations() { ModTranslation text = CreateTranslation("SetTo"); text.SetDefault("Set to: X={0}, Y={1}"); text.AddTranslation(GameCulture.Polish, "Ustawione na: X={0}, Y={1}"); text.AddTranslation(GameCulture.French, "Mis à: X={0}, Y={1}"); text.AddTranslation(GameCulture.Spanish, "Ajustado a: X={0}, Y={1}"); text.AddTranslation(GameCulture.Chinese, "已设置为: X={0}, Y={1}"); AddTranslation(text); text = CreateTranslation("SnowBiomeBlock"); text.SetDefault("Snow Biome Block"); text.AddTranslation(GameCulture.French, "Bloc de biome de neige"); text.AddTranslation(GameCulture.Spanish, "Bloque de Biomas de la Nieve"); text.AddTranslation(GameCulture.Chinese, "雪地环境方块"); AddTranslation(text); text = CreateTranslation("DepositAll"); text.SetDefault("Transfer All"); text.AddTranslation(GameCulture.Russian, "Переместить всё"); text.AddTranslation(GameCulture.French, "Déposer tout"); text.AddTranslation(GameCulture.Spanish, "Depositar todo"); text.AddTranslation(GameCulture.Chinese, "全部存入"); AddTranslation(text); text = CreateTranslation("SearchName"); text.SetDefault("Search Name"); text.AddTranslation(GameCulture.Russian, "Поиск по имени"); text.AddTranslation(GameCulture.French, "Recherche par nom"); text.AddTranslation(GameCulture.Spanish, "búsqueda por nombre"); text.AddTranslation(GameCulture.Chinese, "搜索名称"); AddTranslation(text); text = CreateTranslation("CraftAmount"); text.SetDefault("Craft amount"); AddTranslation(text); text = CreateTranslation("SearchMod"); text.SetDefault("Search Mod"); text.AddTranslation(GameCulture.Russian, "Поиск по моду"); text.AddTranslation(GameCulture.French, "Recherche par mod"); text.AddTranslation(GameCulture.Spanish, "búsqueda por mod"); text.AddTranslation(GameCulture.Chinese, "搜索模组"); AddTranslation(text); text = CreateTranslation("SortDefault"); text.SetDefault("Default Sorting"); text.AddTranslation(GameCulture.Russian, "Стандартная сортировка"); text.AddTranslation(GameCulture.French, "Tri Standard"); text.AddTranslation(GameCulture.Spanish, "Clasificación por defecto"); text.AddTranslation(GameCulture.Chinese, "默认排序"); AddTranslation(text); text = CreateTranslation("SortID"); text.SetDefault("Sort by ID"); text.AddTranslation(GameCulture.Russian, "Сортировка по ID"); text.AddTranslation(GameCulture.French, "Trier par ID"); text.AddTranslation(GameCulture.Spanish, "Ordenar por ID"); text.AddTranslation(GameCulture.Chinese, "按ID排序"); AddTranslation(text); text = CreateTranslation("SortName"); text.SetDefault("Sort by Name"); text.AddTranslation(GameCulture.Russian, "Сортировка по имени"); text.AddTranslation(GameCulture.French, "Trier par nom"); text.AddTranslation(GameCulture.Spanish, "Ordenar por nombre"); text.AddTranslation(GameCulture.Chinese, "按名称排序"); AddTranslation(text); text = CreateTranslation("SortStack"); text.SetDefault("Sort by Stacks"); text.AddTranslation(GameCulture.Russian, "Сортировка по стакам"); text.AddTranslation(GameCulture.French, "Trier par piles"); text.AddTranslation(GameCulture.Spanish, "Ordenar por pilas"); text.AddTranslation(GameCulture.Chinese, "按堆栈排序"); AddTranslation(text); text = CreateTranslation("SortValue"); text.SetDefault("Sort by Value"); text.AddTranslation(GameCulture.Russian, "Сортировать по значению"); text.AddTranslation(GameCulture.French, "Trier par valeur"); text.AddTranslation(GameCulture.Spanish, "Ordenar por valor"); text.AddTranslation(GameCulture.Chinese, "按值排序"); AddTranslation(text); text = CreateTranslation("FilterAll"); text.SetDefault("Filter All"); text.AddTranslation(GameCulture.Russian, "Фильтр (Всё)"); text.AddTranslation(GameCulture.French, "Filtrer tout"); text.AddTranslation(GameCulture.Spanish, "Filtrar todo"); text.AddTranslation(GameCulture.Chinese, "筛选全部"); AddTranslation(text); text = CreateTranslation("FilterWeapons"); text.SetDefault("Filter Weapons"); text.AddTranslation(GameCulture.Russian, "Фильтр (Оружия)"); text.AddTranslation(GameCulture.French, "Filtrer par armes"); text.AddTranslation(GameCulture.Spanish, "Filtrar por armas"); text.AddTranslation(GameCulture.Chinese, "筛选武器"); AddTranslation(text); text = CreateTranslation("FilterTools"); text.SetDefault("Filter Tools"); text.AddTranslation(GameCulture.Russian, "Фильтр (Инструменты)"); text.AddTranslation(GameCulture.French, "Filtrer par outils"); text.AddTranslation(GameCulture.Spanish, "Filtrar por herramientas"); text.AddTranslation(GameCulture.Chinese, "筛选工具"); AddTranslation(text); text = CreateTranslation("FilterEquips"); text.SetDefault("Filter Equipment"); text.AddTranslation(GameCulture.Russian, "Фильтр (Снаряжения)"); text.AddTranslation(GameCulture.French, "Filtrer par Équipement"); text.AddTranslation(GameCulture.Spanish, "Filtrar por equipamiento"); text.AddTranslation(GameCulture.Chinese, "筛选装备"); AddTranslation(text); text = CreateTranslation("FilterWeaponsMelee"); text.SetDefault("Filter Melee Weapons"); AddTranslation(text); text = CreateTranslation("FilterWeaponsRanged"); text.SetDefault("Filter Ranged Weapons"); AddTranslation(text); text = CreateTranslation("FilterWeaponsMagic"); text.SetDefault("Filter Magic Weapons"); AddTranslation(text); text = CreateTranslation("FilterWeaponsSummon"); text.SetDefault("Filter Summons"); AddTranslation(text); text = CreateTranslation("FilterWeaponsThrown"); text.SetDefault("Filter Throwing Weapons"); AddTranslation(text); text = CreateTranslation("FilterAmmo"); text.SetDefault("Filter Ammo"); AddTranslation(text); text = CreateTranslation("FilterArmor"); text.SetDefault("Filter Armor"); AddTranslation(text); text = CreateTranslation("FilterVanity"); text.SetDefault("Filter Vanity Items"); AddTranslation(text); text = CreateTranslation("FilterPotions"); text.SetDefault("Filter Potions"); text.AddTranslation(GameCulture.Russian, "Фильтр (Зелья)"); text.AddTranslation(GameCulture.French, "Filtrer par potions"); text.AddTranslation(GameCulture.Spanish, "Filtrar por poción"); text.AddTranslation(GameCulture.Chinese, "筛选药水"); AddTranslation(text); text = CreateTranslation("FilterTiles"); text.SetDefault("Filter Placeables"); text.AddTranslation(GameCulture.Russian, "Фильтр (Размещаемое)"); text.AddTranslation(GameCulture.French, "Filtrer par placeable"); text.AddTranslation(GameCulture.Spanish, "Filtrar por metido"); text.AddTranslation(GameCulture.Chinese, "筛选放置物"); AddTranslation(text); text = CreateTranslation("FilterMisc"); text.SetDefault("Filter Misc"); text.AddTranslation(GameCulture.Russian, "Фильтр (Разное)"); text.AddTranslation(GameCulture.French, "Filtrer par miscellanées"); text.AddTranslation(GameCulture.Spanish, "Filtrar por otros"); text.AddTranslation(GameCulture.Chinese, "筛选杂项"); AddTranslation(text); text = CreateTranslation("FilterRecent"); text.SetDefault("Filter New Recently Added Items"); AddTranslation(text); text = CreateTranslation("CraftingStations"); text.SetDefault("Crafting Stations"); text.AddTranslation(GameCulture.Russian, "Станции создания"); text.AddTranslation(GameCulture.French, "Stations d'artisanat"); text.AddTranslation(GameCulture.Spanish, "Estaciones de elaboración"); text.AddTranslation(GameCulture.Chinese, "制作站"); AddTranslation(text); text = CreateTranslation("Recipes"); text.SetDefault("Recipes"); text.AddTranslation(GameCulture.Russian, "Рецепты"); text.AddTranslation(GameCulture.French, "Recettes"); text.AddTranslation(GameCulture.Spanish, "Recetas"); text.AddTranslation(GameCulture.Chinese, "合成配方"); AddTranslation(text); text = CreateTranslation("SelectedRecipe"); text.SetDefault("Selected Recipe"); text.AddTranslation(GameCulture.French, "Recette sélectionnée"); text.AddTranslation(GameCulture.Spanish, "Receta seleccionada"); text.AddTranslation(GameCulture.Chinese, "选择配方"); AddTranslation(text); text = CreateTranslation("Ingredients"); text.SetDefault("Ingredients"); text.AddTranslation(GameCulture.French, "Ingrédients"); text.AddTranslation(GameCulture.Spanish, "Ingredientes"); text.AddTranslation(GameCulture.Chinese, "材料"); AddTranslation(text); text = CreateTranslation("StoredItems"); text.SetDefault("Stored Ingredients"); text.AddTranslation(GameCulture.French, "Ingrédients Stockés"); text.AddTranslation(GameCulture.Spanish, "Ingredientes almacenados"); text.AddTranslation(GameCulture.Chinese, "存储中的材料"); AddTranslation(text); text = CreateTranslation("RecipeAvailable"); text.SetDefault("Show craftable recipes"); AddTranslation(text); text = CreateTranslation("RecipeAll"); text.SetDefault("Show all known recipes"); AddTranslation(text); text = CreateTranslation("RecipeBlacklist"); text.SetDefault("Show hidden recipes (ctrl+click on recipe to (un)hide)"); AddTranslation(text); text = CreateTranslation("SortDps"); text.SetDefault("Sort by DPS"); AddTranslation(text); text = CreateTranslation("ShowOnlyFavorited"); text.SetDefault("Only Favorited"); AddTranslation(text); text = CreateTranslation("DepositTooltip"); text.SetDefault("Quick Stack - click, Deposit All - ctrl+click, Restock - right click"); AddTranslation(text); text = CreateTranslation("DepositTooltipAlt"); text.SetDefault("Quick Stack - ctrl+click, Deposit All - click, Restock - right click"); AddTranslation(text); text = CreateTranslation("CraftTooltip"); text.SetDefault("Left click to Craft, Right click to get item for a test (only for new items)"); AddTranslation(text); text = CreateTranslation("TestItemSuffix"); text.SetDefault(" !UNTIL RESPAWN!"); AddTranslation(text); } } }
39.234615
99
0.74081
[ "MIT" ]
ExterminatorX99/MagicStorage
MagicStorageExtra.Translations.cs
10,641
C#
using System; using System.Collections.Generic; using System.Reflection; using Newtonsoft.Json; using Nop.Core.Caching; using Nop.Core.Infrastructure; using Nop.Plugin.Api.Attributes; using Nop.Plugin.Api.Constants; namespace Nop.Plugin.Api.Maps { public class JsonPropertyMapper : IJsonPropertyMapper { private IStaticCacheManager _cacheManager; private IStaticCacheManager StaticCacheManager { get { if (_cacheManager == null) { _cacheManager = EngineContext.Current.Resolve<IStaticCacheManager>(); } return _cacheManager; } } public Dictionary<string, Tuple<string, Type>> GetMap(Type type) { if (!StaticCacheManager.IsSet(Configurations.JsonTypeMapsPattern)) { StaticCacheManager.Set(Configurations.JsonTypeMapsPattern, new Dictionary<string, Dictionary<string, Tuple<string, Type>>>(), int.MaxValue); } var typeMaps = StaticCacheManager.Get<Dictionary<string, Dictionary<string, Tuple<string, Type>>>>(Configurations.JsonTypeMapsPattern); if (!typeMaps.ContainsKey(type.Name)) { Build(type); } return typeMaps[type.Name]; } private void Build(Type type) { Dictionary<string, Dictionary<string, Tuple<string, Type>>> typeMaps = StaticCacheManager.Get<Dictionary<string, Dictionary<string, Tuple<string, Type>>>>(Configurations.JsonTypeMapsPattern); var mapForCurrentType = new Dictionary<string, Tuple<string, Type>>(); var typeProps = type.GetProperties(); foreach (var property in typeProps) { JsonPropertyAttribute jsonAttribute = property.GetCustomAttribute(typeof(JsonPropertyAttribute)) as JsonPropertyAttribute; DoNotMapAttribute doNotMapAttribute = property.GetCustomAttribute(typeof(DoNotMapAttribute)) as DoNotMapAttribute; // If it has json attribute set and is not marked as doNotMap if (jsonAttribute != null && doNotMapAttribute == null) { if (!mapForCurrentType.ContainsKey(jsonAttribute.PropertyName)) { var value = new Tuple<string, Type>(property.Name, property.PropertyType); mapForCurrentType.Add(jsonAttribute.PropertyName, value); } } } if (!typeMaps.ContainsKey(type.Name)) { typeMaps.Add(type.Name, mapForCurrentType); } } } }
36.051948
156
0.59402
[ "MIT" ]
hoatv1008/api-plugin-for-nopcommerce
Nop.Plugin.Api/Maps/JsonPropertyMap.cs
2,778
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("Minedraft")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Minedraft")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("f73b323c-8c50-48a3-9a59-012f1fb56c71")] // 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.459459
84
0.746753
[ "MIT" ]
V-Uzunov/Soft-Uni-Education
07.C#OOPBasic/001.OOP-Basic-Exam/Minedraft/Properties/AssemblyInfo.cs
1,389
C#
using BinaryQuest.Framework.Core.Data; using Duende.IdentityServer.EntityFramework.Options; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace bqStart.Data { public class MainDataContext : BQDataContext<ApplicationUser> { public MainDataContext(DbContextOptions options, Microsoft.Extensions.Options.IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } public DbSet<Department> Departments => Set<Department>(); public DbSet<ExampleClass> ExampleClasses => Set<ExampleClass>(); public DbSet<Order> Orders => Set<Order>(); public DbSet<OrderDetail> OrderDetails => Set<OrderDetail>(); } }
32.965517
185
0.728033
[ "MIT" ]
binaryquest/bqstart
aspnet/src/bqStart/bqStart.Data/MainDataContext.cs
958
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.BLOCKCHAIN.Models { public class QueryDidVcrepositoryFuzzyquerywithdefinedidResponse : TeaModel { // 请求唯一ID,用于链路跟踪和问题排查 [NameInMap("req_msg_id")] [Validation(Required=false)] public string ReqMsgId { get; set; } // 结果码,一般OK表示调用成功 [NameInMap("result_code")] [Validation(Required=false)] public string ResultCode { get; set; } // 异常信息的文本描述 [NameInMap("result_msg")] [Validation(Required=false)] public string ResultMsg { get; set; } // 可验证声明的完整声明列表 [NameInMap("verifiable_claim_content")] [Validation(Required=false)] public List<string> VerifiableClaimContent { get; set; } } }
25
81
0.645714
[ "MIT" ]
alipay/antchain-openapi-prod-sdk
blockchain/csharp/core/Models/QueryDidVcrepositoryFuzzyquerywithdefinedidResponse.cs
973
C#
using System; using System.Linq; namespace RTScript { class Program { [STAThread] private static void Main(string[] args) { if (args.Length != 0) { var console = new RTScriptConsole(args); console.RunCommand(args[0]); } else { var console = new RTScriptConsole(args.ToArray()); console.RunCommand("-?"); } } } }
20.583333
66
0.449393
[ "MIT" ]
miroiu/rt-script
RTScript/Program.cs
496
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BTCPayServer { public interface IStartupTask { Task ExecuteAsync(CancellationToken cancellationToken = default); } }
19.285714
73
0.759259
[ "MIT" ]
Argoneum/btcpayserver
BTCPayServer/IStartupTask.cs
272
C#
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PropertyChanged; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Pet /// </summary> [DataContract] [ImplementPropertyChanged] public partial class Pet : IEquatable<Pet>, IValidatableObject { /// <summary> /// pet status in the store /// </summary> /// <value>pet status in the store</value> [JsonConverter(typeof(StringEnumConverter))] public enum StatusEnum { /// <summary> /// Enum Available for "available" /// </summary> [EnumMember(Value = "available")] Available = 1, /// <summary> /// Enum Pending for "pending" /// </summary> [EnumMember(Value = "pending")] Pending = 2, /// <summary> /// Enum Sold for "sold" /// </summary> [EnumMember(Value = "sold")] Sold = 3 } /// <summary> /// pet status in the store /// </summary> /// <value>pet status in the store</value> [DataMember(Name="status", EmitDefaultValue=false)] public StatusEnum? Status { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Pet" /> class. /// </summary> [JsonConstructorAttribute] protected Pet() { } /// <summary> /// Initializes a new instance of the <see cref="Pet" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Category">Category.</param> /// <param name="Name">Name (required).</param> /// <param name="PhotoUrls">PhotoUrls (required).</param> /// <param name="Tags">Tags.</param> /// <param name="Status">pet status in the store.</param> public Pet(long? Id = default(long?), Category Category = default(Category), string Name = default(string), List<string> PhotoUrls = default(List<string>), List<Tag> Tags = default(List<Tag>), StatusEnum? Status = default(StatusEnum?)) { // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for Pet and cannot be null"); } else { this.Name = Name; } // to ensure "PhotoUrls" is required (not null) if (PhotoUrls == null) { throw new InvalidDataException("PhotoUrls is a required property for Pet and cannot be null"); } else { this.PhotoUrls = PhotoUrls; } this.Id = Id; this.Category = Category; this.Tags = Tags; this.Status = Status; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } /// <summary> /// Gets or Sets Category /// </summary> [DataMember(Name="category", EmitDefaultValue=false)] public Category Category { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets PhotoUrls /// </summary> [DataMember(Name="photoUrls", EmitDefaultValue=false)] public List<string> PhotoUrls { get; set; } /// <summary> /// Gets or Sets Tags /// </summary> [DataMember(Name="tags", EmitDefaultValue=false)] public List<Tag> Tags { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Pet); } /// <summary> /// Returns true if Pet instances are equal /// </summary> /// <param name="input">Instance of Pet to be compared</param> /// <returns>Boolean</returns> public bool Equals(Pet input) { if (input == null) return false; return ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Category == input.Category || (this.Category != null && this.Category.Equals(input.Category)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.PhotoUrls == input.PhotoUrls || this.PhotoUrls != null && this.PhotoUrls.SequenceEqual(input.PhotoUrls) ) && ( this.Tags == input.Tags || this.Tags != null && this.Tags.SequenceEqual(input.Tags) ) && ( this.Status == input.Status || (this.Status != null && this.Status.Equals(input.Status)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Category != null) hashCode = hashCode * 59 + this.Category.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.PhotoUrls != null) hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); if (this.Tags != null) hashCode = hashCode * 59 + this.Tags.GetHashCode(); if (this.Status != null) hashCode = hashCode * 59 + this.Status.GetHashCode(); return hashCode; } } /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Trigger when a property changed /// </summary> /// <param name="propertyName">Property Name</param> public virtual void OnPropertyChanged(string propertyName) { // NOTE: property changed is handled via "code weaving" using Fody. // Properties with setters are modified at compile time to notify of changes. var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
34.642599
243
0.513756
[ "Apache-2.0" ]
Acomodeo/swagger-codegen
samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs
9,596
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.DirectConnect; using Amazon.DirectConnect.Model; namespace Amazon.PowerShell.Cmdlets.DC { /// <summary> /// Adds the specified tags to the specified AWS Direct Connect resource. Each resource /// can have a maximum of 50 tags. /// /// /// <para> /// Each tag consists of a key and an optional value. If a tag with the same key is already /// associated with the resource, this action updates its value. /// </para> /// </summary> [Cmdlet("Add", "DCResourceTag", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS Direct Connect TagResource API operation.", Operation = new[] {"TagResource"}, SelectReturnType = typeof(Amazon.DirectConnect.Model.TagResourceResponse))] [AWSCmdletOutput("None or Amazon.DirectConnect.Model.TagResourceResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.DirectConnect.Model.TagResourceResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class AddDCResourceTagCmdlet : AmazonDirectConnectClientCmdlet, IExecutor { #region Parameter ResourceArn /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of the resource.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ResourceArn { get; set; } #endregion #region Parameter Tag /// <summary> /// <para> /// <para>The tags to add.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyCollection] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [Alias("Tags")] public Amazon.DirectConnect.Model.Tag[] Tag { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.DirectConnect.Model.TagResourceResponse). /// 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; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the ResourceArn parameter. /// The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.ResourceArn), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Add-DCResourceTag (TagResource)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.DirectConnect.Model.TagResourceResponse, AddDCResourceTagCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.ResourceArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ResourceArn = this.ResourceArn; #if MODULAR if (this.ResourceArn == null && ParameterWasBound(nameof(this.ResourceArn))) { WriteWarning("You are passing $null as a value for parameter ResourceArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.Tag != null) { context.Tag = new List<Amazon.DirectConnect.Model.Tag>(this.Tag); } #if MODULAR if (this.Tag == null && ParameterWasBound(nameof(this.Tag))) { WriteWarning("You are passing $null as a value for parameter Tag which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.DirectConnect.Model.TagResourceRequest(); if (cmdletContext.ResourceArn != null) { request.ResourceArn = cmdletContext.ResourceArn; } if (cmdletContext.Tag != null) { request.Tags = cmdletContext.Tag; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.DirectConnect.Model.TagResourceResponse CallAWSServiceOperation(IAmazonDirectConnect client, Amazon.DirectConnect.Model.TagResourceRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Direct Connect", "TagResource"); try { #if DESKTOP return client.TagResource(request); #elif CORECLR return client.TagResourceAsync(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 System.String ResourceArn { get; set; } public List<Amazon.DirectConnect.Model.Tag> Tag { get; set; } public System.Func<Amazon.DirectConnect.Model.TagResourceResponse, AddDCResourceTagCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
44.007843
282
0.604616
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/DirectConnect/Basic/Add-DCResourceTag-Cmdlet.cs
11,222
C#
// // OciBindHandle.cs // // Part of managed C#/.NET library System.Data.OracleClient.dll // // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient.Oci // // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient.Oci // // Author: // Tim Coleman <tim@timcoleman.com> // // Copyright (C) Tim Coleman, 2003 // using System.Runtime.InteropServices; namespace System.Data.OracleClient.Oci { internal sealed class OciBindHandle : OciHandle, IDisposable { #region Fields bool disposed = false; IntPtr value; #endregion // Fields #region Constructors public OciBindHandle(OciHandle parent) : base(OciHandleType.Bind, parent, IntPtr.Zero) { } #endregion // Constructors #region Properties public IntPtr Value { get { return value; } set { this.value = value; } } #endregion // Properties #region Methods protected override void Dispose(bool disposing) { if (!disposed) { try { Marshal.FreeHGlobal(value); disposed = true; } finally { base.Dispose(disposing); } } } #endregion // Methods } }
20.816901
66
0.52977
[ "MIT" ]
TikiBill/oracleClientCore-2.0
src/dotNetCore.Data.OracleClient/System.Data.OracleClient.Oci/OciBindHandle.cs
1,478
C#
using System.Threading.Tasks; using OrchardCore.Environment.Extensions.Features; namespace OrchardCore.Environment.Shell { public interface IFeatureEventHandler { Task InstallingAsync(IFeatureInfo feature); Task InstalledAsync(IFeatureInfo feature); Task EnablingAsync(IFeatureInfo feature); Task EnabledAsync(IFeatureInfo feature); Task DisablingAsync(IFeatureInfo feature); Task DisabledAsync(IFeatureInfo feature); Task UninstallingAsync(IFeatureInfo feature); Task UninstalledAsync(IFeatureInfo feature); } }
32.777778
53
0.744068
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore/OrchardCore.Abstractions/Shell/IFeatureEventHandler.cs
590
C#
/* * Copyright(c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.ComponentModel; namespace Tizen.NUI { /// <summary> /// Sampler is a handle to an object that can be used to provide the sampling parameters to sample textures. /// </summary> /// <since_tizen> 3 </since_tizen> public class Sampler : BaseHandle { /// <summary> /// Create an instance of Sampler. /// </summary> /// <since_tizen> 3 </since_tizen> public Sampler() : this(Interop.Sampler.New(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets the filter modes for this sampler. /// </summary> /// <param name="minFilter">The minification filter that will be used.</param> /// <param name="magFilter">The magnification filter that will be used.</param> /// <since_tizen> 3 </since_tizen> public void SetFilterMode(FilterModeType minFilter, FilterModeType magFilter) { Interop.Sampler.SetFilterMode(SwigCPtr, (int)minFilter, (int)magFilter); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets the wrap modes for this sampler. /// </summary> /// <param name="uWrap">Wrap mode for u coordinates.</param> /// <param name="vWrap">Wrap mode for v coordinates.</param> /// <since_tizen> 3 </since_tizen> public void SetWrapMode(WrapModeType uWrap, WrapModeType vWrap) { Interop.Sampler.SetWrapMode(SwigCPtr, (int)uWrap, (int)vWrap); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets the wrap modes for this sampler. /// </summary> /// <param name="rWrap">Wrap mode for the x direction.</param> /// <param name="sWrap">Wrap mode for the y direction.</param> /// <param name="tWrap">Wrap mode for the z direction.</param> /// <since_tizen> 3 </since_tizen> public void SetWrapMode(WrapModeType rWrap, WrapModeType sWrap, WrapModeType tWrap) { Interop.Sampler.SetWrapMode(SwigCPtr, (int)rWrap, (int)sWrap, (int)tWrap); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Sampler obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.SwigCPtr; } internal Sampler(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } /// This will not be public opened. [EditorBrowsable(EditorBrowsableState.Never)] protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr) { Interop.Sampler.DeleteSampler(swigCPtr); } } }
40.824176
137
0.648991
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
src/Tizen.NUI/src/public/Rendering/Sampler.cs
3,715
C#
using System; using System.Threading; using System.Collections.Generic; namespace ALB { /// <summary> /// extension class (класс для расширений) /// </summary> public static class Extensions { /// <summary> /// returns checked by range value (возвращает значение, проверенное по диапазону) /// </summary> /// <param name="min"> range minimal value (минимальное значение диапазона)</param> /// <param name="max"> range maximal value (максимальное значение диапазона)</param> /// <returns></returns> public static float Range(this float val, float? min, float? max) { float mn = min ?? val; float mx = max ?? val; return Math.Min(Math.Max(mn, val), mx); } /// <summary> /// returns checked by range value (возвращает значение, проверенное по диапазону) /// </summary> /// <param name="min"> range minimal value (минимальное значение диапазона)</param> /// <param name="max"> range maximal value (максимальное значение диапазона)</param> /// <returns></returns> public static int Range(this int val, int? min, int? max) { int mn = min ?? val; int mx = max ?? val; return Math.Min(Math.Max(mn, val), mx); } /// <summary> /// converts grid quantity to X-axis parameter using <see cref="Model.GridSize"/> (конвертирует количество ячеек в значение для координаты X, используя <see cref="Model.GridSize"/>) /// </summary> public static float GridToX(this float size) { return size.GridTo(Model.GridSize.X); } /// <summary> /// converts grid quantity to X-axis parameter using <see cref="Model.GridSize"/> (конвертирует количество ячеек в значение для координаты X, используя <see cref="Model.GridSize"/>) /// </summary> public static int GridToX(this int size) { return size.GridTo(Model.GridSize.X); } /// <summary> /// converts grid quantity to Y-axis parameter using <see cref="Model.GridSize"/> (конвертирует количество ячеек в значение для координаты Y, используя <see cref="Model.GridSize"/>) /// </summary> public static float GridToY(this float size) { return size.GridTo(Model.GridSize.Y); } /// <summary> /// converts grid quantity to Y-axis parameter using <see cref="Model.GridSize"/> (конвертирует количество ячеек в значение для координаты Y, используя <see cref="Model.GridSize"/>) /// </summary> public static int GridToY(this int size) { return size.GridTo(Model.GridSize.Y); } //------ /// <summary> /// converts X-axis parameter to grid quantity using <see cref="Model.GridSize"/> (конвертирует значение для координаты X в количество ячеек, используя <see cref="Model.GridSize"/>) /// </summary> public static float XToGrid(this float size) { return size.ToGrid(Model.GridSize.X); } /// <summary> /// converts X-axis parameter to grid quantity using <see cref="Model.GridSize"/> (конвертирует значение для координаты X в количество ячеек, используя <see cref="Model.GridSize"/>) /// </summary> public static float XToGrid(this int size) { return ((float)size).ToGrid(Model.GridSize.X); } /// <summary> /// converts Y-axis parameter to grid quantity using <see cref="Model.GridSize"/> (конвертирует значение для координаты Y в количество ячеек, используя <see cref="Model.GridSize"/>) /// </summary> public static float YToGrid(this float size) { return size.ToGrid(Model.GridSize.Y); } /// <summary> /// converts Y-axis parameter to grid quantity using <see cref="Model.GridSize"/> (конвертирует значение для координаты Y в количество ячеек, используя <see cref="Model.GridSize"/>) /// </summary> public static float YToGrid(this int size) { return ((float)size).ToGrid(Model.GridSize.Y); } //====== static int GridTo(this int size, float mult) { return size * (int)mult; } static float GridTo(this float size, float mult) { return size * (int)mult; } static float ToGrid(this float size, float mult) { return size / Model.ZeroCheck((int)mult); } } }
37.97541
189
0.587308
[ "MIT" ]
AlexButkov/ALB-Studio
Data/Models/Extensions.cs
5,311
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2018 // // 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. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct PhysicalDeviceFeatures2 { /// <summary> /// /// </summary> public SharpVk.PhysicalDeviceFeatures Features { get; set; } /// <summary> /// /// </summary> internal unsafe void MarshalTo(SharpVk.Interop.PhysicalDeviceFeatures2* pointer) { pointer->Next = null; this.Features.MarshalTo(&pointer->Features); } /// <summary> /// /// </summary> internal static unsafe PhysicalDeviceFeatures2 MarshalFrom(SharpVk.Interop.PhysicalDeviceFeatures2* pointer) { PhysicalDeviceFeatures2 result = default(PhysicalDeviceFeatures2); result.Features = SharpVk.PhysicalDeviceFeatures.MarshalFrom(&pointer->Features); return result; } } }
35.384615
116
0.67087
[ "MIT" ]
sebastianulm/SharpVk
src/SharpVk/PhysicalDeviceFeatures2.gen.cs
2,300
C#
using System; using System.IO; using NUnit.Framework; namespace NiceIO.Tests { [TestFixture] public class CopyFile : TestWithTempDir { [Test] public void FileToSameDirectory() { PopulateTempDir(new[] {"myfile.txt"}); var path = _tempPath.Combine("myfile.txt"); var dest = _tempPath.Combine("mycopy.txt"); var result = path.Copy(dest); Assert.AreEqual(dest, result); AssertTempDir(new[] {"myfile.txt", "mycopy.txt"}); } [Test] public void IntoNonExistingDirectory() { PopulateTempDir(new[] {"myfile.txt"}); var path = _tempPath.Combine("myfile.txt"); var dest = _tempPath.Combine("mydir/mycopy.txt"); path.Copy(dest); AssertTempDir(new[] {"myfile.txt", "mydir/", "mydir/mycopy.txt"}); } [Test] public void OnExistingDirectory() { PopulateTempDir(new[] {"somedir/", "myfile.txt"}); //turns out .net throws an IOException here, and mono an ArgumentException. let's deal with that another day. var result = _tempPath.Combine("myfile.txt").Copy(_tempPath.Combine("somedir")); Assert.AreEqual(_tempPath.Combine("somedir/myfile.txt"), result); AssertTempDir(new[] { "myfile.txt", "somedir/", "somedir/myfile.txt" }); } [Test] public void NonExistingFile() { Assert.Throws<ArgumentException>(() => _tempPath.Combine("nonexisting.txt").Copy(_tempPath.Combine("target"))); } [Test] public void WithRelativeSource() { Assert.Throws<ArgumentException>(() => new NPath("somedir/somefile").Copy(new NPath("irrelevant"))); } [Test] public void WithRelativeDestination() { PopulateTempDir(new[] {"myfile.txt"}); var result = _tempPath.Combine("myfile.txt").Copy(new NPath("myfile2.txt")); Assert.AreEqual(_tempPath.Combine("myfile2.txt"),result); AssertTempDir(new [] { "myfile.txt", "myfile2.txt" }); } } }
25.260274
114
0.670282
[ "MIT" ]
lucasmeijer/NiceIO
NiceIO.Tests/CopyFile.cs
1,846
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Forms.ButtonInternal; using System.Windows.Forms.Layout; using static Interop; namespace System.Windows.Forms { /// <summary> /// Represents a Windows /// check box. /// </summary> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty(nameof(Checked)), DefaultEvent(nameof(CheckedChanged)), DefaultBindingProperty(nameof(CheckState)), ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem," + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionCheckBox)) ] public class CheckBox : ButtonBase { private static readonly object EVENT_CHECKEDCHANGED = new object(); private static readonly object EVENT_CHECKSTATECHANGED = new object(); private static readonly object EVENT_APPEARANCECHANGED = new object(); static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; private bool autoCheck; private bool threeState; private bool accObjDoDefaultAction = false; private ContentAlignment checkAlign = ContentAlignment.MiddleLeft; private CheckState checkState; private Appearance appearance; private const int FlatSystemStylePaddingWidth = 25; private const int FlatSystemStyleMinimumHeight = 13; internal int flatSystemStylePaddingWidth = FlatSystemStylePaddingWidth; internal int flatSystemStyleMinimumHeight = FlatSystemStyleMinimumHeight; /// <summary> /// Initializes a new instance of the <see cref='CheckBox'/> class. /// </summary> public CheckBox() : base() { if (DpiHelper.IsScalingRequirementMet) { flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } // Checkboxes shouldn't respond to right clicks, so we need to do all our own click logic SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, false); SetAutoSizeMode(AutoSizeMode.GrowAndShrink); autoCheck = true; TextAlign = ContentAlignment.MiddleLeft; } private bool AccObjDoDefaultAction { get { return accObjDoDefaultAction; } set { accObjDoDefaultAction = value; } } /// <summary> /// Gets /// or sets the value that determines the appearance of a /// check box control. /// </summary> [ DefaultValue(Appearance.Normal), Localizable(true), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.CheckBoxAppearanceDescr)) ] public Appearance Appearance { get { return appearance; } set { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Appearance)); } if (appearance != value) { using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Appearance)) { appearance = value; if (OwnerDraw) { Refresh(); } else { UpdateStyles(); } OnAppearanceChanged(EventArgs.Empty); } } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.CheckBoxOnAppearanceChangedDescr))] public event EventHandler AppearanceChanged { add => Events.AddHandler(EVENT_APPEARANCECHANGED, value); remove => Events.RemoveHandler(EVENT_APPEARANCECHANGED, value); } /// <summary> /// Gets or sets a value indicating whether the <see cref='Checked'/> or <see cref='CheckState'/> /// value and the check box's appearance are automatically /// changed when it is clicked. /// </summary> [ DefaultValue(true), SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckBoxAutoCheckDescr)) ] public bool AutoCheck { get { return autoCheck; } set { autoCheck = value; } } /// <summary> /// Gets or sets /// the horizontal and vertical alignment of a check box on a check box /// control. /// </summary> [ Bindable(true), Localizable(true), SRCategory(nameof(SR.CatAppearance)), DefaultValue(ContentAlignment.MiddleLeft), SRDescription(nameof(SR.CheckBoxCheckAlignDescr)) ] public ContentAlignment CheckAlign { get { return checkAlign; } set { if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } if (checkAlign != value) { checkAlign = value; LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.CheckAlign); if (OwnerDraw) { Invalidate(); } else { UpdateStyles(); } } } } /// <summary> /// Gets /// or sets a value indicating whether the /// check box /// is checked. /// </summary> [ Bindable(true), SettingsBindable(true), DefaultValue(false), SRCategory(nameof(SR.CatAppearance)), RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckedDescr)) ] public bool Checked { get { return checkState != CheckState.Unchecked; } set { if (value != Checked) { CheckState = value ? CheckState.Checked : CheckState.Unchecked; } } } /// <summary> /// Gets /// or sets a value indicating whether the check box is checked. /// </summary> [ Bindable(true), SRCategory(nameof(SR.CatAppearance)), DefaultValue(CheckState.Unchecked), RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckStateDescr)) ] public CheckState CheckState { get { return checkState; } set { // valid values are 0-2 inclusive. if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CheckState)); } if (checkState != value) { bool oldChecked = Checked; checkState = value; if (IsHandleCreated) { SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0); } if (oldChecked != Checked) { OnCheckedChanged(EventArgs.Empty); } OnCheckStateChanged(EventArgs.Empty); } } } /// <hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler DoubleClick { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// <hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseDoubleClick { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } /// <summary> /// Gets the information used to create the handle for the /// <see cref='CheckBox'/> /// control. /// </summary> protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassName = ComCtl32.WindowClasses.WC_BUTTON; if (OwnerDraw) { cp.Style |= (int)User32.BS.OWNERDRAW; } else { cp.Style |= (int)User32.BS.THREE_STATE; if (Appearance == Appearance.Button) { cp.Style |= (int)User32.BS.PUSHLIKE; } // Determine the alignment of the check box // ContentAlignment align = RtlTranslateContent(CheckAlign); if ((int)(align & anyRight) != 0) { cp.Style |= (int)User32.BS.RIGHTBUTTON; } } return cp; } } /// <summary> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </summary> protected override Size DefaultSize { get { return new Size(104, 24); } } /// <summary> /// When overridden in a derived class, handles rescaling of any magic numbers used in control painting. /// For CheckBox controls, scale the width of the system-style padding, and height of the box. /// Must call the base class method to get the current DPI values. This method is invoked only when /// Application opts-in into the Per-monitor V2 support, targets .NETFX 4.7 and has /// EnableDpiChangedMessageHandling and EnableDpiChangedHighDpiImprovements config switches turned on. /// </summary> /// <param name="deviceDpiOld">Old DPI value</param> /// <param name="deviceDpiNew">New DPI value</param> protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } internal override Size GetPreferredSizeCore(Size proposedConstraints) { if (Appearance == Appearance.Button) { ButtonStandardAdapter adapter = new ButtonStandardAdapter(this); return adapter.GetPreferredSizeCore(proposedConstraints); } if (FlatStyle != FlatStyle.System) { return base.GetPreferredSizeCore(proposedConstraints); } Size textSize = TextRenderer.MeasureText(Text, Font); Size size = SizeFromClientSize(textSize); size.Width += flatSystemStylePaddingWidth; size.Height = Math.Max(size.Height + 5, flatSystemStyleMinimumHeight); // ensure minimum height to avoid truncation of check-box or text return size + Padding.Size; } internal override Rectangle OverChangeRectangle { get { if (Appearance == Appearance.Button) { return base.OverChangeRectangle; } else { if (FlatStyle == FlatStyle.Standard) { // this Rectangle will cause no Invalidation // can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle) return new Rectangle(-1, -1, 1, 1); } else { // Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle return Adapter.CommonLayout().Layout().checkBounds; } } } } internal override Rectangle DownChangeRectangle { get { if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) { return base.DownChangeRectangle; } else { // Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle() return Adapter.CommonLayout().Layout().checkBounds; } } } /// <summary> /// Gets or sets a value indicating the alignment of the /// text on the checkbox control. /// </summary> [ Localizable(true), DefaultValue(ContentAlignment.MiddleLeft) ] public override ContentAlignment TextAlign { get { return base.TextAlign; } set { base.TextAlign = value; } } /// <summary> /// Gets or sets a value indicating /// whether the check box will allow three check states rather than two. /// </summary> [ DefaultValue(false), SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckBoxThreeStateDescr)) ] public bool ThreeState { get { return threeState; } set { threeState = value; } } /// <summary> /// Occurs when the /// value of the <see cref='Checked'/> /// property changes. /// </summary> [SRDescription(nameof(SR.CheckBoxOnCheckedChangedDescr))] public event EventHandler CheckedChanged { add => Events.AddHandler(EVENT_CHECKEDCHANGED, value); remove => Events.RemoveHandler(EVENT_CHECKEDCHANGED, value); } /// <summary> /// Occurs when the /// value of the <see cref='CheckState'/> /// property changes. /// </summary> [SRDescription(nameof(SR.CheckBoxOnCheckStateChangedDescr))] public event EventHandler CheckStateChanged { add => Events.AddHandler(EVENT_CHECKSTATECHANGED, value); remove => Events.RemoveHandler(EVENT_CHECKSTATECHANGED, value); } /// <summary> /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// </summary> protected override AccessibleObject CreateAccessibilityInstance() { return new CheckBoxAccessibleObject(this); } protected virtual void OnAppearanceChanged(EventArgs e) { if (Events[EVENT_APPEARANCECHANGED] is EventHandler eh) { eh(this, e); } } /// <summary> /// Raises the <see cref='CheckedChanged'/> /// event. /// </summary> protected virtual void OnCheckedChanged(EventArgs e) { // accessibility stuff if (FlatStyle == FlatStyle.System) { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureStart, -1); } AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); if (FlatStyle == FlatStyle.System) { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureEnd, -1); } ((EventHandler)Events[EVENT_CHECKEDCHANGED])?.Invoke(this, e); } /// <summary> /// Raises the <see cref='CheckStateChanged'/> event. /// </summary> protected virtual void OnCheckStateChanged(EventArgs e) { if (OwnerDraw) { Refresh(); } ((EventHandler)Events[EVENT_CHECKSTATECHANGED])?.Invoke(this, e); } /// <summary> /// Fires the event indicating that the control has been clicked. /// Inheriting controls should use this in favour of actually listening to /// the event, but should not forget to call base.onClicked() to /// ensure that the event is still fired for external listeners. /// </summary> protected override void OnClick(EventArgs e) { if (autoCheck) { switch (CheckState) { case CheckState.Unchecked: CheckState = CheckState.Checked; break; case CheckState.Checked: if (threeState) { CheckState = CheckState.Indeterminate; // If the check box is clicked as a result of AccObj::DoDefaultAction // then the native check box does not fire OBJ_STATE_CHANGE event when going to Indeterminate state. // So the WinForms layer fires the OBJ_STATE_CHANGE event. if (AccObjDoDefaultAction) { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); } } else { CheckState = CheckState.Unchecked; } break; default: CheckState = CheckState.Unchecked; break; } } base.OnClick(e); } /// <summary> /// We override this to ensure that the control's click values are set up /// correctly. /// </summary> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // Since this is a protected override... // this can be directly called in by a overriden class.. // and the Handle need not be created... // So Check for the handle if (IsHandleCreated) { SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0); } } /// <summary> /// We override this to ensure that press '+' or '=' checks the box, /// while pressing '-' unchecks the box /// </summary> protected override void OnKeyDown(KeyEventArgs e) { /* if (Enabled) { if (e.KeyCode == Keys.Oemplus || e.KeyCode == Keys.Add) { CheckState = CheckState.Checked; } if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract) { CheckState = CheckState.Unchecked; } } */ base.OnKeyDown(e); } /// <summary> /// Raises the <see cref='ButtonBase.OnMouseUp'/> event. /// </summary> protected override void OnMouseUp(MouseEventArgs mevent) { if (mevent.Button == MouseButtons.Left && MouseIsPressed) { // It's best not to have the mouse captured while running Click events if (base.MouseIsDown) { Point pt = PointToScreen(new Point(mevent.X, mevent.Y)); if (User32.WindowFromPoint(pt) == Handle) { //Paint in raised state... ResetFlagsandPaint(); if (!ValidationCancelled) { if (Capture) { OnClick(mevent); } OnMouseClick(mevent); } } } } base.OnMouseUp(mevent); } internal override ButtonBaseAdapter CreateFlatAdapter() { return new CheckBoxFlatAdapter(this); } internal override ButtonBaseAdapter CreatePopupAdapter() { return new CheckBoxPopupAdapter(this); } internal override ButtonBaseAdapter CreateStandardAdapter() { return new CheckBoxStandardAdapter(this); } /// <summary> /// Overridden to handle mnemonics properly. /// </summary> protected internal override bool ProcessMnemonic(char charCode) { if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) { if (Focus()) { //Paint in raised state... // ResetFlagsandPaint(); if (!ValidationCancelled) { OnClick(EventArgs.Empty); } } return true; } return false; } /// <summary> /// Provides some interesting information for the CheckBox control in /// String form. /// </summary> public override string ToString() { string s = base.ToString(); // We shouldn't need to convert the enum to int int checkState = (int)CheckState; return s + ", CheckState: " + checkState.ToString(CultureInfo.InvariantCulture); } [ComVisible(true)] public class CheckBoxAccessibleObject : ButtonBaseAccessibleObject { public CheckBoxAccessibleObject(Control owner) : base(owner) { } public override string DefaultAction { get { string defaultAction = Owner.AccessibleDefaultActionDescription; if (defaultAction != null) { return defaultAction; } if (((CheckBox)Owner).Checked) { return SR.AccessibleActionUncheck; } else { return SR.AccessibleActionCheck; } } } public override AccessibleRole Role { get { AccessibleRole role = Owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } return AccessibleRole.CheckButton; } } public override AccessibleStates State { get { switch (((CheckBox)Owner).CheckState) { case CheckState.Checked: return AccessibleStates.Checked | base.State; case CheckState.Indeterminate: return AccessibleStates.Indeterminate | base.State; } return base.State; } } public override void DoDefaultAction() { CheckBox cb = Owner as CheckBox; if (cb != null) { cb.AccObjDoDefaultAction = true; } try { base.DoDefaultAction(); } finally { if (cb != null) { cb.AccObjDoDefaultAction = false; } } } } } }
33.203085
148
0.497097
[ "MIT" ]
AArnott/winforms
src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs
25,834
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace WinApp { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new p3XamarinApp.App()); } } }
25.787879
94
0.714454
[ "MIT" ]
pierre3/p3XamarinApp
Xamarin/WinApp/MainPage.xaml.cs
853
C#
using NHibernate.Criterion; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ee.SessionFactory.Repository { /// <summary> /// Interface to entity repository, contains the basic CRUD methods that entity repository must implement /// </summary> /// <typeparam name="TEntity"> /// The type of entity that the repository implemntation will manage /// </typeparam> /// <typeparam name="TKey">The type of the key that the repository will manage</typeparam> public interface IEntityRepository<TEntity> where TEntity : class { /// <summary> /// Gets an entity by it's unique ID /// </summary> /// <param name="id">Id of the entity to retrieve</param> /// <returns>The updated entity</returns> TEntity GetById(object id); /// <summary> /// Inserts an entity into the repository /// </summary> /// <param name="entity">the entity to be stored</param> /// <returns>the updated entity</returns> TEntity Create(TEntity entity); /// <summary> /// Updates an entity in the repository /// </summary> /// <param name="entity">the entity to be updated</param> /// <returns>the</returns> TEntity Update(TEntity entity); /// <summary> /// Deletes an entity from the repository /// </summary> /// <param name="entity">the entity to be deleted</param> void Delete(TEntity entity); IEnumerable<TEntity> Query(Expression<Func<TEntity, bool>> expression = null, bool cacheable = false); IEnumerable<TEntity> QueryInCriterion(List<ICriterion> criterions, bool cacheable = false); (IEnumerable<TEntity>, int?) QueryByPage(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, object>> orderby, bool isDesc = false, int pageIndex = 1, int pageSize = 0, PageQueryOption option = PageQueryOption.Both, bool cacheable = false); (IEnumerable<TEntity>, int?) QueryByPageInCriterion(List<ICriterion> criterions, Expression<Func<TEntity, object>> orderby, bool isDesc = false, int pageIndex = 1, int pageSize = 0, PageQueryOption option = PageQueryOption.Both, bool cacheable = false); } }
44.568627
265
0.657721
[ "Apache-2.0" ]
Egoily/iLawyer
01.Framework/ee.SessionFactory/Repository/IEntityRepository.cs
2,275
C#
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class Contact : Resource { public Contact() { } public Contact(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public Contact(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public Contact(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string FirstName { get { return GetValue<string>("first_name", false); } } public string LastName { get { return GetValue<string>("last_name", false); } } public string Email { get { return GetValue<string>("email", true); } } public string Phone { get { return GetValue<string>("phone", false); } } public string Label { get { return GetValue<string>("label", false); } } public bool Enabled { get { return GetValue<bool>("enabled", true); } } public bool SendAccountEmail { get { return GetValue<bool>("send_account_email", true); } } public bool SendBillingEmail { get { return GetValue<bool>("send_billing_email", true); } } #endregion #region Subclasses #endregion } }
23.204301
70
0.528267
[ "MIT" ]
bjacobowski/chargebee-dotnet
ChargeBee/Models/Contact.cs
2,158
C#
using EventBus.Messages.Common; using MassTransit; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Ordering.API.EventBusConsumer; using Ordering.Application; using Ordering.Infrastructure; namespace Ordering.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddApplicationServices(); services.AddInfrastructureServices(Configuration); //MassTransit-RabbitMQ Configuration services.AddMassTransit(confiq => { confiq.AddConsumer<BasketCheckoutConsumer>(); confiq.UsingRabbitMq((ctx, cfg) => { cfg.Host(Configuration["EventBusSettings:HostAddress"]); cfg.ReceiveEndpoint(EventBusConstants.BasketCheckoutQueue, c => { c.ConfigureConsumer<BasketCheckoutConsumer>(ctx); }); }); }); services.AddMassTransitHostedService(); //General Configuration services.AddAutoMapper(typeof(Startup)); services.AddScoped<BasketCheckoutConsumer>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Ordering.API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ordering.API v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
32.74026
106
0.596589
[ "MIT" ]
FarooqFastian/MicroserviceByFarooq
src/Services/Ordering/Ordering.API/Startup.cs
2,521
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class TriviaRewriter : CSharpSyntaxRewriter { private readonly SyntaxNode _node; private readonly SimpleIntervalTree<TextSpan> _spans; private readonly CancellationToken _cancellationToken; private readonly Dictionary<SyntaxToken, SyntaxTriviaList> _trailingTriviaMap; private readonly Dictionary<SyntaxToken, SyntaxTriviaList> _leadingTriviaMap; public TriviaRewriter( SyntaxNode node, SimpleIntervalTree<TextSpan> spanToFormat, Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { Contract.ThrowIfNull(node); Contract.ThrowIfNull(map); _node = node; _spans = spanToFormat; _cancellationToken = cancellationToken; _trailingTriviaMap = new Dictionary<SyntaxToken, SyntaxTriviaList>(); _leadingTriviaMap = new Dictionary<SyntaxToken, SyntaxTriviaList>(); PreprocessTriviaListMap(map, cancellationToken); } public SyntaxNode Transform() { return Visit(_node); } private void PreprocessTriviaListMap( Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { foreach (var pair in map) { cancellationToken.ThrowIfCancellationRequested(); var tuple = GetTrailingAndLeadingTrivia(pair, cancellationToken); if (pair.Key.Item1.RawKind != 0) { _trailingTriviaMap.Add(pair.Key.Item1, tuple.Item1); } if (pair.Key.Item2.RawKind != 0) { _leadingTriviaMap.Add(pair.Key.Item2, tuple.Item2); } } } private ValueTuple<SyntaxTriviaList, SyntaxTriviaList> GetTrailingAndLeadingTrivia( KeyValuePair<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> pair, CancellationToken cancellationToken) { if (pair.Key.Item1.RawKind == 0) { return ValueTuple.Create(default(SyntaxTriviaList), GetLeadingTriviaAtBeginningOfTree(pair.Key, pair.Value, cancellationToken)); } var csharpTriviaData = pair.Value as TriviaDataWithList; if (csharpTriviaData != null) { var triviaList = csharpTriviaData.GetTriviaList(cancellationToken); var index = GetFirstEndOfLineIndexOrRightBeforeComment(triviaList); return ValueTuple.Create( SyntaxFactory.TriviaList(CreateTriviaListFromTo(triviaList, 0, index)), SyntaxFactory.TriviaList(CreateTriviaListFromTo(triviaList, index + 1, triviaList.Count - 1))); } // whitespace trivia case such as spaces/tabes/new lines // these will always have a single text change var text = pair.Value.GetTextChanges(GetTextSpan(pair.Key)).Single().NewText; var trailingTrivia = SyntaxFactory.ParseTrailingTrivia(text); int width = trailingTrivia.GetFullWidth(); var leadingTrivia = SyntaxFactory.ParseLeadingTrivia(text.Substring(width)); return ValueTuple.Create(trailingTrivia, leadingTrivia); } private TextSpan GetTextSpan(ValueTuple<SyntaxToken, SyntaxToken> pair) { if (pair.Item1.RawKind == 0) { return TextSpan.FromBounds(_node.FullSpan.Start, pair.Item2.SpanStart); } if (pair.Item2.RawKind == 0) { return TextSpan.FromBounds(pair.Item1.Span.End, _node.FullSpan.End); } return TextSpan.FromBounds(pair.Item1.Span.End, pair.Item2.SpanStart); } private IEnumerable<SyntaxTrivia> CreateTriviaListFromTo(List<SyntaxTrivia> triviaList, int startIndex, int endIndex) { if (startIndex > endIndex) { yield break; } for (int i = startIndex; i <= endIndex; i++) { yield return triviaList[i]; } } private int GetFirstEndOfLineIndexOrRightBeforeComment(List<SyntaxTrivia> triviaList) { for (int i = 0; i < triviaList.Count; i++) { var trivia = triviaList[i]; if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { return i; } if (trivia.IsDocComment()) { return i - 1; } } return triviaList.Count - 1; } private SyntaxTriviaList GetLeadingTriviaAtBeginningOfTree( ValueTuple<SyntaxToken, SyntaxToken> pair, TriviaData triviaData, CancellationToken cancellationToken) { var csharpTriviaData = triviaData as TriviaDataWithList; if (csharpTriviaData != null) { return SyntaxFactory.TriviaList(csharpTriviaData.GetTriviaList(cancellationToken)); } // whitespace trivia case such as spaces/tabes/new lines // these will always have single text changes var text = triviaData.GetTextChanges(GetTextSpan(pair)).Single().NewText; return SyntaxFactory.ParseLeadingTrivia(text); } public override SyntaxNode Visit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); if (node == null || !_spans.IntersectsWith(node.FullSpan)) { return node; } return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { _cancellationToken.ThrowIfCancellationRequested(); if (!_spans.IntersectsWith(token.FullSpan)) { return token; } var hasChanges = false; // get token span // check whether we have trivia info belongs to this token var leadingTrivia = token.LeadingTrivia; var trailingTrivia = token.TrailingTrivia; if (_trailingTriviaMap.ContainsKey(token)) { // okay, we have this situation // token|trivia trailingTrivia = _trailingTriviaMap[token]; hasChanges = true; } if (_leadingTriviaMap.ContainsKey(token)) { // okay, we have this situation // trivia|token leadingTrivia = _leadingTriviaMap[token]; hasChanges = true; } if (hasChanges) { return CreateNewToken(leadingTrivia, token, trailingTrivia); } // we have no trivia belongs to this one return token; } private SyntaxToken CreateNewToken(SyntaxTriviaList leadingTrivia, SyntaxToken token, SyntaxTriviaList trailingTrivia) { return token.With(leadingTrivia, trailingTrivia); } } }
34.844156
161
0.598087
[ "Apache-2.0" ]
davidfowl/roslyn
src/Workspaces/CSharp/Portable/Formatting/Engine/Trivia/TriviaRewriter.cs
8,051
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.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualGatewaySubjectAlternativeNameMatchers { public readonly ImmutableArray<string> Exact; [OutputConstructor] private VirtualGatewaySubjectAlternativeNameMatchers(ImmutableArray<string> exact) { Exact = exact; } } }
26.64
90
0.714715
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/AppMesh/Outputs/VirtualGatewaySubjectAlternativeNameMatchers.cs
666
C#
using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace TixFactory.Logging.Service.ElasticSearch { internal class SearchHit { [JsonPropertyName("_id")] public string Id { get; set; } } }
18.666667
50
0.758929
[ "MIT" ]
tix-factory/monitoring
Services/Logging/TixFactory.Logging.Service/Models/ElasticSearch/SearchHit.cs
226
C#
using System; using Newtonsoft.Json; using System.Xml.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// KbAdvertContentShareCode Data Structure. /// </summary> [Serializable] public class KbAdvertContentShareCode : AlipayObject { /// <summary> /// 吱口令内容详情 /// </summary> [JsonProperty("share_code_desc")] [XmlElement("share_code_desc")] public string ShareCodeDesc { get; set; } } }
23.714286
56
0.638554
[ "MIT" ]
Aosir/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/KbAdvertContentShareCode.cs
512
C#
using System; using System.Net.Http; using Couchbase.Core.DataMapping; using Couchbase.Core.IO.Operations.Legacy; using Couchbase.Utils; namespace Couchbase.Core.IO.HTTP { /// <summary> /// Base class for HTTP services to inherit from to provide consistent access to configuration, /// http client and data mapper. /// </summary> /// <seealso cref="System.IDisposable" /> internal abstract class HttpServiceBase : IDisposable { private const string ConnectionIdHeaderName = "cb-client-id"; protected HttpServiceBase(HttpClient httpClient, IDataMapper dataMapper, IConfiguration configuration) { HttpClient = httpClient; DataMapper = dataMapper; Configuration = configuration; // set custom header for client / connection ID httpClient.DefaultRequestHeaders.Add(ConnectionIdHeaderName, ClientIdentifier.FormatConnectionString(ConnectionId)); } /// <summary> /// Gets the client configuration. /// </summary> protected Couchbase.IConfiguration Configuration { get; set; } /// <summary> /// The <see cref="HttpClient"/> used to execute the HTTP request against the Couchbase server. /// </summary> protected HttpClient HttpClient { get; set; } /// <summary> /// The <see cref="IDataMapper"/> to use for mapping the output stream to a Type. /// </summary> protected IDataMapper DataMapper { get; set; } /// <summary> /// Gets or sets the last activity. /// </summary> public DateTime? LastActivity { get; private set; } /// <summary> /// Gets the connection identifier for this HTTP service instance. /// </summary> public ulong ConnectionId { get; } = SequenceGenerator.GetRandomLong(); /// <summary> /// The configuration context for this instance. /// </summary> // protected ConfigContextBase Context { get; set; } public void Dispose() { HttpClient?.Dispose(); } protected void UpdateLastActivity() { LastActivity = DateTime.UtcNow; } } } #region [ License information ] /* ************************************************************ * * @author Couchbase <info@couchbase.com> * @copyright 2017 Couchbase, Inc. * * 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
33.663043
128
0.609622
[ "Apache-2.0" ]
MikeGoldsmith/dotnet-couchbase-client
src/Couchbase/Core/IO/HTTP/HttpServiceBase.cs
3,099
C#
using System.Collections.Generic; namespace essentialMix.Collections; public interface ISiblingNode<TNode, T> : ITreeNode<TNode, T> where TNode : ISiblingNode<TNode, T> { TNode Child { get; } TNode Sibling { get; } bool IsLeaf { get; } IEnumerable<TNode> Children(); IEnumerable<TNode> Siblings(); } public interface ISiblingNode<TNode, TKey, TValue> : ISiblingNode<TNode, TValue>, ITreeNode<TNode, TKey, TValue> where TNode : ISiblingNode<TNode, TKey, TValue> { }
26.555556
112
0.736402
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix/Collections/ISiblingNode.cs
480
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AsteroidSmallPool { public ObjectPool<AsteroidView> AsteroidPool; public AsteroidSmallPool(int startCount, bool isExpandable, Transform parentObject, AsteroidView prefab) { AsteroidPool = new ObjectPool<AsteroidView>(prefab, startCount, parentObject, isExpandable); } public void DeactivateAsteroid(AsteroidView asteroid) { AsteroidPool.ReturnObjectToPool(asteroid); } }
29.882353
108
0.765748
[ "MIT" ]
Neron94/Asteroid
Assets/Scripts/Other Functions/AsteroidSmallPool.cs
508
C#
#nullable enable using System; using System.Collections.Generic; using System.Threading.Tasks; using AppKit; using CoreGraphics; using Foundation; using Uno.Extensions; using Uno.Foundation.Logging; using Windows.Foundation; namespace Windows.ApplicationModel.DataTransfer { public partial class DataTransferManager { private const int DefaultPickerWidth = 120; private const int DefaultPickerHeight = 160; public static bool IsSupported() => true; private static async Task<bool> ShowShareUIAsync(ShareUIOptions options, DataPackage dataPackage) { var window = NSApplication.SharedApplication.MainWindow; if (window == null) { throw new InvalidOperationException("Sharing is not possible when no window is active."); } var view = window.ContentView; if (view != null) { var dataPackageView = dataPackage.GetView(); var sharedData = new List<NSObject>(); if (dataPackageView.Contains(StandardDataFormats.Text)) { var text = await dataPackageView.GetTextAsync(); sharedData.Add(new NSString(text)); } var uri = await GetSharedUriAsync(dataPackageView); if (uri != null && NSUrl.FromString(uri.OriginalString) is { } nsUrl) { sharedData.Add(nsUrl); } CGRect targetRect; if (options.SelectionRect != null) { targetRect = options.SelectionRect.Value; } else { // Try to center the picker within the window targetRect = new CGRect( view.Bounds.Width / 2f - DefaultPickerWidth / 2, view.Bounds.Height / 2 - DefaultPickerHeight / 2, 0, 0); } var picker = new NSSharingServicePicker(sharedData.ToArray()); var completionSource = new TaskCompletionSource<bool>(); picker.DidChooseSharingService += (s, e) => { completionSource.SetResult(e.Service != null); }; picker.ShowRelativeToRect(targetRect, view, NSRectEdge.MinYEdge); return await completionSource.Task; } else { if (typeof(DataTransferManager).Log().IsEnabled(LogLevel.Error)) { typeof(DataTransferManager).Log().LogError($"The current Window.ContentView is null, unable to run ShowShareUIAsync"); } return false; } } } }
24.32967
123
0.69467
[ "Apache-2.0" ]
iury-kc/uno
src/Uno.UWP/ApplicationModel/DataTransfer/DataTransferManager.macOS.cs
2,216
C#
using Microsoft.AspNetCore.Mvc; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Mvc.Rendering; using TreatShop.Models; using System; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using System.Security.Claims; using System.Collections.Generic; namespace TreatShop.Controllers { public class TreatsController : Controller { private readonly TreatShopContext _db; private readonly UserManager<ApplicationUser> _userManager; public TreatsController(TreatShopContext db, UserManager<ApplicationUser> userManager) { _db = db; _userManager = userManager; } public ActionResult Index() { return View(_db.Treats.ToList()); } [Authorize] public ActionResult Create() { ViewBag.FlavorId = new SelectList(_db.Flavors, "FlavorId", "Name"); return View(); } [HttpPost] public async Task<ActionResult> Create(Treat treat, int FlavorId) { var userId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var currentUser = await _userManager.FindByIdAsync(userId); treat.User = currentUser; _db.Treats.Add(treat); if (FlavorId != 0) { _db.TreatFlavor.Add(new TreatFlavor() {FlavorId = FlavorId, TreatId = treat.TreatId}); } _db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Details(int id) { var thisTreat = _db.Treats .Include(treat => treat.Flavors) .ThenInclude(join => join.Flavor) .Include(treat => treat.User) .FirstOrDefault(treat => treat.TreatId == id); var userId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; ViewBag.IsCurrentUser = userId != null ? userId == thisTreat.User.Id : false; return View(thisTreat); } [Authorize] public async Task<ActionResult> Edit(int id) { var userId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var currentUser = await _userManager.FindByIdAsync(userId); Treat thisTreat = _db.Treats.Where(entry => entry.User.Id == currentUser.Id).FirstOrDefault(treat => treat.TreatId == id); if(thisTreat == null) { return RedirectToAction("Details", new {id = id}); } ViewBag.FlavorId = new SelectList(_db.Flavors, "FlavorId", "Name"); return View(thisTreat); } [HttpPost] public ActionResult Edit(int FlavorId, Treat treat) { if (FlavorId != 0) { _db.TreatFlavor.Add(new TreatFlavor() { FlavorId = FlavorId, TreatId = treat.TreatId }); } _db.Entry(treat).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Details", new {id = treat.TreatId}); } public ActionResult AddFlavor(int id) { Treat thisTreat = _db.Treats.FirstOrDefault(treat => treat.TreatId == id); ViewBag.FlavorId = new SelectList(_db.Flavors, "FlavorId", "Name"); return View(thisTreat); } [HttpPost] public ActionResult AddFlavor(Treat treat, int FlavorId) { if(FlavorId != 0) { _db.TreatFlavor.Add(new TreatFlavor {FlavorId = FlavorId, TreatId = treat.TreatId}); } _db.Entry(treat).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Details", new {id = treat.TreatId}); } public ActionResult Delete(int id) { Treat treatToDelete = _db.Treats.FirstOrDefault(treat => treat.TreatId == id); return View(treatToDelete); } [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirm(int id) { Treat treatToDelete = _db.Treats.FirstOrDefault(treat => treat.TreatId == id); _db.Treats.Remove(treatToDelete); _db.SaveChanges(); return RedirectToAction("Index"); } } }
30.265625
128
0.662881
[ "MIT" ]
KeturahDev/TreatShop
TreatShop/Controllers/TreatsController.cs
3,874
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Au.Models.Common; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using KeyPayV2.Au.Enums; namespace KeyPayV2.Au.Models.Common { public class KioskEmployeeModel { public bool PinExpired { get; set; } public int EmployeeId { get; set; } public string FirstName { get; set; } public string Surname { get; set; } public string Name { get; set; } public bool HasEmail { get; set; } public string ProfileImageUrl { get; set; } public string MobileNumber { get; set; } [JsonConverter(typeof(StringEnumConverter))] public TimeAttendanceStatus Status { get; set; } public bool LongShift { get; set; } public DateTime? ClockOnTimeUtc { get; set; } public DateTime? BreakStartTimeUtc { get; set; } public DateTime? RecordedTimeUtc { get; set; } public int? CurrentShiftId { get; set; } public IList<Int32> EmployeeGroupIds { get; set; } public DateTime? EmployeeStartDate { get; set; } } }
36.34375
59
0.638865
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Au/Models/Common/KioskEmployeeModel.cs
1,163
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("83f4b607-e9fe-404e-8d72-29613e3b8bf3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.952381
56
0.748355
[ "BSD-3-Clause" ]
shoupn/npgsqlDotnet
Test/Properties/AssemblyInfo.cs
609
C#
using MsCoreOne.Application.Common.Interfaces.Repositories; using MsCoreOne.Domain.Entities; using MsCoreOne.Infrastructure.Persistence; using System; using System.Collections.Generic; using System.Text; namespace MsCoreOne.Infrastructure.Repositories { public class ProductRepository : RepositoryBase<Product>, IProductRepository { public ProductRepository(ApplicationDbContext context) : base(context) { } } }
27.8125
80
0.779775
[ "MIT" ]
jillmnolan/MsCoreOne
src/MsCoreOne.Infrastructure/Repositories/ProductRepository.cs
447
C#
using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks; namespace MSFSTouchPortalPlugin.Interfaces { /// <summary> /// Handles communication with the Touch Portal /// </summary> internal interface IPluginService : IHostedService { new Task StartAsync(CancellationToken cancellationToken); new Task StopAsync(CancellationToken cancellationToken); } }
28.857143
61
0.777228
[ "MIT" ]
mpaperno/MSFSTouchPortalPlugin
MSFSTouchPortalPlugin/Interfaces/IPluginService.cs
406
C#
// -------------------------------------------------------------------------------------------------------------------- // <auto-generated> // Generated using OBeautifulCode.CodeGen.ModelObject (1.0.0.0) // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.CodeGen.ModelObject.Test { using global::System; using global::System.CodeDom.Compiler; using global::System.Collections.Concurrent; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Diagnostics.CodeAnalysis; using global::System.Globalization; using global::System.Linq; using global::OBeautifulCode.Cloning.Recipes; using global::OBeautifulCode.Equality.Recipes; using global::OBeautifulCode.Type; using global::OBeautifulCode.Type.Recipes; using static global::System.FormattableString; [Serializable] public partial class ModelCloningPublicSetReadOnlyCollection : IDeepCloneable<ModelCloningPublicSetReadOnlyCollection> { /// <inheritdoc /> public object Clone() => this.DeepClone(); } }
39.064516
122
0.593724
[ "MIT" ]
OBeautifulCode/OBeautifulCode.CodeGen
OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/Cloning/PublicSet/ReadOnlyCollection/ModelCloningPublicSetReadOnlyCollection.designer.cs
1,213
C#
using GameEngine.Exceptions; using GameEngine.Services.ComputerMove; using System.Collections.Generic; using static GameEngine.PlayerEnum; namespace GameEngine { public class Game : IGame { // TODO ~ this member being public is just a quick hack while buulding `ComputerMove` rules // the UI will need to be able to set this public ComputerLevel ComputerLevel { get; set; } // TODO ~ this is also a hack, this state should be controlled by well defined methods public bool GameOver { get; set; } private string _currentPlayer = Player.X.ToString(); // X is now the human forever more, this is not great as this is then assumed in the `ComputerMoveX` classes private Dictionary<int, string> _board; public Game() { ComputerLevel = ComputerLevel.Hard; GameOver = false; ResetBoard(); } public void SwapCurrentPlayer() { if (_currentPlayer.Equals(Player.X.ToString())) _currentPlayer = Player.O.ToString(); else _currentPlayer = Player.X.ToString(); } public void ResetBoard() { _board = new Dictionary<int, string>(); for (int i = 1; i <= 9; i++) { _board.Add(i, string.Empty); } } public void SetPosition(Player player, int position) { if (position <= 0) throw new PositionException("Position selection too small."); if (position >= 10) throw new PositionException("Position selection too large."); if (_board.TryGetValue(position, out string s)) { if (s.Equals(string.Empty)) _board[position] = player.ToString(); else throw new PositionException("Position already taken."); } } public string GetPositionValue(int position) { if (_board.TryGetValue(position, out string s)) return s; return string.Empty; } public Dictionary<int, string> GetCurrentBoard() { return _board; } public string GetCurrentPlayer() { return _currentPlayer; } } }
29.8
169
0.551594
[ "MIT" ]
carlpaton/TicTacToe
GameEngine/Game.cs
2,386
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace ArcMovies.Models { [DataContract] public class MovieVideo { [DataMember(Name = "id")] public int MovieId { get; set; } [DataMember(Name = "results")] public IList<MovieVideoItem> Videos { get; set; } } }
22.266667
57
0.637725
[ "MIT" ]
andrewBezerra/ArcMovies
ArcMovies/ArcMovies/Models/MovieVideo.cs
336
C#
// <copyright file="GoalReminderActivityHelper.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.GoalTracker.Helpers { using System; using System.Globalization; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using AdaptiveCards; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Teams.Apps.GoalTracker.Cards; using Microsoft.Teams.Apps.GoalTracker.Common; using Microsoft.Teams.Apps.GoalTracker.Models; using Polly; using Polly.Contrib.WaitAndRetry; using Polly.Retry; /// <summary> /// Class to send goal reminder in personal bot and in team. /// </summary> public class GoalReminderActivityHelper : IGoalReminderActivityHelper { /// <summary> /// Represents retry delay. /// </summary> private const int RetryDelay = 1000; /// <summary> /// Represents retry count. /// </summary> private const int RetryCount = 2; /// <summary> /// Retry policy with jitter, retry twice with a jitter delay of up to 1 sec. Retry for HTTP 429(transient error)/502 bad gateway. /// </summary> /// <remarks> /// Reference: https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry#new-jitter-recommendation. /// </remarks> private readonly AsyncRetryPolicy retryPolicy = Policy.Handle<ErrorResponseException>( ex => ex.Response.StatusCode == HttpStatusCode.TooManyRequests || ex.Response.StatusCode == HttpStatusCode.BadGateway) .WaitAndRetryAsync(Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromMilliseconds(RetryDelay), RetryCount)); /// <summary> /// Microsoft application credentials. /// </summary> private readonly MicrosoftAppCredentials microsoftAppCredentials; /// <summary> /// Bot adapter. /// </summary> private readonly IBotFrameworkHttpAdapter adapter; /// <summary> /// Instance to send logs to the Application Insights service. /// </summary> private readonly ILogger<GoalReminderActivityHelper> logger; /// <summary> /// The current cultures' string localizer. /// </summary> private readonly IStringLocalizer<Strings> localizer; /// <summary> /// A set of key/value application configuration properties for Activity settings. /// </summary> private readonly IOptions<GoalTrackerActivityHandlerOptions> options; /// <summary> /// Storage provider for working with personal goal data in storage. /// </summary> private readonly IPersonalGoalStorageProvider personalGoalStorageProvider; /// <summary> /// Storage provider for working with personal goal note data in storage. /// </summary> private readonly IPersonalGoalNoteStorageProvider personalGoalNoteStorageProvider; /// <summary> /// Storage provider for working with team goal data in storage. /// </summary> private readonly ITeamGoalStorageProvider teamGoalStorageProvider; /// <summary> /// Instance of class that handles goal helper methods. /// </summary> private readonly GoalHelper goalHelper; /// <summary> /// Initializes a new instance of the <see cref="GoalReminderActivityHelper"/> class. /// BackgroundService class that inherits IHostedService and implements the methods related to sending notification tasks. /// </summary> /// <param name="logger">Instance to send logs to the Application Insights service.</param> /// <param name="localizer">The current cultures' string localizer.</param> /// <param name="options">A set of key/value application configuration properties for activity handler.</param> /// <param name="microsoftAppCredentials">Instance for Microsoft application credentials.</param> /// <param name="adapter">An instance of bot adapter.</param> /// <param name="personalGoalStorageProvider">Storage provider for working with personal goal data in storage.</param> /// <param name="personalGoalNoteStorageProvider">Storage provider for working with personal goal note data in storage</param> /// <param name="teamGoalStorageProvider">Storage provider for working with team goal data in storage.</param> /// <param name="goalHelper">Instance of class that handles goal helper methods.</param> public GoalReminderActivityHelper( ILogger<GoalReminderActivityHelper> logger, IStringLocalizer<Strings> localizer, IOptions<GoalTrackerActivityHandlerOptions> options, MicrosoftAppCredentials microsoftAppCredentials, IBotFrameworkHttpAdapter adapter, IPersonalGoalStorageProvider personalGoalStorageProvider, IPersonalGoalNoteStorageProvider personalGoalNoteStorageProvider, ITeamGoalStorageProvider teamGoalStorageProvider, GoalHelper goalHelper) { this.logger = logger; this.localizer = localizer; this.options = options; this.microsoftAppCredentials = microsoftAppCredentials; this.adapter = adapter; this.personalGoalStorageProvider = personalGoalStorageProvider; this.personalGoalNoteStorageProvider = personalGoalNoteStorageProvider; this.teamGoalStorageProvider = teamGoalStorageProvider; this.goalHelper = goalHelper; } /// <summary> /// Method to send goal reminder card to personal bot. /// </summary> /// <param name="personalGoalDetail">Holds personal goal detail entity data sent from background service.</param> /// <param name="isReminderBeforeThreeDays">Determines reminder to be sent prior 3 days to end date.</param> /// <returns>A Task represents goal reminder card is sent to the bot, installed in the personal scope.</returns> public async Task SendGoalReminderToPersonalBotAsync(PersonalGoalDetail personalGoalDetail, bool isReminderBeforeThreeDays = false) { personalGoalDetail = personalGoalDetail ?? throw new ArgumentNullException(nameof(personalGoalDetail)); var conversationReference = new ConversationReference() { ChannelId = Constants.TeamsBotFrameworkChannelId, Bot = new ChannelAccount() { Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}" }, ServiceUrl = personalGoalDetail.ServiceUrl, Conversation = new ConversationAccount() { ConversationType = Constants.PersonalConversationType, Id = personalGoalDetail.ConversationId, TenantId = this.options.Value.TenantId }, }; try { await this.retryPolicy.ExecuteAsync(async () => { await ((BotFrameworkAdapter)this.adapter).ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, conversationReference, async (turnContext, cancellationToken) => { string reminderType = string.Empty; AdaptiveTextColor reminderTypeColor = AdaptiveTextColor.Accent; if (isReminderBeforeThreeDays) { reminderType = this.localizer.GetString("PersonalGoalEndingAfterThreeDays"); reminderTypeColor = AdaptiveTextColor.Attention; } else { reminderType = this.GetReminderTypeString(personalGoalDetail.ReminderFrequency); } var goalReminderAttachment = MessageFactory.Attachment(GoalReminderCard.GetGoalReminderCard(this.localizer, this.options.Value.ManifestId, this.options.Value.GoalsTabEntityId, reminderType, reminderTypeColor)); this.logger.LogInformation($"Sending goal reminder card to Personal bot. Conversation id: {personalGoalDetail.ConversationId}"); await turnContext.SendActivityAsync(goalReminderAttachment, cancellationToken); }, CancellationToken.None); }); } catch (Exception ex) { this.logger.LogError(ex, $"Error while sending goal reminder card to personal bot: {ex.Message} at {nameof(this.SendGoalReminderToPersonalBotAsync)}"); throw; } } /// <summary> /// Update personal goal details and personal goal note details in storage when personal goal cycle is ended. /// </summary> /// <param name="userAadObjectId">AAD object id of the user whose goal details needs to be deleted.</param> /// <returns>A task that represents personal goal detail entity data is saved or updated.</returns> public async Task UpdatePersonalGoalAndNoteDetailsAsync(string userAadObjectId) { try { var personalGoalEntities = await this.personalGoalStorageProvider.GetPersonalGoalDetailsByUserAadObjectIdAsync(userAadObjectId); personalGoalEntities = personalGoalEntities.Where(personalGoal => !personalGoal.IsAligned); // Update personal goal details data when goal cycle is ended for unaligned goals foreach (var personalGoalEntity in personalGoalEntities) { personalGoalEntity.IsActive = false; personalGoalEntity.IsReminderActive = false; personalGoalEntity.LastModifiedOn = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture); var personalGoalNoteEntities = await this.personalGoalNoteStorageProvider.GetPersonalGoalNoteDetailsAsync(personalGoalEntity.PersonalGoalId, userAadObjectId); // Update personal goal note details data when goal cycle is ended for unaligned goals foreach (var personalGoalNoteEntity in personalGoalNoteEntities) { personalGoalNoteEntity.IsActive = false; personalGoalNoteEntity.LastModifiedOn = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture); } await this.personalGoalNoteStorageProvider.CreateOrUpdatePersonalGoalNoteDetailsAsync(personalGoalNoteEntities); } await this.personalGoalStorageProvider.CreateOrUpdatePersonalGoalDetailsAsync(personalGoalEntities); } catch (Exception ex) { this.logger.LogError(ex, $"Failed to save personal goal detail data to table storage at {nameof(this.UpdatePersonalGoalAndNoteDetailsAsync)}: {ex.Message}"); throw; } } /// <summary> /// Method to send goal reminder card to team and team members or update team goal, personal goal and note details in storage. /// </summary> /// <param name="teamGoalDetail">Holds team goal detail entity data sent from background service.</param> /// <param name="isReminderBeforeThreeDays">Determines reminder to be sent prior 3 days to end date.</param> /// <returns>A Task represents goal reminder card is sent to team and team members.</returns> public async Task SendGoalReminderToTeamAndTeamMembersAsync(TeamGoalDetail teamGoalDetail, bool isReminderBeforeThreeDays = false) { teamGoalDetail = teamGoalDetail ?? throw new ArgumentNullException(nameof(teamGoalDetail)); try { var teamId = teamGoalDetail.TeamId; string serviceUrl = teamGoalDetail.ServiceUrl; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); var conversationReference = new ConversationReference() { ChannelId = Constants.TeamsBotFrameworkChannelId, Bot = new ChannelAccount() { Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}" }, ServiceUrl = serviceUrl, Conversation = new ConversationAccount() { ConversationType = Constants.ChannelConversationType, IsGroup = true, Id = teamId, TenantId = this.options.Value.TenantId }, }; await this.retryPolicy.ExecuteAsync(async () => { try { await ((BotFrameworkAdapter)this.adapter).ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, conversationReference, async (turnContext, cancellationToken) => { string reminderType = string.Empty; AdaptiveTextColor reminderTypeColor = AdaptiveTextColor.Accent; if (isReminderBeforeThreeDays) { reminderType = this.localizer.GetString("TeamGoalEndingAfterThreeDays"); reminderTypeColor = AdaptiveTextColor.Warning; } else { reminderType = this.GetReminderTypeString(teamGoalDetail.ReminderFrequency); } var goalReminderAttachment = MessageFactory.Attachment(GoalReminderCard.GetGoalReminderCard(this.localizer, this.options.Value.ManifestId, this.options.Value.GoalsTabEntityId, reminderType, reminderTypeColor)); this.logger.LogInformation($"Sending goal reminder card to teamId: {teamId}"); await turnContext.SendActivityAsync(goalReminderAttachment, cancellationToken); await this.SendGoalReminderToTeamMembersAsync(turnContext, teamGoalDetail, goalReminderAttachment, cancellationToken); }, CancellationToken.None); } catch (Exception ex) { this.logger.LogError(ex, $"Error while performing retry logic to send goal reminder card for : {teamGoalDetail.TeamGoalId}."); throw; } }); } #pragma warning disable CA1031 // Catching general exceptions to log exception details in telemetry client. catch (Exception ex) #pragma warning restore CA1031 // Catching general exceptions to log exception details in telemetry client. { this.logger.LogError(ex, $"Error while sending goal reminder in team from background service for : {teamGoalDetail.TeamGoalId} at {nameof(this.SendGoalReminderToTeamAndTeamMembersAsync)}"); } } /// <summary> /// Method to update team goal, personal goal and note details in storage when team goal is ended. /// </summary> /// <param name="teamGoalDetail">Holds team goal detail entity data sent from background service.</param> /// <returns>A task that represents team goal, personal goal and personal goal note details data is saved or updated.</returns> public async Task UpdateGoalDetailsAsync(TeamGoalDetail teamGoalDetail) { teamGoalDetail = teamGoalDetail ?? throw new ArgumentNullException(nameof(teamGoalDetail)); try { var teamId = teamGoalDetail.TeamId; string serviceUrl = teamGoalDetail.ServiceUrl; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); var conversationReference = new ConversationReference() { ChannelId = Constants.TeamsBotFrameworkChannelId, Bot = new ChannelAccount() { Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}" }, ServiceUrl = serviceUrl, Conversation = new ConversationAccount() { ConversationType = Constants.ChannelConversationType, IsGroup = true, Id = teamId, TenantId = this.options.Value.TenantId }, }; await this.retryPolicy.ExecuteAsync(async () => { try { await ((BotFrameworkAdapter)this.adapter).ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, conversationReference, async (turnContext, cancellationToken) => { await this.UpdateGoalEntitiesAsync(turnContext, teamGoalDetail, cancellationToken); }, CancellationToken.None); } catch (Exception ex) { this.logger.LogError(ex, $"Error while performing retry logic to send goal reminder card for : {teamGoalDetail.TeamGoalId}."); throw; } }); } #pragma warning disable CA1031 // Catching general exceptions to log exception details in telemetry client. catch (Exception ex) #pragma warning restore CA1031 // Catching general exceptions to log exception details in telemetry client. { this.logger.LogError(ex, $"Error while updating personal goal, team goal and personal goal note detail from background service for : {teamGoalDetail.TeamGoalId} at {nameof(this.UpdateGoalDetailsAsync)}"); } } /// <summary> /// Update team goal, personal goal and personal goal note details in storage if team goal cycle is ended. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="teamGoalDetail">Holds team goal detail entity data sent from background service.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents team goal, personal goal and personal goal note details data is saved or updated.</returns> private async Task UpdateGoalEntitiesAsync(ITurnContext turnContext, TeamGoalDetail teamGoalDetail, CancellationToken cancellationToken) { try { var teamGoalEntities = await this.teamGoalStorageProvider.GetTeamGoalDetailsByTeamIdAsync(teamGoalDetail.TeamId); // Update team goal details data when goal cycle is ended foreach (var teamGoalEntity in teamGoalEntities) { teamGoalEntity.IsActive = false; teamGoalEntity.IsReminderActive = false; teamGoalEntity.LastModifiedOn = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture); } await this.teamGoalStorageProvider.CreateOrUpdateTeamGoalDetailsAsync(teamGoalEntities); var teamMembers = await this.goalHelper.GetMembersInTeamAsync(turnContext, cancellationToken); foreach (var teamMember in teamMembers) { var userAadObjectId = teamMember.AadObjectId; var alignedGoalDetails = await this.personalGoalStorageProvider.GetUserAlignedGoalDetailsByTeamIdAsync(teamGoalDetail.TeamId, userAadObjectId); if (alignedGoalDetails.FirstOrDefault() != null) { // Update personal goal details data when goal cycle is ended for aligned goals foreach (var personalGoalEntity in alignedGoalDetails) { personalGoalEntity.IsActive = false; personalGoalEntity.IsReminderActive = false; personalGoalEntity.LastModifiedOn = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture); var personalGoalNoteEntities = await this.personalGoalNoteStorageProvider.GetPersonalGoalNoteDetailsAsync(personalGoalEntity.PersonalGoalId, userAadObjectId); // Update personal goal note details data when goal cycle is ended for aligned goals foreach (var personalGoalNoteEntity in personalGoalNoteEntities) { personalGoalNoteEntity.IsActive = false; personalGoalNoteEntity.LastModifiedOn = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture); } await this.personalGoalNoteStorageProvider.CreateOrUpdatePersonalGoalNoteDetailsAsync(personalGoalNoteEntities); } await this.personalGoalStorageProvider.CreateOrUpdatePersonalGoalDetailsAsync(alignedGoalDetails); } } } catch (Exception ex) { this.logger.LogError(ex, $"Failed to save team goal detail data to table storage at {nameof(this.UpdateGoalEntitiesAsync)} for team id: {teamGoalDetail.TeamId}"); throw; } } /// <summary> /// Sends goal reminder card to each member of team if he/she has aligned goal with the team. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="teamGoalDetail">Team goal details obtained from storage.</param> /// <param name="goalReminderActivity">Goal reminder activity to send.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A Task represents goal reminder card is sent to team and team members.</returns> private async Task SendGoalReminderToTeamMembersAsync(ITurnContext turnContext, TeamGoalDetail teamGoalDetail, IMessageActivity goalReminderActivity, CancellationToken cancellationToken) { var teamMembers = await this.goalHelper.GetMembersInTeamAsync(turnContext, cancellationToken); ConversationReference conversationReference = null; foreach (var teamMember in teamMembers) { // Send goal reminder card to those team members who have aligned their personal goals with the team var alignedGoalDetails = await this.personalGoalStorageProvider.GetUserAlignedGoalDetailsByTeamIdAsync(teamGoalDetail.TeamId, teamMember.AadObjectId); if (alignedGoalDetails.Any()) { var conversationParameters = new ConversationParameters { Bot = turnContext.Activity.Recipient, Members = new ChannelAccount[] { teamMember }, TenantId = turnContext.Activity.Conversation.TenantId, }; try { await this.retryPolicy.ExecuteAsync(async () => { await ((BotFrameworkAdapter)turnContext.Adapter).CreateConversationAsync( teamGoalDetail.TeamId, teamGoalDetail.ServiceUrl, new MicrosoftAppCredentials(this.microsoftAppCredentials.MicrosoftAppId, this.microsoftAppCredentials.MicrosoftAppPassword), conversationParameters, async (createConversationtTurnContext, cancellationToken1) => { conversationReference = createConversationtTurnContext.Activity.GetConversationReference(); await ((BotFrameworkAdapter)turnContext.Adapter).ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, conversationReference, async (continueConversationTurnContext, continueConversationCancellationToken) => { this.logger.LogInformation($"Sending goal reminder card to: {teamMember.Name} from team: {teamGoalDetail.TeamId}"); await continueConversationTurnContext.SendActivityAsync(goalReminderActivity, continueConversationCancellationToken); }, cancellationToken); }, cancellationToken); }); } catch (Exception ex) { this.logger.LogError(ex, $"Error while sending goal reminder card to members of the team : {teamGoalDetail.TeamId} at {nameof(this.SendGoalReminderToTeamMembersAsync)}"); throw; } } } } /// <summary> /// Method to get text based on reminder frequency. /// </summary> /// <param name="reminderFrequency">Reminder frequency i.e. Weekly/Bi-weekly/Monthly/Quarterly.</param> /// <returns>Return text based on reminder frequency.</returns> private string GetReminderTypeString(int reminderFrequency) { switch (reminderFrequency) { case (int)ReminderFrequency.Weekly: return this.localizer.GetString("WeeklyReminderTypeString"); case (int)ReminderFrequency.Biweekly: return this.localizer.GetString("Bi-weeklyReminderTypeString"); case (int)ReminderFrequency.Monthly: return this.localizer.GetString("MonthlyReminderTypeString"); case (int)ReminderFrequency.Quarterly: return this.localizer.GetString("QuarterlyReminderTypeString"); default: return string.Empty; } } } }
55.579592
242
0.609422
[ "MIT" ]
v-riagr/MasterVSOGoal
Source/Microsoft.Teams.Apps.GoalTracker/Helpers/GoalReminderActivityHelper.cs
27,236
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.ApiManagement.Latest.Outputs { [OutputType] public sealed class BackendServiceFabricClusterPropertiesResponse { /// <summary> /// The client certificate thumbprint for the management endpoint. /// </summary> public readonly string ClientCertificatethumbprint; /// <summary> /// The cluster management endpoint. /// </summary> public readonly ImmutableArray<string> ManagementEndpoints; /// <summary> /// Maximum number of retries while attempting resolve the partition. /// </summary> public readonly int? MaxPartitionResolutionRetries; /// <summary> /// Thumbprints of certificates cluster management service uses for tls communication /// </summary> public readonly ImmutableArray<string> ServerCertificateThumbprints; /// <summary> /// Server X509 Certificate Names Collection /// </summary> public readonly ImmutableArray<Outputs.X509CertificateNameResponse> ServerX509Names; [OutputConstructor] private BackendServiceFabricClusterPropertiesResponse( string clientCertificatethumbprint, ImmutableArray<string> managementEndpoints, int? maxPartitionResolutionRetries, ImmutableArray<string> serverCertificateThumbprints, ImmutableArray<Outputs.X509CertificateNameResponse> serverX509Names) { ClientCertificatethumbprint = clientCertificatethumbprint; ManagementEndpoints = managementEndpoints; MaxPartitionResolutionRetries = maxPartitionResolutionRetries; ServerCertificateThumbprints = serverCertificateThumbprints; ServerX509Names = serverX509Names; } } }
37.280702
93
0.692235
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/Latest/Outputs/BackendServiceFabricClusterPropertiesResponse.cs
2,125
C#
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.Net.Http.Headers; using Microsoft.OpenApi.Models; using PlanthorWebApiServer.Context; namespace PlanthorWebApiServer { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "PlanthorWebApiServer", Version = "v1" }); // Include 'SecurityScheme' to use JWT Authentication c.AddSecurityDefinition( "oauth", new OpenApiSecurityScheme { Flows = new OpenApiOAuthFlows { ClientCredentials = new OpenApiOAuthFlow { Scopes = new Dictionary<string, string> { ["api"] = "api scope description" }, TokenUrl = new Uri("https://demo.identityserver.io/connect/token"), }, }, In = ParameterLocation.Header, Name = HeaderNames.Authorization, Type = SecuritySchemeType.OAuth2 }); c.AddSecurityRequirement( new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth" }, }, new[] { "api" } } }); }); IConfigurationRoot configuration = InitialConfigurationFiles(); services.AddDbContext<PlanthorDbContext>(options => { options.UseNpgsql(configuration.GetConnectionString("MainPlanthorPostgresql")).EnableSensitiveDataLogging(true); }); services.AddLogging(config => { config.AddDebug(); config.AddConsole(); }); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:5001"; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; }); services.AddAuthorization(options => { options.AddPolicy("ApiScope", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim("scope", "planthorwebapi"); }); }); } private static IConfigurationRoot InitialConfigurationFiles() { return new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .AddJsonFile("appsettings.Development.json", optional: true) .Build(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "PlanthorWebApiServer v1"); }); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireAuthorization("ApiScope"); }); } } }
35.763889
128
0.497476
[ "MIT" ]
Planthor-Team/Planthor_ClientBackEndWebApp
src/Startup.cs
5,150
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Inputs.Enterprise.V1Alpha2 { /// <summary> /// DownwardAPIVolumeFile represents information to create the file containing the pod field /// </summary> public class LicenseMasterSpecVolumesDownwardAPIItemsArgs : Pulumi.ResourceArgs { /// <summary> /// Required: Selects a field of the pod: only annotations, labels, name and namespace are supported. /// </summary> [Input("fieldRef")] public Input<Pulumi.Kubernetes.Types.Inputs.Enterprise.V1Alpha2.LicenseMasterSpecVolumesDownwardAPIItemsFieldRefArgs>? FieldRef { get; set; } /// <summary> /// Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set. /// </summary> [Input("mode")] public Input<int>? Mode { get; set; } /// <summary> /// Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..' /// </summary> [Input("path", required: true)] public Input<string> Path { get; set; } = null!; /// <summary> /// Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported. /// </summary> [Input("resourceFieldRef")] public Input<Pulumi.Kubernetes.Types.Inputs.Enterprise.V1Alpha2.LicenseMasterSpecVolumesDownwardAPIItemsResourceFieldRefArgs>? ResourceFieldRef { get; set; } public LicenseMasterSpecVolumesDownwardAPIItemsArgs() { } } }
45.957447
272
0.684259
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/splunk/dotnet/Kubernetes/Crds/Operators/Splunk/Enterprise/V1Alpha2/Inputs/LicenseMasterSpecVolumesDownwardAPIItemsArgs.cs
2,160
C#
using Android.App; using Android.OS; using Android.Speech.Tts; using GreatQuotes.Services; // Note: this class requires at least Android SDK 5.0 (Lollypop) // to build due to changes in the TTS APIs. namespace GreatQuotes.Droid.Services { public class TextToSpeechService : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener { private string lastText; private TextToSpeech speech; public void OnInit(OperationResult status) { if (status == OperationResult.Success) { if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) speech.Speak(lastText, QueueMode.Flush, null, null); else { #pragma warning disable 0618 speech.Speak(lastText, QueueMode.Flush, null); #pragma warning restore 0618 } lastText = null; } } public void Speak(string text) { if (speech == null) { lastText = text; speech = new TextToSpeech(Application.Context, this); } else { if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) speech.Speak(text, QueueMode.Flush, null, null); else { #pragma warning disable 0618 speech.Speak(text, QueueMode.Flush, null); #pragma warning restore 0618 } } } } }
29.288462
100
0.546947
[ "MIT" ]
renebentes/XamarinPlayground
mslearn-xamarin-forms-design-patterns/src/exercise1/final/GreatQuotes.Android/Services/TextToSpeechService.cs
1,523
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace web_service_users { // REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom d'interface "IService1" à la fois dans le code et le fichier de configuration. [ServiceContract] public interface IUserProfil { [OperationContract] string addToFridge(string[] args); [OperationContract] string removeFromFridge(string[] args); [OperationContract] string inquirePreferences(string[] args); [OperationContract] string removePreferences(string[] args); [OperationContract] string inquireAllergies(string[] args); [OperationContract] string removeAllergies(string[] args); [OperationContract] string emptyFridge(string[] args); // TODO: ajoutez vos opérations de service ici } // Utilisez un contrat de données comme indiqué dans l'exemple ci-après pour ajouter les types composites aux opérations de service. // Vous pouvez ajouter des fichiers XSD au projet. Une fois le projet généré, vous pouvez utiliser directement les types de données qui y sont définis, avec l'espace de noms "web_service_users.ContractType". [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }
29.5
209
0.719128
[ "MIT" ]
Enaifuos/Recommandation-System-Food-Eatrack-Application
client-recommendation-web-service-Q/web-service/web-service-users/IUserProfil.cs
1,664
C#
using System.Collections.Generic; using System.Text; using JetBrains.Annotations; namespace CSharpGuidelinesAnalyzer.Test.TestDataBuilders { /// <summary /> internal sealed class MemberSourceCodeBuilder : SourceCodeBuilder { [NotNull] [ItemNotNull] private readonly List<string> members = new List<string>(); public MemberSourceCodeBuilder() : base(DefaultNamespaceImports) { } protected override string GetSourceCode() { var builder = new StringBuilder(); AppendClassStart(builder); AppendClassMembers(builder); AppendClassEnd(builder); return builder.ToString(); } private static void AppendClassStart([NotNull] StringBuilder builder) { builder.AppendLine("public class Test"); builder.AppendLine("{"); } private void AppendClassMembers([NotNull] StringBuilder builder) { string code = GetLinesOfCode(members); builder.AppendLine(code); } private static void AppendClassEnd([NotNull] StringBuilder builder) { builder.AppendLine("}"); } [NotNull] public MemberSourceCodeBuilder InDefaultClass([NotNull] string memberCode) { Guard.NotNull(memberCode, nameof(memberCode)); members.Add(memberCode); return this; } } }
26.087719
82
0.599866
[ "Apache-2.0" ]
MineMaarten/CSharpGuidelinesAnalyzer
src/CSharpGuidelinesAnalyzer/CSharpGuidelinesAnalyzer.Test/TestDataBuilders/MemberSourceCodeBuilder.cs
1,489
C#
// ------------------------------------- // PhotonInkPainterView.cs // Copyright (c) 2019 sotan. // Licensed under the MIT License. // ------------------------------------- using UnityEngine; using Photon.Pun; namespace InkPainterExtension { [AddComponentMenu("Photon Networking/Photon Ink Painter")] [RequireComponent(typeof(PhotonView))] [RequireComponent(typeof(PhotonTransformView))] public class PhotonInkPainterView : MonoBehaviour, IPunObservable { private PhotonView m_PhotonView; private InkPainter m_InkPainter; private bool m_PaintEnabled = false; private Vector3 m_RayOrigin; private Vector3 m_RayDirection; private float m_BrushColorR; private float m_BrushColorG; private float m_BrushColorB; private float m_BrushColorA; private bool m_Erase = false; void Awake() { m_PhotonView = GetComponent<PhotonView>(); m_InkPainter = GetComponent<InkPainterExtension.InkPainter>(); } void Update() { if (!m_PhotonView.IsMine) { m_InkPainter.paintEnabled = m_PaintEnabled; m_InkPainter.ray.origin = m_RayOrigin; m_InkPainter.ray.direction = m_RayDirection; m_InkPainter.brushColor.r = m_BrushColorR; m_InkPainter.brushColor.g = m_BrushColorG; m_InkPainter.brushColor.b = m_BrushColorB; m_InkPainter.brushColor.a = m_BrushColorA; m_InkPainter.erase = m_Erase; } } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if (stream.IsWriting) { stream.SendNext(m_InkPainter.paintEnabled); stream.SendNext(m_InkPainter.ray.origin); stream.SendNext(m_InkPainter.ray.direction); stream.SendNext(m_InkPainter.brushColor.r); stream.SendNext(m_InkPainter.brushColor.g); stream.SendNext(m_InkPainter.brushColor.b); stream.SendNext(m_InkPainter.brushColor.a); stream.SendNext(m_InkPainter.erase); } else { m_PaintEnabled = (bool)stream.ReceiveNext(); m_RayOrigin = (Vector3)stream.ReceiveNext(); m_RayDirection = (Vector3)stream.ReceiveNext(); m_BrushColorR = (float)stream.ReceiveNext(); m_BrushColorG = (float)stream.ReceiveNext(); m_BrushColorB = (float)stream.ReceiveNext(); m_BrushColorA = (float)stream.ReceiveNext(); m_Erase = (bool)stream.ReceiveNext(); } } } }
35.794872
86
0.582736
[ "MIT" ]
sotanmochi/InkPainterSharingSample
Assets/InkPainterSharingSample/InkPainterExtension/PhotonInkPainterView.cs
2,792
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.HttpTransport.Clients { using System.Net.Http; using System.Threading; using System.Threading.Tasks; using GreenPipes; using GreenPipes.Agents; using MassTransit.Pipeline; public class ClientContextFactory : IPipeContextFactory<ClientContext> { readonly IReceivePipe _receivePipe; public ClientContextFactory(IReceivePipe receivePipe) { _receivePipe = receivePipe; } public IPipeContextAgent<ClientContext> CreateContext(ISupervisor supervisor) { var client = new HttpClient(); ClientContext clientContext = new HttpClientContext(client, _receivePipe, supervisor.Stopped); return supervisor.AddContext(clientContext); } public IActivePipeContextAgent<ClientContext> CreateActiveContext(ISupervisor supervisor, PipeContextHandle<ClientContext> context, CancellationToken cancellationToken = default) { return supervisor.AddActiveContext(context, CreateSharedConnection(context.Context, cancellationToken)); } static async Task<ClientContext> CreateSharedConnection(Task<ClientContext> context, CancellationToken cancellationToken) { var clientContext = await context.ConfigureAwait(false); return new SharedHttpClientContext(clientContext, cancellationToken); } } }
39.444444
140
0.696244
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit.HttpTransport/Clients/ClientContextFactory.cs
2,130
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host.Blobs; using Microsoft.Azure.WebJobs.Host.Config; using Newtonsoft.Json; using Xunit; using Azure.Storage.Queues; using Azure.Storage.Queues.Models; using Azure.Storage.Blobs.Specialized; using Microsoft.Azure.WebJobs.Host.TestCommon; using Azure.WebJobs.Extensions.Storage.Common.Tests; using Microsoft.Azure.WebJobs.Extensions.Storage.Common; namespace Microsoft.Azure.WebJobs.Host.FunctionalTests { // Some tests in this class aren't as targeted as most other tests in this project. // (Look elsewhere for better examples to use as templates for new tests.) [Collection(AzuriteCollection.Name)] public class HostCallTests { private const string ContainerName = "container-hostcalltests"; private const string BlobName = "blob"; private const string BlobPath = ContainerName + "/" + BlobName; private const string OutputBlobName = "blob.out"; private const string OutputBlobPath = ContainerName + "/" + OutputBlobName; private const int TestValue = Int32.MinValue; private readonly StorageAccount account; public HostCallTests(AzuriteFixture azuriteFixture) { account = azuriteFixture.GetAccount(); account.CreateBlobServiceClient().GetBlobContainerClient(ContainerName).DeleteIfExists(); } [Theory] [InlineData("FuncWithString")] [InlineData("FuncWithTextReader")] [InlineData("FuncWithStreamRead")] [InlineData("FuncWithBlockBlob")] [InlineData("FuncWithOutStringNull")] [InlineData("FuncWithT")] [InlineData("FuncWithOutTNull")] [InlineData("FuncWithValueT")] public async Task Blob_IfBoundToTypeAndBlobIsMissing_DoesNotCreate(string methodName) { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetBlockBlobClient(BlobName); // Act await CallAsync(account, typeof(MissingBlobProgram), methodName, typeof(CustomBlobConverterExtensionConfigProvider)); // Assert Assert.False(await blob.ExistsAsync()); } [Theory] [InlineData("FuncWithOutString")] [InlineData("FuncWithStreamWriteNoop")] [InlineData("FuncWithTextWriter")] [InlineData("FuncWithStreamWrite")] [InlineData("FuncWithOutT")] [InlineData("FuncWithOutValueT")] public async Task Blob_IfBoundToTypeAndBlobIsMissing_Creates(string methodName) { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetBlockBlobClient(BlobName); // Act await CallAsync(account, typeof(MissingBlobProgram), methodName, typeof(CustomBlobConverterExtensionConfigProvider)); // Assert Assert.True(await blob.ExistsAsync()); } [Fact] public async Task BlobTrigger_IfHasUnboundParameter_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); const string inputBlobName = "note-monday.csv"; var inputBlob = container.GetBlockBlobClient(inputBlobName); await container.CreateIfNotExistsAsync(); await inputBlob.UploadTextAsync("abc"); IDictionary<string, object> arguments = new Dictionary<string, object> { { "values", ContainerName + "/" + inputBlobName }, { "unbound", "test" } }; // Act await CallAsync(account, typeof(BlobProgram), "UnboundParameter", arguments); var outputBlob = container.GetBlockBlobClient("note.csv"); string content = await outputBlob.DownloadTextAsync(); Assert.Equal("done", content); // $$$ Put this in its own unit test? Guid? guid = BlobCausalityManager.GetWriterAsync(outputBlob, CancellationToken.None).GetAwaiter().GetResult(); Assert.True(guid != Guid.Empty, "Blob is missing causality information"); } [Fact] public async Task Blob_IfBoundToCloudBlockBlob_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var inputBlob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await inputBlob.UploadTextAsync("ignore"); // Act await CallAsync(account, typeof(BlobProgram), "BindToCloudBlockBlob"); } [Fact] public async Task Blob_IfBoundToString_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var inputBlob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await inputBlob.UploadTextAsync("0,1,2"); await CallAsync(account, typeof(BlobProgram), "BindToString"); } [Fact] public async Task Blob_IfCopiedViaString_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var inputBlob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); string expectedContent = "abc"; await inputBlob.UploadTextAsync(expectedContent); // Act await CallAsync(account, typeof(BlobProgram), "CopyViaString"); // Assert var outputBlob = container.GetBlockBlobClient(OutputBlobName); string outputContent = await outputBlob.DownloadTextAsync(); Assert.Equal(expectedContent, outputContent); } [Fact] public async Task BlobTrigger_IfCopiedViaTextReaderTextWriter_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var inputBlob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); string expectedContent = "abc"; await inputBlob.UploadTextAsync(expectedContent); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "values", BlobPath } }; // Act await CallAsync(account, typeof(BlobProgram), "CopyViaTextReaderTextWriter", arguments); // Assert var outputBlob = container.GetBlockBlobClient(OutputBlobName); string outputContent = await outputBlob.DownloadTextAsync(); Assert.Equal(expectedContent, outputContent); } [Fact] public async Task BlobTrigger_IfBoundToICloudBlob_CanCallWithBlockBlob() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await blob.UploadTextAsync("ignore"); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "blob", BlobPath } }; // Act BlobBaseClient result = await CallAsync<BlobBaseClient>(account, typeof(BlobTriggerBindToICloudBlobProgram), "Call", arguments, (s) => BlobTriggerBindToICloudBlobProgram.TaskSource = s); // Assert Assert.NotNull(result); Assert.IsType<BlockBlobClient>(result); } [Fact] public async Task BlobTrigger_IfBoundToICloudBlob_CanCallWithPageBlob() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetPageBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await blob.CreateIfNotExistsAsync(512); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "blob", BlobPath } }; // Act BlobBaseClient result = await CallAsync<BlobBaseClient>(account, typeof(BlobTriggerBindToICloudBlobProgram), "Call", arguments, (s) => BlobTriggerBindToICloudBlobProgram.TaskSource = s); // Assert Assert.NotNull(result); Assert.IsType<PageBlobClient>(result); } [Fact] public async Task BlobTrigger_IfBoundToICloudBlobAndTriggerArgumentIsMissing_CallThrows() { // Act Exception exception = await CallFailureAsync(account, typeof(BlobTriggerBindToICloudBlobProgram), "Call"); // Assert Assert.IsType<InvalidOperationException>(exception); Assert.Equal("Missing value for trigger parameter 'blob'.", exception.Message); } [Fact] public async Task BlobTrigger_IfBoundToCloudBlockBlob_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await blob.UploadTextAsync("ignore"); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "blob", BlobPath } }; // Act var result = await CallAsync<BlockBlobClient>(account, typeof(BlobTriggerBindToCloudBlockBlobProgram), "Call", arguments, (s) => BlobTriggerBindToCloudBlockBlobProgram.TaskSource = s); // Assert Assert.NotNull(result); } [Fact] public async Task BlobTrigger_IfBoundToCloudBLockBlobAndTriggerArgumentIsMissing_CallThrows() { // Act Exception exception = await CallFailureAsync(account, typeof(BlobTriggerBindToCloudBlockBlobProgram), "Call"); // Assert Assert.IsType<InvalidOperationException>(exception); Assert.Equal("Missing value for trigger parameter 'blob'.", exception.Message); } private class BlobTriggerBindToCloudBlockBlobProgram { public static TaskCompletionSource<BlockBlobClient> TaskSource { get; set; } public static void Call([BlobTrigger(BlobPath)] BlockBlobClient blob) { TaskSource.TrySetResult(blob); } } [Fact] public async Task BlobTrigger_IfBoundToCloudPageBlob_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetPageBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await blob.CreateIfNotExistsAsync(512); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "blob", BlobPath } }; // Act PageBlobClient result = await CallAsync<PageBlobClient>(account, typeof(BlobTriggerBindToCloudPageBlobProgram), "Call", arguments, (s) => BlobTriggerBindToCloudPageBlobProgram.TaskSource = s); // Assert Assert.NotNull(result); } [Fact] public async Task BlobTrigger_IfBoundToCloudPageBlobAndTriggerArgumentIsMissing_CallThrows() { // Act Exception exception = await CallFailureAsync(account, typeof(BlobTriggerBindToCloudPageBlobProgram), "Call"); // Assert Assert.IsType<InvalidOperationException>(exception); Assert.Equal("Missing value for trigger parameter 'blob'.", exception.Message); } private class BlobTriggerBindToCloudPageBlobProgram { public static TaskCompletionSource<PageBlobClient> TaskSource { get; set; } public static void Call([BlobTrigger(BlobPath)] PageBlobClient blob) { TaskSource.TrySetResult(blob); } } [Fact] public async Task BlobTrigger_IfBoundToCloudAppendBlob_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var blob = container.GetAppendBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await blob.UploadTextAsync("test"); // TODO: Remove argument once host.Call supports more flexibility. IDictionary<string, object> arguments = new Dictionary<string, object> { { "blob", BlobPath } }; // Act var result = await CallAsync<AppendBlobClient>(account, typeof(BlobTriggerBindToCloudAppendBlobProgram), "Call", arguments, (s) => BlobTriggerBindToCloudAppendBlobProgram.TaskSource = s); // Assert Assert.NotNull(result); } [Fact] public async Task BlobTrigger_IfBoundToCloudAppendBlobAndTriggerArgumentIsMissing_CallThrows() { // Act Exception exception = await CallFailureAsync(account, typeof(BlobTriggerBindToCloudAppendBlobProgram), "Call"); // Assert Assert.IsType<InvalidOperationException>(exception); Assert.Equal("Missing value for trigger parameter 'blob'.", exception.Message); } private class BlobTriggerBindToCloudAppendBlobProgram { public static TaskCompletionSource<AppendBlobClient> TaskSource { get; set; } public static void Call([BlobTrigger(BlobPath)] AppendBlobClient blob) { TaskSource.TrySetResult(blob); } } [Fact] public async Task Int32Argument_CanCallViaStringParse() { IDictionary<string, object> arguments = new Dictionary<string, object> { { "value", "15" } }; // Act int result = await CallAsync<int>(account, typeof(UnboundInt32Program), "Call", arguments, (s) => UnboundInt32Program.TaskSource = s); Assert.Equal(15, result); } private class UnboundInt32Program { public static TaskCompletionSource<int> TaskSource { get; set; } [NoAutomaticTrigger] public static void Call(int value) { TaskSource.TrySetResult(value); } } [Fact] public async Task Binder_IfBindingBlobToTextWriter_CanCall() { // Act await CallAsync(account, typeof(BindToBinderBlobTextWriterProgram), "Call"); // Assert var container = account.CreateBlobServiceClient().GetBlobContainerClient(ContainerName); var blob = container.GetBlockBlobClient(OutputBlobName); string content = await blob.DownloadTextAsync(); Assert.Equal("output", content); } private class BindToBinderBlobTextWriterProgram { [NoAutomaticTrigger] public static void Call(IBinder binder) { TextWriter tw = binder.Bind<TextWriter>(new BlobAttribute(OutputBlobPath)); tw.Write("output"); // closed automatically } } [Fact] public async Task BlobTrigger_IfCopiedViaPoco_CanCall() { // Arrange var client = account.CreateBlobServiceClient(); var container = client.GetBlobContainerClient(ContainerName); var inputBlob = container.GetBlockBlobClient(BlobName); await container.CreateIfNotExistsAsync(); await inputBlob.UploadTextAsync("abc"); Dictionary<string, object> arguments = new Dictionary<string, object> { { "input", BlobPath } }; // Act await CallAsync(account, typeof(CopyBlobViaPocoProgram), "CopyViaPoco", arguments, typeof(CustomBlobConverterExtensionConfigProvider)); // Assert var outputBlob = container.GetBlockBlobClient(OutputBlobName); string content = await outputBlob.DownloadTextAsync(); Assert.Equal("*abc*", content); } private class CopyBlobViaPocoProgram { public static void CopyViaPoco( [BlobTrigger(BlobPath)] PocoBlob input, [Blob(OutputBlobPath)] out PocoBlob output) { output = new PocoBlob { Value = "*" + input.Value + "*" }; } } private class PocoBlob { public string Value; } private static async Task CallAsync(StorageAccount account, Type programType, string methodName, params Type[] customExtensions) { await FunctionalTest.CallAsync(account, programType, programType.GetMethod(methodName), null, customExtensions); } private static async Task CallAsync(StorageAccount account, Type programType, string methodName, IDictionary<string, object> arguments, params Type[] customExtensions) { await FunctionalTest.CallAsync(account, programType, programType.GetMethod(methodName), arguments, customExtensions); } private static async Task<TResult> CallAsync<TResult>(StorageAccount account, Type programType, string methodName, IDictionary<string, object> arguments, Action<TaskCompletionSource<TResult>> setTaskSource) { return await FunctionalTest.CallAsync<TResult>(account, programType, programType.GetMethod(methodName), arguments, setTaskSource); } private static async Task<Exception> CallFailureAsync(StorageAccount account, Type programType, string methodName) { return await FunctionalTest.CallFailureAsync(account, programType, programType.GetMethod(methodName), null); } private struct CustomDataValue { public int ValueId { get; set; } public string Content { get; set; } } private class CustomDataObject { public int ValueId { get; set; } public string Content { get; set; } } private class MissingBlobProgram { public static void FuncWithBlockBlob([Blob(BlobPath)] BlockBlobClient blob) { Assert.NotNull(blob); Assert.Equal(BlobName, blob.Name); Assert.Equal(ContainerName, blob.BlobContainerName); } public static void FuncWithStreamRead([Blob(BlobPath, FileAccess.Read)] Stream stream) { Assert.Null(stream); } public static void FuncWithStreamWrite([Blob(BlobPath, FileAccess.Write)] Stream stream) { Assert.NotNull(stream); const byte ignore = 0xFF; stream.WriteByte(ignore); } public static void FuncWithStreamWriteNoop([Blob(BlobPath, FileAccess.Write)] Stream stream) { Assert.NotNull(stream); } public static void FuncWithTextReader([Blob(BlobPath)] TextReader reader) { Assert.Null(reader); } public static void FuncWithTextWriter([Blob(BlobPath)] TextWriter writer) { Assert.NotNull(writer); } public static void FuncWithString([Blob(BlobPath)] string content) { Assert.Null(content); } public static void FuncWithOutString([Blob(BlobPath)] out string content) { content = "ignore"; } public static void FuncWithOutStringNull([Blob(BlobPath)] out string content) { content = null; } public static void FuncWithT([Blob(BlobPath)] CustomDataObject value) { Assert.Null(value); // null value is Blob is Missing } public static void FuncWithOutT([Blob(BlobPath)] out CustomDataObject value) { value = new CustomDataObject { ValueId = TestValue, Content = "ignore" }; } public static void FuncWithOutTNull([Blob(BlobPath)] out CustomDataObject value) { value = null; } public static void FuncWithValueT([Blob(BlobPath)] CustomDataValue value) { // default(T) is blob is missing #pragma warning disable xUnit2002 // Do not use null check on value type Assert.NotNull(value); #pragma warning restore xUnit2002 // Do not use null check on value type Assert.Equal(0, value.ValueId); } public static void FuncWithOutValueT([Blob(BlobPath)] out CustomDataValue value) { value = new CustomDataValue { ValueId = TestValue, Content = "ignore" }; } } private class BlobProgram { // This can be invoked explicitly (and providing parameters) // or it can be invoked implicitly by triggering on input. // (assuming no unbound parameters) [NoAutomaticTrigger] public static void UnboundParameter( string name, string date, // used by input string unbound, // not used by in/out [BlobTrigger(ContainerName + "/{name}-{date}.csv")] TextReader values, [Blob(ContainerName + "/{name}.csv")] TextWriter output ) { Assert.Equal("test", unbound); Assert.Equal("note", name); Assert.Equal("monday", date); string content = values.ReadToEnd(); Assert.Equal("abc", content); output.Write("done"); } public static void BindToCloudBlockBlob([Blob(BlobPath)] BlockBlobClient blob) { Assert.NotNull(blob); Assert.Equal(BlobName, blob.Name); } public static void BindToString([Blob(BlobPath)] string content) { Assert.NotNull(content); string[] strings = content.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // Verify expected number of entries in CloudBlob Assert.Equal(3, strings.Length); for (int i = 0; i < 3; ++i) { bool parsed = int.TryParse(strings[i], out int value); string message = String.Format("Unable to parse CloudBlob strings[{0}]: '{1}'", i, strings[i]); Assert.True(parsed, message); // Ensure expected value in CloudBlob Assert.Equal(i, value); } } public static void CopyViaString( [Blob(BlobPath)] string blobIn, [Blob(OutputBlobPath)] out string blobOut ) { blobOut = blobIn; } public static void CopyViaTextReaderTextWriter( [BlobTrigger(BlobPath)] TextReader values, [Blob(OutputBlobPath)] TextWriter output) { string content = values.ReadToEnd(); output.Write(content); } } private class BlobTriggerBindToICloudBlobProgram { public static TaskCompletionSource<BlobBaseClient> TaskSource { get; set; } public static void Call([BlobTrigger(BlobPath)] BlobBaseClient blob) { TaskSource.TrySetResult(blob); } } internal class CustomBlobConverterExtensionConfigProvider : IExtensionConfigProvider { public void Initialize(ExtensionConfigContext context) { context.AddConverter<Stream, PocoBlob>(s => { TextReader reader = new StreamReader(s); string text = reader.ReadToEnd(); return new PocoBlob { Value = text }; }); context.AddConverter<ApplyConversion<PocoBlob, Stream>, object>(p => { PocoBlob value = p.Value; Stream stream = p.Existing; TextWriter writer = new StreamWriter(stream); writer.WriteAsync(value.Value).GetAwaiter().GetResult(); writer.FlushAsync().GetAwaiter().GetResult(); return null; }); context.AddConverter<Stream, CustomDataObject>(s => { // Read() shouldn't be called if the stream is missing. Assert.False(true, "If stream is missing, should never call Read() converter"); return null; }); context.AddConverter<ApplyConversion<CustomDataObject, Stream>, object>(p => { CustomDataObject value = p.Value; Stream stream = p.Existing; if (value != null) { Assert.Equal(TestValue, value.ValueId); const byte ignore = 0xFF; stream.WriteByte(ignore); } return null; }); context.AddConverter<Stream, CustomDataValue>(s => { // Read() shouldn't be called if the stream is missing. Assert.False(true, "If stream is missing, should never call Read() converter"); return default(CustomDataValue); }); context.AddConverter<ApplyConversion<CustomDataValue, Stream>, object>(p => { CustomDataValue value = p.Value; Stream stream = p.Existing; Assert.Equal(TestValue, value.ValueId); const byte ignore = 0xFF; stream.WriteByte(ignore); return null; }); } } } }
38.234973
147
0.590539
[ "MIT" ]
Banani-Rath/azure-sdk-for-net
sdk/storage/Azure.Storage.Webjobs.Extensions.Blobs/tests/HostCallTests.cs
27,990
C#
namespace Sinch.ServerSdk.Calling.Callbacks.Response { public interface IAceSvamletBuilder : IBridgedCallSvamletBuilder<IAceSvamletBuilder> { } }
26.166667
88
0.789809
[ "MIT" ]
gustafasinch/nuget-serversdk
src/Sinch.ServerSdk/Calling/Callbacks/Response/IAceSvamletBuilder.cs
157
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace Bookstore.Controllers { public static class REST { public static async Task<TResult> SendGet<TResult>(string target) { using (var client = new HttpClient()) { return await SendGet<TResult>(target, client); } } public static async Task<TResult> SendGet<TResult>(string target, HttpClient client) { var dtoJSON = await client.GetStringAsync(target); var result = JsonConvert.DeserializeObject<TResult>(dtoJSON); return result; } public static async Task<TResult> SendPost<TResult>(string target) { using (var client = new HttpClient()) { return await SendPost<TResult>(target, client); } } public static async Task<TResult> SendPost<TResult, TBody>(string target, TBody body) { using(var client = new HttpClient()) { return await SendPost<TResult, TBody>(target, body, client); } } public static async Task<TResult> SendPost<TResult>(string target, HttpClient client) { var dtoJSON = await client.PostAsync(target, null).Result.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TResult>(dtoJSON); } public static async Task<TResult> SendPost<TResult, TBody>(string target, TBody body, HttpClient client) { var dtoJSON = await client.PostAsJsonAsync(target, body).Result.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<TResult>(dtoJSON); return result; } public static async Task<TItem> SendPut<TItem>(string target, TItem item) { using(var client = new HttpClient()) { return await SendPut(target, item, client); } } public static async Task<TItem> SendPut<TItem>(string target, TItem item, HttpClient client) { var dtoJSON = await client.PutAsJsonAsync(target, item).Result.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TItem>(dtoJSON); } public static void SendDelete(string target) { using(var client = new HttpClient()) { SendDelete(target, client); } } public static async Task<TResult> SendPatch<TResult>(string target) { using (var client = new HttpClient()) { return await SendPatch<TResult>(target); } } public static async Task<TResult> SendPatch<TResult>(string target, HttpClient client) { var dtoJson = await client.PatchAsync(target, null).Result.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TResult>(dtoJson); } public static void SendDelete(string target, HttpClient client) { client.DeleteAsync(target); } } }
32.53
112
0.590839
[ "MIT" ]
vv-b-s/bookstore
asp.net/Bookstore/Controllers/REST.cs
3,255
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using EnsureThat; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Health.Fhir.Core.Features.Routing; using Microsoft.Health.Fhir.SqlServer.Api.Features.Filters; using Microsoft.Health.Fhir.SqlServer.Api.Features.Routing; using Microsoft.Health.Fhir.SqlServer.Features.Schema; namespace Microsoft.Health.Fhir.SqlServer.Api.Controllers { [NotImplementedExceptionFilter] [Route(KnownRoutes.SchemaRoot)] public class SchemaController : Controller { private readonly SchemaInformation _schemaInformation; private readonly IUrlResolver _urlResolver; private readonly ILogger<SchemaController> _logger; public SchemaController(SchemaInformation schemaInformation, IUrlResolver urlResolver, ILogger<SchemaController> logger) { EnsureArg.IsNotNull(schemaInformation, nameof(schemaInformation)); EnsureArg.IsNotNull(urlResolver, nameof(urlResolver)); EnsureArg.IsNotNull(logger, nameof(logger)); _schemaInformation = schemaInformation; _urlResolver = urlResolver; _logger = logger; } [HttpGet] [AllowAnonymous] [Route(KnownRoutes.Versions)] public ActionResult AvailableVersions() { _logger.LogInformation("Attempting to get available schemas"); var availableSchemas = new List<object>(); var currentVersion = _schemaInformation.Current ?? 0; foreach (var version in Enum.GetValues(typeof(SchemaVersion)).Cast<SchemaVersion>().Where(sv => sv >= currentVersion)) { var routeValues = new Dictionary<string, object> { { "id", (int)version } }; Uri scriptUri = _urlResolver.ResolveRouteNameUrl(RouteNames.Script, routeValues); availableSchemas.Add(new { id = version, script = scriptUri }); } return new JsonResult(availableSchemas); } [HttpGet] [AllowAnonymous] [Route(KnownRoutes.Current)] public ActionResult CurrentVersion() { _logger.LogInformation("Attempting to get current schemas"); throw new NotImplementedException(Resources.CurrentVersionNotImplemented); } [HttpGet] [AllowAnonymous] [Route(KnownRoutes.Script, Name = RouteNames.Script)] public ActionResult SqlScript(int id) { _logger.LogInformation($"Attempting to get script for schema version: {id}"); throw new NotImplementedException(Resources.ScriptNotImplemented); } [HttpGet] [AllowAnonymous] [Route(KnownRoutes.Compatibility)] public ActionResult Compatibility() { _logger.LogInformation("Attempting to get compatibility"); throw new NotImplementedException(Resources.CompatibilityNotImplemented); } } }
38.370787
130
0.638067
[ "MIT" ]
NHSDigital/azure-fhir-server
src/Microsoft.Health.Fhir.SqlServer.Api/Controllers/SchemaController.cs
3,417
C#
namespace VapeCalculator.Forms { partial class NewFlavourForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblFlavourName = new System.Windows.Forms.Label(); this.lblFlavourWeight = new System.Windows.Forms.Label(); this.txtFlavourName = new System.Windows.Forms.TextBox(); this.txtFlavourWeight = new System.Windows.Forms.TextBox(); this.btnAddFlavour = new System.Windows.Forms.Button(); this.SuspendLayout(); // // lblFlavourName // this.lblFlavourName.AutoSize = true; this.lblFlavourName.Location = new System.Drawing.Point(13, 13); this.lblFlavourName.Name = "lblFlavourName"; this.lblFlavourName.Size = new System.Drawing.Size(73, 13); this.lblFlavourName.TabIndex = 0; this.lblFlavourName.Text = "Flavour Name"; // // lblFlavourWeight // this.lblFlavourWeight.AutoSize = true; this.lblFlavourWeight.Location = new System.Drawing.Point(127, 13); this.lblFlavourWeight.Name = "lblFlavourWeight"; this.lblFlavourWeight.Size = new System.Drawing.Size(41, 13); this.lblFlavourWeight.TabIndex = 1; this.lblFlavourWeight.Text = "Weight"; // // txtFlavourName // this.txtFlavourName.Location = new System.Drawing.Point(13, 30); this.txtFlavourName.Name = "txtFlavourName"; this.txtFlavourName.Size = new System.Drawing.Size(100, 20); this.txtFlavourName.TabIndex = 2; // // txtFlavourWeight // this.txtFlavourWeight.Location = new System.Drawing.Point(130, 30); this.txtFlavourWeight.Name = "txtFlavourWeight"; this.txtFlavourWeight.Size = new System.Drawing.Size(100, 20); this.txtFlavourWeight.TabIndex = 3; // // btnAddFlavour // this.btnAddFlavour.Location = new System.Drawing.Point(84, 57); this.btnAddFlavour.Name = "btnAddFlavour"; this.btnAddFlavour.Size = new System.Drawing.Size(75, 23); this.btnAddFlavour.TabIndex = 4; this.btnAddFlavour.Text = "Add"; this.btnAddFlavour.UseVisualStyleBackColor = true; this.btnAddFlavour.Click += new System.EventHandler(this.btnAddFlavour_Click); // // NewFlavourForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(243, 92); this.Controls.Add(this.btnAddFlavour); this.Controls.Add(this.txtFlavourWeight); this.Controls.Add(this.txtFlavourName); this.Controls.Add(this.lblFlavourWeight); this.Controls.Add(this.lblFlavourName); this.Name = "NewFlavourForm"; this.Text = "New Flavour"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblFlavourName; private System.Windows.Forms.Label lblFlavourWeight; private System.Windows.Forms.TextBox txtFlavourName; private System.Windows.Forms.TextBox txtFlavourWeight; private System.Windows.Forms.Button btnAddFlavour; } }
42.4
108
0.575247
[ "MIT" ]
furkick/Vape-Calculator
VapeCalculator/Forms/NewFlavourForm.Designer.cs
4,454
C#
using System; using System.IO; using System.Reflection; namespace GitVersionCore.Tests.Helpers { public static class PathHelper { public static string GetCurrentDirectory() { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } public static string GetExecutable() { #if NETFRAMEWORK var executable = Path.Combine(GetExeDirectory(), "GitVersion.exe"); #else var executable = "dotnet"; #endif return executable; } public static string GetExecutableArgs(string args) { #if !NETFRAMEWORK args = $"{Path.Combine(GetExeDirectory(), "GitVersion.dll")} {args}"; #endif return args; } public static string GetTempPath() { return Path.Combine(GetCurrentDirectory(), "TestRepositories", Guid.NewGuid().ToString()); } private static string GetExeDirectory() { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("GitVersionExe.Tests", "GitVersionExe"); } } }
27.069767
133
0.603093
[ "MIT" ]
BaY1251/GitVersion
src/GitVersionCore.Tests/Helpers/PathHelper.cs
1,122
C#