content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; namespace RefundableFocus.Common; public static class Utils { public static void SafeInvoke(Action action, Action after) { try { action(); after(); } catch (Exception ex) { Plugin.Log.LogError(ex); } } public static T SafeInvoke<T>(Func<T> action, Action after) { T r = default; try { r = action(); after(); } catch (Exception ex) { Plugin.Log.LogError(ex); } return r; } }
17.735294
63
0.452736
[ "MIT" ]
amadare42/refundablefocus
Common/Utils.cs
605
C#
namespace Vonage.Voice.EventWebhooks { public class Timeout : CallStatusEvent { } }
12.25
42
0.673469
[ "Apache-2.0" ]
Cereal-Killa/vonage-dotnet-sdk
Vonage/Voice/EventWebhooks/Timeout.cs
100
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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.CSharp.Outlining; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Outlining { public class CompilationUnitOutlinerTests : AbstractOutlinerTests<CompilationUnitSyntax> { internal override IEnumerable<OutliningSpan> GetRegions(CompilationUnitSyntax node) { var outliner = new CompilationUnitOutliner(); return outliner.GetOutliningSpans(node, CancellationToken.None).WhereNotNull(); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestUsings() { var tree = ParseLines("using System;", "using System.Core;"); var compilationUnit = tree.GetRoot() as CompilationUnitSyntax; var actualRegion = GetRegion(compilationUnit); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(6, 33), hintSpan: TextSpan.FromBounds(0, 33), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion, actualRegion); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestUsingAliases() { var tree = ParseLines("using System;", "using System.Core;", "using text = System.Text;", "using linq = System.Linq;"); var compilationUnit = tree.GetRoot() as CompilationUnitSyntax; var actualRegion = GetRegion(compilationUnit); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(6, 87), hintSpan: TextSpan.FromBounds(0, 87), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion, actualRegion); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestExternAliases() { var tree = ParseLines("extern alias Foo;", "extern alias Bar;"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegion = GetRegion(compilationUnit); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(7, 36), hintSpan: TextSpan.FromBounds(0, 36), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion, actualRegion); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestExternAliasesAndUsings() { var tree = ParseLines("extern alias Foo;", "extern alias Bar;", "using System;", "using System.Core;"); var compilationUnit = tree.GetRoot() as CompilationUnitSyntax; var actualRegion = GetRegion(compilationUnit); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(7, 71), hintSpan: TextSpan.FromBounds(0, 71), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion, actualRegion); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments() { var tree = ParseLines("// Foo", "// Bar", "extern alias Foo;", "extern alias Bar;", "// Foo", "// Bar", "using System;", "using System.Core;", "// Foo", "// Bar"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegions = GetRegions(compilationUnit).ToList(); Assert.Equal(3, actualRegions.Count); var expectedRegion1 = new OutliningSpan( TextSpan.FromBounds(0, 14), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion1, actualRegions[0]); var expectedRegion2 = new OutliningSpan( TextSpan.FromBounds(23, 103), hintSpan: TextSpan.FromBounds(16, 103), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion2, actualRegions[1]); var expectedRegion3 = new OutliningSpan( TextSpan.FromBounds(105, 119), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion3, actualRegions[2]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestUsingsWithComments() { var tree = ParseLines("// Foo", "// Bar", "using System;", "using System.Core;"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegions = GetRegions(compilationUnit).ToList(); Assert.Equal(2, actualRegions.Count); var expectedRegion1 = new OutliningSpan( TextSpan.FromBounds(0, 14), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion1, actualRegions[0]); var expectedRegion2 = new OutliningSpan( TextSpan.FromBounds(22, 49), hintSpan: TextSpan.FromBounds(16, 49), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion2, actualRegions[1]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestExternAliasesWithComments() { var tree = ParseLines("// Foo", "// Bar", "extern alias Foo;", "extern alias Bar;"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegions = GetRegions(compilationUnit).ToList(); Assert.Equal(2, actualRegions.Count); var expectedRegion1 = new OutliningSpan( TextSpan.FromBounds(0, 14), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion1, actualRegions[0]); var expectedRegion2 = new OutliningSpan( TextSpan.FromBounds(23, 52), hintSpan: TextSpan.FromBounds(16, 52), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion2, actualRegions[1]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestWithComments() { var tree = ParseLines("// Foo", "// Bar"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegion = GetRegion(compilationUnit); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(0, 14), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion, actualRegion); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void TestWithCommentsAtEnd() { var tree = ParseLines("using System;", "// Foo", "// Bar"); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegions = GetRegions(compilationUnit).ToList(); var expectedRegion1 = new OutliningSpan( TextSpan.FromBounds(6, 13), hintSpan: TextSpan.FromBounds(0, 13), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion1, actualRegions[0]); var expectedRegion2 = new OutliningSpan( TextSpan.FromBounds(15, 29), "// Foo ...", autoCollapse: true); AssertRegion(expectedRegion2, actualRegions[1]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(539359)] public void TestUsingKeywordWithSpace() { var tree = ParseLines("using "); var compilationUnit = (CompilationUnitSyntax)tree.GetRoot(); var actualRegions = GetRegions(compilationUnit).ToList(); var expectedRegion = new OutliningSpan( TextSpan.FromBounds(6, 6), TextSpan.FromBounds(0, 5), bannerText: CSharpOutliningHelpers.Ellipsis, autoCollapse: true); AssertRegion(expectedRegion, actualRegions[0]); } } }
37.829545
161
0.541103
[ "Apache-2.0" ]
AlessandroDelSole/Roslyn
src/EditorFeatures/CSharpTest/Outlining/CompilationUnitOutlinerTests.cs
9,989
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.ModelConfiguration.Edm { using System.Data.Entity.Core.Mapping; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Utilities; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; internal static class StorageEntityTypeMappingExtensions { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used by test code.")] public static object GetConfiguration(this EntityTypeMapping entityTypeMapping) { DebugCheck.NotNull(entityTypeMapping); return entityTypeMapping.Annotations.GetConfiguration(); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used by test code.")] public static void SetConfiguration(this EntityTypeMapping entityTypeMapping, object configuration) { DebugCheck.NotNull(entityTypeMapping); DebugCheck.NotNull(configuration); entityTypeMapping.Annotations.SetConfiguration(configuration); } public static ColumnMappingBuilder GetPropertyMapping( this EntityTypeMapping entityTypeMapping, params EdmProperty[] propertyPath) { DebugCheck.NotNull(entityTypeMapping); DebugCheck.NotNull(propertyPath); Debug.Assert(propertyPath.Length > 0); return entityTypeMapping.MappingFragments .SelectMany(f => f.ColumnMappings) .Single(p => p.PropertyPath.SequenceEqual(propertyPath)); } public static EntityType GetPrimaryTable(this EntityTypeMapping entityTypeMapping) { return entityTypeMapping.MappingFragments.First().Table; } public static bool UsesOtherTables(this EntityTypeMapping entityTypeMapping, EntityType table) { return entityTypeMapping.MappingFragments.Any(f => f.Table != table); } public static Type GetClrType(this EntityTypeMapping entityTypeMappping) { DebugCheck.NotNull(entityTypeMappping); return entityTypeMappping.Annotations.GetClrType(); } public static void SetClrType(this EntityTypeMapping entityTypeMapping, Type type) { DebugCheck.NotNull(entityTypeMapping); DebugCheck.NotNull(type); entityTypeMapping.Annotations.SetClrType(type); } public static EntityTypeMapping Clone(this EntityTypeMapping entityTypeMapping) { DebugCheck.NotNull(entityTypeMapping); var clone = new EntityTypeMapping(null); clone.AddType(entityTypeMapping.EntityType); entityTypeMapping.Annotations.Copy(clone.Annotations); return clone; } } }
36.559524
132
0.669163
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/ModelConfiguration/Edm/StorageEntityTypeMappingExtensions.cs
3,071
C#
 namespace SSN.Data.Models { public enum VoteType { DownVote = -1, Neutral = 0, UpVote = 1, } }
13.3
27
0.481203
[ "MIT" ]
Plamen91Ivanov/DoctorInformation
src/Data/SSN.Data.Models/VoteType.cs
135
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemBehavior : MonoBehaviour { void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "Player") { Destroy(this.transform.gameObject); Debug.Log("Item collected!"); } } }
21.625
50
0.644509
[ "MIT" ]
PacktPublishing/Learning-C-by-Developing-Games-with-Unity-Sixth-Edition
Ch_08_Starter/Assets/Scripts/ItemBehavior.cs
346
C#
using NUnit.Framework; using System.Collections.Generic; namespace Exodrifter.Rumor.Engine.Tests { public static class AppendExecution { [Test] public static void AppendSuccess() { var rumor = new Rumor( new Dictionary<string, List<Node>> { { Rumor.MainIdentifier, new List<Node>() { new AppendDialogNode("Alice", "Hello world!") , new AppendDialogNode("Alice", "How are you?") } } } ); rumor.Start(); Assert.IsTrue(rumor.Executing); Assert.AreEqual( new Dictionary<string, string>() { { "Alice", "Hello world!" } }, rumor.State.GetDialog() ); rumor.Advance(); Assert.IsTrue(rumor.Executing); Assert.AreEqual( new Dictionary<string, string>() { { "Alice", "Hello world! How are you?" } }, rumor.State.GetDialog() ); rumor.Advance(); Assert.IsFalse(rumor.Executing); Assert.AreEqual(1, rumor.FinishCount); Assert.AreEqual(0, rumor.CancelCount); } } }
20.204082
53
0.624242
[ "MIT" ]
exodrifter/unity-rumor
Engine/Tests/AppendExecution.cs
992
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.Storage.V20171001 { public static class ListStorageAccountServiceSAS { /// <summary> /// The List service SAS credentials operation response. /// </summary> public static Task<ListStorageAccountServiceSASResult> InvokeAsync(ListStorageAccountServiceSASArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListStorageAccountServiceSASResult>("azure-nextgen:storage/v20171001:listStorageAccountServiceSAS", args ?? new ListStorageAccountServiceSASArgs(), options.WithVersion()); } public sealed class ListStorageAccountServiceSASArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// The response header override for cache control. /// </summary> [Input("cacheControl")] public string? CacheControl { get; set; } /// <summary> /// The canonical path to the signed resource. /// </summary> [Input("canonicalizedResource", required: true)] public string CanonicalizedResource { get; set; } = null!; /// <summary> /// The response header override for content disposition. /// </summary> [Input("contentDisposition")] public string? ContentDisposition { get; set; } /// <summary> /// The response header override for content encoding. /// </summary> [Input("contentEncoding")] public string? ContentEncoding { get; set; } /// <summary> /// The response header override for content language. /// </summary> [Input("contentLanguage")] public string? ContentLanguage { get; set; } /// <summary> /// The response header override for content type. /// </summary> [Input("contentType")] public string? ContentType { get; set; } /// <summary> /// An IP address or a range of IP addresses from which to accept requests. /// </summary> [Input("iPAddressOrRange")] public string? IPAddressOrRange { get; set; } /// <summary> /// A unique value up to 64 characters in length that correlates to an access policy specified for the container, queue, or table. /// </summary> [Input("identifier")] public string? Identifier { get; set; } /// <summary> /// The key to sign the account SAS token with. /// </summary> [Input("keyToSign")] public string? KeyToSign { get; set; } /// <summary> /// The end of partition key. /// </summary> [Input("partitionKeyEnd")] public string? PartitionKeyEnd { get; set; } /// <summary> /// The start of partition key. /// </summary> [Input("partitionKeyStart")] public string? PartitionKeyStart { get; set; } /// <summary> /// The signed permissions for the service SAS. Possible values include: Read (r), Write (w), Delete (d), List (l), Add (a), Create (c), Update (u) and Process (p). /// </summary> [Input("permissions")] public Union<string, Pulumi.AzureNextGen.Storage.V20171001.Permissions>? Permissions { get; set; } /// <summary> /// The protocol permitted for a request made with the account SAS. /// </summary> [Input("protocols")] public Pulumi.AzureNextGen.Storage.V20171001.HttpProtocol? Protocols { get; set; } /// <summary> /// The signed services accessible with the service SAS. Possible values include: Blob (b), Container (c), File (f), Share (s). /// </summary> [Input("resource", required: true)] public Union<string, Pulumi.AzureNextGen.Storage.V20171001.SignedResource> Resource { get; set; } = null!; /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The end of row key. /// </summary> [Input("rowKeyEnd")] public string? RowKeyEnd { get; set; } /// <summary> /// The start of row key. /// </summary> [Input("rowKeyStart")] public string? RowKeyStart { get; set; } /// <summary> /// The time at which the shared access signature becomes invalid. /// </summary> [Input("sharedAccessExpiryTime")] public string? SharedAccessExpiryTime { get; set; } /// <summary> /// The time at which the SAS becomes valid. /// </summary> [Input("sharedAccessStartTime")] public string? SharedAccessStartTime { get; set; } public ListStorageAccountServiceSASArgs() { } } [OutputType] public sealed class ListStorageAccountServiceSASResult { /// <summary> /// List service SAS credentials of specific resource. /// </summary> public readonly string ServiceSasToken; [OutputConstructor] private ListStorageAccountServiceSASResult(string serviceSasToken) { ServiceSasToken = serviceSasToken; } } }
36.187879
225
0.605259
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Storage/V20171001/ListStorageAccountServiceSAS.cs
5,971
C#
using System.Collections.Generic; using System.Linq; using UKitchen.Localizations.Model; using UnityEditor; namespace UKitchen.Localizations { public abstract class AbsLocalizationMonoStateHelperEditor : Editor { } public abstract class AbsLocalizationMonoStateHelperEditor<TWord, TSettings, TInstaller, THelper> : AbsLocalizationMonoStateHelperEditor where TWord : AbsWord where TSettings : AbsLocalizationSettings<TWord> where TInstaller : AbsLocalizationInstaller<TWord, TSettings> where THelper : AbsLocalizationMonoStateHelper<TWord, TSettings, TInstaller> { private SerializedProperty m_Installer; private SerializedProperty m_Text; private SerializedProperty m_useState; private SerializedProperty _stateItems; private SerializedProperty _defaultStateValue; private TInstaller _installer; private bool _changeCheck; private void OnEnable() { m_Installer = serializedObject.FindProperty("m_Installer"); m_Text = serializedObject.FindProperty("m_Text"); m_useState = serializedObject.FindProperty("m_useState"); _stateItems = serializedObject.FindProperty("_stateItems"); _defaultStateValue = serializedObject.FindProperty("_defaultStateValue"); Init(); } private void Init() { if (m_Installer.objectReferenceValue == null || _installer == null) { _installer = AssetDatabase.LoadAssetAtPath<TInstaller>( "Assets/Resources/UnityKitchen/LocalizationInstaller.asset"); m_Installer.objectReferenceValue = _installer; } } public override void OnInspectorGUI() { serializedObject.Update(); Init(); THelper comp = (THelper) target; EditorGUI.BeginChangeCheck(); EditorGUI.BeginDisabledGroup(true); EditorGUILayout.PropertyField(m_Installer); EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(m_Text); EditorGUILayout.PropertyField(m_useState); EditorGUILayout.PropertyField(_defaultStateValue); EditorGUI.indentLevel++; ShowStateList(_stateItems); EditorGUI.indentLevel--; _changeCheck = EditorGUI.EndChangeCheck(); if (_changeCheck) { m_Text?.serializedObject.ApplyModifiedProperties(); if (m_useState.boolValue) { comp.StateValue = _defaultStateValue.intValue; } } serializedObject.ApplyModifiedProperties(); } private void ShowStateList(SerializedProperty list) { if (_installer == null) return; var tmp = list?.FindPropertyRelative("Array.size"); if(tmp == null) return; List<TWord> wordList = _installer.settings.wordList; string[] keyList = wordList.Select(s => s.key).ToArray(); EditorGUILayout.PropertyField(list, false); if (list.isExpanded) { EditorGUILayout.PropertyField(list.FindPropertyRelative("Array.size")); for (int i = 0; i < list.arraySize; i++) { EditorGUI.indentLevel++; SerializedProperty item = list.GetArrayElementAtIndex(i); EditorGUILayout.PropertyField(item, false); if (item.isExpanded) { EditorGUI.indentLevel++; SerializedProperty _stateValue = item.FindPropertyRelative("_stateValue"); SerializedProperty useLocalization = item.FindPropertyRelative("useLocalization"); SerializedProperty toUpper = item.FindPropertyRelative("toUpper"); SerializedProperty key = item.FindPropertyRelative("key"); SerializedProperty stateStr = item.FindPropertyRelative("text"); EditorGUILayout.PropertyField(_stateValue); EditorGUILayout.PropertyField(useLocalization); if (useLocalization.boolValue) { EditorGUILayout.PropertyField(toUpper); if (string.IsNullOrEmpty(key.stringValue)) key.stringValue = keyList[0]; string search = string.Empty; search = EditorGUILayout.TextField("Search", search); if (!string.IsNullOrEmpty(search) && keyList.Contains(search)) { key.stringValue = search; } int keyIndex = wordList.FindIndex(s => s.key == key.stringValue); keyIndex = EditorGUILayout.Popup(keyIndex, keyList); TWord word = wordList.FirstOrDefault(s => s.key == keyList[keyIndex]); if (word != null) { stateStr.stringValue = _installer.settings.GetText(key.stringValue); key.stringValue = keyList[keyIndex]; } } EditorGUILayout.PropertyField(stateStr); //} EditorGUI.indentLevel--; } EditorGUI.indentLevel--; } } } } }
35.636364
106
0.543878
[ "MIT" ]
CengizKuscu/UnityKitchen
Assets/UKitchen/Localizations/Editor/AbsLocalizationMonoStateHelperEditor.cs
5,880
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Security.Principal; using System.Web.Security; using System.Web.UI; namespace Microsoft.AspNet.SignalR.Samples.Hubs.Auth { public partial class _Default : Page { protected void Login(object sender, EventArgs e) { var userId = Guid.NewGuid().ToString(); FormsAuthentication.SetAuthCookie(userId, createPersistentCookie: false); var identity = new GenericIdentity(userName.Text); var principal = new GenericPrincipal(identity, SplitString(roles.Text)); Context.User = principal; Cache[userId] = principal; } private static string[] SplitString(string original) { if (String.IsNullOrEmpty(original)) { return new string[0]; } var split = from piece in original.Split(',') let trimmed = piece.Trim() where !String.IsNullOrEmpty(trimmed) select trimmed; return split.ToArray(); } } }
32.74359
111
0.603759
[ "Apache-2.0" ]
286378618/ios-
samples/Microsoft.AspNet.SignalR.Samples/Hubs/Auth/Default.aspx.cs
1,279
C#
using System.Windows.Forms; using LiveChartsCore.SkiaSharpView.WinForms; using ViewModelsSamples.VisualTest.ReattachVisual; namespace WinFormsSample.VisualTest.ReattachVisual; public partial class View : UserControl { private bool _isInVisualTree = true; private readonly CartesianChart _cartesianChart; /// <summary> /// Initializes a new instance of the <see cref="View"/> class. /// </summary> public View() { InitializeComponent(); Size = new System.Drawing.Size(50, 50); var viewModel = new ViewModel(); _cartesianChart = new CartesianChart { Series = viewModel.Series, // out of livecharts properties... Location = new System.Drawing.Point(0, 0), Size = new System.Drawing.Size(50, 50), Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom }; var b = new Button { Size = new System.Drawing.Size(150, 50), Text = "Toggle" }; b.Click += B_Click; Controls.Add(_cartesianChart); Controls.Add(b); b.BringToFront(); } private void B_Click(object sender, System.EventArgs e) { if (_isInVisualTree) { Controls.Remove(_cartesianChart); _isInVisualTree = false; return; } Controls.Add(_cartesianChart); _isInVisualTree = true; } }
26
100
0.60054
[ "MIT" ]
Live-Charts/LiveCharts2
samples/WinFormsSample/VisualTest/ReattachVisual/View.cs
1,484
C#
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using Windows.Security.ExchangeActiveSyncProvisioning; using Windows.UI.Xaml; namespace ModernApp4Me.Universal.Metadata { /// <author>Ludovic Roland</author> /// <since>2015.11.19</since> /// <summary> /// Provides information about the device. /// </summary> public sealed class M4MDeviceInformation { private static volatile M4MDeviceInformation instance; private static readonly object InstanceLock = new Object(); public static M4MDeviceInformation Instance { get { if (instance == null) { lock (InstanceLock) { if (instance == null) { instance = new M4MDeviceInformation(); } } } return instance; } } private readonly EasClientDeviceInformation deviceInformation; private M4MDeviceInformation() { deviceInformation = new EasClientDeviceInformation(); } public string FriendlyName { get { return deviceInformation.FriendlyName; } } public string OperatingSystem { get { return deviceInformation.OperatingSystem; } } public string SystemManufacturer { get { return deviceInformation.SystemManufacturer; } } public string SystemProductName { get { return deviceInformation.SystemProductName; } } public string SystemSku { get { return deviceInformation.SystemSku; } } public Guid Id { get { return deviceInformation.Id; } } public double ScreenWidth { get { return Window.Current.Bounds.Width; } } public double ScreenHeight { get { return Window.Current.Bounds.Height; } } } }
22.533333
81
0.642669
[ "MIT" ]
smartnsoft/ModernApp4Me
ModernApp4Me.Universal/Metadata/M4MDeviceInformation.cs
3,044
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace UiPathCloudAPISharp.Models { public class Info<T> { [JsonProperty(PropertyName = "@odata.context")] public string Context { get; set; } [JsonProperty(PropertyName = "@odata.count")] public int Count { get; set; } [JsonProperty(PropertyName = "value")] public List<T> Items { get; set; } } }
23.444444
55
0.625592
[ "MIT" ]
DrGennadius/UiPathCloudAPI
UiPathCloudAPI/Models/Info.cs
424
C#
using UnityEngine; using System.Collections; using UniPromise; using UniRx; namespace Tweasing { public abstract class DurationScalableEmersionTweener : EmersionTweener { public override Promise<CUnit> Show () { return Show (GetDefaultShowEasingDuration (), GetExecutor ()); } public Promise<CUnit> Show (float duration) { return Show (duration, GetExecutor ()); } public Promise<CUnit> Show (TweenExecutor executor) { return Show (GetDefaultShowEasingDuration(), executor); } public Promise<CUnit> Show (float duration, TweenExecutor executor) { var result = DoShow (duration, executor); Tweening.Disposable = result; return result; } protected abstract Promise<CUnit> DoShow (float duration, TweenExecutor executor); public override Promise<CUnit> Hide () { return Hide (GetDefaultHideEasingDuration (), GetExecutor ()); } public Promise<CUnit> Hide (float duration) { return Hide (duration, GetExecutor ()); } public Promise<CUnit> Hide (TweenExecutor executor) { return Hide (GetDefaultHideEasingDuration(), executor); } public Promise<CUnit> Hide(float duration, TweenExecutor executor) { var result = DoHide (duration, executor); Tweening.Disposable = result; return result; } protected abstract Promise<CUnit> DoHide (float duration, TweenExecutor executor); protected TweenExecutor GetExecutor() { return TweasingManager.Instance.Executor; } protected virtual float GetDefaultShowEasingDuration() { throw new System.NotImplementedException (); } protected virtual float GetDefaultHideEasingDuration () { throw new System.NotImplementedException (); } protected override Promise<CUnit> DoShow () { throw new System.NotImplementedException ("never be called"); } protected override Promise<CUnit> DoHide () { throw new System.NotImplementedException ("never be called"); } } }
27.652174
84
0.736373
[ "MIT" ]
shinji-yoshida/Tweasing
Assets/Plugins/Tweasing/DurationScalableEmersionTweener.cs
1,910
C#
// Copyright 2017 Esri. // // 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 Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Ogc; using System; using System.Collections.Generic; using System.Linq; using Windows.UI.Popups; using Microsoft.UI.Xaml; namespace ArcGISRuntime.WinUI.Samples.WmsIdentify { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Identify WMS features", category: "Layers", description: "Identify features in a WMS layer and display the associated popup content.", instructions: "Tap a feature to identify it. The HTML content associated with the feature will be displayed in a web view.", tags: new[] { "IdentifyLayerAsync", "OGC", "ShowCalloutAt", "WMS", "callout", "web map service" })] public partial class WmsIdentify { // Create and hold the URL to the WMS service showing EPA water info. private readonly Uri _wmsUrl = new Uri( "https://watersgeo.epa.gov/arcgis/services/OWPROGRAM/SDWIS_WMERC/MapServer/WMSServer?request=GetCapabilities&service=WMS"); // Create and hold a list of uniquely-identifying WMS layer names to display. private readonly List<string> _wmsLayerNames = new List<string> {"4"}; // Hold the WMS layer. private WmsLayer _wmsLayer; public WmsIdentify() { InitializeComponent(); // Initialize the sample. Initialize(); } private async void Initialize() { // Apply an imagery basemap to the map. MyMapView.Map = new Map(Basemap.CreateImagery()); // Create a new WMS layer displaying the specified layers from the service. _wmsLayer = new WmsLayer(_wmsUrl, _wmsLayerNames); try { // Load the layer. await _wmsLayer.LoadAsync(); // Add the layer to the map. MyMapView.Map.OperationalLayers.Add(_wmsLayer); // Zoom to the layer's extent. MyMapView.SetViewpoint(new Viewpoint(_wmsLayer.FullExtent)); // Subscribe to tap events - starting point for feature identification. MyMapView.GeoViewTapped += MyMapView_GeoViewTapped; } catch (Exception e) { await new MessageDialog2(e.ToString(), "Error").ShowAsync(); } } private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e) { // Clear any existing result. ResultWebView.Visibility = Visibility.Collapsed; try { // Perform the identify operation. IdentifyLayerResult myIdentifyResult = await MyMapView.IdentifyLayerAsync(_wmsLayer, e.Position, 20, false); // Return if there's nothing to show. if (!myIdentifyResult.GeoElements.Any()) { return; } // Retrieve the identified feature, which is always a WmsFeature for WMS layers. WmsFeature identifiedFeature = (WmsFeature) myIdentifyResult.GeoElements[0]; // Retrieve the WmsFeature's HTML content. string htmlContent = identifiedFeature.Attributes["HTML"].ToString(); // Note that the service returns a boilerplate HTML result if there is no feature found. // This test should work for most arcGIS-based WMS services, but results may vary. if (!htmlContent.Contains("OBJECTID")) { // Return without showing the callout. return; } // Show the result. ResultWebView.NavigateToString(htmlContent); ResultWebView.Visibility = Visibility.Visible; } catch (Exception ex) { await new MessageDialog2(ex.ToString(), "Error").ShowAsync(); } } } }
40.26087
135
0.615983
[ "Apache-2.0" ]
Esri/arcgis-runtime-samples-dotne
src/WinUI/ArcGISRuntime.WinUI.Viewer/Samples/Layers/WmsIdentify/WmsIdentify.xaml.cs
4,630
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Deployment.WindowsInstaller; namespace MyCustomAction { public class CustomActions { [CustomAction] public static ActionResult ShowTime(Session session) { ResetProgress(session); NumberOfTicksPerActionData(session, 100); DisplayActionData(session, "Message 1"); System.Threading.Thread.Sleep(2000); DisplayActionData(session, "Message 2"); System.Threading.Thread.Sleep(2000); DisplayActionData(session, "Message 3"); System.Threading.Thread.Sleep(2000); return ActionResult.Success; } private static void ResetProgress(Session session) { Record record = new Record(4); record[1] = "0"; record[2] = "1000"; record[3] = "0"; record[4] = "0"; session.Message(InstallMessage.Progress, record); } private static void NumberOfTicksPerActionData( Session session, int ticks) { Record record = new Record(3); record[1] = "1"; record[2] = ticks.ToString(); record[3] = "1"; session.Message(InstallMessage.Progress, record); } private static void DisplayActionData(Session session, string message) { Record record = new Record(1); record[1] = message; session.Message(InstallMessage.ActionData, record); } } }
28.754386
63
0.568029
[ "MIT" ]
PacktPublishing/WiX-3.6-A-Developer-s-Guide-to-Windows-Installer-XML
Chapter 8/TimeRemaining example/MyCustomAction/CustomAction.cs
1,641
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL.Contacts { [TLObject(1891070632)] public class TLTopPeers : TLAbsTopPeers { public override int Constructor { get { return 1891070632; } } public TLVector<TLTopPeerCategoryPeers> Categories { get; set; } public TLVector<TLAbsChat> Chats { get; set; } public TLVector<TLAbsUser> Users { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { this.Categories = (TLVector<TLTopPeerCategoryPeers>)ObjectUtils.DeserializeVector<TLTopPeerCategoryPeers>(br); this.Chats = (TLVector<TLAbsChat>)ObjectUtils.DeserializeVector<TLAbsChat>(br); this.Users = (TLVector<TLAbsUser>)ObjectUtils.DeserializeVector<TLAbsUser>(br); } public override void SerializeBody(BinaryWriter bw) { bw.Write(this.Constructor); ObjectUtils.SerializeObject(this.Categories, bw); ObjectUtils.SerializeObject(this.Chats, bw); ObjectUtils.SerializeObject(this.Users, bw); } } }
27.387755
122
0.632638
[ "MIT" ]
slctr/Men.Telegram.ClientApi
Men.Telegram.ClientApi/TL/TL/Contacts/TLTopPeers.cs
1,342
C#
using System.Web; using System.Web.Mvc; namespace Web2Test { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.642857
80
0.651341
[ "MIT" ]
tlaothong/lab-swp-scalable
Web2Test/Web2Test/App_Start/FilterConfig.cs
263
C#
// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // 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. // // ------------------------------------------------------------------------------- // SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet // published with the following license: // ------------------------------------------------------------------------------- // // Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry // // 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. namespace Xenko.Core.Yaml.Tokens { /// <summary> /// Represents a document start token. /// </summary> public class DocumentStart : Token { /// <summary> /// Initializes a new instance of the <see cref="DocumentStart"/> class. /// </summary> public DocumentStart() : this(Mark.Empty, Mark.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="DocumentStart"/> class. /// </summary> /// <param name="start">The start position of the token.</param> /// <param name="end">The end position of the token.</param> public DocumentStart(Mark start, Mark end) : base(start, end) { } } }
46.676056
82
0.672601
[ "MIT" ]
Aminator/xenko
sources/core/Xenko.Core.Yaml/Tokens/DocumentStart.cs
3,314
C#
using Owin; namespace TraceBot { public static class AppBuilderExtensions { public static IAppBuilder UseTraceBot(this IAppBuilder builder) { builder.Use(WebSockets.Upgrade); return builder; } } }
18.5
71
0.6139
[ "MIT" ]
rwhitmire/TraceBot
TraceBot/AppBuilderExtensions.cs
261
C#
namespace YouInject { public interface IYouInjectLogger { void Log(object message); } }
15.428571
37
0.638889
[ "MIT" ]
Holygoe/YouInject
Runtime/IYouInjectLogger.cs
110
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Application.cs" company="Diego Arenas T."> // © All rights reserved // </copyright> // <summary> // Application // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace XamarinNinjaCourse.Mobile.iOS { using UIKit; /// <summary> /// Application /// </summary> public class Application { /// <summary> /// Defines the entry point of the application. This is the main entry point of the application. /// </summary> /// <param name="args">The arguments.</param> private static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
32.677419
120
0.451135
[ "MIT" ]
dtarenas/XamarinNinjaCourse
XamarinNinjaCourse.Mobile/XamarinNinjaCourse.Mobile.iOS/Main.cs
1,016
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AllReady.Areas.Admin.Features.Events; using AllReady.Areas.Admin.Models; using AllReady.Models; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AllReady.UnitTest.Areas.Admin.Features.Events { public class EditEvent : TestBase { [Fact] public async Task EventDoesNotExist() { var context = ServiceProvider.GetService<AllReadyContext>(); var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); context.Organizations.Add(htb); context.SaveChanges(); var vm = new EventDetailModel { CampaignId = 1, TimeZoneId = "Central Standard Time" }; var query = new EditEventCommand { Event = vm }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.True(result > 0); var data = context.Events.Count(_ => _.Id == result); Assert.True(data == 1); } [Fact] public async Task ExistingEvent() { var context = ServiceProvider.GetService<AllReadyContext>(); var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); var queenAnne = new Event { Id = 100, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = new Location { Id = 1 }, RequiredSkills = new List<EventSkill>() }; context.Organizations.Add(htb); context.Events.Add(queenAnne); context.SaveChanges(); const string NEW_NAME = "Some new name value"; var startDateTime = new DateTime(2015, 7, 12, 4, 15, 0); var endDateTime = new DateTime(2015, 12, 7, 15, 10, 0); var vm = new EventDetailModel { CampaignId = queenAnne.CampaignId, CampaignName = queenAnne.Campaign.Name, Description = queenAnne.Description, EndDateTime = endDateTime, Id = queenAnne.Id, ImageUrl = queenAnne.ImageUrl, Location = null, Name = NEW_NAME, RequiredSkills = queenAnne.RequiredSkills, TimeZoneId = "Central Standard Time", StartDateTime = startDateTime, Tasks = null, OrganizationId = queenAnne.Campaign.ManagingOrganizationId, OrganizationName = queenAnne.Campaign.ManagingOrganization.Name, Volunteers = null }; var query = new EditEventCommand { Event = vm }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.Equal(100, result); // should get back the event id var data = context.Events.Single(_ => _.Id == result); Assert.Equal(NEW_NAME, data.Name); Assert.Equal(2015, data.StartDateTime.Year); Assert.Equal(7, data.StartDateTime.Month); Assert.Equal(12, data.StartDateTime.Day); Assert.Equal(4, data.StartDateTime.Hour); Assert.Equal(15, data.StartDateTime.Minute); Assert.Equal(-5, data.StartDateTime.Offset.TotalHours); Assert.Equal(2015, data.EndDateTime.Year); Assert.Equal(12, data.EndDateTime.Month); Assert.Equal(7, data.EndDateTime.Day); Assert.Equal(15, data.EndDateTime.Hour); Assert.Equal(10, data.EndDateTime.Minute); Assert.Equal(-6, data.EndDateTime.Offset.TotalHours); } [Fact] public async Task ExistingEventUpdateLocation() { var seattlePostalCode = "98117"; var seattle = new Location { Id = 1, Address1 = "123 Main Street", Address2 = "Unit 2", City = "Seattle", PostalCode = seattlePostalCode, Country = "USA", State = "WA", Name = "Organizer name", PhoneNumber = "555-555-5555" }; var context = ServiceProvider.GetService<AllReadyContext>(); var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); var queenAnne = new Event { Id = 100, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = seattle, RequiredSkills = new List<EventSkill>() }; context.Locations.Add(seattle); context.Organizations.Add(htb); context.Events.Add(queenAnne); context.SaveChanges(); var NEW_LOCATION = LocationExtensions.ToEditModel(new Location { Address1 = "123 new address", Address2 = "new suite", PostalCode = "98004", City = "Bellevue", State = "WA", Country = "USA", Name = "New name", PhoneNumber = "New number" }); var locationEdit = new EventDetailModel { CampaignId = queenAnne.CampaignId, CampaignName = queenAnne.Campaign.Name, Description = queenAnne.Description, EndDateTime = queenAnne.EndDateTime, Id = queenAnne.Id, ImageUrl = queenAnne.ImageUrl, Location = NEW_LOCATION, Name = queenAnne.Name, RequiredSkills = queenAnne.RequiredSkills, TimeZoneId = "Central Standard Time", StartDateTime = queenAnne.StartDateTime, Tasks = null, OrganizationId = queenAnne.Campaign.ManagingOrganizationId, OrganizationName = queenAnne.Campaign.ManagingOrganization.Name, Volunteers = null }; var query = new EditEventCommand { Event = locationEdit }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.Equal(100, result); // should get back the event id var data = context.Events.Single(a => a.Id == result); Assert.Equal(data.Location.Address1, NEW_LOCATION.Address1); Assert.Equal(data.Location.Address2, NEW_LOCATION.Address2); Assert.Equal(data.Location.City, NEW_LOCATION.City); Assert.Equal(data.Location.PostalCode, NEW_LOCATION.PostalCode); Assert.Equal(data.Location.State, NEW_LOCATION.State); Assert.Equal(data.Location.Country, NEW_LOCATION.Country); Assert.Equal(data.Location.PhoneNumber, NEW_LOCATION.PhoneNumber); Assert.Equal(data.Location.Name, NEW_LOCATION.Name); } } }
37.863636
85
0.531158
[ "MIT" ]
HydAu/AllReadyCopyJune10_2016
AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Events/EditEvent.cs
9,165
C#
using System; namespace SnelStart.B2B.V2.Client.Operations { /// <summary> /// De gegevenscontainer voor een kasboeking. /// </summary> public class KasboekingModel : IdentifierModel { /// <summary> /// Geeft de naam van deze gegevenscontainer terug. /// </summary> public const string ResourceName = "kasboekingen"; /// <summary> /// Geeft een instantie van een <see cref="KasboekingModel"/> terug. /// </summary> public KasboekingModel() : base(ResourceName) { } public DateTime ModifiedOn { get; set; } public DateTime Datum { get; set; } public bool Markering { get; set; } public string Boekstuk { get; set; } public bool GewijzigdDoorAccountant { get; set; } public string Omschrijving { get; set; } public GrootboekBoekingsRegelModel[] GrootboekBoekingsRegels { get; set; } = new GrootboekBoekingsRegelModel[0]; public InkoopBoekingVerantwoordingsRegelModel[] InkoopboekingBoekingsRegels { get; set; } = new InkoopBoekingVerantwoordingsRegelModel[0]; public VerkoopBoekingVerantwoordingsRegelModel[] VerkoopboekingBoekingsRegels { get; set; } = new VerkoopBoekingVerantwoordingsRegelModel[0]; public BtwBoekingregelModel[] BtwBoekingsregels { get; set; } = new BtwBoekingregelModel[0]; public decimal BedragUitgegeven { get; set; } public decimal BedragOntvangen { get; set; } public DagboekIdentifierModel Dagboek { get; set; } } }
38.85
149
0.662162
[ "MIT" ]
BeyondDefinition/B2B.client.v2.net
SnelStart.B2B.V2.Client/Operations/Kasboekingen/KasboekingModel.cs
1,554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; namespace CustomUpdateEngine { public class CreateFolderAction : GenericAction { public CreateFolderAction(string xmlFragment) { LogInitialization(xmlFragment); XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlFragment)); if (!reader.ReadToFollowing("FullPath")) throw new ArgumentException("Unable to find token : FullPath"); FullPath = reader.ReadElementContentAsString(); LogCompletion(); } public string FullPath { get; private set; } public override void Run(ref ReturnCodeAction returnCode) { Logger.Write("Running CreateFolder. FullPath = " + this.FullPath); try { this.FullPath = Tools.GetExpandedPath(this.FullPath); DirectoryInfo destinationFolder = new DirectoryInfo(this.FullPath); if (!destinationFolder.Exists) { destinationFolder.Create(); destinationFolder.Refresh(); Logger.Write(destinationFolder.Exists ? "Successfully created : " + this.FullPath : "Unable to create : " + this.FullPath); } else { Logger.Write("The folder already exists."); } } catch (Exception ex) { Logger.Write("Failed to create the folder : " + this.FullPath + "\r\n" + ex.Message); } Logger.Write("End of CreateFolder."); } } }
31.981132
143
0.573451
[ "MIT" ]
DCourtel/Wsus_Package_Publisher
code/CustomUpdateEngine/Actions/CreateFolderAction.cs
1,697
C#
using Content.Server.Atmos.EntitySystems; using Content.Shared.Atmos; using Content.Shared.Maps; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.ViewVariables; namespace Content.Server.Atmos { /// <summary> /// Internal Atmos class that stores data about the atmosphere in a grid. /// You shouldn't use this directly, use <see cref="AtmosphereSystem"/> instead. /// </summary> public class TileAtmosphere : IGasMixtureHolder { [ViewVariables] public int CurrentCycle; [ViewVariables] public float Temperature { get; set; } = Atmospherics.T20C; [ViewVariables] public TileAtmosphere? PressureSpecificTarget { get; set; } [ViewVariables] public float PressureDifference { get; set; } [ViewVariables(VVAccess.ReadWrite)] public float HeatCapacity { get; set; } = 1f; [ViewVariables] public float ThermalConductivity { get; set; } = 0.05f; [ViewVariables] public bool Excited { get; set; } /// <summary> /// Adjacent tiles in the same order as <see cref="AtmosDirection"/>. (NSEW) /// </summary> [ViewVariables] public readonly TileAtmosphere?[] AdjacentTiles = new TileAtmosphere[Atmospherics.Directions]; [ViewVariables] public AtmosDirection AdjacentBits = AtmosDirection.Invalid; [ViewVariables] public MonstermosInfo MonstermosInfo; [ViewVariables] public Hotspot Hotspot; [ViewVariables] public AtmosDirection PressureDirection; [ViewVariables] public GridId GridIndex { get; } [ViewVariables] public TileRef? Tile => GridIndices.GetTileRef(GridIndex); [ViewVariables] public Vector2i GridIndices { get; } [ViewVariables] public ExcitedGroup? ExcitedGroup { get; set; } /// <summary> /// The air in this tile. If null, this tile is completely air-blocked. /// This can be immutable if the tile is spaced. /// </summary> [ViewVariables] public GasMixture? Air { get; set; } GasMixture IGasMixtureHolder.Air { get => Air ?? new GasMixture(Atmospherics.CellVolume){ Temperature = Temperature }; set => Air = value; } [ViewVariables] public float MaxFireTemperatureSustained { get; set; } [ViewVariables] public AtmosDirection BlockedAirflow { get; set; } = AtmosDirection.Invalid; public TileAtmosphere(GridId gridIndex, Vector2i gridIndices, GasMixture? mixture = null, bool immutable = false) { GridIndex = gridIndex; GridIndices = gridIndices; Air = mixture; if(immutable) Air?.MarkImmutable(); } } }
29.742268
121
0.620451
[ "MIT" ]
AJCM-git/space-station-14
Content.Server/Atmos/TileAtmosphere.cs
2,885
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.Batch.V20181201 { public static class ListBatchAccountKeys { public static Task<ListBatchAccountKeysResult> InvokeAsync(ListBatchAccountKeysArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListBatchAccountKeysResult>("azure-nextgen:batch/v20181201:listBatchAccountKeys", args ?? new ListBatchAccountKeysArgs(), options.WithVersion()); } public sealed class ListBatchAccountKeysArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the Batch account. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// The name of the resource group that contains the Batch account. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public ListBatchAccountKeysArgs() { } } [OutputType] public sealed class ListBatchAccountKeysResult { /// <summary> /// The Batch account name. /// </summary> public readonly string AccountName; /// <summary> /// The primary key associated with the account. /// </summary> public readonly string Primary; /// <summary> /// The secondary key associated with the account. /// </summary> public readonly string Secondary; [OutputConstructor] private ListBatchAccountKeysResult( string accountName, string primary, string secondary) { AccountName = accountName; Primary = primary; Secondary = secondary; } } }
30.376812
199
0.627385
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Batch/V20181201/ListBatchAccountKeys.cs
2,096
C#
using OpenKh.Kh2; using OpenKh.Kh2.Battle; using OpenKh.Tools.Common.Models; using OpenKh.Tools.Kh2BattleEditor.Extensions; using OpenKh.Tools.Kh2BattleEditor.Interfaces; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; namespace OpenKh.Tools.Kh2BattleEditor.ViewModels { public class BtlvViewModel : MyGenericListModel<BtlvViewModel.BtlvEntryViewModel>, IBattleGetChanges { public class BtlvEntryViewModel { public Btlv Btlv { get; } public BtlvEntryViewModel(Btlv btlv) { Btlv = btlv; } public string Name => $"{Btlv.Id:X02}"; public int Id { get => Btlv.Id; set => Btlv.Id = value; } public int ProgressFlag { get => Btlv.ProgressFlag; set => Btlv.ProgressFlag = value; } public byte WorldZZ { get => Btlv.WorldZZ; set => Btlv.WorldZZ = value; } public byte WorldOfDarkness { get => Btlv.WorldOfDarkness; set => Btlv.WorldOfDarkness = value; } public byte TwilightTown { get => Btlv.TwilightTown; set => Btlv.TwilightTown = value; } public byte DestinyIslands { get => Btlv.DestinyIslands; set => Btlv.DestinyIslands = value; } public byte HollowBastion { get => Btlv.HollowBastion; set => Btlv.HollowBastion = value; } public byte BeastCastle { get => Btlv.BeastCastle; set => Btlv.BeastCastle = value; } public byte OlympusColiseum { get => Btlv.OlympusColiseum; set => Btlv.OlympusColiseum = value; } public byte Agrabah { get => Btlv.Agrabah; set => Btlv.Agrabah = value; } public byte LandOfDragons { get => Btlv.LandOfDragons; set => Btlv.LandOfDragons = value; } public byte HundredAcreWoods { get => Btlv.HundredAcreWoods; set => Btlv.HundredAcreWoods = value; } public byte PrideLands { get => Btlv.PrideLands; set => Btlv.PrideLands = value; } public byte Atlantica { get => Btlv.Atlantica; set => Btlv.Atlantica = value; } public byte DisneyCastle { get => Btlv.DisneyCastle; set => Btlv.DisneyCastle = value; } public byte TimelessRiver { get => Btlv.TimelessRiver; set => Btlv.TimelessRiver = value; } public byte HalloweenTown { get => Btlv.HalloweenTown; set => Btlv.HalloweenTown = value; } public byte WorldMap { get => Btlv.WorldMap; set => Btlv.WorldMap = value; } public byte PortRoyal { get => Btlv.PortRoyal; set => Btlv.PortRoyal = value; } public byte SpaceParanoids { get => Btlv.SpaceParanoids; set => Btlv.SpaceParanoids = value; } public byte TheWorldThatNeverWas { get => Btlv.TheWorldThatNeverWas; set => Btlv.TheWorldThatNeverWas = value; } } private const string entryName = "btlv"; private string _searchTerm; public BtlvViewModel(IEnumerable<Bar.Entry> entries) : this(Btlv.Read(entries.GetBattleStream(entryName))) { } public BtlvViewModel() : this(new List<Btlv>()) { } private BtlvViewModel(IEnumerable<Btlv> items) : base(items.Select(Map)) { } public string EntryName => entryName; public Visibility IsItemEditingVisible => IsItemSelected ? Visibility.Visible : Visibility.Collapsed; public Visibility IsItemEditMessageVisible => !IsItemSelected ? Visibility.Visible : Visibility.Collapsed; public Stream CreateStream() { var stream = new MemoryStream(); Btlv.Write(stream, UnfilteredItems.Select(x => x.Btlv)); return stream; } protected override void OnSelectedItem(BtlvEntryViewModel item) { base.OnSelectedItem(item); OnPropertyChanged(nameof(IsItemEditingVisible)); OnPropertyChanged(nameof(IsItemEditMessageVisible)); } private static BtlvEntryViewModel Map(Btlv item) => new BtlvEntryViewModel(item); } }
45.111111
124
0.636946
[ "Apache-2.0" ]
1234567890num/OpenKh
OpenKh.Tools.Kh2BattleEditor/ViewModels/BtlvViewModel.cs
4,060
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest. /// </summary> public partial class DeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest : BaseRequest, IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest { /// <summary> /// Constructs a new DeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified UserExperienceAnalyticsCategory to the collection via POST. /// </summary> /// <param name="userExperienceAnalyticsCategory">The UserExperienceAnalyticsCategory to add.</param> /// <returns>The created UserExperienceAnalyticsCategory.</returns> public System.Threading.Tasks.Task<UserExperienceAnalyticsCategory> AddAsync(UserExperienceAnalyticsCategory userExperienceAnalyticsCategory) { return this.AddAsync(userExperienceAnalyticsCategory, CancellationToken.None); } /// <summary> /// Adds the specified UserExperienceAnalyticsCategory to the collection via POST. /// </summary> /// <param name="userExperienceAnalyticsCategory">The UserExperienceAnalyticsCategory to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created UserExperienceAnalyticsCategory.</returns> public System.Threading.Tasks.Task<UserExperienceAnalyticsCategory> AddAsync(UserExperienceAnalyticsCategory userExperienceAnalyticsCategory, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<UserExperienceAnalyticsCategory>(userExperienceAnalyticsCategory, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IDeviceManagementUserExperienceAnalyticsCategoriesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IDeviceManagementUserExperienceAnalyticsCategoriesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<DeviceManagementUserExperienceAnalyticsCategoriesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Expand(Expression<Func<UserExperienceAnalyticsCategory, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Select(Expression<Func<UserExperienceAnalyticsCategory, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
44.054795
186
0.616397
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/DeviceManagementUserExperienceAnalyticsCategoriesCollectionRequest.cs
9,648
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; using System.Net; using System.Net.Http; using System.Web.Http; using DotNetNuke.Entities.Users; using DotNetNuke.Entities.Users.Social; using DotNetNuke.Instrumentation; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Social.Messaging.Internal; using DotNetNuke.Services.Social.Notifications; using DotNetNuke.Web.Api; namespace DotNetNuke.Web.InternalServices { [DnnAuthorize] public class RelationshipServiceController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RelationshipServiceController)); [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage AcceptFriend(NotificationDTO postData) { var success = false; try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); int userRelationshipId; if (int.TryParse(notification.Context, out userRelationshipId)) { var userRelationship = RelationshipController.Instance.GetUserRelationship(userRelationshipId); if (userRelationship != null) { var friend = UserController.GetUserById(this.PortalSettings.PortalId, userRelationship.UserId); FriendsController.Instance.AcceptFriend(friend); success = true; } } } } catch (Exception exc) { Logger.Error(exc); } if(success) { return this.Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); } return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage FollowBack(NotificationDTO postData) { var success = false; try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); int targetUserId; if (int.TryParse(notification.Context, out targetUserId)) { var targetUser = UserController.GetUserById(this.PortalSettings.PortalId, targetUserId); if (targetUser == null) { var response = new { Message = Localization.GetExceptionMessage("UserDoesNotExist", "The user you are trying to follow no longer exists.") }; return this.Request.CreateResponse(HttpStatusCode.InternalServerError, response); } FollowersController.Instance.FollowUser(targetUser); NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, this.UserInfo.UserID); success = true; } } } catch (UserRelationshipExistsException exc) { Logger.Error(exc); var response = new { Message = Localization.GetExceptionMessage("AlreadyFollowingUser", "You are already following this user.") }; return this.Request.CreateResponse(HttpStatusCode.InternalServerError, response); } catch (Exception exc) { Logger.Error(exc); return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc.Message); } if (success) { return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } } }
40.172131
136
0.569884
[ "MIT" ]
MaiklT/Dnn.Platform
DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs
4,903
C#
using Microsoft.Management.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using SimCim.Core; namespace SimCim.Root.StandardCimV2 { public class CIMDNSGeneralSettingData : CIMIPAssignmentSettingData { public CIMDNSGeneralSettingData() { } public CIMDNSGeneralSettingData(IInfrastructureObjectScope scope, CimInstance instance): base(scope, instance) { } public System.Boolean? AppendParentSuffixes { get { System.Boolean? result; this.GetProperty("AppendParentSuffixes", out result); return result; } set { this.SetProperty("AppendParentSuffixes", value); } } public System.Boolean? AppendPrimarySuffixes { get { System.Boolean? result; this.GetProperty("AppendPrimarySuffixes", out result); return result; } set { this.SetProperty("AppendPrimarySuffixes", value); } } public System.String[] DNSSuffixesToAppend { get { System.String[] result; this.GetProperty("DNSSuffixesToAppend", out result); return result; } set { this.SetProperty("DNSSuffixesToAppend", value); } } } }
25.34375
119
0.496917
[ "Apache-2.0" ]
simonferquel/simcim
SimCim.Root.StandardCimV2/ClassCIMDNSGeneralSettingData.cs
1,624
C#
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace MQTTnet.EventBus.DependencyInjection.Builder.Impl { public class ServicesBuilder : IServicesBuilder { private readonly IServiceCollection _services; private readonly HashSet<ServiceType> _addedServices; public ServicesBuilder(IServiceCollection services, HashSet<ServiceType> tempreryData) { _services = services; _addedServices = tempreryData; } public IServicesBuilder AddServices(Action<IServiceCollection> addServices, ServiceType serviceType = ServiceType.Custom) { _addedServices.Add(serviceType); addServices.Invoke(_services); return this; } } }
30.769231
129
0.69875
[ "MIT" ]
Revalcon/MQTTnet.EventBus
src/MQTTnet.EventBus/DependencyInjection/Builder/Impl/ServicesBuilder.cs
802
C#
// ILReader.cs // Author: Sergey Chaban (serge@wildwestsoftware.com) using System; using System.IO; using System.Text; using System.Collections; namespace Mono.ILASM { /// <summary> /// </summary> public class ILReader { readonly private StreamReader reader; readonly private Stack putback_stack; readonly private Location location; private Location markedLocation; public ILReader (StreamReader reader) { this.reader = reader; putback_stack = new Stack (); location = new Location (); markedLocation = Location.Unknown; } /// <summary> /// </summary> public Location Location { get { return location; } } /// <summary> /// Provides access to underlying StreamReader. /// </summary> public StreamReader BaseReader { get { return reader; } } private int DoRead () { if (putback_stack.Count > 0) return (char) putback_stack.Pop (); return reader.Read (); } private int DoPeek () { if (putback_stack.Count > 0) return (char) putback_stack.Peek (); return reader.Peek (); } /// <summary> /// </summary> /// <returns></returns> public int Read () { int read = DoRead (); if (read == '\n') location.NewLine (); else location.NextColumn (); return read; } /// <summary> /// </summary> /// <returns></returns> public int Peek () { return DoPeek (); } /// <summary> /// </summary> public void Unread (char c) { putback_stack.Push (c); if ('\n' == c) location.PreviousLine (); location.PreviousColumn (); } /// <summary> /// </summary> /// <param name="chars"></param> public void Unread (char [] chars) { for (int i=chars.Length-1; i>=0; i--) Unread (chars[i]); } /// <summary> /// </summary> /// <param name="c"></param> public void Unread (int c) { Unread ((char)c); } /// <summary> /// </summary> public void SkipWhitespace () { int ch = Read (); for (; ch != -1 && Char.IsWhiteSpace((char) ch); ch = Read ()); if (ch != -1) Unread (ch); } /// <summary> /// </summary> /// <returns></returns> public string ReadToWhitespace () { StringBuilder sb = new StringBuilder (); int ch = Read (); for (; ch != -1 && !Char.IsWhiteSpace((char) ch); sb.Append ((char) ch), ch = Read ()); if (ch != -1) Unread (ch); return sb.ToString (); } /// <summary> /// </summary> public void MarkLocation () { if (markedLocation == Location.Unknown) { markedLocation = new Location (location); } else { markedLocation.CopyFrom (location); } } /// <summary> /// </summary> public void RestoreLocation () { if (markedLocation != Location.Unknown) { location.CopyFrom (markedLocation); } } } }
16.850299
90
0.578181
[ "MIT" ]
stephen-riley/Mobius.ILasm
Mobius.ILasm/ilasm/scanner/ILReader.cs
2,814
C#
//This must be on "Players" in Unity using UnityEngine; public class Controllers : MonoBehaviour { private bool _isClickedLeft, _isTouchLeft; private bool _isClickedRight, _isTouchRight; private PlayerController _playerController; private void Awake() { _playerController = new PlayerController(); _playerController.PlayerControllers.Move.performed += _ => Move(); } private void OnEnable() => _playerController.Enable(); private void OnDisable() => _playerController.Disable(); private void Move() { var moveInput = _playerController.PlayerControllers.Move.ReadValue<float>(); if (moveInput > 0 || _isTouchRight) { _isClickedRight = true; _isClickedLeft = false; } else if (moveInput < 0 || _isTouchLeft) { _isClickedRight = false; _isClickedLeft = true; } else { _isClickedLeft = false; _isClickedRight = false; } } private void FixedUpdate() { Move(); } public bool IsClickedLeft() { return _isClickedLeft; } public bool IsClickedRight() { return _isClickedRight; } public void ClickedLeft(bool state) { _isTouchLeft = state; } public void ClickedRight(bool state) { _isTouchRight = state; } }
20.782609
84
0.588563
[ "MIT" ]
lg-lg-lg/car2dracing
Assets/Scripts/Controllers.cs
1,434
C#
namespace System { /// <summary> /// Extension method class for <see cref="object"/>. /// </summary> public static partial class ObjectExt { } }
20.75
60
0.590361
[ "MIT" ]
DonaldRecord/TeamSwim.Extensions
Source/TeamSwim.Extensions/Methods/System/Object/_ObjectExt.cs
168
C#
namespace SecurityFever.CredentialManager { /// <summary> /// Type of credential persistence. /// </summary> public enum CredentialPersist : uint { Session = 0x01, LocalMachine = 0x02, Enterprise = 0x03 } }
20.230769
42
0.577947
[ "MIT" ]
Kagre/SecurityFever
SecurityFever.Library/CredentialManager/CredentialPersist.cs
265
C#
/* The MIT License (MIT) Copyright (c) 2015 Patrick McCuller Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Algorithms; namespace AlgorithmsTests { [TestClass] public class TopologicalSortTest { [TestMethod] public void TopoTest_Empty() { TopologicalSort.Sort(new List<TopologicalSort.Node>()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TopoTest_Null() { TopologicalSort.Sort(null); } [TestMethod] public void TopoTest_One() { TopologicalSort.Node node = new TopologicalSort.Node(); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {node}; List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); Assert.AreEqual(sortedNodes[0], nodes[0]); } [TestMethod] public void TopoTest_Two() { TopologicalSort.Node a = new TopologicalSort.Node(); TopologicalSort.Node b = new TopologicalSort.Node(); a.Dependencies.Add(b); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b}; List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); Assert.AreEqual(sortedNodes[0], b); Assert.AreEqual(sortedNodes[1], a); } [TestMethod] public void TopoTest_Three() { TopologicalSort.Node a = new TopologicalSort.Node(); TopologicalSort.Node b = new TopologicalSort.Node(); TopologicalSort.Node c = new TopologicalSort.Node(); a.Dependencies.Add(b); b.Dependencies.Add(c); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b, c}; List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); Assert.AreEqual(sortedNodes[0], c); Assert.AreEqual(sortedNodes[1], b); Assert.AreEqual(sortedNodes[2], a); } [TestMethod] public void TopoTest_Multiple() { TopologicalSort.Node a = new TopologicalSort.Node(); TopologicalSort.Node b = new TopologicalSort.Node(); TopologicalSort.Node c = new TopologicalSort.Node(); TopologicalSort.Node d = new TopologicalSort.Node(); a.Dependencies.Add(b); a.Dependencies.Add(c); b.Dependencies.Add(d); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b, c, d}; List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); Assert.IsTrue(sortedNodes.IndexOf(d) < sortedNodes.IndexOf(b)); Assert.IsTrue(sortedNodes.IndexOf(b) < sortedNodes.IndexOf(a)); Assert.IsTrue(sortedNodes.IndexOf(c) < sortedNodes.IndexOf(a)); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TopoTest_Circular() { TopologicalSort.Node a = new TopologicalSort.Node(); TopologicalSort.Node b = new TopologicalSort.Node(); a.Dependencies.Add(b); b.Dependencies.Add(a); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b}; // ReSharper disable once UnusedVariable List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); } [TestMethod] public void TopoTest_NoDependencies() { TopologicalSort.Node a = new TopologicalSort.Node(); TopologicalSort.Node b = new TopologicalSort.Node(); List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b}; List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes); Assert.IsTrue(sortedNodes.Contains(a)); Assert.IsTrue(sortedNodes.Contains(b)); } } }
41.508197
91
0.651659
[ "MIT" ]
pmcculler/datastructures
AlgorithmsTests/TopologicalSortTest.cs
5,066
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; 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.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// trivia factory. /// /// it will cache some commonly used trivia to reduce memory footprint and heap allocation /// </summary> internal partial class TriviaDataFactory : AbstractTriviaDataFactory { public TriviaDataFactory(TreeData treeInfo, OptionSet optionSet) : base(treeInfo, optionSet) { } private static bool IsCSharpWhitespace(char c) { return SyntaxFacts.IsWhitespace(c) || SyntaxFacts.IsNewLine(c); } public override TriviaData CreateLeadingTrivia(SyntaxToken token) { // no trivia if (!token.HasLeadingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(default(SyntaxToken), token).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Leading(token); var info = GetWhitespaceOnlyTriviaInfo(default(SyntaxToken), token, result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(default(SyntaxToken), token).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.OptionSet, this.TreeInfo, default(SyntaxToken), token); } public override TriviaData CreateTrailingTrivia(SyntaxToken token) { // no trivia if (!token.HasTrailingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default(SyntaxToken)).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Trailing(token); var info = GetWhitespaceOnlyTriviaInfo(token, default(SyntaxToken), result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default(SyntaxToken)).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.OptionSet, this.TreeInfo, token, default(SyntaxToken)); } public override TriviaData Create(SyntaxToken token1, SyntaxToken token2) { // no trivia in between if (!token1.HasTrailingTrivia && !token2.HasLeadingTrivia) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Between(token1, token2); var info = GetWhitespaceOnlyTriviaInfo(token1, token2, result); if (info != null) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return info; } return new ComplexTrivia(this.OptionSet, this.TreeInfo, token1, token2); } private bool ContainsOnlyWhitespace(Analyzer.AnalysisResult result) { if (result.HasComments || result.HasPreprocessor || result.HasSkippedTokens || result.HasSkippedOrDisabledText) { return false; } return true; } private TriviaData GetWhitespaceOnlyTriviaInfo(SyntaxToken token1, SyntaxToken token2, Analyzer.AnalysisResult result) { if (!ContainsOnlyWhitespace(result)) { return null; } // only whitespace in between int space = GetSpaceOnSingleLine(result); Contract.ThrowIfFalse(space >= -1); if (space >= 0) { // check whether we can use cache return GetSpaceTriviaData(space, result.TreatAsElastic); } // tab is used in a place where it is not an indentation if (result.LineBreaks == 0 && result.Tab > 0) { // calculate actual space size from tab var spaces = CalculateSpaces(token1, token2); return new ModifiedWhitespace(this.OptionSet, result.LineBreaks, indentation: spaces, elastic: result.TreatAsElastic, language: LanguageNames.CSharp); } // check whether we can cache trivia info for current indentation var lineCountAndIndentation = GetLineBreaksAndIndentation(result); var canUseTriviaAsItIs = lineCountAndIndentation.Item1; return GetWhitespaceTriviaData(lineCountAndIndentation.Item2, lineCountAndIndentation.Item3, canUseTriviaAsItIs, result.TreatAsElastic); } private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) { var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp), token1) + token1.Span.Length; var textSnippet = this.TreeInfo.GetTextBetween(token1, token2); return textSnippet.ConvertTabToSpace(this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp), initialColumn, textSnippet.Length); } private ValueTuple<bool, int, int> GetLineBreaksAndIndentation(Analyzer.AnalysisResult result) { Debug.Assert(result.Tab >= 0); Debug.Assert(result.LineBreaks >= 0); var indentation = result.Tab * this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp) + result.Space; if (result.HasTrailingSpace || result.HasUnknownWhitespace) { return ValueTuple.Create(false, result.LineBreaks, indentation); } if (!this.OptionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp)) { if (result.Tab > 0) { return ValueTuple.Create(false, result.LineBreaks, indentation); } return ValueTuple.Create(true, result.LineBreaks, indentation); } Debug.Assert(this.OptionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp)); // tab can only appear before space to be a valid tab for indentation if (result.HasTabAfterSpace) { return ValueTuple.Create(false, result.LineBreaks, indentation); } if (result.Space >= this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)) { return ValueTuple.Create(false, result.LineBreaks, indentation); } Debug.Assert((indentation / this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)) == result.Tab); Debug.Assert((indentation % this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)) == result.Space); return ValueTuple.Create(true, result.LineBreaks, indentation); } private int GetSpaceOnSingleLine(Analyzer.AnalysisResult result) { if (result.HasTrailingSpace || result.HasUnknownWhitespace || result.LineBreaks > 0 || result.Tab > 0) { return -1; } return result.Space; } } }
40.538462
196
0.62859
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Workspaces/CSharp/Portable/Formatting/Engine/Trivia/TriviaDataFactory.cs
7,907
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using LCUSharp; using System.Net.Http; using System.Diagnostics; namespace NewLeagueApp.Client { public class RiotConnecter { /// <summary> /// Sends a request to League client /// </summary> /// <param name="httpMethodType">type of request</param> /// <param name="url">url to the request ( do not include the base url )</param> internal async Task<string> SendRequestToRiot(LCUSharp.HttpMethod httpMethodType, string url) { try { var League = await LeagueClient.Connect(); HttpResponseMessage results; results = await League.MakeApiRequest(httpMethodType, url); var data = await results.Content.ReadAsStringAsync(); return data; } catch (Exception err) { throw err; } } /// <summary> /// Sends a request to League client /// </summary> /// <param name="httpMethodType">type of request</param> /// <param name="url">url to the request ( do not include the base url )</param> /// <param name="data">the data that goes with the request ( for none get requests )</param> internal async Task<HttpResponseMessage> SendRequestToRiot(LCUSharp.HttpMethod httpMethodType, string url, object data) { try { var League = await LeagueClient.Connect(); HttpResponseMessage results; results = await League.MakeApiRequest(httpMethodType, url, data); return results; } catch (Exception err) { throw err; } } public async Task WaitForLeageToStart() { await Task.Delay(10000); while (true) { Process[] pname = Process.GetProcessesByName("League of Legends"); if (pname.Length > 0) return; else await Task.Delay(3000); } } public async Task WaitForLeageToClose() { await Task.Delay(10000); while(true) { Process[] pname = Process.GetProcessesByName("League of Legends.exe"); if (pname.Length == 0) return; else await Task.Delay(3000); } } } }
36.552239
129
0.570845
[ "MIT" ]
moahmmed199898/SmartRunes
NewLeagueApp/Client/RiotConnecter.cs
2,451
C#
// <auto-generated /> // This file was generated by a T4 template. // Don't change it directly as your change would get overwritten. Instead, make changes // to the .tt file (i.e. the T4 template) and save it to regenerate this file. // Make sure the compiler doesn't complain about missing Xml comments and CLS compliance // 0108: suppress "Foo hides inherited member Foo. Use the new keyword if hiding was intended." when a controller and its abstract parent are both processed // 0114: suppress "Foo.BarController.Baz()' hides inherited member 'Qux.BarController.Baz()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." when an action (with an argument) overrides an action in a parent controller #pragma warning disable 1591, 3008, 3009, 0108, 0114 #region T4MVC using System; using System.Diagnostics; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using T4MVC; namespace T4MVCHostMvcApp.Controllers { public partial class SomeAsyncController { [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public SomeAsyncController() { } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] protected SomeAsyncController(Dummy d) { } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] protected RedirectToRouteResult RedirectToAction(ActionResult result) { var callInfo = result.GetT4MVCResult(); return RedirectToRoute(callInfo.RouteValueDictionary); } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult) { return RedirectToAction(taskResult.Result); } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result) { var callInfo = result.GetT4MVCResult(); return RedirectToRoutePermanent(callInfo.RouteValueDictionary); } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult) { return RedirectToActionPermanent(taskResult.Result); } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public SomeAsyncController Actions { get { return MVC.SomeAsync; } } [GeneratedCode("T4MVC", "2.0")] public readonly string Area = ""; [GeneratedCode("T4MVC", "2.0")] public readonly string Name = "SomeAsync"; [GeneratedCode("T4MVC", "2.0")] public const string NameConst = "SomeAsync"; [GeneratedCode("T4MVC", "2.0")] static readonly ActionNamesClass s_actions = new ActionNamesClass(); [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public ActionNamesClass ActionNames { get { return s_actions; } } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public class ActionNamesClass { public readonly string SomeAction = "SomeAction"; } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public class ActionNameConstants { public const string SomeAction = "SomeAction"; } static readonly ViewsClass s_views = new ViewsClass(); [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public ViewsClass Views { get { return s_views; } } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public class ViewsClass { static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass(); public _ViewNamesClass ViewNames { get { return s_ViewNames; } } public class _ViewNamesClass { } } } [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode] public partial class T4MVC_SomeAsyncController : T4MVCHostMvcApp.Controllers.SomeAsyncController { public T4MVC_SomeAsyncController() : base(Dummy.Instance) { } [NonAction] partial void SomeActionOverride(T4MVC_System_Web_Mvc_ActionResult callInfo); [NonAction] public override System.Web.Mvc.ActionResult SomeAction() { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.SomeAction); SomeActionOverride(callInfo); return callInfo; } } } #endregion T4MVC #pragma warning restore 1591, 3008, 3009, 0108, 0114
38.96748
285
0.679741
[ "Apache-2.0" ]
T4MVC/T4MVC
T4MVCHostMvcApp/T4MVC Files/SomeAsyncController.generated.cs
4,793
C#
/* Copyright (c) 2017, Nokia All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using net.nuagenetworks.bambou; using net.nuagenetworks.vspk.v6; namespace net.nuagenetworks.vspk.v6.fetchers { public class IngressAuditACLEntryTemplatesFetcher: RestFetcher<IngressAuditACLEntryTemplate> { private const long serialVersionUID = 1L; public IngressAuditACLEntryTemplatesFetcher(RestObject parentRestObj) : base(parentRestObj, typeof(IngressAuditACLEntryTemplate)) { } } }
43.085106
96
0.756543
[ "BSD-3-Clause" ]
nuagenetworks/vspk-csharp
vspk/vspk/IngressAuditACLEntryTemplatesFetcher.cs
2,025
C#
using System; using System.Linq.Expressions; using Gamma.Binding.Core; namespace Gamma.Widgets.SidePanels { [System.ComponentModel.ToolboxItem(true)] public partial class RightSidePanel : Gtk.Bin { public event EventHandler PanelOpened; public event EventHandler PanelHided; public BindingControler<RightSidePanel> Binding { get; private set; } Gtk.Widget panel; public Gtk.Widget Panel { get { return panel; } set { if (panel == value) return; if(panel != null) { hboxMain.Remove (panel); } panel = value; if(panel != null) { hboxMain.PackEnd (panel); hboxMain.ReorderChild (panel, 1); panel.Visible = !IsHided; panel.NoShowAll = true; } } } public string Title { get { return labelTitle.LabelProp; } set{ labelTitle.LabelProp = value; } } [System.ComponentModel.Browsable(false)] public bool ClosedByUser{ get; private set;} [System.ComponentModel.Browsable(false)] public bool OpenedByUser{ get; private set;} public bool IsHided { get { return arrowSlider.ArrowType == Gtk.ArrowType.Left; } set { if(value) { arrowSlider.ArrowType = Gtk.ArrowType.Left; } else { arrowSlider.ArrowType = Gtk.ArrowType.Right; } if (Panel != null) { panel.Visible = !value; } if (value) { if (PanelHided != null) PanelHided(this, EventArgs.Empty); } else { if (PanelOpened != null) PanelOpened(this, EventArgs.Empty); } Binding.FireChange(x => x.IsHided); ClosedByUser = false; OpenedByUser = false; } } public RightSidePanel () { this.Build (); Binding = new BindingControler<RightSidePanel>(this, new Expression<Func<RightSidePanel, object>>[] { (w => w.IsHided), }); } protected void OnEventboxArrowButtonPressEvent (object o, Gtk.ButtonPressEventArgs args) { var newHiddenState = !IsHided; IsHided = newHiddenState; ClosedByUser = newHiddenState; OpenedByUser = !newHiddenState; } } }
18.776786
104
0.63243
[ "Apache-2.0" ]
Art8m/QSProjects
Binding/Gamma.Binding/Widgets/SidePanels/RightSidePanel.cs
2,105
C#
using System; namespace DiStock.DAL { public class ProjectData { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public byte IsPublic { get; set; } public DateTime Date { get; set; } } }
16.555556
47
0.563758
[ "MIT" ]
Chators/Digger
src/Digger.DAL/DiStock.DAL/DiStock.DAL/Datas/Project/ProjectData.cs
300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using SimpleDB.core.IO; namespace SimpleDB.core.TableManagement { public class TableList { private static TableList tableList = null; private static XDocument xTable; private List<Table> Tables = new List<Table>(); private XAttribute headElement; private TableIO IO = new TableIO(); public List<string> Names { get; private set; } = new List<string>(); private TableList() { } private void Initialize() { var tables = xTable.Root.Elements(); foreach(var table in tables) { Names.Add(table.Value); } } public Table loadTable(string tableName) { Table table = new Table(IO.LoadXMLTable(tableName, CoreDB.getPath()), tableName); Tables.Add(table); return table; } public Table getTable(string tableName) { try { return Tables.First(table => table.tableName == tableName); } catch { return loadTable(tableName); } } public bool Release(string tableName) { Table tableToRemove = Tables.First(table => table.tableName == tableName); var result = Tables.Remove(tableToRemove); tableToRemove = null; Names.Remove(tableName); return result; } public IEnumerable<string> tablesInMemory() { List<string> tablesMem = new List<string>(); foreach(Table table in Tables) { tablesMem.Add(table.tableName); } return tablesMem; } public static TableList getTableList() { if (tableList == null) { tableList = new TableList(); } return tableList; } internal void Rename(string oldName, string newName) { xTable.Root.Elements().First(el => el.Value == oldName).Value = newName; SaveTable(); } internal void addReferencePrefix(string tableName) { xTable.Root.Elements().First(element => element.Value == tableName).Add(new XAttribute("FOREIGN_KEY","")); new TableIO().Save("table_list", CoreDB.getPath(), xTable); } internal void removeReferencePrefix(string tableName) { try { xTable.Root.Elements().First(element => element.Value == tableName).Attribute("FOREIGN_KEY").Remove(); new TableIO().Save("table_list", CoreDB.getPath(), xTable); } catch { } } internal void addTableNameToList(string tableName) { IncreaseHead(); xTable.Root.Add(new XElement("Table", tableName)); Names.Add(tableName); new TableIO().Save("table_list", CoreDB.getPath(), xTable); } internal void removeTableFromList(string tableName) { DecreaseHead(); xTable.Root.Elements().First(el => el.Value == tableName).Remove(); } internal IEnumerable<string> getTablesNamesWithReferences() { var elements = xTable.Root.Elements().Where(element => element.Attribute("FOREIGN_KEY") != null); List<string> tmpList = new List<string>(); foreach(var ele in elements) { tmpList.Add(ele.Value); } return tmpList; } internal int getHeadID() { return Convert.ToInt32(headElement.Value); } internal void IncreaseHead() { headElement.Value = (Convert.ToInt32(headElement.Value) + 1).ToString(); } internal void DecreaseHead() { headElement.Value = (Convert.ToInt32(headElement.Value) - 1).ToString(); } internal static void initializeXDocument(XDocument document, TableIO IO) { xTable = document; getTableList().Initialize(); getTableList().headElement = xTable.Root.Attribute("id"); } internal void SaveTable() { new TableIO().Save("table_list", CoreDB.getPath(), xTable); } } }
27.780488
118
0.538191
[ "MIT" ]
Lukasz199312/SimpleDB
core/TableManagement/TableList.cs
4,558
C#
namespace Call_in_a_Doctor { partial class frmAdminConsultancyReq { /// <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.dgvFreeRequest = new System.Windows.Forms.DataGridView(); this.label3 = new System.Windows.Forms.Label(); this.dgvCallinRequest = new System.Windows.Forms.DataGridView(); this.label2 = new System.Windows.Forms.Label(); this.dgvInPersonRequest = new System.Windows.Forms.DataGridView(); this.label1 = new System.Windows.Forms.Label(); this.dgvOnlineRequest = new System.Windows.Forms.DataGridView(); this.label36 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.btnBackAdmin = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgvFreeRequest)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvCallinRequest)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvInPersonRequest)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvOnlineRequest)).BeginInit(); this.SuspendLayout(); // // dgvFreeRequest // this.dgvFreeRequest.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvFreeRequest.Location = new System.Drawing.Point(246, 549); this.dgvFreeRequest.Name = "dgvFreeRequest"; this.dgvFreeRequest.RowTemplate.Height = 24; this.dgvFreeRequest.Size = new System.Drawing.Size(863, 87); this.dgvFreeRequest.TabIndex = 42; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Times New Roman", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(25, 541); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(160, 87); this.label3.TabIndex = 41; this.label3.Text = "Free \r\nAppointment \r\nRequest"; // // dgvCallinRequest // this.dgvCallinRequest.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvCallinRequest.Location = new System.Drawing.Point(246, 410); this.dgvCallinRequest.Name = "dgvCallinRequest"; this.dgvCallinRequest.RowTemplate.Height = 24; this.dgvCallinRequest.Size = new System.Drawing.Size(863, 91); this.dgvCallinRequest.TabIndex = 40; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Times New Roman", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.Black; this.label2.Location = new System.Drawing.Point(25, 402); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(160, 87); this.label2.TabIndex = 39; this.label2.Text = "Call in \r\nAppointment \r\nRequest"; // // dgvInPersonRequest // this.dgvInPersonRequest.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvInPersonRequest.Location = new System.Drawing.Point(246, 265); this.dgvInPersonRequest.Name = "dgvInPersonRequest"; this.dgvInPersonRequest.RowTemplate.Height = 24; this.dgvInPersonRequest.Size = new System.Drawing.Size(863, 91); this.dgvInPersonRequest.TabIndex = 38; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Times New Roman", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(25, 257); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(160, 87); this.label1.TabIndex = 37; this.label1.Text = "In Person \r\nAppointment \r\nRequest"; // // dgvOnlineRequest // this.dgvOnlineRequest.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvOnlineRequest.Location = new System.Drawing.Point(246, 120); this.dgvOnlineRequest.Name = "dgvOnlineRequest"; this.dgvOnlineRequest.RowTemplate.Height = 24; this.dgvOnlineRequest.Size = new System.Drawing.Size(863, 92); this.dgvOnlineRequest.TabIndex = 36; // // label36 // this.label36.AutoSize = true; this.label36.BackColor = System.Drawing.Color.Transparent; this.label36.Font = new System.Drawing.Font("Times New Roman", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label36.ForeColor = System.Drawing.Color.Black; this.label36.Location = new System.Drawing.Point(25, 112); this.label36.Name = "label36"; this.label36.Size = new System.Drawing.Size(160, 87); this.label36.TabIndex = 35; this.label36.Text = "Online\r\nAppointment \r\nRequest"; // // label7 // this.label7.AutoSize = true; this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Font = new System.Drawing.Font("Bahnschrift Condensed", 30F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.Color.Lime; this.label7.Location = new System.Drawing.Point(492, 18); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(270, 60); this.label7.TabIndex = 44; this.label7.Text = "Call in a Doctor"; // // btnBackAdmin // this.btnBackAdmin.Font = new System.Drawing.Font("Modern No. 20", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnBackAdmin.Location = new System.Drawing.Point(12, 18); this.btnBackAdmin.Name = "btnBackAdmin"; this.btnBackAdmin.Size = new System.Drawing.Size(67, 36); this.btnBackAdmin.TabIndex = 271; this.btnBackAdmin.Text = "Back"; this.btnBackAdmin.UseVisualStyleBackColor = true; this.btnBackAdmin.Click += new System.EventHandler(this.btnBackAdmin_Click); // // frmAdminConsultancyReq // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::Call_in_a_Doctor.Properties.Resources.AdminConsultancy; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(1232, 703); this.Controls.Add(this.btnBackAdmin); this.Controls.Add(this.label7); this.Controls.Add(this.dgvFreeRequest); this.Controls.Add(this.label3); this.Controls.Add(this.dgvCallinRequest); this.Controls.Add(this.label2); this.Controls.Add(this.dgvInPersonRequest); this.Controls.Add(this.label1); this.Controls.Add(this.dgvOnlineRequest); this.Controls.Add(this.label36); this.Name = "frmAdminConsultancyReq"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Consultancy Request"; this.Load += new System.EventHandler(this.frmAdminConsultancyReq_Load); ((System.ComponentModel.ISupportInitialize)(this.dgvFreeRequest)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvCallinRequest)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvInPersonRequest)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvOnlineRequest)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.DataGridView dgvFreeRequest; private System.Windows.Forms.Label label3; private System.Windows.Forms.DataGridView dgvCallinRequest; private System.Windows.Forms.Label label2; private System.Windows.Forms.DataGridView dgvInPersonRequest; private System.Windows.Forms.Label label1; private System.Windows.Forms.DataGridView dgvOnlineRequest; private System.Windows.Forms.Label label36; private System.Windows.Forms.Label label7; private System.Windows.Forms.Button btnBackAdmin; } }
54.178571
166
0.614276
[ "MIT" ]
Atanusaha143/Call-in-a-Doctor
Call in a Doctor/Call in a Doctor/AdminConsultancyReq.Designer.cs
10,621
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace JSNLogDemo_Log4Net_NoOnErrorHandler { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
25.125
99
0.603648
[ "MIT" ]
mperdeck/jsnlog.SimpleWorkingDemoGenerator
EmptySolution/jsnlogSimpleWorkingDemos/JSNLogDemo_Log4Net_NoOnErrorHandler/App_Start/RouteConfig.cs
605
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.Azure.KeyVault; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.IdentityModel.Tokens; namespace Microsoft.AspNetCore.Identity.Service.AzureKeyVault { public class KeyVaultSigningCredentialSource : ISigningCredentialsSource { private readonly IOptions<KeyVaultSigningCredentialsSourceOptions> _options; public KeyVaultSigningCredentialSource(IOptions<KeyVaultSigningCredentialsSourceOptions> options) { _options = options; } public async Task<IEnumerable<SigningCredentialsDescriptor>> GetCredentials() { var options = _options.Value; var client = new KeyVaultClient(KeyVaultCallBack, options.ClientHandler); var certificateBundle = await client.GetCertificateAsync(options.VaultUri, options.CertificateName); var secret = await client.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier); var certificate = new X509Certificate2(Base64UrlEncoder.DecodeBytes(secret.Value), string.Empty); var signingCredentials = new SigningCredentials(new X509SecurityKey(certificate), CryptographyHelpers.FindAlgorithm(certificate)); var descriptor = new SigningCredentialsDescriptor( signingCredentials, CryptographyHelpers.GetAlgorithm(signingCredentials), certificateBundle.Attributes.NotBefore.Value.ToUniversalTime(), certificateBundle.Attributes.Expires.Value.ToUniversalTime(), GetMetadata(signingCredentials)); return new List<SigningCredentialsDescriptor>() { descriptor }; IDictionary<string, string> GetMetadata(SigningCredentials credentials) { var rsaParameters = CryptographyHelpers.GetRSAParameters(credentials); return new Dictionary<string, string> { [JsonWebKeyParameterNames.E] = Base64UrlEncoder.Encode(rsaParameters.Exponent), [JsonWebKeyParameterNames.N] = Base64UrlEncoder.Encode(rsaParameters.Modulus), }; } async Task<string> KeyVaultCallBack(string authority, string resource, string scope) { var adCredential = new ClientCredential(options.ClientId, options.ClientSecret); var authenticationContext = new AuthenticationContext(authority, null); var tokenResponse = await authenticationContext.AcquireTokenAsync(resource, adCredential); return tokenResponse.AccessToken; } } } }
47.790323
142
0.702666
[ "Apache-2.0" ]
Asesjix/Identity
src/Service.AzureKeyVault/KeyVaultSigningCredentialSource.cs
2,965
C#
using System; namespace Humanizer { /// <summary> /// ApplyCase method to allow changing the case of a sentence easily /// </summary> public static class CasingExtensions { /// <summary> /// Changes the casing of the provided input /// </summary> /// <param name="input"></param> /// <param name="casing"></param> /// <returns></returns> public static string ApplyCase(this string input, LetterCasing casing) { switch (casing) { case LetterCasing.Title: return input.Transform(To.TitleCase); case LetterCasing.LowerCase: return input.Transform(To.LowerCase); case LetterCasing.AllCaps: return input.Transform(To.UpperCase); case LetterCasing.Sentence: return input.Transform(To.SentenceCase); default: throw new ArgumentOutOfRangeException(nameof(casing)); } } } }
30.216216
79
0.5161
[ "MIT" ]
0xced/Humanizer
src/Humanizer/CasingExtensions.cs
1,084
C#
using System; using Xamarin.Forms; using System.Threading; using System.Globalization; [assembly:Dependency(typeof(Sensus.Locale_Android))] namespace Sensus { public class Locale_Android : ILocale { public void SetLocale (CultureInfo ci){ Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; } /// <remarks> /// Not sure if we can cache this info rather than querying every time /// </remarks> public CultureInfo GetCurrent() { var androidLocale = Java.Util.Locale.Default; // user's preferred locale // en, es, ja var netLanguage = AndroidToLanguage(androidLocale.Language.Replace ("_", "-")); var ci = new System.Globalization.CultureInfo (netLanguage); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; return ci; } string AndroidToLanguage(string androidlanguage) { var netLanguage = androidlanguage; switch (androidlanguage) { case "da": netLanguage = "da"; break; default: netLanguage = "en"; break; } return netLanguage; } } }
22.135593
83
0.592649
[ "Apache-2.0" ]
cph-cachet/radmis.Moribus.vs2
Sensus.Android/Locale_Android.cs
1,308
C#
// // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Performance.SDK; using Microsoft.Performance.SDK.Extensibility; using Microsoft.Performance.SDK.Processing; using MsQuicTracing.DataModel; namespace MsQuicTracing.Tables { [Table] public sealed class QuicWorkerActivityTable { public static readonly TableDescriptor TableDescriptor = new TableDescriptor( Guid.Parse("{605F8393-0260-45B1-85E5-381B7C3BADDE}"), "QUIC Workers", "QUIC Workers", category: "Computation", requiredDataCookers: new List<DataCookerPath> { QuicEventCooker.CookerPath }); private static readonly ColumnConfiguration workerColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{9e14c926-73be-4c7c-8b3a-447156fa422e}"), "Worker"), new UIHints { AggregationMode = AggregationMode.UniqueCount }); private static readonly ColumnConfiguration processIdColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{da6c804b-2d19-5b9e-4941-ec903c62ba98}"), "Process (ID)"), new UIHints { AggregationMode = AggregationMode.Max }); private static readonly ColumnConfiguration threadIdColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{530749a6-4e3f-5ad3-91f8-91ec9332ab09}"), "ThreadId"), new UIHints { AggregationMode = AggregationMode.Max }); private static readonly ColumnConfiguration countColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{3c554919-7249-5268-42d1-bc57bf89dbee}"), "Count"), new UIHints { AggregationMode = AggregationMode.Sum }); private static readonly ColumnConfiguration weightColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{1f74ed75-a116-42f5-ae5d-ca3b398e4f2e}"), "Weight"), new UIHints { AggregationMode = AggregationMode.Sum, SortOrder = SortOrder.Descending }); private static readonly ColumnConfiguration percentWeightColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{abe589d5-1ca1-401f-9734-527277cb87cb}"), "% Weight") { IsPercent = true }, new UIHints { AggregationMode = AggregationMode.Sum }); private static readonly ColumnConfiguration timeColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{21117af5-ae65-4358-95db-b63544458d03}"), "Time"), new UIHints { AggregationMode = AggregationMode.Max }); private static readonly ColumnConfiguration durationColumnConfig = new ColumnConfiguration( new ColumnMetadata(new Guid("{07638cdc-ae16-409c-9619-cf8e6e75fa71}"), "Duration"), new UIHints { AggregationMode = AggregationMode.Sum }); private static readonly TableConfiguration tableConfig1 = new TableConfiguration("Timeline by Worker") { Columns = new[] { workerColumnConfig, TableConfiguration.PivotColumn, TableConfiguration.LeftFreezeColumn, processIdColumnConfig, threadIdColumnConfig, countColumnConfig, weightColumnConfig, percentWeightColumnConfig, TableConfiguration.RightFreezeColumn, TableConfiguration.GraphColumn, timeColumnConfig, durationColumnConfig, } }; private static readonly TableConfiguration tableConfig2 = new TableConfiguration("Utilization by Worker") { Columns = new[] { workerColumnConfig, TableConfiguration.PivotColumn, TableConfiguration.LeftFreezeColumn, processIdColumnConfig, threadIdColumnConfig, countColumnConfig, weightColumnConfig, timeColumnConfig, durationColumnConfig, TableConfiguration.RightFreezeColumn, TableConfiguration.GraphColumn, percentWeightColumnConfig, }, ChartType = ChartType.Line }; public static bool IsDataAvailable(IDataExtensionRetrieval tableData) { Debug.Assert(!(tableData is null)); var quicState = tableData.QueryOutput<QuicState>(new DataOutputPath(QuicEventCooker.CookerPath, "State")); return quicState != null && quicState.DataAvailableFlags.HasFlag(QuicDataAvailableFlags.WorkerActivity); } public static void BuildTable(ITableBuilder tableBuilder, IDataExtensionRetrieval tableData) { Debug.Assert(!(tableBuilder is null) && !(tableData is null)); var quicState = tableData.QueryOutput<QuicState>(new DataOutputPath(QuicEventCooker.CookerPath, "State")); if (quicState == null) { return; } var workers = quicState.Workers; if (workers.Count == 0) { return; } var data = workers.SelectMany( x => x.GetActivityEvents().Select( y => new ValueTuple<QuicWorker, QuicActivityData>(x, y))).ToArray(); var table = tableBuilder.SetRowCount(data.Length); var dataProjection = Projection.Index(data); table.AddColumn(workerColumnConfig, dataProjection.Compose(ProjectId)); table.AddColumn(processIdColumnConfig, dataProjection.Compose(ProjectProcessId)); table.AddColumn(threadIdColumnConfig, dataProjection.Compose(ProjectThreadId)); table.AddColumn(countColumnConfig, Projection.Constant<uint>(1)); table.AddColumn(weightColumnConfig, dataProjection.Compose(ProjectWeight)); table.AddColumn(percentWeightColumnConfig, dataProjection.Compose(ProjectPercentWeight)); table.AddColumn(timeColumnConfig, dataProjection.Compose(ProjectTime)); table.AddColumn(durationColumnConfig, dataProjection.Compose(ProjectDuration)); tableConfig1.AddColumnRole(ColumnRole.StartTime, timeColumnConfig); tableConfig1.AddColumnRole(ColumnRole.Duration, durationColumnConfig); tableConfig1.InitialExpansionQuery = "[Series Name]:=\"Process (ID)\""; tableConfig1.InitialSelectionQuery = "[Series Name]:=\"Worker\""; tableBuilder.AddTableConfiguration(tableConfig1); tableConfig2.AddColumnRole(ColumnRole.StartTime, timeColumnConfig); tableConfig2.AddColumnRole(ColumnRole.Duration, durationColumnConfig); tableConfig2.InitialExpansionQuery = "[Series Name]:=\"Process (ID)\""; tableConfig2.InitialSelectionQuery = "[Series Name]:=\"Worker\""; tableBuilder.AddTableConfiguration(tableConfig2); tableBuilder.SetDefaultTableConfiguration(tableConfig1); } #region Projections private static ulong ProjectId(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item1.Id; } private static uint ProjectProcessId(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item1.ProcessId; } private static uint ProjectThreadId(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item1.ThreadId; } private static TimestampDelta ProjectWeight(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item2.Duration; } private static double ProjectPercentWeight(ValueTuple<QuicWorker, QuicActivityData> data) { TimestampDelta TimeNs = data.Item1.FinalTimeStamp - data.Item1.InitialTimeStamp; return 100.0 * data.Item2.Duration.ToNanoseconds / TimeNs.ToNanoseconds; } private static Timestamp ProjectTime(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item2.TimeStamp; } private static TimestampDelta ProjectDuration(ValueTuple<QuicWorker, QuicActivityData> data) { return data.Item2.Duration; } #endregion } }
43.20197
120
0.632497
[ "MIT" ]
anrossi/msquic
src/plugins/wpa/Tables/QuicWorkerActivityTable.cs
8,772
C#
using System.Collections.Generic; using UnityEngine; using DRDevTools.TypeAdapters.Variables; namespace DRDevTools.Events { [CreateAssetMenu(menuName = "Events/Vector3")] public class Vector3GameEvent : ScriptableObject { private readonly List<Vector3GameEventListener> eventListeners = new List<Vector3GameEventListener>(); public void Raise(Vector3Variable vector) { for (var i = eventListeners.Count - 1; i >= 0; i--) eventListeners[i].OnEventRaised(vector); } public void RegisterListener(Vector3GameEventListener listener) { if (!eventListeners.Contains(listener)) eventListeners.Add(listener); } public void UnregisterListener(Vector3GameEventListener listener) { if (eventListeners.Contains(listener)) eventListeners.Remove(listener); } } }
31.066667
110
0.652361
[ "MIT" ]
DarrenRuane/dr-dev-tools
Assets/DRDevTools/Events/Vector3GameEvent.cs
934
C#
using System; namespace FastNetLib { /// <summary> /// Interface to implement for your own logger /// </summary> public interface INetLogger { void WriteNet(ConsoleColor color, string str, params object[] args); } /// <summary> /// Static class for defining your own FastNetLib logger instead of Console.WriteLine /// or Debug.Log if compiled with UNITY flag /// </summary> public static class NetDebug { public static INetLogger Logger = null; } }
23.636364
89
0.640385
[ "MIT" ]
DanisJoyal/FastNetLib
FastNetLib/NetDebug.cs
522
C#
using InjectionScript.Runtime; using System; using System.Collections.Generic; using System.Text; namespace Infusion.LegacyApi.Injection { public interface IInjectionWindow { void Open(InjectionRuntime runtime, InjectionApiUO injectionApi, Legacy infusionApi, InjectionHost host); } public sealed class NullInjectionWindow : IInjectionWindow { public void Open(InjectionRuntime runtime, InjectionApiUO injectionApi, Legacy infusionApi, InjectionHost host) { /*do nothing*/ } } }
29
138
0.760536
[ "MIT" ]
3HMonkey/Infusion
Infusion.LegacyApi/IInjectionWindow.cs
524
C#
using FluentValidation; using FluentValidation.Results; using Gadget.Notifications.Domain.Enums; using System.Net.Mail; namespace Gadget.Notifications.Requests.Validations { public class CreateWebhookValidator : AbstractValidator<CreateWebhook> { public override ValidationResult Validate(ValidationContext<CreateWebhook> context) { RuleFor(x => x.Receiver).NotEmpty().NotNull().WithMessage("Receiver is mandatory"); RuleFor(x => x.NotifierType).Must(n => n != NotifierType.None).WithMessage("Chose correct webhook type."); RuleFor(x => x).Must(r => ValidateReceiver(r)).WithMessage("Receiver is not in correct format"); return base.Validate(context); } private bool ValidateReceiver(CreateWebhook createWebhook) { switch (createWebhook.NotifierType) { case NotifierType.Email: return ValidateEmail(createWebhook.Receiver); case NotifierType.Discord: return ValidateDiscord(createWebhook.Receiver); default:return false; } } private bool ValidateEmail(string webhook) { try { var email = new MailAddress(webhook); return true; } catch (System.Exception) { return false; throw; } } private bool ValidateDiscord(string webhook) { return false; } } }
32.104167
118
0.593121
[ "MIT" ]
charconstpointer/gadget
Gadget.Notifications/Requests/Validations/CreateWebhookValidator.cs
1,543
C#
using NUnit.Framework; namespace Stratosphere.Tests.Math { public class Given_single_element_matrix : Given_transformed_matrix { [SetUp] public void Given_test_matrix() { _matrix = "2"; _expectedMatrix = "2"; } [Test] public void Then_can_be_converted_to_number() { Assert.AreEqual(2.0, (double)_matrix); } } }
21.2
71
0.568396
[ "MIT" ]
mandrek44/stratosphere-net
UnitTests/Stratosphere.Tests.Math/Given_single_element_matrix.cs
424
C#
/* Copyright (c) 2019 Denis Zykov, GameDevWare.com This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. This source code is distributed via Unity Asset Store, to use it in your project you should accept Terms of Service and EULA https://unity3d.com/ru/legal/as_terms */ using System; using System.Text; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization { internal static class JsonUtils { internal static readonly long UnixEpochTicks = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks; private static readonly char[] ZerBuff = new char[] {'0', '0', '0', '0', '0', '0', '0', '0',}; private static readonly char[] HexChar = "0123456789ABCDEF".ToCharArray(); public static string UnescapeAndUnquote(string stringToUnescape) { if (stringToUnescape == null) throw new ArgumentNullException("stringToUnescape"); var start = 0; var len = stringToUnescape.Length; if (stringToUnescape.Length > 0 && stringToUnescape[0] == '"') { start += 1; len -= 2; } return UnescapeBuffer(stringToUnescape.ToCharArray(), start, len); } public static string EscapeAndQuote(string stringToEscape) { if (stringToEscape == null) throw new ArgumentNullException("stringToEscape"); var stringHasNonLatinCharacters = false; var newSize = stringToEscape.Length + 2; for (var i = 0; i < stringToEscape.Length; i++) { var charToCheck = stringToEscape[i]; var isNonLatinOrSpecial = ((int) charToCheck < 32 || charToCheck == '\\' || charToCheck == '"'); if (isNonLatinOrSpecial) newSize += 5; // encoded characters add 4 hex symbols and "u" stringHasNonLatinCharacters = stringHasNonLatinCharacters || isNonLatinOrSpecial; } // if it"s a latin - write as is if (!stringHasNonLatinCharacters) return string.Concat("\"", stringToEscape, "\""); // else tranform and write var sb = new StringBuilder(newSize); var hexBuff = new char[12]; // 4 for zeroes and 8 for number sb.Append('"'); for (var i = 0; i < stringToEscape.Length; i++) { var charToCheck = stringToEscape[i]; if ((int) charToCheck < 32 || charToCheck == '\\' || charToCheck == '"') { sb.Append("\\u"); Buffer.BlockCopy(ZerBuff, 0, hexBuff, 0, sizeof (char)*8); // clear buffer with "0" var hexlen = UInt32ToHexBuffer((uint) charToCheck, hexBuff, 4); sb.Append(hexBuff, hexlen, 4); } else sb.Append(charToCheck); } sb.Append('"'); return sb.ToString(); } public static int EscapeBuffer(string value, ref int offset, char[] outputBuffer, int outputBufferOffset) { if (value == null) throw new ArgumentNullException("value"); if (offset < 0 || offset >= value.Length) throw new ArgumentOutOfRangeException("offset"); if (outputBuffer == null) throw new ArgumentNullException("outputBuffer"); if (outputBufferOffset < 0 || outputBufferOffset >= outputBuffer.Length) throw new ArgumentOutOfRangeException("outputBufferOffset"); const ushort LOWER_BOUND_CHAR = 32; const ushort QUOTE_CHAR = '\\'; const ushort DOUBLE_QUOTE_CHAR = '"'; var written = 0; for (; offset < value.Length; offset++) { var charCode = (ushort) value[offset]; if (charCode < LOWER_BOUND_CHAR || charCode == QUOTE_CHAR || charCode == DOUBLE_QUOTE_CHAR) { if (outputBuffer.Length - outputBufferOffset < 6) return written; outputBuffer[outputBufferOffset++] = '\\'; outputBuffer[outputBufferOffset++] = 'u'; outputBufferOffset += UInt16ToPaddedHexBuffer(charCode, outputBuffer, outputBufferOffset); written += 6; } else { if (outputBuffer.Length - outputBufferOffset == 0) return written; // dont escape outputBuffer[outputBufferOffset++] = (char) charCode; written++; } } return written; } public static string UnescapeBuffer(char[] charsToUnescape, int start, int length) { if (charsToUnescape == null) throw new ArgumentNullException("charsToUnescape"); if (start < 0 || start + length > charsToUnescape.Length) throw new ArgumentOutOfRangeException("start"); var sb = new StringBuilder(length); var plainStart = start; var plainLen = 0; var end = start + length; for (var i = start; i < end; i++) { var ch = charsToUnescape[i]; if (ch == '\\') { var seqLength = 1; // append unencoded chunk if (plainLen != 0) { sb.Append(charsToUnescape, plainStart, plainLen); plainLen = 0; } var seqKind = charsToUnescape[i + 1]; switch (seqKind) { case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 'b': sb.Append('\b'); break; case 'f': sb.Append('\f'); break; case 't': sb.Append('\t'); break; case '\\': sb.Append('\\'); break; case '\'': sb.Append('\''); break; case '\"': sb.Append('\"'); break; // unicode symbol case 'u': sb.Append((char) HexStringToUInt32(charsToUnescape, i + 2, 4)); seqLength = 5; break; // latin hex encoded symbol case 'x': sb.Append((char) HexStringToUInt32(charsToUnescape, i + 2, 2)); seqLength = 3; break; // latin dec encoded symbol case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': sb.Append((char) StringToInt32(charsToUnescape, i + 1, 3)); seqLength = 3; break; default: #if STRICT throw new Exceptions.UnknownEscapeSequence("\\" + seqKind.ToString(), null); #else sb.Append(charsToUnescape[i + 1]); break; #endif } // set next chunk start right after this escape plainStart = i + seqLength + 1; i += seqLength; } else plainLen++; } // append last unencoded chunk if (plainLen != 0) sb.Append(charsToUnescape, plainStart, plainLen); return sb.ToString(); } public static uint HexStringToUInt32(char[] buffer, int start, int len) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const uint ZERO = (ushort) '0'; const uint a = (ushort) 'a'; const uint A = (ushort) 'A'; var result = 0u; for (var i = 0; i < len; i++) { var c = buffer[start + i]; var d = 0u; if (c >= '0' && c <= '9') d = (c - ZERO); else if (c >= 'a' && c <= 'f') d = 10u + (c - a); else if (c >= 'A' && c <= 'F') d = 10u + (c - A); else throw new FormatException(); result = 16u*result + d; } return result; } public static int UInt32ToHexBuffer(uint uvalue, char[] buffer, int start) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); var hex = HexChar; if (uvalue == 0) { buffer[start] = '0'; return 1; } var length = 0; for (var i = 0; i < 8; i++) { var c = hex[((uvalue >> i*4) & 15u)]; buffer[start + i] = c; } for (length = 8; length > 0; length--) if (buffer[start + length - 1] != '0') break; Array.Reverse(buffer, start, length); return length; } public static int UInt16ToPaddedHexBuffer(ushort uvalue, char[] buffer, int start) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); const int LENGTH = 4; const string HEX = "0123456789ABCDEF"; var end = start + LENGTH; if (uvalue == 0) { for (var i = start; i < end; i++) buffer[i] = '0'; return LENGTH; } for (var i = 0; i < LENGTH; i++) { var c = HEX[(int) ((uvalue >> i*4) & 15u)]; buffer[end - i - 1] = c; } return LENGTH; } public static ushort PaddedHexStringToUInt16(char[] buffer, int start, int len) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const uint ZERO = (ushort) '0'; const uint a = (ushort) 'a'; const uint A = (ushort) 'A'; var result = 0u; for (var i = 0; i < len; i++) { var c = buffer[start + i]; var d = 0u; if (c >= '0' && c <= '9') d = (c - ZERO); else if (c >= 'a' && c <= 'f') d = 10u + (c - a); else if (c >= 'A' && c <= 'F') d = 10u + (c - A); else throw new FormatException(); result = 16u*result + d; } return checked((ushort) result); } public static long StringToInt64(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const ulong ZERO = (ushort) '0'; var result = 0UL; var neg = false; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (i == 0 && c == '-') { neg = true; continue; } else if (c < '0' || c > '9') throw new FormatException(); result = checked(10UL*result + (c - ZERO)); } if (neg) return -(long) (result); else return (long) result; } public static int StringToInt32(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const uint ZERO = (ushort) '0'; var result = 0u; var neg = false; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (i == 0 && c == '-') { neg = true; continue; } else if (c < '0' || c > '9') throw new FormatException(); result = checked(10u*result + (c - ZERO)); } if (neg) return -(int) (result); else return (int) result; } public static ulong StringToUInt64(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const ulong ZERO = (ushort) '0'; var result = 0UL; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (c < '0' || c > '9') throw new FormatException(); result = checked(10UL*result + (c - ZERO)); } return result; } public static uint StringToUInt32(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); const uint ZERO = (ushort) '0'; var result = 0U; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (c < '0' || c > '9') throw new FormatException(); result = checked(10*result + (c - ZERO)); } return result; } public static double StringToDouble(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); /* const uint ZERO = (ushort)'0'; char decimalSep = '.'; var whole = 0UL; var fraction = 0U; var fracCount = 0; var neg = false; var decimals = false; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (i == 0 && c == '-') { neg = true; continue; } else if (c == decimalSep) { decimals = true; continue; } else if (c < '0' || c > '9') throw new FormatException(); if (decimals) { if (fracCount >= 9) // maximum precision 9 digits break; fraction = checked(10U * fraction + (c - ZERO)); fracCount++; } else whole = checked(10UL * whole + (c - ZERO)); } var result = checked((double)whole + (fraction / pow10d[fracCount])); if (neg) result = -result; return result; */ return double.Parse(new string(buffer, start, len), formatProvider); } public static float StringToFloat(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); /* const uint ZERO = (ushort)'0'; char decimalSep = '.'; var whole = 0U; var fraction = 0U; var fracCount = 0; var neg = false; var decimals = false; for (var i = 0; i < len; i++) { var c = buffer[start + i]; if (i == 0 && c == '-') { neg = true; continue; } else if (c == decimalSep) { decimals = true; continue; } else if (c < '0' || c > '9') throw new FormatException(); if (decimals) { if (fracCount > 9) // maximum precision 9 digits break; fraction = checked(10U * fraction + (c - ZERO)); fracCount++; } else whole = checked(10U * whole + (c - ZERO)); } var result = checked((float)whole + (fraction / pow10s[fracCount])); if (neg) result = -result; return result; */ return float.Parse(new string(buffer, start, len), formatProvider); } public static decimal StringToDecimal(char[] buffer, int start, int len, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0) throw new ArgumentOutOfRangeException("start"); if (len < 0) throw new ArgumentOutOfRangeException("len"); if (start + len > buffer.Length) throw new ArgumentOutOfRangeException(); return decimal.Parse(new string(buffer, start, len), formatProvider); } public static int Int32ToBuffer(int value, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); const int ZERO = (ushort) '0'; var idx = start; var neg = value < 0; // Take care of sign var uvalue = neg ? (uint) (-value) : (uint) value; // Conversion. Number is reversed. do buffer[idx++] = (char) (ZERO + (uvalue%10)); while ((uvalue /= 10) != 0); if (neg) buffer[idx++] = '-'; var length = idx - start; // Reverse string Array.Reverse(buffer, start, length); return length; } public static int Int64ToBuffer(long value, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); const int ZERO = (ushort) '0'; var idx = start; // Take care of sign var neg = (value < 0); var uvalue = neg ? (ulong) (-value) : (ulong) value; // Conversion. Number is reversed. do buffer[idx++] = (char) (ZERO + (uvalue%10)); while ((uvalue /= 10) != 0); if (neg) buffer[idx++] = '-'; var length = idx - start; // Reverse string Array.Reverse(buffer, start, length); return length; } public static int UInt32ToBuffer(uint uvalue, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); const int ZERO = (ushort) '0'; var idx = start; // Take care of sign // Conversion. Number is reversed. do buffer[idx++] = (char) (ZERO + (uvalue%10)); while ((uvalue /= 10) != 0); var length = idx - start; // Reverse string Array.Reverse(buffer, start, length); return length; } public static int UInt64ToBuffer(ulong uvalue, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); const ulong ZERO = (ulong) '0'; var idx = start; // Conversion. Number is reversed. do buffer[idx++] = (char) (ZERO + (uvalue%10)); while ((uvalue /= 10) != 0UL); var length = idx - start; // Reverse string Array.Reverse(buffer, start, length); return length; } public static int SingleToBuffer(float value, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); var valueStr = value.ToString("R", formatProvider); valueStr.CopyTo(0, buffer, start, valueStr.Length); return valueStr.Length; } public static int DoubleToBuffer(double value, char[] buffer, int start, IFormatProvider formatProvider = null) { if (buffer == null) throw new ArgumentNullException("buffer"); if (start < 0 || start >= buffer.Length) throw new ArgumentOutOfRangeException("start"); var valueStr = value.ToString("R", formatProvider); valueStr.CopyTo(0, buffer, start, valueStr.Length); return valueStr.Length; } public static int DecimalToBuffer(decimal value, char[] buffer, int start, IFormatProvider formatProvider = null) { var valueStr = value.ToString(null, formatProvider); valueStr.CopyTo(0, buffer, start, valueStr.Length); return valueStr.Length; } } }
26.7107
116
0.585559
[ "Apache-2.0" ]
FromSeabedOfReverie/SubmarineMirageFrameworkForUnity
Assets/Plugins/ExternalAssets/Systems/GameDevWare.Serialization/JsonUtils.cs
20,220
C#
using System; namespace Solutions.Core.Time { public class TimeService : ITimeService { private readonly Func<DateTime> func; public static TimeService Default { get { return new TimeService(() => DateTime.Now); } } public static TimeService DefaultUtc { get { return new TimeService(() => DateTime.UtcNow); } } public TimeService(Func<DateTime> func) { this.func = func; } public DateTime Now { get { return func(); } } } }
21.178571
66
0.524452
[ "MIT" ]
mletunov/SolutionsNet
Solutions.Core/Time/TimeService.cs
595
C#
using System; namespace NetConf.Helpers.Interfaces { public interface IMinotaur : IHuman { void StrikeWithHorn(); void StrikeWithAxe() => Console.WriteLine("Axe hit: 100"); void IHuman.Speak() => Console.WriteLine("I am Minotaurrrrrrrr!!"); } }
21.769231
75
0.646643
[ "MIT" ]
xitaocrazy/whats-new-in-c-8-p2
NetConf/Helpers/Interfaces/IMinotaur.cs
283
C#
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace AsyncStreams { class Program { static async Task Main(string[] args) { //OLD // var foo = new AsyncIntegersOld(); //foreach (var integer in foo) // { // var result = await integer; // Console.WriteLine(result); // Console.WriteLine($"Current thread: {Thread.CurrentThread.ManagedThreadId}"); // } // Console.WriteLine($"Finished, current thread: {Thread.CurrentThread.ManagedThreadId}"); //NEW var foo = new AsyncIntegers(); await foreach (int integer in foo) { Console.WriteLine(integer); Console.WriteLine($"Current thread: {Thread.CurrentThread.ManagedThreadId}"); } Console.WriteLine($"Finished, current thread: {Thread.CurrentThread.ManagedThreadId}"); Console.ReadKey(); } } public class AsyncIntegersOld : IEnumerable<Task<int>> { public IEnumerator<Task<int>> GetEnumerator() { for (var i = 0; i < 100; i++) { yield return Task.Run(() => i); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class AsyncIntegers : IAsyncEnumerable<int> { public async IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default) { for (var i = 0; i < 100; i++) { yield return await Task.Run(() => i); } } } }
27.523077
108
0.534377
[ "MIT" ]
Barsonax/CsharpFeatureShowcase
CsharpFeatureShowcase/AsyncStreams/Program.cs
1,791
C#
/** * Copyright (c) 2015, GruntTheDivine All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. **/ using System; using Iodine.Runtime; namespace Iodine.Interop { class BoolTypeMapping : TypeMapping { public override object ConvertFrom (TypeRegistry registry, IodineObject obj) { IodineBool boolean = obj as IodineBool; return boolean.Value; } public override IodineObject ConvertFrom (TypeRegistry registry, object obj) { return ((IodineBool)obj).Value ? IodineBool.True : IodineBool.False; } } }
41.86
88
0.73053
[ "BSD-3-Clause" ]
SplittyDev/Iodine-Library
src/Iodine/Interop/TypeMappings/BoolTypeMapping.cs
2,093
C#
namespace Животинско_царство { using System; using System.Collections.Generic; using System.Text; interface IMakeTrick { public string MakeTrick(); } }
15.5
37
0.655914
[ "MIT" ]
Kalin1603/School-Repository
ИНФ-уч-др/Животинско царство/IMakeTrick.cs
205
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AntMerchantExpandMapplyorderQueryResponse. /// </summary> public class AntMerchantExpandMapplyorderQueryResponse : AopResponse { /// <summary> /// 支付宝端商户入驻申请单据号 /// </summary> [XmlElement("order_no")] public string OrderNo { get; set; } /// <summary> /// 支付宝商户入驻申请单状态 /// </summary> [XmlElement("order_status")] public string OrderStatus { get; set; } /// <summary> /// 外部入驻申请单据号 /// </summary> [XmlElement("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 入驻申请单认证审核、签约审核详情 /// </summary> [XmlArray("result_info")] [XmlArrayItem("merchant_apply_result_record")] public List<MerchantApplyResultRecord> ResultInfo { get; set; } } }
25.333333
72
0.584008
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Response/AntMerchantExpandMapplyorderQueryResponse.cs
1,088
C#
// <copyright file="DocumentTypeConverter.cs" company="Glenn Watson"> // Copyright (c) 2018 Glenn Watson. All rights reserved. // See LICENSE file in the project root for full license information. // </copyright> namespace ReactiveGit.Gui.WPF.Converters { using System; using ReactiveGit.Gui.Core.ViewModel.Repository; using ReactiveUI; /// <summary> /// Converts from avalon dock to the view model selected document property. /// Will make repository documents set appropriately, and ignore child repository documents. /// </summary> public class DocumentTypeConverter : IBindingTypeConverter { /// <inheritdoc /> public int GetAffinityForObjects(Type fromType, Type toType) { if (toType != typeof(IRepositoryDocumentViewModel)) { return 0; } if (fromType == typeof(object)) { return 100; } return 0; } /// <inheritdoc /> public bool TryConvert(object from, Type toType, object conversionHint, out object result) { if (from == null) { result = null; return true; } var repositoryDocument = from as IRepositoryDocumentViewModel; if (repositoryDocument == null) { result = null; return false; } result = repositoryDocument; return true; } } }
27.087719
98
0.560233
[ "MIT" ]
punker76/ReactiveGit
ReactiveGit.Gui.WPF/Converters/DocumentTypeConverter.cs
1,546
C#
using AnnoSavegameViewer.Serialization.Core; using System.Collections.Generic; namespace AnnoSavegameViewer.Structures.Savegame.Generated { public class TargetParticipant { [BinaryContent(Name = "value", NodeType = BinaryContentTypes.Node)] public TargetParticipantValue Value { get; set; } } }
25.833333
71
0.780645
[ "MIT" ]
brumiros/AnnoSavegameViewer
AnnoSavegameViewer/Structures/Savegame/Generated/NoContent/TargetParticipant.cs
310
C#
using ReactiveUI; namespace KyoshinEewViewer.Core.Models.Events { public class DisplayWarningMessageUpdated { public DisplayWarningMessageUpdated(string message) { Message = message; } public string Message { get; } public static void SendWarningMessage(string message) => MessageBus.Current.SendMessage(new DisplayWarningMessageUpdated(message)); } }
20.833333
80
0.776
[ "MIT" ]
ingen084/KyoshinEewViewerIngen
src/KyoshinEewViewer.Core/Models/Events/DisplayWarningMessageUpdated.cs
377
C#
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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. namespace ConnectQl.Tools.Mef.Results.Converters { using System; using System.Globalization; using System.Windows; using System.Windows.Data; using JetBrains.Annotations; /// <summary> /// The divide converter. /// </summary> [PublicAPI] public class DivideConverter : IValueConverter { /// <summary> /// Gets or sets the value to divide by. /// </summary> public double By { get; set; } /// <summary>Converts a value. </summary> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is double doubleValue) { // ReSharper disable once CompareOfFloatsByEqualityOperator return doubleValue / (this.By == 0 ? 1 : this.By); } return DependencyProperty.UnsetValue; } /// <summary>Throws a <see cref="NotSupportedException"/>. </summary> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <exception cref="NotSupportedException">Always thrown.</exception> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
44.875
107
0.672857
[ "MIT" ]
MaartenX/ConnectQL
src/ConnectQl.Tools/Mef/Results/Converters/DivideConverter.cs
3,233
C#
 using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMove : MonoBehaviour { public GameObject bullet; public float speed; public float rotationSpeed; public float raycastDist; public float boxDist; Move move; Transform player; void Start() { player = GameObject.Find("Player").transform; move = new Move(gameObject, speed, rotationSpeed); } void Update() { if (player != null) { // If the player is alive Vector2 toMove = Vector2.zero; // Get all nearby colliders Collider2D[] hitColliders = Physics2D.OverlapBoxAll(transform.position, new Vector2(boxDist, boxDist), 0); List<Collider2D> colliders = new List<Collider2D>(); foreach (Collider2D col in hitColliders) { if (col.tag == "Obstacle") colliders.Add(col); // If the collider is an obstacle } if (colliders.Count > 0) { // If we need to avoid an obstacle Collider2D closest = colliders[0]; // The cloest obstacle foreach (Collider2D col in colliders) { if (Vector2.Distance(transform.position, col.transform.position) > Vector2.Distance(transform.position, closest.transform.position)) { closest = col; } } float xdiff = closest.transform.position.x - transform.position.x; float ydiff = closest.transform.position.y - transform.position.y; // Move away from the obstacle if (Mathf.Abs(xdiff) < Mathf.Abs(ydiff)) { if (xdiff > 0) { move.Left(); } else move.Right(); } else { if (ydiff > 0) { move.Down(); } else move.Up(); } } else { // No obstacles nearby, so we can chase the player float xdiff = player.transform.position.x - transform.position.x; float ydiff = player.transform.position.y - transform.position.y; if (Mathf.Abs(xdiff) > Mathf.Abs(ydiff)) { if (xdiff > 0) { move.Right(); } else move.Left(); } else { if (ydiff > 0) { move.Up(); } else move.Down(); } } move.EndMove(); } } }
33.857143
118
0.500959
[ "CC0-1.0" ]
EthanBar/Tanks
Assets/Script/EnemyMove.cs
2,609
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Negri.Wot.WgApi { /// <summary> /// Um clã /// </summary> public class Clan { /// <summary> /// Id do Clã (nunca muda) /// </summary> [JsonProperty("clan_id")] public long ClanId { get; set; } /// <summary> /// Tag do Clã (as vezes muda) /// </summary> public string Tag { get; set; } /// <summary> /// Nome do Clã (muda com frequencia) /// </summary> public string Name { get; set; } /// <summary> /// Numero de membros do clã /// </summary> [JsonProperty("members_count")] public int MembersCount { get; set; } /// <summary> /// Data de criação do clã /// </summary> [JsonProperty("created_at")] public long CreatedAtUnix { get; set; } public DateTime CreatedAtUtc => CreatedAtUnix.ToDateTime(); /// <summary> /// Se o clã foi desfeito /// </summary> [JsonProperty("is_clan_disbanded")] public bool IsDisbanded { get; set; } /// <summary> /// Os membros e seus papeis no clã /// </summary> public Dictionary<long, Member> Members { get; set; } = new Dictionary<long, Member>(); [JsonProperty("members_ids")] public long[] MembersIds { get; set; } = new long[0]; } }
25.810345
95
0.530394
[ "MIT" ]
negri/wotclans
WoTStat/WgApi/Clan.cs
1,509
C#
using Ef5TipsTricks.DataAccess.Entities.Common; using System.Collections.Generic; namespace Ef5TipsTricks.DataAccess.Entities { public class Person : DeletableEntity { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<Address> Addresses { get; set; } } }
22.588235
67
0.674479
[ "MIT" ]
marcominerva/EntityFrameworkCoreTipsTricks
Ef5TipsTricks/DataAccess/Entities/Person.cs
386
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Saule { /// <summary> /// Formatter priority for configuration /// </summary> public enum FormatterPriority { /// <summary> /// Formatter will be inserted at the start of the collection /// </summary> AddFormatterToStart = 0, /// <summary> /// Formatter will be inserted at the end of the collection /// </summary> AddFormatterToEnd = 1, /// <summary> /// Other formatters will be cleared /// </summary> OverwriteOtherFormatters = 2, } }
22.933333
69
0.59593
[ "MIT" ]
BookerSoftwareInc/saule
Saule/FormatterPriority.cs
690
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ecm.V20190719.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateNetworkInterfaceRequest : AbstractModel { /// <summary> /// VPC实例ID。可通过DescribeVpcs接口返回值中的VpcId获取。 /// </summary> [JsonProperty("VpcId")] public string VpcId{ get; set; } /// <summary> /// 弹性网卡名称,最大长度不能超过60个字节。 /// </summary> [JsonProperty("NetworkInterfaceName")] public string NetworkInterfaceName{ get; set; } /// <summary> /// 弹性网卡所在的子网实例ID,例如:subnet-0ap8nwca。 /// </summary> [JsonProperty("SubnetId")] public string SubnetId{ get; set; } /// <summary> /// ECM 地域,形如ap-xian-ecm。 /// </summary> [JsonProperty("EcmRegion")] public string EcmRegion{ get; set; } /// <summary> /// 弹性网卡描述,可任意命名,但不得超过60个字符。 /// </summary> [JsonProperty("NetworkInterfaceDescription")] public string NetworkInterfaceDescription{ get; set; } /// <summary> /// 新申请的内网IP地址个数,内网IP地址个数总和不能超过配额数。 /// </summary> [JsonProperty("SecondaryPrivateIpAddressCount")] public ulong? SecondaryPrivateIpAddressCount{ get; set; } /// <summary> /// 指定绑定的安全组,例如:['sg-1dd51d']。 /// </summary> [JsonProperty("SecurityGroupIds")] public string[] SecurityGroupIds{ get; set; } /// <summary> /// 指定的内网IP信息,单次最多指定10个。 /// </summary> [JsonProperty("PrivateIpAddresses")] public PrivateIpAddressSpecification[] PrivateIpAddresses{ get; set; } /// <summary> /// 指定绑定的标签列表,例如:[{"Key": "city", "Value": "shanghai"}] /// </summary> [JsonProperty("Tags")] public Tag[] Tags{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "VpcId", this.VpcId); this.SetParamSimple(map, prefix + "NetworkInterfaceName", this.NetworkInterfaceName); this.SetParamSimple(map, prefix + "SubnetId", this.SubnetId); this.SetParamSimple(map, prefix + "EcmRegion", this.EcmRegion); this.SetParamSimple(map, prefix + "NetworkInterfaceDescription", this.NetworkInterfaceDescription); this.SetParamSimple(map, prefix + "SecondaryPrivateIpAddressCount", this.SecondaryPrivateIpAddressCount); this.SetParamArraySimple(map, prefix + "SecurityGroupIds.", this.SecurityGroupIds); this.SetParamArrayObj(map, prefix + "PrivateIpAddresses.", this.PrivateIpAddresses); this.SetParamArrayObj(map, prefix + "Tags.", this.Tags); } } }
35.5
117
0.622535
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Ecm/V20190719/Models/CreateNetworkInterfaceRequest.cs
3,846
C#
namespace IntakerConsole.Configuration { public class IntakerConsoleAppConfig { public string SpecsPath { get; set; } public string InputPath { get; set; } public string OutputPath { get; set; } } }
23.6
46
0.644068
[ "MIT" ]
dbsafe/intaker-demo
IntakerDemos/IntakerConsole/Configuration/IntakerConsoleAppConfig.cs
238
C#
namespace ProjetoApollo.EntityFrameworkCore.Seed.Host { public class InitialHostDbBuilder { private readonly ProjetoApolloDbContext _context; public InitialHostDbBuilder(ProjetoApolloDbContext context) { _context = context; } public void Create() { new DefaultEditionCreator(_context).Create(); new DefaultLanguagesCreator(_context).Create(); new HostRoleAndUserCreator(_context).Create(); new DefaultSettingsCreator(_context).Create(); _context.SaveChanges(); } } }
26.565217
67
0.631751
[ "MIT" ]
ArthurNascimento019/ProjetoApollo
Portal/aspnet-core/src/ProjetoApollo.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/InitialHostDbBuilder.cs
613
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LevelEditor { class StmNewline : Statement { public StmNewline(int Index) : base(Index, Environment.NewLine) { } public static bool IsThisYou(string str, string cln) { return false; //"NL".Equals(cln); } } }
19.47619
71
0.623472
[ "MIT" ]
OnionBurger/PlaneSmith
LevelEditor/classes/generation/StmNewline.cs
411
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-sync-2014-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CognitoSync.Model { /// <summary> /// Container for the parameters to the SetIdentityPoolConfiguration operation. /// Sets the necessary configuration for push sync. /// /// /// <para> /// This API can only be called with developer credentials. You cannot call this API with /// the temporary user credentials provided by Cognito Identity. /// </para> /// </summary> public partial class SetIdentityPoolConfigurationRequest : AmazonCognitoSyncRequest { private CognitoStreams _cognitoStreams; private string _identityPoolId; private PushSync _pushSync; /// <summary> /// Gets and sets the property CognitoStreams. Options to apply to this identity pool /// for Amazon Cognito streams. /// </summary> public CognitoStreams CognitoStreams { get { return this._cognitoStreams; } set { this._cognitoStreams = value; } } // Check to see if CognitoStreams property is set internal bool IsSetCognitoStreams() { return this._cognitoStreams != null; } /// <summary> /// Gets and sets the property IdentityPoolId. /// <para> /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created /// by Amazon Cognito. This is the ID of the pool to modify. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=55)] public string IdentityPoolId { get { return this._identityPoolId; } set { this._identityPoolId = value; } } // Check to see if IdentityPoolId property is set internal bool IsSetIdentityPoolId() { return this._identityPoolId != null; } /// <summary> /// Gets and sets the property PushSync. /// <para> /// Options to apply to this identity pool for push synchronization. /// </para> /// </summary> public PushSync PushSync { get { return this._pushSync; } set { this._pushSync = value; } } // Check to see if PushSync property is set internal bool IsSetPushSync() { return this._pushSync != null; } } }
31.872549
110
0.626269
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CognitoSync/Generated/Model/SetIdentityPoolConfigurationRequest.cs
3,251
C#
using System.Linq; using System.Linq.Expressions; using System.Reflection; using HappyMapper.AutoMapper.ConfigurationAPI.Configuration; namespace HappyMapper.AutoMapper.ConfigurationAPI.Mappers { public class ImplicitConversionOperatorMapper : IObjectMapper { public bool IsMatch(TypePair context) { var methodInfo = GetImplicitConversionOperator(context); return methodInfo != null; } private static MethodInfo GetImplicitConversionOperator(TypePair context) { var destinationType = context.DestinationType; if(destinationType.IsNullableType()) { destinationType = destinationType.GetTypeOfNullable(); } var sourceTypeMethod = context.SourceType .GetDeclaredMethods() .FirstOrDefault(mi => mi.IsPublic && mi.IsStatic && mi.Name == "op_Implicit" && mi.ReturnType == destinationType); return sourceTypeMethod ?? destinationType.GetDeclaredMethod("op_Implicit", new[] { context.SourceType }); } public Expression MapExpression(TypeMapRegistry typeMapRegistry, IConfigurationProvider configurationProvider, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) { var implicitOperator = GetImplicitConversionOperator(new TypePair(sourceExpression.Type, destExpression.Type)); return Expression.Call(null, implicitOperator, sourceExpression); } } }
41
229
0.696406
[ "MIT" ]
chumakov-ilya/HappyMapper
AutoMapper.ConfigurationAPI/AutoMapper/Mappers/ImplicitConversionOperatorMapper.cs
1,558
C#
using System; using System.Threading.Tasks; using Convey.CQRS.Commands; using Pacco.Services.Parcels.Application.Events; using Pacco.Services.Parcels.Application.Exceptions; using Pacco.Services.Parcels.Application.Services; using Pacco.Services.Parcels.Core.Entities; using Pacco.Services.Parcels.Core.Exceptions; using Pacco.Services.Parcels.Core.Repositories; namespace Pacco.Services.Parcels.Application.Commands.Handlers { public class AddParcelHandler : ICommandHandler<AddParcel> { private readonly IParcelRepository _parcelRepository; private readonly ICustomerRepository _customerRepository; private readonly IMessageBroker _messageBroker; private readonly IDateTimeProvider _dateTimeProvider; public AddParcelHandler(IParcelRepository parcelRepository, ICustomerRepository customerRepository, IMessageBroker messageBroker, IDateTimeProvider dateTimeProvider) { _parcelRepository = parcelRepository; _customerRepository = customerRepository; _messageBroker = messageBroker; _dateTimeProvider = dateTimeProvider; } public async Task HandleAsync(AddParcel command) { if (!Enum.TryParse<Variant>(command.Variant, true, out var variant)) { throw new InvalidParcelVariantException(command.Variant); } if (!Enum.TryParse<Size>(command.Size, true, out var size)) { throw new InvalidParcelSizeException(command.Size); } if (!(await _customerRepository.ExistsAsync(command.CustomerId))) { throw new CustomerNotFoundException(command.CustomerId); } var parcel = new Parcel(command.ParcelId, command.CustomerId, variant, size, command.Name, command.Description, _dateTimeProvider.Now); await _parcelRepository.AddAsync(parcel); await _messageBroker.PublishAsync(new ParcelAdded(command.ParcelId)); } } }
38.314815
107
0.693088
[ "MIT" ]
Microservices-DetectingQoSViolations/Pacco.Services.Parcels
src/Pacco.Services.Parcels.Application/Commands/Handlers/AddParcelHandler.cs
2,069
C#
using LiveHTS.Presentation.Interfaces.ViewModel; using LiveHTS.Presentation.Interfaces.ViewModel.Template; using LiveHTS.Presentation.Interfaces.ViewModel.Wrapper; using MvvmCross.Core.ViewModels; namespace LiveHTS.Presentation.ViewModel.Wrapper { public class FamilyTraceTemplateWrap : IFamilyTraceTemplateWrap { private IFamilyTraceTemplate _traceTemplate; private IMvxCommand _deleteTraceCommand; private IMvxCommand _editTraceCommand; private IMemberTracingViewModel _parent; public FamilyTraceTemplateWrap(IMemberTracingViewModel parent,IFamilyTraceTemplate traceTemplate) { _traceTemplate = traceTemplate; _parent = parent; } public IMemberTracingViewModel Parent { get { return _parent; } } public IFamilyTraceTemplate TraceTemplate { get { return _traceTemplate; } } public IMvxCommand EditTraceCommand { get { _editTraceCommand = _editTraceCommand ?? new MvxCommand(EditTrace); return _editTraceCommand; } } public IMvxCommand DeleteTraceCommand { get { _deleteTraceCommand = _deleteTraceCommand ?? new MvxCommand(DeleteTrace); return _deleteTraceCommand; } } private void EditTrace() { Parent.EditTrace(TraceTemplate.TraceResult); } private void DeleteTrace() { Parent.DeleteTrace(TraceTemplate.TraceResult); } } }
28.016949
105
0.623109
[ "MIT" ]
palladiumkenya/afyamobile
LiveHTS.Presentation/ViewModel/Wrapper/FamilyTraceTemplateWrap.cs
1,655
C#
// Copyright (c) 2016 Framefield. All rights reserved. // Released under the MIT license. (see LICENSE.txt) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace Framefield.Tooll { /// <summary> /// Interaction logic for CodeSectionTabControl.xaml /// </summary> //note: this assumes that a sectionid is unique within all code sections public partial class CodeSectionTabControl : UserControl { #region Properties public ObservableCollection<CodeSectionViewModel> JoinedCodeSections { get; set; } public List<CodeSectionManager> CodeSectionManagers { get { return _codeSectionManagers; } set { //remove old handlers if (_codeSectionManagers != null) { foreach (var csm in _codeSectionManagers) { csm.CodeSections.CollectionChanged -=CodeSections_CollectionChangedHandler; } } _codeSectionManagers = value; foreach(var csm in _codeSectionManagers) { csm.CodeSections.CollectionChanged += CodeSections_CollectionChangedHandler; } BuildJoinedCodeSectionList(); } } #endregion public CodeSectionTabControl() { InitializeComponent(); JoinedCodeSections = new ObservableCollection<CodeSectionViewModel>(); } public void SetActiveSectionId(string sectionId) { int foundIdx = -1; int idx = 0; foreach (var csvm in JoinedCodeSections) { if (csvm.Id == sectionId) { foundIdx = idx; break; } ++idx; } if (foundIdx >= 0) { //workaround to enforce triggering a changed signal even if the new index equals the old one XSectionTabControl.SelectedIndex = -1; XSectionTabControl.SelectedIndex = foundIdx; } } #region defining change event public class SectionChangedEventArgs : EventArgs { public CodeSectionManager CodeSectionManager { get; set; } public CodeSectionViewModel CodeSection { get; set; } } public delegate void SectionClickedDelegate(object o, SectionChangedEventArgs e); public event SectionClickedDelegate SectionChangedEvent; #endregion #region event handlers private void OnLoaded(object sender, RoutedEventArgs e) { if (App.Current != null) { var sectionBinding = new Binding() { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Source = this, Path = new PropertyPath("JoinedCodeSections") }; BindingOperations.SetBinding(XSectionTabControl, ItemsControl.ItemsSourceProperty, sectionBinding); } } void CodeSections_CollectionChangedHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { BuildJoinedCodeSectionList(); } private void TabControl_SelectionChangedHandler(object sender, SelectionChangedEventArgs e) { if (!_tabChangedEventsEnabled) return; var tc = sender as TabControl; if( tc == null) return; var index = tc.SelectedIndex; if (index == -1) return; var csvm = JoinedCodeSections[index]; CodeSectionManager csm = null; foreach(var csmI in CodeSectionManagers) { foreach( var cs in csmI.CodeSections ) { if( cs == csvm ) { csm = csmI; break; } } } SectionChangedEvent(this, new SectionChangedEventArgs() { CodeSection= csvm, CodeSectionManager= csm }); } #endregion #region private stuff private void BuildJoinedCodeSectionList() { _tabChangedEventsEnabled = false; JoinedCodeSections.Clear(); foreach(var csm in _codeSectionManagers) { foreach (var cs in csm.CodeSections) { if (!cs.Id.StartsWith("_")) { JoinedCodeSections.Add(cs); } } } _tabChangedEventsEnabled = true; } private List<CodeSectionManager> _codeSectionManagers; private bool _tabChangedEventsEnabled = true; #endregion } }
34.782895
135
0.558918
[ "MIT" ]
kajott/tooll
Tooll/Components/CodeEditor/CodeSectionTabControl.xaml.cs
5,289
C#
using UnityEngine; using System.Collections; public class Pig : MonoBehaviour { public float sinkScale = 0.5f; public float raiseScale = 0.2f; Vector2 basePosition; bool isSinking = false; bool sunk = false; float i = 0.0f; float q = 0.0f; float t = 0.0f; public AudioClip[] jumpSounds; // Use this for initialization void Start () { basePosition = transform.position; } // Update is called once per frame void Update () { if(isSinking) { if (t < 1.0f) { t += Time.deltaTime * sinkScale; } } else if(!isSinking) { if (t > 0.0f) { t -= Time.deltaTime * raiseScale; } } transform.position = Vector2.Lerp(basePosition, new Vector2(basePosition.x, basePosition.y - 1.0f), t); } void OnTriggerEnter2D(Collider2D col) { if(col.gameObject.tag == "Player") { isSinking = true; sunk = true; if (!gameObject.GetComponent<AudioSource>().isPlaying) { gameObject.GetComponent<AudioSource>().PlayOneShot(jumpSounds[Random.Range(0, jumpSounds.Length)]); } } } void OnTriggerExit2D(Collider2D col) { if (col.gameObject.tag == "Player") { isSinking = false; } } }
21.909091
115
0.519364
[ "MIT" ]
sashaquatch/Morning-Ritual
MorningRitual/Assets/Scripts/Animal/Pig.cs
1,448
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebHost { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
25.08
77
0.665072
[ "MIT" ]
codeyu/netcore-generic-host-demo
src/WebHost/Program.cs
629
C#
using System; using JetBrains.Annotations; using Vostok.Clusterclient.Model; namespace Vostok.Clusterclient.Strategies.DelayProviders { /// <summary> /// Represents a timeout provider that combines a <see cref="FixedDelaysProvider"/> for first few requests and uses an <see cref="EqualDelaysProvider"/> for the rest of them. /// </summary> public class FixedThenEqualDelaysProvider : IForkingDelaysProvider { private readonly FixedDelaysProvider fixedProvider; private readonly EqualDelaysProvider equalProvider; private readonly int fixedDelaysCount; public FixedThenEqualDelaysProvider(int tailDivisionFactor, [NotNull] params TimeSpan[] firstDelays) { equalProvider = new EqualDelaysProvider(tailDivisionFactor); fixedProvider = new FixedDelaysProvider(TailDelayBehaviour.StopIssuingDelays, firstDelays); fixedDelaysCount = firstDelays.Length; } public TimeSpan? GetForkingDelay(Request request, IRequestTimeBudget budget, int currentReplicaIndex, int totalReplicas) { return currentReplicaIndex < fixedDelaysCount ? fixedProvider.GetForkingDelay(request, budget, currentReplicaIndex, totalReplicas) : equalProvider.GetForkingDelay(request, budget, currentReplicaIndex, totalReplicas); } public override string ToString() { return $"{fixedProvider} + {equalProvider}"; } } }
41.527778
178
0.709699
[ "MIT" ]
vostok-archives/clusterclient.prototype
Vostok.ClusterClient/Strategies/DelayProviders/FixedThenEqualDelaysProvider.cs
1,497
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipayOpenPublicMenuQueryResponse. /// </summary> public class AlipayOpenPublicMenuQueryResponse : AopResponse { /// <summary> /// 一级菜单数组,个数应为1~4个 /// </summary> [XmlElement("menu_content")] public string MenuContent { get; set; } } }
21.833333
64
0.613232
[ "MIT" ]
BJDIIL/DiiL
Sdk/AlipaySdk/Response/AlipayOpenPublicMenuQueryResponse.cs
417
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2021 Ingo Herbote * https://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * https://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 YAF.Core.Extensions { #region Using using System.Collections.Generic; using System.Net.Mail; using YAF.Types; using YAF.Types.Interfaces; using YAF.Types.Interfaces.Services; #endregion /// <summary> /// The YAF send mail extensions. /// </summary> public static class ISendMailExtensions { #region Public Methods and Operators /// <summary> /// The send. /// </summary> /// <param name="sendMail">The send Mail.</param> /// <param name="fromEmail">The from email.</param> /// <param name="toEmail">The to email.</param> /// <param name="senderEmail">The sender email.</param> /// <param name="subject">The subject.</param> /// <param name="body">The body.</param> public static void Send( [NotNull] this IMailService sendMail, [NotNull] string fromEmail, [NotNull] string toEmail, [NotNull] string senderEmail, [CanBeNull] string subject, [CanBeNull] string body) { CodeContracts.VerifyNotNull(fromEmail, "fromEmail"); CodeContracts.VerifyNotNull(toEmail, "toEmail"); sendMail.Send( new MailAddress(fromEmail), new MailAddress(toEmail), new MailAddress(senderEmail), subject, body); } /// <summary> /// The send. /// </summary> /// <param name="sendMail">The send mail.</param> /// <param name="fromEmail">The from email.</param> /// <param name="fromName">The from name.</param> /// <param name="toEmail">The to email.</param> /// <param name="toName">The to name.</param> /// <param name="senderEmail">The sender email.</param> /// <param name="senderName">Name of the sender.</param> /// <param name="subject">The subject.</param> /// <param name="bodyText">The body text.</param> /// <param name="bodyHtml">The body html.</param> public static void Send( [NotNull] this IMailService sendMail, [NotNull] string fromEmail, [CanBeNull] string fromName, [NotNull] string toEmail, [CanBeNull] string toName, [NotNull] string senderEmail, [CanBeNull] string senderName, [CanBeNull] string subject, [CanBeNull] string bodyText, [CanBeNull] string bodyHtml) { sendMail.Send( new MailAddress(fromEmail, fromName), new MailAddress(toEmail, toName), new MailAddress(senderEmail, senderName), subject, bodyText, bodyHtml); } /// <summary> /// The send. /// </summary> /// <param name="sendMail">The send Mail.</param> /// <param name="fromAddress">The from address.</param> /// <param name="toAddress">The to address.</param> /// <param name="senderAddress">The sender address.</param> /// <param name="subject">The subject.</param> /// <param name="bodyText">The body text.</param> public static void Send( [NotNull] this IMailService sendMail, [NotNull] MailAddress fromAddress, [NotNull] MailAddress toAddress, [NotNull] MailAddress senderAddress, [CanBeNull] string subject, [CanBeNull] string bodyText) { sendMail.Send(fromAddress, toAddress, senderAddress, subject, bodyText, null); } /// <summary> /// The send. /// </summary> /// <param name="sendMail">The send mail.</param> /// <param name="fromAddress">The from address.</param> /// <param name="toAddress">The to address.</param> /// <param name="senderAddress">The sender address.</param> /// <param name="subject">The subject.</param> /// <param name="bodyText">The body text.</param> /// <param name="bodyHtml">The body html.</param> public static void Send( [NotNull] this IMailService sendMail, [NotNull] MailAddress fromAddress, [NotNull] MailAddress toAddress, [NotNull] MailAddress senderAddress, [CanBeNull] string subject, [CanBeNull] string bodyText, [CanBeNull] string bodyHtml) { CodeContracts.VerifyNotNull(sendMail, "sendMail"); CodeContracts.VerifyNotNull(fromAddress, "fromAddress"); CodeContracts.VerifyNotNull(toAddress, "toAddress"); var mailMessage = new MailMessage(); mailMessage.Populate(fromAddress, toAddress, senderAddress, subject, bodyText, bodyHtml); sendMail.SendAll(new List<MailMessage> { mailMessage }); } /// <summary> /// The send. /// </summary> /// <param name="sendMail"> /// The send mail. /// </param> /// <param name="fromAddress"> /// The from address. /// </param> /// <param name="toAddress"> /// The to address. /// </param> /// <param name="senderAddress"> /// The sender address. /// </param> /// <param name="subject"> /// The subject. /// </param> /// <param name="bodyText"> /// The body text. /// </param> /// <param name="bodyHtml"> /// The body html. /// </param> /// <returns> /// The <see cref="MailMessage"/>. /// </returns> public static MailMessage CreateMessage( [NotNull] this IMailService sendMail, [NotNull] MailAddress fromAddress, [NotNull] MailAddress toAddress, [NotNull] MailAddress senderAddress, [CanBeNull] string subject, [CanBeNull] string bodyText, [CanBeNull] string bodyHtml) { CodeContracts.VerifyNotNull(sendMail, "sendMail"); CodeContracts.VerifyNotNull(fromAddress, "fromAddress"); CodeContracts.VerifyNotNull(toAddress, "toAddress"); var mailMessage = new MailMessage(); mailMessage.Populate(fromAddress, toAddress, senderAddress, subject, bodyText, bodyHtml); return mailMessage; } #endregion } }
37.609756
102
0.560311
[ "Apache-2.0" ]
10by10pixel/YAFNET
yafsrc/YAF.Core/Extensions/ISendMailExtensions.cs
7,507
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections; using UnityEngine; using HoloToolkit.Unity; #if UNITY_WSA && !UNITY_EDITOR using System.Collections.Generic; #if UNITY_2017_2_OR_NEWER using UnityEngine.XR.WSA; using UnityEngine.XR.WSA.Persistence; using UnityEngine.XR.WSA.Sharing; #else using UnityEngine.VR.WSA; using UnityEngine.VR.WSA.Persistence; using UnityEngine.VR.WSA.Sharing; #endif #endif namespace HoloToolkit.Sharing.Tests { /// <summary> /// Manages creating anchors and sharing the anchors with other clients. /// </summary> public class ImportExportAnchorManager : Singleton<ImportExportAnchorManager> { /// <summary> /// Enum to track the progress through establishing a shared coordinate system. /// </summary> private enum ImportExportState { // Overall states Start, Failed, Ready, RoomApiInitializing, RoomApiInitialized, AnchorEstablished, // AnchorStore states AnchorStore_Initializing, // Anchor creation values InitialAnchorRequired, CreatingInitialAnchor, ReadyToExportInitialAnchor, UploadingInitialAnchor, // Anchor values DataRequested, DataReady, Importing } private ImportExportState currentState = ImportExportState.Start; public string StateName { get { return currentState.ToString(); } } public bool AnchorEstablished { get { return currentState == ImportExportState.AnchorEstablished; } } /// <summary> /// The Room Id of the current room. /// </summary> public long RoomID { get { return roomID; } set { if (currentRoom == null) { roomID = value; } } } private static bool ShouldLocalUserCreateRoom { get { if (SharingStage.Instance == null || SharingStage.Instance.SessionUsersTracker == null) { return false; } long localUserId; using (User localUser = SharingStage.Instance.Manager.GetLocalUser()) { localUserId = localUser.GetID(); } for (int i = 0; i < SharingStage.Instance.SessionUsersTracker.CurrentUsers.Count; i++) { if (SharingStage.Instance.SessionUsersTracker.CurrentUsers[i].GetID() < localUserId) { return false; } } return true; } } /// <summary> /// Called once the anchor has fully uploaded /// </summary> public event Action<bool> AnchorUploaded; #if UNITY_WSA && !UNITY_EDITOR /// <summary> /// Called when the anchor has been loaded /// </summary> public event Action AnchorLoaded; /// <summary> /// WorldAnchorTransferBatch is the primary object in serializing/deserializing anchors. /// <remarks>Only available on device.</remarks> /// </summary> private WorldAnchorTransferBatch sharedAnchorInterface; /// <summary> /// Keeps track of locally stored anchors. /// <remarks>Only available on device.</remarks> /// </summary> private WorldAnchorStore anchorStore; /// <summary> /// Keeps track of the name of the anchor we are exporting. /// </summary> private string exportingAnchorName; /// <summary> /// The datablob of the anchor. /// </summary> private List<byte> exportingAnchorBytes = new List<byte>(); /// <summary> /// Sometimes we'll see a really small anchor blob get generated. /// These tend to not work, so we have a minimum trustworthy size. /// </summary> private const uint MinTrustworthySerializedAnchorDataSize = 100000; #endif /// <summary> /// Keeps track of stored anchor data blob. /// </summary> private byte[] rawAnchorData; /// <summary> /// Keeps track of if the sharing service is ready. /// We need the sharing service to be ready so we can /// upload and download data for sharing anchors. /// </summary> private bool sharingServiceReady; /// <summary> /// The room manager API for the sharing service. /// </summary> private RoomManager roomManager; /// <summary> /// Keeps track of the current room we are connected to. Anchors /// are kept in rooms. /// </summary> private Room currentRoom; /// <summary> /// Some room ID for indicating which room we are in. /// </summary> private long roomID = 8675309; /// <summary> /// Indicates if the room should kept around even after all users leave /// </summary> public bool KeepRoomAlive; /// <summary> /// Room name to join /// </summary> public string RoomName = "DefaultRoom"; /// <summary> /// Debug text for displaying information. /// </summary> public TextMesh AnchorDebugText; /// <summary> /// Provides updates when anchor data is uploaded/downloaded. /// </summary> private RoomManagerAdapter roomManagerListener; #region Unity APIs protected override void Awake() { base.Awake(); #if UNITY_WSA && !UNITY_EDITOR // We need to get our local anchor store started up. currentState = ImportExportState.AnchorStore_Initializing; WorldAnchorStore.GetAsync(AnchorStoreReady); #else currentState = ImportExportState.Ready; #endif } private void Start() { // SharingStage should be valid at this point, but we may not be connected. if (SharingStage.Instance.IsConnected) { Connected(); } else { SharingStage.Instance.SharingManagerConnected += Connected; } } private void Update() { switch (currentState) { // If the local anchor store is initialized. case ImportExportState.Ready: if (sharingServiceReady) { StartCoroutine(InitRoomApi()); } break; case ImportExportState.RoomApiInitialized: StartAnchorProcess(); break; #if UNITY_WSA && !UNITY_EDITOR case ImportExportState.DataReady: // DataReady is set when the anchor download completes. currentState = ImportExportState.Importing; WorldAnchorTransferBatch.ImportAsync(rawAnchorData, ImportComplete); break; case ImportExportState.InitialAnchorRequired: currentState = ImportExportState.CreatingInitialAnchor; CreateAnchorLocally(); break; case ImportExportState.ReadyToExportInitialAnchor: // We've created an anchor locally and it is ready to export. currentState = ImportExportState.UploadingInitialAnchor; Export(); break; #endif } } protected override void OnDestroy() { if (SharingStage.Instance != null) { if (SharingStage.Instance.SessionsTracker != null) { SharingStage.Instance.SessionsTracker.CurrentUserJoined -= CurrentUserJoinedSession; SharingStage.Instance.SessionsTracker.CurrentUserLeft -= CurrentUserLeftSession; } } if (roomManagerListener != null) { roomManagerListener.AnchorsChangedEvent -= RoomManagerCallbacks_AnchorsChanged; roomManagerListener.AnchorsDownloadedEvent -= RoomManagerListener_AnchorsDownloaded; roomManagerListener.AnchorUploadedEvent -= RoomManagerListener_AnchorUploaded; if (roomManager != null) { roomManager.RemoveListener(roomManagerListener); } roomManagerListener.Dispose(); roomManagerListener = null; } if (roomManager != null) { roomManager.Dispose(); roomManager = null; } base.OnDestroy(); } #endregion #region Event Callbacks /// <summary> /// Called when the sharing stage connects to a server. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Events Arguments.</param> private void Connected(object sender = null, EventArgs e = null) { SharingStage.Instance.SharingManagerConnected -= Connected; if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Starting..."); } if (AnchorDebugText != null) { AnchorDebugText.text += "\nConnected to Server"; } // Setup the room manager callbacks. roomManager = SharingStage.Instance.Manager.GetRoomManager(); roomManagerListener = new RoomManagerAdapter(); roomManagerListener.AnchorsChangedEvent += RoomManagerCallbacks_AnchorsChanged; roomManagerListener.AnchorsDownloadedEvent += RoomManagerListener_AnchorsDownloaded; roomManagerListener.AnchorUploadedEvent += RoomManagerListener_AnchorUploaded; roomManager.AddListener(roomManagerListener); // We will register for session joined and left to indicate when the sharing service // is ready for us to make room related requests. SharingStage.Instance.SessionsTracker.CurrentUserJoined += CurrentUserJoinedSession; SharingStage.Instance.SessionsTracker.CurrentUserLeft += CurrentUserLeftSession; } /// <summary> /// Called when anchor upload operations complete. /// </summary> private void RoomManagerListener_AnchorUploaded(bool successful, XString failureReason) { if (successful) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Successfully uploaded anchor"); } if (AnchorDebugText != null) { AnchorDebugText.text += "\nSuccessfully uploaded anchor"; } currentState = ImportExportState.AnchorEstablished; } else { if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\n Upload failed " + failureReason); } Debug.LogError("Anchor Manager: Upload failed " + failureReason); currentState = ImportExportState.Failed; } if (AnchorUploaded != null) { AnchorUploaded(successful); } } /// <summary> /// Called when anchor download operations complete. /// </summary> private void RoomManagerListener_AnchorsDownloaded(bool successful, AnchorDownloadRequest request, XString failureReason) { // If we downloaded anchor data successfully we should import the data. if (successful) { int dataSize = request.GetDataSize(); if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: Anchor size: {0} bytes.", dataSize.ToString()); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nAnchor size: {0} bytes.", dataSize.ToString()); } rawAnchorData = new byte[dataSize]; request.GetData(rawAnchorData, dataSize); currentState = ImportExportState.DataReady; } else { if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nAnchor DL failed " + failureReason); } // If we failed, we can ask for the data again. Debug.LogWarning("Anchor Manager: Anchor DL failed " + failureReason); #if UNITY_WSA && !UNITY_EDITOR MakeAnchorDataRequest(); #endif } } /// <summary> /// Called when the anchors have changed in the room. /// </summary> /// <param name="room">The room where the anchors have changed.</param> private void RoomManagerCallbacks_AnchorsChanged(Room room) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: Anchors in room {0} changed", room.GetName()); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nAnchors in room {0} changed", room.GetName()); } // if we're currently in the room where the anchors changed if (currentRoom == room) { ResetState(); } } /// <summary> /// Called when the user joins a session. /// In this case, we are using this event is used to signal that the sharing service is ready to make room-related requests. /// </summary> /// <param name="session">Session joined.</param> private void CurrentUserJoinedSession(Session session) { if (SharingStage.Instance.Manager.GetLocalUser().IsValid()) { sharingServiceReady = true; } else { Debug.LogWarning("Unable to get local user on session joined"); } } /// <summary> /// Called when the user leaves a session. /// This event is used to signal that the sharing service must stop making room-related requests. /// </summary> /// <param name="session">Session left.</param> private void CurrentUserLeftSession(Session session) { sharingServiceReady = false; // Reset the state so that we join a new room when we eventually rejoin a session ResetState(); } #endregion /// <summary> /// Resets the Anchor Manager state. /// </summary> private void ResetState() { #if UNITY_WSA && !UNITY_EDITOR if (anchorStore != null) { currentState = ImportExportState.Ready; } else { currentState = ImportExportState.AnchorStore_Initializing; } #else currentState = ImportExportState.Ready; #endif } /// <summary> /// Initializes the room API. /// </summary> private IEnumerator InitRoomApi() { currentState = ImportExportState.RoomApiInitializing; // First check if there is a current room currentRoom = roomManager.GetCurrentRoom(); while (currentRoom == null) { // If we have a room, we'll join the first room we see. // If we are the user with the lowest user ID, we will create the room. // Otherwise we will wait for the room to be created. yield return new WaitForEndOfFrame(); if (roomManager.GetRoomCount() == 0) { if (ShouldLocalUserCreateRoom) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Creating room " + RoomName); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nCreating room " + RoomName); } // To keep anchors alive even if all users have left the session ... // Pass in true instead of false in CreateRoom. currentRoom = roomManager.CreateRoom(new XString(RoomName), roomID, KeepRoomAlive); } } else { // Look through the existing rooms and join the one that matches the room name provided. int roomCount = roomManager.GetRoomCount(); for (int i = 0; i < roomCount; i++) { Room room = roomManager.GetRoom(i); if (room.GetName().GetString().Equals(RoomName, StringComparison.OrdinalIgnoreCase)) { currentRoom = room; roomManager.JoinRoom(currentRoom); if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Joining room " + room.GetName().GetString()); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nJoining room " + room.GetName().GetString()); } break; } } if (currentRoom == null) { // Couldn't locate a matching room, just join the first one. currentRoom = roomManager.GetRoom(0); roomManager.JoinRoom(currentRoom); RoomName = currentRoom.GetName().GetString(); } currentState = ImportExportState.RoomApiInitialized; } yield return new WaitForEndOfFrame(); } if (currentRoom.GetAnchorCount() == 0) { #if UNITY_WSA && !UNITY_EDITOR // If the room has no anchors, request the initial anchor currentState = ImportExportState.InitialAnchorRequired; #else currentState = ImportExportState.RoomApiInitialized; #endif } else { // Room already has anchors currentState = ImportExportState.RoomApiInitialized; } if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: In room {0} with ID {1}", roomManager.GetCurrentRoom().GetName().GetString(), roomManager.GetCurrentRoom().GetID().ToString()); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nIn room {0} with ID {1}", roomManager.GetCurrentRoom().GetName().GetString(), roomManager.GetCurrentRoom().GetID().ToString()); } yield return null; } /// <summary> /// Kicks off the process of creating the shared space. /// </summary> private void StartAnchorProcess() { // First, are there any anchors in this room? int anchorCount = currentRoom.GetAnchorCount(); if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: {0} anchors found.", anchorCount.ToString()); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\n{0} anchors found.", anchorCount.ToString()); } #if UNITY_WSA && !UNITY_EDITOR // If there are anchors, we should attach to the first one. if (anchorCount > 0) { // Extract the name of the anchor. XString storedAnchorString = currentRoom.GetAnchorName(0); string storedAnchorName = storedAnchorString.GetString(); // Attempt to attach to the anchor in our local anchor store. if (AttachToCachedAnchor(storedAnchorName) == false) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Starting room anchor download of " + storedAnchorString); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nStarting room anchor download of " + storedAnchorString); } // If we cannot find the anchor by name, we will need the full data blob. MakeAnchorDataRequest(); } } #else currentState = ImportExportState.AnchorEstablished; if (AnchorDebugText != null) { AnchorDebugText.text += anchorCount > 0 ? "\n" + currentRoom.GetAnchorName(0).ToString() : "\nNo Anchors Found"; } #endif } #region WSA Specific Methods #if UNITY_WSA && !UNITY_EDITOR /// <summary> /// Kicks off getting the datablob required to import the shared anchor. /// When finished downloading, the RoomManager will raise RoomManagerListener_AnchorsDownloaded. /// </summary> private void MakeAnchorDataRequest() { if (roomManager.DownloadAnchor(currentRoom, currentRoom.GetAnchorName(0))) { currentState = ImportExportState.DataRequested; } else { Debug.LogError("Anchor Manager: Couldn't make the download request."); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nCouldn't make the download request."); } currentState = ImportExportState.Failed; } } /// <summary> /// Called when the local anchor store is ready. /// </summary> /// <param name="store"></param> private void AnchorStoreReady(WorldAnchorStore store) { anchorStore = store; if (!KeepRoomAlive) { anchorStore.Clear(); } currentState = ImportExportState.Ready; } /// <summary> /// Starts establishing a new anchor. /// </summary> private void CreateAnchorLocally() { WorldAnchor anchor = this.EnsureComponent<WorldAnchor>(); if (anchor.isLocated) { currentState = ImportExportState.ReadyToExportInitialAnchor; } else { anchor.OnTrackingChanged += Anchor_OnTrackingChanged_InitialAnchor; } } /// <summary> /// Callback to trigger when an anchor has been 'found'. /// </summary> private void Anchor_OnTrackingChanged_InitialAnchor(WorldAnchor self, bool located) { if (located) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Found anchor, ready to export"); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nFound anchor, ready to export"); } currentState = ImportExportState.ReadyToExportInitialAnchor; } else { Debug.LogError("Anchor Manager: Failed to locate local anchor!"); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nFailed to locate local anchor!"); } currentState = ImportExportState.Failed; } self.OnTrackingChanged -= Anchor_OnTrackingChanged_InitialAnchor; } /// <summary> /// Attempts to attach to an anchor by anchorName in the local store. /// </summary> /// <returns>True if it attached, false if it could not attach</returns> private bool AttachToCachedAnchor(string anchorName) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: Looking for cached anchor {0}...", anchorName); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nLooking for cached anchor {0}...", anchorName); } string[] ids = anchorStore.GetAllIds(); for (int index = 0; index < ids.Length; index++) { if (ids[index] == anchorName) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.LogFormat("Anchor Manager: Attempting to load cached anchor {0}...", anchorName); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nAttempting to load cached anchor {0}...", anchorName); } WorldAnchor anchor = anchorStore.Load(ids[index], gameObject); if (anchor.isLocated) { AnchorLoadComplete(); } else { if (AnchorDebugText != null) { AnchorDebugText.text += "\n"+anchorName; } anchor.OnTrackingChanged += ImportExportAnchorManager_OnTrackingChanged_Attaching; currentState = ImportExportState.AnchorEstablished; } return true; } } // Didn't find the anchor, so we'll download from room. return false; } /// <summary> /// Called when tracking changes for a 'cached' anchor. /// </summary> /// <param name="self"></param> /// <param name="located"></param> private void ImportExportAnchorManager_OnTrackingChanged_Attaching(WorldAnchor self, bool located) { if (located) { AnchorLoadComplete(); } else { Debug.LogWarning("Anchor Manager: Failed to find local anchor from cache."); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nFailed to find local anchor from cache."); } MakeAnchorDataRequest(); } self.OnTrackingChanged -= ImportExportAnchorManager_OnTrackingChanged_Attaching; } /// <summary> /// Called when a remote anchor has been deserialized. /// </summary> /// <param name="status"></param> /// <param name="anchorBatch"></param> private void ImportComplete(SerializationCompletionReason status, WorldAnchorTransferBatch anchorBatch) { if (status == SerializationCompletionReason.Succeeded) { if (anchorBatch.GetAllIds().Length > 0) { string first = anchorBatch.GetAllIds()[0]; if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Successfully imported anchor " + first); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nSuccessfully imported anchor " + first); } WorldAnchor anchor = anchorBatch.LockObject(first, gameObject); anchorStore.Save(first, anchor); } AnchorLoadComplete(); } else { Debug.LogError("Anchor Manager: Import failed"); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nImport failed"); } currentState = ImportExportState.DataReady; } } private void AnchorLoadComplete() { if (AnchorLoaded != null) { AnchorLoaded(); } currentState = ImportExportState.AnchorEstablished; } /// <summary> /// Exports the currently created anchor. /// </summary> private void Export() { WorldAnchor anchor = this.GetComponent<WorldAnchor>(); string guidString = Guid.NewGuid().ToString(); exportingAnchorName = guidString; // Save the anchor to our local anchor store. if (anchor != null && anchorStore.Save(exportingAnchorName, anchor)) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Exporting anchor " + exportingAnchorName); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nExporting anchor {0}", exportingAnchorName); } sharedAnchorInterface = new WorldAnchorTransferBatch(); sharedAnchorInterface.AddWorldAnchor(guidString, anchor); WorldAnchorTransferBatch.ExportAsync(sharedAnchorInterface, WriteBuffer, ExportComplete); } else { Debug.LogWarning("Anchor Manager: Failed to export anchor, trying again..."); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nFailed to export anchor, trying again..."); } currentState = ImportExportState.InitialAnchorRequired; } } /// <summary> /// Called by the WorldAnchorTransferBatch as anchor data is available. /// </summary> /// <param name="data"></param> private void WriteBuffer(byte[] data) { exportingAnchorBytes.AddRange(data); } /// <summary> /// Called by the WorldAnchorTransferBatch when anchor exporting is complete. /// </summary> /// <param name="status"></param> private void ExportComplete(SerializationCompletionReason status) { if (status == SerializationCompletionReason.Succeeded && exportingAnchorBytes.Count > MinTrustworthySerializedAnchorDataSize) { if (SharingStage.Instance.ShowDetailedLogs) { Debug.Log("Anchor Manager: Uploading anchor: " + exportingAnchorName); } if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nUploading anchor: " + exportingAnchorName); } roomManager.UploadAnchor( currentRoom, new XString(exportingAnchorName), exportingAnchorBytes.ToArray(), exportingAnchorBytes.Count); } else { Debug.LogWarning("Anchor Manager: Failed to upload anchor, trying again..."); if (AnchorDebugText != null) { AnchorDebugText.text += string.Format("\nFailed to upload anchor, trying again..."); } currentState = ImportExportState.InitialAnchorRequired; } } #endif // UNITY_WSA #endregion // WSA Specific Methods } }
34.3069
137
0.520083
[ "MIT" ]
ActiveNick/MixedRealityToolkit-Unity
Assets/HoloToolkit-Examples/Sharing/SharingService/Scripts/ImportExportAnchorManager.cs
33,314
C#
namespace VDTracker { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon2 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon3 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon4 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon5 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon6 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon7 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon8 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon9 = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon0 = new System.Windows.Forms.NotifyIcon(this.components); this.SuspendLayout(); // // notifyIcon1 // this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon"))); this.notifyIcon1.Text = "notifyIcon1"; this.notifyIcon1.Visible = true; // // notifyIcon2 // this.notifyIcon2.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon2.Icon"))); this.notifyIcon2.Text = "notifyIcon1"; this.notifyIcon2.Visible = true; // // notifyIcon3 // this.notifyIcon3.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon3.Icon"))); this.notifyIcon3.Text = "notifyIcon1"; this.notifyIcon3.Visible = true; // // notifyIcon4 // this.notifyIcon4.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon4.Icon"))); this.notifyIcon4.Text = "notifyIcon1"; this.notifyIcon4.Visible = true; // // notifyIcon5 // this.notifyIcon5.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon5.Icon"))); this.notifyIcon5.Text = "notifyIcon1"; this.notifyIcon5.Visible = true; // // notifyIcon6 // this.notifyIcon6.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon6.Icon"))); this.notifyIcon6.Text = "notifyIcon1"; this.notifyIcon6.Visible = true; // // notifyIcon7 // this.notifyIcon7.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon7.Icon"))); this.notifyIcon7.Text = "notifyIcon1"; this.notifyIcon7.Visible = true; // // notifyIcon8 // this.notifyIcon8.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon8.Icon"))); this.notifyIcon8.Text = "notifyIcon1"; this.notifyIcon8.Visible = true; // // notifyIcon9 // this.notifyIcon9.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon9.Icon"))); this.notifyIcon9.Text = "notifyIcon1"; this.notifyIcon9.Visible = true; // // notifyIcon0 // this.notifyIcon0.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon0.Icon"))); this.notifyIcon0.Text = "notifyIcon1"; this.notifyIcon0.Visible = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.NotifyIcon notifyIcon1; private System.Windows.Forms.NotifyIcon notifyIcon2; private System.Windows.Forms.NotifyIcon notifyIcon3; private System.Windows.Forms.NotifyIcon notifyIcon4; private System.Windows.Forms.NotifyIcon notifyIcon5; private System.Windows.Forms.NotifyIcon notifyIcon6; private System.Windows.Forms.NotifyIcon notifyIcon7; private System.Windows.Forms.NotifyIcon notifyIcon8; private System.Windows.Forms.NotifyIcon notifyIcon9; private System.Windows.Forms.NotifyIcon notifyIcon0; } }
35.29771
128
0.714749
[ "CC0-1.0" ]
belzecue/VDTracker
WindowsFormsApp2/Form1.Designer.cs
4,626
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.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class HttpContextIsDebuggingEnabledAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "UA0006"; private const string Category = "Upgrade"; private const string MemberName = "IsDebuggingEnabled"; private static readonly string[] HttpContextTypes = new[] { "System.Web.HttpContext", "Microsoft.AspNetCore.Http.HttpContext" }; private static readonly string[] WellKnownInstances = new[] { "HttpContext.Current", "HttpContextHelper.Current" }; private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.HttpContextDebuggingEnabledTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.HttpContextDebuggingEnabledMessageFormat), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.HttpContextDebuggingEnabledDescription), Resources.ResourceManager, typeof(Resources)); private static readonly DiagnosticDescriptor Rule = new(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSyntaxNodeAction(AnalyzeMemberAccess, SyntaxKind.SimpleMemberAccessExpression); } private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) { var expression = (MemberAccessExpressionSyntax)context.Node; // If the member being accessed isn't named "IsDebuggingEnabled", bail out if (!expression.Name.Identifier.Text.Equals(MemberName, StringComparison.Ordinal)) { return; } // Find the type containing the 'IsDebuggingEnabled' member var containingSymbolType = context.SemanticModel.GetSymbolInfo(expression.Expression).Symbol switch { ILocalSymbol localSymbol => localSymbol.Type, IFieldSymbol fieldSymbol => fieldSymbol.Type, IPropertySymbol propSymbol => propSymbol.Type, IMethodSymbol methodSymbol => methodSymbol.ReturnType, _ => null }; if (containingSymbolType is null) { // If we can't resolve the expression's symbol, just check for syntax referring to a couple well-known // HttpContext properties. if (WellKnownInstances.Any(i => expression.Expression.ToString().EndsWith(i, StringComparison.Ordinal))) { context.ReportDiagnostic(Diagnostic.Create(Rule, expression.GetLocation())); return; } } else { // If we can resolve the expression's type, check to see if it is an HttpContext if (HttpContextTypes.Contains(containingSymbolType.ToDisplayString(NullableFlowState.NotNull), StringComparer.Ordinal)) { context.ReportDiagnostic(Diagnostic.Create(Rule, expression.GetLocation())); return; } } } } }
49.149425
202
0.686155
[ "MIT" ]
kreghek/upgrade-assistant
src/extensions/default/analyzers/Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers/HttpContextIsDebuggingEnabledAnalyzer.cs
4,278
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Agent.Docker { using System; using System.Collections.Generic; using Microsoft.Azure.Devices.Edge.Agent.Core; using Microsoft.Azure.Devices.Edge.Util; using Newtonsoft.Json; public class EdgeAgentDockerModule : DockerModule, IEdgeAgentModule { static readonly DictionaryComparer<string, EnvVal> EnvDictionaryComparer = new DictionaryComparer<string, EnvVal>(); [JsonConstructor] public EdgeAgentDockerModule(string type, DockerConfig settings, ImagePullPolicy imagePullPolicy, ConfigurationInfo configuration, IDictionary<string, EnvVal> env, string version = "") : base(Core.Constants.EdgeAgentModuleName, version, ModuleStatus.Running, RestartPolicy.Always, settings, imagePullPolicy, Core.Constants.HighestPriority, configuration, env) { Preconditions.CheckArgument(type?.Equals("docker") ?? false); } public override bool Equals(IModule<DockerConfig> other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!string.Equals(this.Name, other.Name) || !string.Equals(this.Type, other.Type) || !string.Equals(this.Config.Image, other.Config.Image)) return false; IDictionary<string, string> labels = other.Config.CreateOptions?.Labels ?? new Dictionary<string, string>(); if (!labels.TryGetValue(Core.Constants.Labels.CreateOptions, out string createOptions) || !labels.TryGetValue(Core.Constants.Labels.Env, out string env)) return true; // If the 'net.azure-devices.edge.create-options' and 'net.azure-devices.edge.env' labels exist // on the other IModule, compare them to this IModule string thisCreateOptions = JsonConvert.SerializeObject(this.Config.CreateOptions); if (!thisCreateOptions.Equals(createOptions, StringComparison.Ordinal)) return false; var otherEnv = JsonConvert.DeserializeObject<IDictionary<string, EnvVal>>(env); return EnvDictionaryComparer.Equals(this.Env, otherEnv); } public override int GetHashCode() { unchecked { // ReSharper disable once NonReadonlyMemberInGetHashCode int hashCode = this.Name != null ? this.Name.GetHashCode() : 0; // ReSharper restore NonReadonlyMemberInGetHashCode hashCode = (hashCode * 397) ^ (this.Type != null ? this.Type.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (this.Config?.Image != null ? this.Config.Image.GetHashCode() : 0); return hashCode; } } } }
46.854839
192
0.642685
[ "MIT" ]
ArchanaMSFT/iotedge
edge-agent/src/Microsoft.Azure.Devices.Edge.Agent.Docker/EdgeAgentDockerModule.cs
2,905
C#
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace LoginPage.Droid.Models { public class Constants { public static bool IsDev = true; public static Color BackgroundColor = Color.FromRgb(14,158,21); public static Color MainTextColor = Color.White; public static string APPURL = "https://contact-billing-xamarin.azurewebsites.net"; public static int LogoHeight = 120; } }
24.65
91
0.6714
[ "MIT" ]
Trevis42/Software_Engineering_Project
Models/Constants.cs
495
C#
using System; using System.Linq.Expressions; namespace MassivePixel.Common { public static class Member<TClass> { public static string Name<TReturn>(Expression<Func<TClass, TReturn>> propertySelector) { if (propertySelector == null) throw new ArgumentNullException("propertySelector"); var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression == null) throw new ArgumentException("Parameter must be MemberExpression", "propertySelector"); return memberExpression.Member.Name; } } public static class Member { public static string Name<T>(Expression<Func<T>> propertySelector) { if (propertySelector == null) throw new ArgumentNullException("propertySelector"); var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression != null) return memberExpression.Member.Name; var newExpression = propertySelector.Body as NewExpression; if (newExpression != null) return newExpression.Type.Name; throw new ArgumentException("Parameter must be MemberExpression", "propertySelector"); } } }
32.121951
102
0.637054
[ "Apache-2.0" ]
MassivePixel/wp-common
MassivePixel.Common.WP8/Member.cs
1,319
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the personalize-runtime-2018-05-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.PersonalizeRuntime.Model { /// <summary> /// This is the response object from the GetPersonalizedRanking operation. /// </summary> public partial class GetPersonalizedRankingResponse : AmazonWebServiceResponse { private List<PredictedItem> _personalizedRanking = new List<PredictedItem>(); /// <summary> /// Gets and sets the property PersonalizedRanking. /// <para> /// A list of items in order of most likely interest to the user. The maximum is 500. /// </para> /// </summary> public List<PredictedItem> PersonalizedRanking { get { return this._personalizedRanking; } set { this._personalizedRanking = value; } } // Check to see if PersonalizedRanking property is set internal bool IsSetPersonalizedRanking() { return this._personalizedRanking != null && this._personalizedRanking.Count > 0; } } }
33.553571
117
0.684939
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/PersonalizeRuntime/Generated/Model/GetPersonalizedRankingResponse.cs
1,879
C#
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.custom_fields". /// </summary> public class CustomField : DbAccess, ICustomFieldRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "custom_fields". /// </summary> public override string _ObjectName => "custom_fields"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.custom_fields". /// </summary> /// <returns>Returns the number of rows of the table "config.custom_fields".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomField\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.custom_fields;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_fields" to return all instances of the "CustomField" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"CustomField\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_fields" to return all instances of the "CustomField" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"CustomField\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_fields" with a where filter on the column "custom_field_id" to return a single instance of the "CustomField" class. /// </summary> /// <param name="customFieldId">The column "custom_field_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomField Get(long customFieldId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"CustomField\" filtered by \"CustomFieldId\" with value {CustomFieldId} was denied to the user with Login ID {_LoginId}", customFieldId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields WHERE custom_field_id=@0;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql, customFieldId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.custom_fields". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomField GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"CustomField\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.custom_fields" sorted by customFieldId. /// </summary> /// <param name="customFieldId">The column "custom_field_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomField GetPrevious(long customFieldId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"CustomField\" by \"CustomFieldId\" with value {CustomFieldId} was denied to the user with Login ID {_LoginId}", customFieldId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields WHERE custom_field_id < @0 ORDER BY custom_field_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql, customFieldId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.custom_fields" sorted by customFieldId. /// </summary> /// <param name="customFieldId">The column "custom_field_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomField GetNext(long customFieldId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"CustomField\" by \"CustomFieldId\" with value {CustomFieldId} was denied to the user with Login ID {_LoginId}", customFieldId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields WHERE custom_field_id > @0 ORDER BY custom_field_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql, customFieldId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.custom_fields". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomField GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"CustomField\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.custom_fields" with a where filter on the column "custom_field_id" to return a multiple instances of the "CustomField" class. /// </summary> /// <param name="customFieldIds">Array of column "custom_field_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "CustomField" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> Get(long[] customFieldIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"CustomField\" was denied to the user with Login ID {LoginId}. customFieldIds: {customFieldIds}.", this._LoginId, customFieldIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields WHERE custom_field_id IN (@0);"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql, customFieldIds); } /// <summary> /// Custom fields are user defined form elements for config.custom_fields. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.custom_fields</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"CustomField\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.custom_fields' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.custom_fields'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.custom_fields. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.custom_fields</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"CustomField\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT custom_field_id AS key, custom_field_id as value FROM config.custom_fields;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of CustomField class on the database table "config.custom_fields". /// </summary> /// <param name="customField">The instance of "CustomField" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic customField, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } object primaryKeyValue = customField.custom_field_id; if (Cast.To<long>(primaryKeyValue) > 0) { this.Update(customField, Cast.To<long>(primaryKeyValue)); } else { primaryKeyValue = this.Add(customField); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.custom_fields')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.custom_fields', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of CustomField class on the database table "config.custom_fields". /// </summary> /// <param name="customField">The instance of "CustomField" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic customField) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"CustomField\" was denied to the user with Login ID {LoginId}. {CustomField}", this._LoginId, customField); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, customField, "config.custom_fields", "custom_field_id"); } /// <summary> /// Inserts or updates multiple instances of CustomField class on the database table "config.custom_fields"; /// </summary> /// <param name="customFields">List of "CustomField" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> customFields) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"CustomField\" was denied to the user with Login ID {LoginId}. {customFields}", this._LoginId, customFields); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic customField in customFields) { line++; object primaryKeyValue = customField.custom_field_id; if (Cast.To<long>(primaryKeyValue) > 0) { result.Add(customField.custom_field_id); db.Update("config.custom_fields", "custom_field_id", customField, customField.custom_field_id); } else { result.Add(db.Insert("config.custom_fields", "custom_field_id", customField)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.custom_fields" with an instance of "CustomField" class against the primary key value. /// </summary> /// <param name="customField">The instance of "CustomField" class to update.</param> /// <param name="customFieldId">The value of the column "custom_field_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic customField, long customFieldId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"CustomField\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {CustomField}", customFieldId, this._LoginId, customField); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, customField, customFieldId, "config.custom_fields", "custom_field_id"); } /// <summary> /// Deletes the row of the table "config.custom_fields" against the primary key value. /// </summary> /// <param name="customFieldId">The value of the column "custom_field_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(long customFieldId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"CustomField\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", customFieldId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.custom_fields WHERE custom_field_id=@0;"; Factory.NonQuery(this._Catalog, sql, customFieldId); } /// <summary> /// Performs a select statement on table "config.custom_fields" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"CustomField\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.custom_fields" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"CustomField\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.custom_fields ORDER BY custom_field_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.custom_fields' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.custom_fields". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "CustomField" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomField\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_fields WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomField(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.custom_fields" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"CustomField\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_fields WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomField(), filters); sql.OrderBy("custom_field_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.custom_fields". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "CustomField" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomField\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_fields WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomField(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.custom_fields" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "CustomField" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomField> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"CustomField\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_fields WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomField(), filters); sql.OrderBy("custom_field_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.CustomField>(this._Catalog, sql); } } }
45.055952
222
0.570455
[ "MIT" ]
2ia/frapid
src/Frapid.Web/Areas/Frapid.Config/DataAccess/CustomField.cs
37,847
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 securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecurityHub.Model { /// <summary> /// The details of an Amazon EC2 instance. /// </summary> public partial class AwsEc2InstanceDetails { private string _iamInstanceProfileArn; private string _imageId; private List<string> _ipV4Addresses = new List<string>(); private List<string> _ipV6Addresses = new List<string>(); private string _keyName; private string _launchedAt; private string _subnetId; private string _type; private string _vpcId; /// <summary> /// Gets and sets the property IamInstanceProfileArn. /// <para> /// The IAM profile ARN of the instance. /// </para> /// </summary> public string IamInstanceProfileArn { get { return this._iamInstanceProfileArn; } set { this._iamInstanceProfileArn = value; } } // Check to see if IamInstanceProfileArn property is set internal bool IsSetIamInstanceProfileArn() { return this._iamInstanceProfileArn != null; } /// <summary> /// Gets and sets the property ImageId. /// <para> /// The Amazon Machine Image (AMI) ID of the instance. /// </para> /// </summary> public string ImageId { get { return this._imageId; } set { this._imageId = value; } } // Check to see if ImageId property is set internal bool IsSetImageId() { return this._imageId != null; } /// <summary> /// Gets and sets the property IpV4Addresses. /// <para> /// The IPv4 addresses associated with the instance. /// </para> /// </summary> public List<string> IpV4Addresses { get { return this._ipV4Addresses; } set { this._ipV4Addresses = value; } } // Check to see if IpV4Addresses property is set internal bool IsSetIpV4Addresses() { return this._ipV4Addresses != null && this._ipV4Addresses.Count > 0; } /// <summary> /// Gets and sets the property IpV6Addresses. /// <para> /// The IPv6 addresses associated with the instance. /// </para> /// </summary> public List<string> IpV6Addresses { get { return this._ipV6Addresses; } set { this._ipV6Addresses = value; } } // Check to see if IpV6Addresses property is set internal bool IsSetIpV6Addresses() { return this._ipV6Addresses != null && this._ipV6Addresses.Count > 0; } /// <summary> /// Gets and sets the property KeyName. /// <para> /// The key name associated with the instance. /// </para> /// </summary> public string KeyName { get { return this._keyName; } set { this._keyName = value; } } // Check to see if KeyName property is set internal bool IsSetKeyName() { return this._keyName != null; } /// <summary> /// Gets and sets the property LaunchedAt. /// <para> /// Indicates when the instance was launched. /// </para> /// /// <para> /// Uses the <code>date-time</code> format specified in <a href="https://tools.ietf.org/html/rfc3339#section-5.6">RFC /// 3339 section 5.6, Internet Date/Time Format</a>. The value cannot contain spaces. /// For example, <code>2020-03-22T13:22:13.933Z</code>. /// </para> /// </summary> public string LaunchedAt { get { return this._launchedAt; } set { this._launchedAt = value; } } // Check to see if LaunchedAt property is set internal bool IsSetLaunchedAt() { return this._launchedAt != null; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// The identifier of the subnet that the instance was launched in. /// </para> /// </summary> public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The instance type of the instance. /// </para> /// </summary> public string Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property VpcId. /// <para> /// The identifier of the VPC that the instance was launched in. /// </para> /// </summary> public string VpcId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this._vpcId != null; } } }
30.553488
126
0.532349
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/AwsEc2InstanceDetails.cs
6,569
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Media; using System.Windows.Forms.VisualStyles; namespace EvertTimer { public partial class timertoolForm : Form { public timertoolForm() { InitializeComponent(); timer1.Tick += new EventHandler(TimeReached); timer2.Tick += new EventHandler(ShowSecond); timer3.Tick += new EventHandler(Exclamate); } private void timertoolForm_Resize(object sender, System.EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { notifyIcon.BalloonTipTitle = "EvertTimer"; notifyIcon.BalloonTipText = "I am hiding in the tray."; notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(2000); Hide(); } else { notifyIcon.Visible = false; } } private void notifyIcon_Restore(object sender, MouseEventArgs e) { Show(); this.WindowState = FormWindowState.Normal; } private static int countdown = 0; DateTime StartTime; DateTime FinishTime; private void StopIt() { timer1.Enabled = false; timer2.Enabled = false; timer1.Stop(); timer2.Stop(); txtHours.Enabled = true; txtMinutes.Enabled = true; lbl_seconds.Text = "00"; btn_start.Text = "start"; btn_start.BackColor = Color.LightGreen; progressbarSimple1.Value = 0; btn_5min.Enabled = true; btn_15min.Enabled = true; btn_30min.Enabled = true; btn_1hour.Enabled = true; } private void btn_start_Click(object sender, EventArgs e) { if (btn_start.Text == "start") { int seconds = 0; seconds += Convert.ToInt16(txtMinutes.Text) * 60; seconds += Convert.ToInt16(txtHours.Text) * 60 * 60; if (seconds == 0) { for (int i = 0; i < 5; i++) { btn_start.BackColor = Color.Tomato; btn_start.Refresh(); System.Threading.Thread.Sleep(200); btn_start.BackColor = Color.LightGreen; btn_start.Refresh(); System.Threading.Thread.Sleep(200); } return; } StartTime = DateTime.Now; FinishTime = StartTime; FinishTime = FinishTime.AddSeconds(seconds); timer1.Interval = seconds * 1000; timer1.Enabled = true; timer1.Start(); timer2.Interval = 1000; // 1 second timer2.Enabled = true; timer2.Start(); btn_start.Text = "stop"; txtHours.Enabled = false; txtMinutes.Enabled = false; btn_5min.Enabled = false; btn_15min.Enabled = false; btn_30min.Enabled = false; btn_1hour.Enabled = false; progressbarSimple1.Maximum = seconds; btn_start.BackColor = Color.LightCoral; } else { StopIt(); } } public void TimeReached(object sender, EventArgs eArgs) { StopIt(); if (chk_beep.Checked) { // sounds 3 times a beep (exclamation mark) SystemSounds.Exclamation.Play(); countdown = 1; timer3.Interval = 2000; timer3.Enabled = true; } notifyIcon.BalloonTipTitle = "EvertTimer"; notifyIcon.BalloonTipText = "Time is up!"; notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(4000); Show(); Activate(); MessageBox.Show("Time is up!","EvertTimer"); progressbarSimple1.Value = 0; } public void ShowSecond(object sender, EventArgs eArgs) { int h, m, s; string sh = ""; string sm = ""; string ss = ""; TimeSpan TimeToGo = FinishTime - DateTime.Now; h = TimeToGo.Hours; m = TimeToGo.Minutes; s = TimeToGo.Seconds; if (h < 10) sh = "0"; if (m < 10) sm = "0"; if (s < 10) ss = "0"; txtHours.Text = sh + Convert.ToString(h); txtMinutes.Text = sm + Convert.ToString(m); lbl_seconds.Text = ss + Convert.ToString(s); progressbarSimple1.Value = Convert.ToInt32(TimeToGo.TotalSeconds); } public void Exclamate(object sender, EventArgs eArgs) { SystemSounds.Exclamation.Play(); if (countdown == 0) { if (!chk_repeat.Checked) { timer3.Stop(); timer3.Enabled = false; chk_repeat.ForeColor = DefaultForeColor; } else { chk_repeat.ForeColor = Color.DarkOrange; } } else countdown--; } private void btn_5min_Click(object sender, EventArgs e) { txtHours.Text = "00"; txtMinutes.Text = "05"; } private void btn_15min_Click(object sender, EventArgs e) { txtHours.Text = "00"; txtMinutes.Text = "15"; } private void btn_30min_Click(object sender, EventArgs e) { txtHours.Text = "00"; txtMinutes.Text = "30"; } private void btn_1hour_Click(object sender, EventArgs e) { txtHours.Text = "01"; txtMinutes.Text = "00"; } private void txtHours_TextChanged(object sender, EventArgs e) { int n; bool isNumeric = int.TryParse(txtHours.Text, out n); if (!isNumeric) { txtHours.Text = ""; for (int i = 0; i < 1; i++) { txtHours.BackColor = Color.Tomato; txtHours.Refresh(); System.Threading.Thread.Sleep(200); txtHours.BackColor = Color.White; txtHours.Refresh(); System.Threading.Thread.Sleep(200); } } } private void txtMinutes_TextChanged(object sender, EventArgs e) { int n; bool isNumeric = int.TryParse(txtMinutes.Text, out n); if (!isNumeric) { txtMinutes.Text = ""; for (int i = 0; i < 1; i++) { txtMinutes.BackColor = Color.Tomato; txtMinutes.Refresh(); System.Threading.Thread.Sleep(200); txtMinutes.BackColor = Color.White; txtMinutes.Refresh(); System.Threading.Thread.Sleep(200); } } } private void chk_beep_CheckedChanged(object sender, EventArgs e) { if (chk_beep.Checked) chk_repeat.Enabled = true; else chk_repeat.Enabled = false; } private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.evertmouw.nl/"); } } }
31.864341
91
0.468434
[ "Unlicense" ]
evert-mouw/EvertTimer
source/timertool.cs
8,223
C#
using System.Linq; using Microsoft.EntityFrameworkCore; namespace SportsStore.Models { public class EFOrderRepository : IOrderRepository { private StoreDbContext context; public EFOrderRepository(StoreDbContext ctx) { context = ctx; } public IQueryable<Order> Orders => context .Orders .Include(o => o.Lines) .ThenInclude(l => l.Product); public void SaveOrder(Order order) { context.AttachRange(order.Lines.Select(l => l.Product)); if (order.OrderID == 0) { context.Orders.Add(order); } context.SaveChanges(); } } }
26.111111
68
0.561702
[ "MIT" ]
JeannAndrade/SportsStore
SportsStore/Models/EFOrderRepository.cs
705
C#
using System.Threading.Tasks; using YesSql.Indexes; using YesSql.Tests.Models; namespace YesSql.Tests.Indexes { public class PersonByName : MapIndex { public string SomeName { get; set; } public static string Normalize(string name) { return name.ToUpperInvariant(); } } public class PersonIndexProvider : IndexProvider<Person> { public override void Describe(DescribeContext<Person> context) { context .For<PersonByName>() .Map(person => new PersonByName { SomeName = person.Firstname }); } } public class PersonAsyncIndexProvider : IndexProvider<Person> { public override void Describe(DescribeContext<Person> context) { context .For<PersonByName>() .Map(async person => { await Task.Delay(10); return new PersonByName { SomeName = person.Firstname }; }); } } public class ScopedPersonAsyncIndexProvider : IndexProvider<Person> { private readonly int _seed; public ScopedPersonAsyncIndexProvider(int seed) { _seed = seed; } public override void Describe(DescribeContext<Person> context) { context .For<PersonByName>() .Map(async person => { await Task.Delay(10); return new PersonByName { SomeName = person.Firstname + _seed }; }); } } }
27.274194
85
0.519219
[ "MIT" ]
VE-2016/YesSQL
test/YesSql.Tests/Indexes/PersonByName.cs
1,691
C#
namespace GS.Hex.Communication.Asynchronous.Dashboard.Pages { internal partial class PerPageSelector { private readonly Pager _pager; public PerPageSelector(Pager pager) { _pager = pager; } } }
19.384615
60
0.619048
[ "MIT" ]
krzysztofdudek/hex
Source/Communication/Asynchronous/Dashboard/Pages/_PerPageSelector.cs
254
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Owpini.EntityFramework; namespace Owpini.EntityFramework.Migrations { [DbContext(typeof(OwpiniDbContext))] [Migration("20170629170821_update business entity")] partial class updatebusinessentity { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Owpini.Core.Businesses.Business", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1") .IsRequired() .HasMaxLength(500); b.Property<string>("Address2"); b.Property<string>("City") .IsRequired() .HasMaxLength(500); b.Property<string>("Description") .HasMaxLength(500); b.Property<string>("Name") .IsRequired() .HasMaxLength(500); b.Property<string>("Phone") .IsRequired(); b.Property<string>("State") .IsRequired() .HasMaxLength(500); b.Property<string>("WebAddress"); b.Property<int>("Zip"); b.HasKey("Id"); b.ToTable("Businesses"); }); } } }
31.216667
117
0.514682
[ "Apache-2.0" ]
tthiatma/Owpini
Owpini.EntityFramework/Migrations/20170629170821_update business entity.Designer.cs
1,875
C#
namespace ClearHl7.Codes.V270 { /// <summary> /// HL7 Version 2 Table 0653 - Date Format. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0653</remarks> public enum CodeDateFormat { /// <summary> /// 1 - mm/dd/yy. /// </summary> MmDdYyWithSlashes, /// <summary> /// 2 - yy.mm.dd. /// </summary> YyMmDdWithPeriods, /// <summary> /// 3 - dd/mm/yy. /// </summary> DdMmYyWithSlashes, /// <summary> /// 4 - dd.mm.yy. /// </summary> DdMmYyWithPeriods, /// <summary> /// 5 - yy/mm/dd. /// </summary> YyMmDdWithSlashes, /// <summary> /// 6 - Yymmdd. /// </summary> Yymmdd } }
20.05
59
0.435162
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7.Codes/V270/CodeDateFormat.cs
804
C#
public partial class MyTestEntity { public EntitasRedux.Tests.DeepCopyComponent DeepCopy { get { return (EntitasRedux.Tests.DeepCopyComponent)GetComponent(MyTestComponentsLookup.DeepCopy); } } public bool HasDeepCopy { get { return HasComponent(MyTestComponentsLookup.DeepCopy); } } public void AddDeepCopy(EntitasRedux.Tests.CloneableObject newValue, System.Collections.Generic.List<EntitasRedux.Tests.CloneableObject> newList, System.Collections.Generic.Dictionary<EntitasRedux.Tests.CloneableObject, EntitasRedux.Tests.CloneableObject> newDict) { var index = MyTestComponentsLookup.DeepCopy; var component = (EntitasRedux.Tests.DeepCopyComponent)CreateComponent(index, typeof(EntitasRedux.Tests.DeepCopyComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = newValue; component.list = newList; component.dict = newDict; #endif AddComponent(index, component); } public void ReplaceDeepCopy(EntitasRedux.Tests.CloneableObject newValue, System.Collections.Generic.List<EntitasRedux.Tests.CloneableObject> newList, System.Collections.Generic.Dictionary<EntitasRedux.Tests.CloneableObject, EntitasRedux.Tests.CloneableObject> newDict) { var index = MyTestComponentsLookup.DeepCopy; var component = (EntitasRedux.Tests.DeepCopyComponent)CreateComponent(index, typeof(EntitasRedux.Tests.DeepCopyComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = newValue; component.list = newList; component.dict = newDict; #endif ReplaceComponent(index, component); } public void CopyDeepCopyTo(EntitasRedux.Tests.DeepCopyComponent copyComponent) { var index = MyTestComponentsLookup.DeepCopy; var component = (EntitasRedux.Tests.DeepCopyComponent)CreateComponent(index, typeof(EntitasRedux.Tests.DeepCopyComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = (EntitasRedux.Tests.CloneableObject)copyComponent.value.Clone(); component.list = (System.Collections.Generic.List<EntitasRedux.Tests.CloneableObject>)JCMG.EntitasRedux.ListTools.DeepCopy(copyComponent.list); component.dict = (System.Collections.Generic.Dictionary<EntitasRedux.Tests.CloneableObject, EntitasRedux.Tests.CloneableObject>)JCMG.EntitasRedux.DictionaryTools.DeepCopy(copyComponent.dict); #endif ReplaceComponent(index, component); } public void RemoveDeepCopy() { RemoveComponent(MyTestComponentsLookup.DeepCopy); } } public sealed partial class MyTestMatcher { static JCMG.EntitasRedux.IMatcher<MyTestEntity> _matcherDeepCopy; public static JCMG.EntitasRedux.IMatcher<MyTestEntity> DeepCopy { get { if (_matcherDeepCopy == null) { var matcher = (JCMG.EntitasRedux.Matcher<MyTestEntity>)JCMG.EntitasRedux.Matcher<MyTestEntity>.AllOf(MyTestComponentsLookup.DeepCopy); matcher.ComponentNames = MyTestComponentsLookup.ComponentNames; _matcherDeepCopy = matcher; } return _matcherDeepCopy; } } }
42.746269
269
0.811103
[ "MIT" ]
MaxShwachko/entitas-redux-modified
Unity/Assets/JCMG/EntitasRedux/Scripts/Editor/Tests/Generated/MyTest/Components/MyTestDeepCopyComponent.cs
2,864
C#