content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; namespace DotVVM.Framework.Binding.Expressions { public enum ErrorHandlingMode { ReturnNull, ThrowException, ReturnException } public interface IBinding { object? GetProperty(Type type, ErrorHandlingMode errorMode = ErrorHandlingMode.ThrowException); //IDictionary<Type, object> Properties { get; } //IList<Delegate> AdditionalServices { get; } } public interface ICloneableBinding: IBinding { IEnumerable<object> GetAllComputedProperties(); } }
23.6
103
0.681356
[ "Apache-2.0" ]
riganti/dotvvm
src/Framework/Framework/Binding/Expressions/IBinding.cs
592
C#
using NBitcoin; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace WalletWasabi.Blockchain.Transactions { public class TransactionBroadcastEntry { public Transaction Transaction { get; } public uint256 TransactionId { get; } public string NodeRemoteSocketEndpoint { get; } private bool Broadcasted { get; set; } private int PropagationConfirmations { get; set; } private object Lock { get; } public TransactionBroadcastEntry(Transaction transaction, string nodeRemoteSocketEndpoint) { Lock = new object(); Transaction = transaction; TransactionId = Transaction.GetHash(); Broadcasted = false; PropagationConfirmations = 0; NodeRemoteSocketEndpoint = nodeRemoteSocketEndpoint; } public void MakeBroadcasted() { lock (Lock) { Broadcasted = true; } } public bool IsBroadcasted() { lock (Lock) { return Broadcasted; } } public void ConfirmPropagationOnce() { lock (Lock) { Broadcasted = true; PropagationConfirmations++; } } public void ConfirmPropagationForGood() { lock (Lock) { Broadcasted = true; PropagationConfirmations = 21; } } public int GetPropagationConfirmations() { lock (Lock) { return PropagationConfirmations; } } } }
18.232877
92
0.694966
[ "MIT" ]
BCSNProject/WalletWasabi
WalletWasabi/Blockchain/Transactions/TransactionBroadcastEntry.cs
1,331
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using Microsoft.MobileBlazorBindings.Core; using System; using XF = Xamarin.Forms; namespace Microsoft.MobileBlazorBindings.Elements.Handlers { public class MenuItemHandler : BaseMenuItemHandler { public MenuItemHandler(NativeComponentRenderer renderer, XF.MenuItem menuItemControl) : base(renderer, menuItemControl) { MenuItemControl = menuItemControl ?? throw new ArgumentNullException(nameof(menuItemControl)); MenuItemControl.Clicked += (s, e) => { if (ClickEventHandlerId != default) { renderer.Dispatcher.InvokeAsync(() => renderer.DispatchEventAsync(ClickEventHandlerId, null, e)); } }; } public XF.MenuItem MenuItemControl { get; } public ulong ClickEventHandlerId { get; set; } public override void ApplyAttribute(ulong attributeEventHandlerId, string attributeName, object attributeValue, string attributeEventUpdatesAttributeName) { switch (attributeName) { case nameof(XF.MenuItem.IconImageSource): MenuItemControl.IconImageSource = AttributeHelper.StringToImageSource((string)attributeValue); break; case nameof(XF.MenuItem.IsDestructive): MenuItemControl.IsDestructive = AttributeHelper.GetBool(attributeValue); break; case nameof(XF.MenuItem.Text): MenuItemControl.Text = (string)attributeValue; break; case "onclick": Renderer.RegisterEvent(attributeEventHandlerId, () => ClickEventHandlerId = 0); ClickEventHandlerId = attributeEventHandlerId; break; default: base.ApplyAttribute(attributeEventHandlerId, attributeName, attributeValue, attributeEventUpdatesAttributeName); break; } } } }
41.431373
162
0.613346
[ "MIT" ]
Kahbazi/MobileBlazorBindings
src/Microsoft.MobileBlazorBindings/Elements/Handlers/MenuItemHandler.cs
2,115
C#
using Grpc.Net.Client; using gTimedTask.RegistrationCenter; using Quartz; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace gTimedTask.Core { /// <summary> /// 远程调用执行器任务 /// </summary> //[Quartz.DisallowConcurrentExecution] public class RemoteCallJob : IJob { //public RemoteHttpJob(System.Net.Http.IHttpClientFactory clientFactory) //{ // this._httpClientFactory = clientFactory; //} public async Task Execute(IJobExecutionContext context) { var s = context.JobDetail; var url = s.JobDataMap.Get("url"); var executor = JobExecutorManager.GetExecutor("gTimedTask.Executor.Handler.LogHandler", LoadBalanceStrategy.First);//s.Key.Name, LoadBalanceStrategy.First); if (executor == null) { return; } var address = executor.Address; //todo:抽象通讯模型 GrpcChannel channel = TransportManager.GetOrAddChannel(address); var triggerjobClient = new JobHandlerTrigger.JobHandlerTriggerClient(channel); await triggerjobClient.TriggerJobAsync(new JobHandlerTriggerRequest { Name = s.Key.Name }); context.Result = "a"; JobKey jobKey = context.Trigger.JobKey; Console.WriteLine(DateTime.Now); // trigger // JobTrriger.Trigger(jobId); } } }
32.630435
168
0.62958
[ "MIT" ]
ShyUncle/gTimedTask
src/gTimedTask.Core/TaskDispatchCenter/RemoteCallJob.cs
1,533
C#
using System; using Xamarin.Forms; namespace AppControl { class Program : global::Xamarin.Forms.Platform.Tizen.FormsApplication { /// <summary> /// Called when the application is launched. /// If base.OnCreated() is not called, the event 'Created' will not be emitted. /// </summary> protected override void OnCreate() { base.OnCreate(); LoadApplication(new App()); } /// <summary> /// The entry point for the application. /// </summary> /// <param name="args"> A list of command line arguments.</param> static void Main(string[] args) { var app = new Program(); Forms.Init(app); Tizen.Wearable.CircularUI.Forms.Renderer.FormsCircularUI.Init(); app.Run(args); } } }
27.03125
87
0.553757
[ "Apache-2.0" ]
AchoWang/Tizen-CSharp-Samples
Wearable/AppControl/AppControl/AppControl.cs
865
C#
// <copyright file="WorkInfo.cs" company="SoftChains"> // Copyright 2016 Dan Gershony // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // </copyright> namespace Blockchain.Protocol.Bitcoin.Client.Types { /// <summary> /// The work info. /// TODO: Populate with properties. /// </summary> public class WorkInfo { } }
35.277778
102
0.705512
[ "MIT" ]
CoinVault/Bitcoin.cs
src/Blockchain.Protocol.Bitcoin/Client/Types/WorkInfo.cs
637
C#
//----------------------------------------------------------------------- // <copyright file="MatchesAll.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- namespace Akka.TestKit.Internal.StringMatcher { /// <summary> /// <remarks>Note! Part of internal API. Breaking changes may occur without notice. Use at own risk.</remarks> /// </summary> public class MatchesAll : IStringMatcher { private static readonly IStringMatcher _instance = new MatchesAll(); private MatchesAll() { } public static IStringMatcher Instance { get { return _instance; } } public bool IsMatch(string s) { return true; } public override string ToString() { return ""; } } }
28.5
114
0.520468
[ "Apache-2.0" ]
to11mtm/akka.net
src/core/Akka.TestKit/EventFilter/Internal/StringMatcher/MatchesAll.cs
1,028
C#
namespace ToDo.Web.ViewModels.Manage { public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } }
22.6
46
0.738938
[ "MIT" ]
WouterDeKort/Utopia
src/ToDo.Web/ViewModels/Manage/TwoFactorAuthenticationViewModel.cs
228
C#
using HotChocolate.Language; using HotChocolate.Properties; namespace HotChocolate.Types.Introspection { [Introspection] #pragma warning disable IDE1006 // Naming Styles internal sealed class __InputValue #pragma warning restore IDE1006 // Naming Styles : ObjectType<IInputField> { protected override void Configure( IObjectTypeDescriptor<IInputField> descriptor) { descriptor.Name("__InputValue"); descriptor.Description( TypeResources.InputValue_Description); descriptor.BindFields(BindingBehavior.Explicit); descriptor.Field(t => t.Name) .Type<NonNullType<StringType>>(); descriptor.Field(t => t.Description); descriptor.Field(t => t.Type) .Type<NonNullType<__Type>>(); descriptor.Field(t => t.DefaultValue) .Description(TypeResources.InputValue_DefaultValue) .Type<StringType>() .Resolver(c => { IInputField field = c.Parent<IInputField>(); if (field.DefaultValue.IsNull()) { return null; } if (field.DefaultValue != null) { return QuerySyntaxSerializer .Serialize(field.DefaultValue); } return null; }); } } }
29.461538
67
0.522846
[ "MIT" ]
Coldplayer1995/GraphQLTest
src/Core/Types/Types/Introspection/__InputValue.cs
1,532
C#
using UnityEngine; using UnityEditor; namespace uCPf { [CustomPropertyDrawer(typeof(HSV))] public sealed class HSVEditor : PropertyDrawer { public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty (position, label, property); float h = property.FindPropertyRelative("h").floatValue; float s = property.FindPropertyRelative("s").floatValue; float v = property.FindPropertyRelative("v").floatValue; float a = property.FindPropertyRelative("a").floatValue; var hsv = new HSV (h, s, v, a); position = EditorGUI.PrefixLabel (position, GUIUtility.GetControlID (FocusType.Passive), label); var color = EditorGUI.ColorField (position,(Color)hsv); hsv = color; if (hsv.v == 0) { hsv.s = s; hsv.h = h; } if (hsv.s == 0) hsv.h = h; property.FindPropertyRelative("h").floatValue = hsv.h; property.FindPropertyRelative("s").floatValue = hsv.s; property.FindPropertyRelative("v").floatValue = hsv.v; property.FindPropertyRelative("a").floatValue = hsv.a; EditorGUI.EndProperty (); } } }
27.875
99
0.699552
[ "Apache-2.0" ]
IdahoLabCuttingBoard/PowDDeR
Assets/uGUIColorPicker-free/Core/Editor/HSVEditor.cs
1,117
C#
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information. using Moq; namespace Microsoft.VisualStudio.Shell.Interop { internal static class IVsSolutionBuildManager3Factory { public static IVsSolutionBuildManager3 Create( IVsUpdateSolutionEvents3? solutionEventsListener = null, VSSOLNBUILDUPDATEFLAGS? buildFlags = null) { var buildManager = new Mock<IVsSolutionBuildManager3>(); solutionEventsListener ??= IVsUpdateSolutionEvents3Factory.Create(); var flags = (uint)(buildFlags ?? VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_NONE); buildManager.Setup(b => b.QueryBuildManagerBusyEx(out flags)) .Returns(VSConstants.S_OK); return buildManager.Object; } } }
38.8
201
0.669072
[ "MIT" ]
Ashishpatel2321/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Mocks/IVsSolutionBuildManager3Factory.cs
948
C#
namespace TomsToolbox.Wpf.Converters { using System; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Media; using JetBrains.Annotations; using TomsToolbox.Desktop; /// <summary> /// Applies the <see cref="BinaryOperationConverter.Operation"/> on the value and the converter parameter.<para/> /// May also be used as <see cref="IMultiValueConverter"/> where both operands are specified using bindings. /// </summary> /// <returns> /// If the conversions succeed, the result of the operation is returned. If any error occurs, the result is <see cref="DependencyProperty.UnsetValue"/>. /// </returns> /// <remarks> /// Either<para/> /// - both value and parameter must be convertible to a double<para/> /// or<para/> /// - value must have an explicit operator for the specified operation and parameter has a type converter matching the expected operator parameter.<para/> /// If the value supports implicit or explicit casts, the operation is retried on all types that the original type can be casted to. This enables the converter to handle most operations on <see cref="Vector"/>, <see cref="Size"/>, <see cref="Point"/>, etc...<para/> /// <para/> /// For <see cref="Rect"/> the <see cref="BinaryOperation.Addition"/> is mapped to <see cref="Rect.Offset(Vector)"/> and /// the <see cref="BinaryOperation.Multiply"/> is mapped to <see cref="Rect.Transform(Matrix)"/> /// </remarks> [ValueConversion(typeof(object), typeof(object))] public class BinaryOperationConverter : ValueConverter, IMultiValueConverter { [CanBeNull] private BinaryOperationProcessor _processor; /// <summary> /// The default addition converter. /// </summary> [NotNull] public static readonly IValueConverter Addition = new BinaryOperationConverter { Operation = BinaryOperation.Addition }; /// <summary> /// The default subtraction converter. /// </summary> [NotNull] public static readonly IValueConverter Subtraction = new BinaryOperationConverter { Operation = BinaryOperation.Subtraction }; /// <summary> /// The default multiplication converter. /// </summary> [NotNull] public static readonly IValueConverter Multiply = new BinaryOperationConverter { Operation = BinaryOperation.Multiply }; /// <summary> /// The default division converter. /// </summary> [NotNull] public static readonly IValueConverter Division = new BinaryOperationConverter { Operation = BinaryOperation.Division }; /// <summary> /// The default equality converter. /// </summary> [NotNull] public static readonly IValueConverter Equality = new BinaryOperationConverter { Operation = BinaryOperation.Equality }; /// <summary> /// The default inequality converter. /// </summary> [NotNull] public static readonly IValueConverter Inequality = new BinaryOperationConverter { Operation = BinaryOperation.Inequality }; /// <summary> /// The default greater than converter. /// </summary> [NotNull] public static readonly IValueConverter GreaterThan = new BinaryOperationConverter { Operation = BinaryOperation.GreaterThan }; /// <summary> /// The default less than converter. /// </summary> [NotNull] public static readonly IValueConverter LessThan = new BinaryOperationConverter { Operation = BinaryOperation.LessThan }; /// <summary> /// The default greater than or equals converter. /// </summary> [NotNull] public static readonly IValueConverter GreaterThanOrEqual = new BinaryOperationConverter { Operation = BinaryOperation.GreaterThanOrEqual }; /// <summary> /// The default less than or equals converter. /// </summary> [NotNull] public static readonly IValueConverter LessThanOrEqual = new BinaryOperationConverter { Operation = BinaryOperation.LessThanOrEqual }; /// <summary> /// Gets or sets the operation the converter is performing. /// </summary> public BinaryOperation Operation { get => Processor.Operation; set => _processor = new BinaryOperationProcessor(value); } [NotNull] private BinaryOperationProcessor Processor { get { return _processor ?? (_processor = new BinaryOperationProcessor(BinaryOperation.Addition)); } } /// <summary> /// Converts a value. /// </summary> /// <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> /// <returns> /// A converted value. If the method returns null, the valid null value is used. /// </returns> protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter == null) return value; return Processor.Execute(value, parameter); } /// <summary> /// Converts source values to a value for the binding target. The data binding engine calls this method when it propagates the values from source bindings to the binding target. /// </summary> /// <param name="values">The array of values that the source bindings in the <see cref="T:System.Windows.Data.MultiBinding" /> produces. The value <see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the source binding has no value to provide for conversion.</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> /// <returns> /// A converted value.If the method returns null, the valid null value is used.A return value of <see cref="T:System.Windows.DependencyProperty" />.<see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the converter did not produce a value, and that the binding will use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> if it is available, or else will use the default value.A return value of <see cref="T:System.Windows.Data.Binding" />.<see cref="F:System.Windows.Data.Binding.DoNothing" /> indicates that the binding does not transfer the value or use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> or the default value. /// </returns> /// <exception cref="System.ArgumentException">MultiValueConverter requires two values.;values</exception> [CanBeNull] public object Convert([CanBeNull] object[] values, [CanBeNull] Type targetType, [CanBeNull] object parameter, [CanBeNull] CultureInfo culture) { if (values == null) return null; if (values.Any(value => (value == null) || (value == DependencyProperty.UnsetValue))) return DependencyProperty.UnsetValue; if (values.Length != 2) throw new ArgumentException("MultiValueConverter requires two values.", nameof(values)); return Processor.Execute(values[0], values[1]); } /// <summary> /// Converts a binding target value to the source binding values. /// </summary> /// <param name="value">The value that the binding target produces.</param> /// <param name="targetTypes">The array of types to convert to. The array length indicates the number and types of values that are suggested for the method to return.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns> /// An array of values that have been converted from the target value back to the source values. /// </returns> /// <exception cref="System.InvalidOperationException">This operation is not supported.</exception> public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } }
56.248408
693
0.647832
[ "MIT" ]
tom-englert/TomsToolbox1
TomsToolbox.Wpf/Converters/BinaryOperationConverter.cs
8,833
C#
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ActorDb.Api { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
21.526316
61
0.577017
[ "Apache-2.0" ]
danielcrenna/actordb-net
actordb-api/Program.cs
411
C#
using UnityEngine; using System.Collections; public class AudioRandomSound : MonoBehaviour { public float MinWait; public float MaxWait; public string Sound; // Use this for initialization IEnumerator Start () { while (true) { yield return new WaitForSeconds(Random.Range(MinWait, MaxWait)); AudioController.Instance.PlaySound(Sound); } } }
22.611111
76
0.663391
[ "MIT" ]
hagish/tektix
taktik/Assets/Scripts/Audio/AudioRandomSound.cs
409
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 pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Pinpoint.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations { /// <summary> /// CustomMessageActivity Marshaller /// </summary> public class CustomMessageActivityMarshaller : IRequestMarshaller<CustomMessageActivity, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(CustomMessageActivity requestObject, JsonMarshallerContext context) { if(requestObject.IsSetDeliveryUri()) { context.Writer.WritePropertyName("DeliveryUri"); context.Writer.Write(requestObject.DeliveryUri); } if(requestObject.IsSetEndpointTypes()) { context.Writer.WritePropertyName("EndpointTypes"); context.Writer.WriteArrayStart(); foreach(var requestObjectEndpointTypesListValue in requestObject.EndpointTypes) { context.Writer.Write(requestObjectEndpointTypesListValue); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetMessageConfig()) { context.Writer.WritePropertyName("MessageConfig"); context.Writer.WriteObjectStart(); var marshaller = JourneyCustomMessageMarshaller.Instance; marshaller.Marshall(requestObject.MessageConfig, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetNextActivity()) { context.Writer.WritePropertyName("NextActivity"); context.Writer.Write(requestObject.NextActivity); } if(requestObject.IsSetTemplateName()) { context.Writer.WritePropertyName("TemplateName"); context.Writer.Write(requestObject.TemplateName); } if(requestObject.IsSetTemplateVersion()) { context.Writer.WritePropertyName("TemplateVersion"); context.Writer.Write(requestObject.TemplateVersion); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static CustomMessageActivityMarshaller Instance = new CustomMessageActivityMarshaller(); } }
35.019608
116
0.640817
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/CustomMessageActivityMarshaller.cs
3,572
C#
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, All Rights Reserved // // File: WmpBitmapDecoder.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Security; using System.Security.Permissions; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using Microsoft.Win32.SafeHandles; using MS.Internal; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; namespace System.Windows.Media.Imaging { #region WmpBitmapDecoder /// <summary> /// The built-in Microsoft Wmp (Bitmap) Decoder. /// </summary> public sealed class WmpBitmapDecoder : BitmapDecoder { /// <summary> /// Don't allow construction of a decoder with no params /// </summary> private WmpBitmapDecoder() { } /// <summary> /// Create a WmpBitmapDecoder given the Uri /// </summary> /// <param name="bitmapUri">Uri to decode</param> /// <param name="createOptions">Bitmap Create Options</param> /// <param name="cacheOption">Bitmap Caching Option</param> /// <SecurityNote> /// Critical - access critical resource /// PublicOk - inputs verified or safe /// </SecurityNote> [SecurityCritical] public WmpBitmapDecoder( Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatWmp) { } /// <summary> /// If this decoder cannot handle the bitmap stream, it will throw an exception. /// </summary> /// <param name="bitmapStream">Stream to decode</param> /// <param name="createOptions">Bitmap Create Options</param> /// <param name="cacheOption">Bitmap Caching Option</param> /// <SecurityNote> /// Critical - access critical resource /// PublicOk - inputs verified or safe /// </SecurityNote> [SecurityCritical] public WmpBitmapDecoder( Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption ) : base(bitmapStream, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatWmp) { } /// <summary> /// Internal Constructor /// </summary> /// <SecurityNote> /// Critical: Uses a SafeFileHandle, which is a SecurityCritical type (in v4). /// Calls SecurityCritical base class constructor. /// </SecurityNote> [SecurityCritical] internal WmpBitmapDecoder( SafeMILHandle decoderHandle, BitmapDecoder decoder, Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, bool insertInDecoderCache, bool originalWritable, Stream uriStream, UnmanagedMemoryStream unmanagedMemoryStream, SafeFileHandle safeFilehandle ) : base(decoderHandle, decoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, originalWritable, uriStream, unmanagedMemoryStream, safeFilehandle) { } #region Internal Abstract /// Need to implement this to derive from the "sealed" object internal override void SealObject() { throw new NotImplementedException(); } #endregion } #endregion }
32.880342
184
0.600728
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Core/CSharp/System/Windows/Media/Imaging/WmpBitmapDecoder.cs
3,847
C#
namespace Switchvox.Admins { class GetList { } }
8.857143
27
0.580645
[ "MIT" ]
bfranklin825/SwitchvoxAPI
SwitchvoxAPI/_Unimplemented/Admins/GetList.cs
64
C#
// <copyright file="WeatherForecastController.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // 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. // </copyright> using Microsoft.AspNetCore.Mvc; namespace Examples.EventCounter.AspNetCore.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching", }; private readonly ILogger<WeatherForecastController> logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { this.logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)], }) .ToArray(); } } }
34.26
107
0.655575
[ "Apache-2.0" ]
hananiel/opentelemetry-dotnet-contrib
examples/eventcounters/Examples.EventCounters.AspNetCore/Controllers/WeatherForecastController.cs
1,715
C#
using Hl7.Fhir.Model; using Hl7.Fhir.Specification.Source; using System; using System.Collections.Generic; using System.Diagnostics; namespace Hl7.Fhir.Specification.Tests { class TimingSource : IConformanceSource { IConformanceSource _source; TimeSpan _duration = TimeSpan.Zero; public TimingSource(IConformanceSource source) { _source = source; } public IConformanceSource Source => _source; public IEnumerable<ConceptMap> FindConceptMaps(string sourceUri = null, string targetUri = null) => measureDuration(() => _source.FindConceptMaps(sourceUri, targetUri)); public NamingSystem FindNamingSystem(string uniqueid) => measureDuration(() => _source.FindNamingSystem(uniqueid)); // public ValueSet FindValueSetBySystem(string system) => measureDuration(() => _source.FindValueSetBySystem(system)); public CodeSystem FindCodeSystemByValueSet(string system) => measureDuration(() => _source.FindCodeSystemByValueSet(system)); public IEnumerable<string> ListResourceUris(ResourceType? filter = default(ResourceType?)) => _source.ListResourceUris(filter); // => measureDuration(() => _source.ListResourceUris(filter)); public Resource ResolveByCanonicalUri(string uri) => measureDuration(() => _source.ResolveByCanonicalUri(uri)); public Resource ResolveByUri(string uri) => measureDuration(() => _source.ResolveByUri(uri)); T measureDuration<T>(Func<T> f) { Stopwatch sw = new Stopwatch(); sw.Start(); var result = f(); sw.Stop(); _duration += sw.Elapsed; return result; } public TimeSpan Duration => _duration; public void Reset() { _duration = TimeSpan.Zero; } public void ShowDuration(int count, TimeSpan totalDuration) { var totalMs = totalDuration.TotalMilliseconds; var resolverMs = _duration.TotalMilliseconds; var resolverFraction = resolverMs / totalMs; var snapshotMs = totalMs - resolverMs; var snapshotFraction = snapshotMs / totalMs; // Debug.Print($"Generated {count} snapshots in {totalMs} ms = {sourceMs} ms (resolver) + {snapshotMs} (snapshot) ({perc:2}%), on average {avg} ms per snapshot."); Debug.WriteLine($"Generated {count} snapshots in {totalMs} ms = {resolverMs} ms (resolver) ({resolverFraction:P0}) + {snapshotMs} (snapshot) ({snapshotFraction:P0})."); var totalAvg = totalMs / count; var resolverAvg = resolverMs / count; var snapshotAvg = snapshotMs / count; Debug.WriteLine($"Average per resource: {totalAvg} = {resolverAvg} ms (resolver) + {snapshotAvg} ms (snapshot)"); } } }
43.890625
180
0.660733
[ "BSD-3-Clause" ]
CASPA-Care/caspa-fhir-net-api
src/Hl7.Fhir.Specification.Tests/Snapshot/TimingSource.cs
2,811
C#
namespace SevenZip.Compression.RangeCoder { internal struct BitTreeEncoder { private readonly BitEncoder[] _models; private readonly int _numBitLevels; public BitTreeEncoder(int numBitLevels) { _numBitLevels = numBitLevels; _models = new BitEncoder[1 << numBitLevels]; } public void Init() { for (uint i = 1; i < (1 << _numBitLevels); i++) _models[i].Init(); } public void Encode(Encoder rangeEncoder, uint symbol) { uint m = 1; for (var bitIndex = _numBitLevels; bitIndex > 0;) { bitIndex--; var bit = (symbol >> bitIndex) & 1; _models[m].Encode(rangeEncoder, bit); m = (m << 1) | bit; } } public void ReverseEncode(Encoder rangeEncoder, uint symbol) { uint m = 1; for (uint i = 0; i < _numBitLevels; i++) { var bit = symbol & 1; _models[m].Encode(rangeEncoder, bit); m = (m << 1) | bit; symbol >>= 1; } } public uint GetPrice(uint symbol) { uint price = 0; uint m = 1; for (var bitIndex = _numBitLevels; bitIndex > 0;) { bitIndex--; var bit = (symbol >> bitIndex) & 1; price += _models[m].GetPrice(bit); m = (m << 1) + bit; } return price; } public uint ReverseGetPrice(uint symbol) { uint price = 0; uint m = 1; for (var i = _numBitLevels; i > 0; i--) { var bit = symbol & 1; symbol >>= 1; price += _models[m].GetPrice(bit); m = (m << 1) | bit; } return price; } public static uint ReverseGetPrice(BitEncoder[] models, uint startIndex, int numBitLevels, uint symbol) { uint price = 0; uint m = 1; for (var i = numBitLevels; i > 0; i--) { var bit = symbol & 1; symbol >>= 1; price += models[startIndex + m].GetPrice(bit); m = (m << 1) | bit; } return price; } public static void ReverseEncode(BitEncoder[] models, uint startIndex, Encoder rangeEncoder, int numBitLevels, uint symbol) { uint m = 1; for (var i = 0; i < numBitLevels; i++) { var bit = symbol & 1; models[startIndex + m].Encode(rangeEncoder, bit); m = (m << 1) | bit; symbol >>= 1; } } } internal struct BitTreeDecoder { private readonly BitDecoder[] _models; private readonly int _numBitLevels; public BitTreeDecoder(int numBitLevels) { _numBitLevels = numBitLevels; _models = new BitDecoder[1 << numBitLevels]; } public void Init() { for (uint i = 1; i < (1 << _numBitLevels); i++) _models[i].Init(); } public uint Decode(Decoder rangeDecoder) { uint m = 1; for (var bitIndex = _numBitLevels; bitIndex > 0; bitIndex--) m = (m << 1) + _models[m].Decode(rangeDecoder); return m - ((uint) 1 << _numBitLevels); } public uint ReverseDecode(Decoder rangeDecoder) { uint m = 1; uint symbol = 0; for (var bitIndex = 0; bitIndex < _numBitLevels; bitIndex++) { var bit = _models[m].Decode(rangeDecoder); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } public static uint ReverseDecode(BitDecoder[] models, uint startIndex, Decoder rangeDecoder, int numBitLevels) { uint m = 1; uint symbol = 0; for (var bitIndex = 0; bitIndex < numBitLevels; bitIndex++) { var bit = models[startIndex + m].Decode(rangeDecoder); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } } }
29.909677
93
0.433132
[ "Unlicense" ]
AndreySeVeN/ReplayBot
LZMA/RangeCoderBitTree.cs
4,636
C#
using MyEmployees.Entities; using System; using System.Data.SQLite; using System.Reflection; using System.Windows.Forms; namespace ExportDataLibrary { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { string result = Assembly.GetExecutingAssembly().Location; int index = result.LastIndexOf("\\"); string dbPath = $"{result.Substring(0, index)}\\Employees.db"; SQLiteConnection connection = new SQLiteConnection($"Data Source= {dbPath}"); using (SQLiteCommand command = new SQLiteCommand(connection)) { connection.Open(); command.CommandText = "SELECT * FROM Employees"; using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Employee employee = new Employee { EmployeeId = int.Parse(reader[0].ToString()), FirstName = reader[1].ToString(), LastName = reader[2].ToString(), Email = reader[3].ToString() }; employeeBindingSource.Add(employee); } } } dataGridView1.DataSource = employeeBindingSource; } } }
30.45283
89
0.494424
[ "MIT" ]
Bhaskers-Blu-Org2/Windows-AppConsult-Samples-DesktopBridge
Blog-AdvancedInstaller/MyEmployees/Form1.cs
1,616
C#
using OpenQA.Selenium; using WordpressAutomationTests.Core.Infrastructure; using WordpressAutomationTests.Sections.Administration.AdminBar; using WordpressAutomationTests.Sections.Administration.AdminMenu; namespace WordpressAutomationTests.Pages.Administration.Shared { public abstract class AdminPageBase<TElements, TAsserts> : SectionBase<TElements, TAsserts> where TElements : ElementsBase where TAsserts : AssertsBase<TElements> { protected AdminPageBase(IWebDriver webDriver, TElements elements, TAsserts asserts) : base(webDriver, elements, asserts) { AdminBar = new AdminBarSection(webDriver); AdminMenu = new AdminMenuSection(webDriver); } public AdminBarSection AdminBar { get; } public AdminMenuSection AdminMenu { get; } } }
36.73913
95
0.731361
[ "MIT" ]
clickstormio/automation-test-example
WordpressAutomationTests/Pages/Administration/Shared/AdminPageBase.cs
847
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Schema; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.Rest; namespace Microsoft.Bot.Connector.Authentication { internal class ParameterizedBotFrameworkAuthentication : BotFrameworkAuthentication { private static HttpClient _defaultHttpClient = new HttpClient(); private readonly bool _validateAuthority; private readonly string _toChannelFromBotLoginUrl; private readonly string _toChannelFromBotOAuthScope; private readonly string _toBotFromChannelTokenIssuer; private readonly string _oAuthUrl; private readonly string _toBotFromChannelOpenIdMetadataUrl; private readonly string _toBotFromEmulatorOpenIdMetadataUrl; private readonly string _callerId; private readonly ServiceClientCredentialsFactory _credentialFactory; private readonly AuthenticationConfiguration _authConfiguration; private readonly HttpClient _httpClient; private readonly ILogger _logger; public ParameterizedBotFrameworkAuthentication( bool validateAuthority, string toChannelFromBotLoginUrl, string toChannelFromBotOAuthScope, string toBotFromChannelTokenIssuer, string oAuthUrl, string toBotFromChannelOpenIdMetadataUrl, string toBotFromEmulatorOpenIdMetadataUrl, string callerId, ServiceClientCredentialsFactory credentialFactory, AuthenticationConfiguration authConfiguration, HttpClient httpClient = null, ILogger logger = null) { _validateAuthority = validateAuthority; _toChannelFromBotLoginUrl = toChannelFromBotLoginUrl; _toChannelFromBotOAuthScope = toChannelFromBotOAuthScope; _toBotFromChannelTokenIssuer = toBotFromChannelTokenIssuer; _oAuthUrl = oAuthUrl; _toBotFromChannelOpenIdMetadataUrl = toBotFromChannelOpenIdMetadataUrl; _toBotFromEmulatorOpenIdMetadataUrl = toBotFromEmulatorOpenIdMetadataUrl; _callerId = callerId; _credentialFactory = credentialFactory; _authConfiguration = authConfiguration; _httpClient = httpClient ?? _defaultHttpClient; _logger = logger; } public override async Task<AuthenticateRequestResult> AuthenticateRequestAsync(Activity activity, string authHeader, CancellationToken cancellationToken) { var claimsIdentity = await JwtTokenValidation_AuthenticateRequestAsync(activity, authHeader, _credentialFactory, _authConfiguration, _httpClient, cancellationToken).ConfigureAwait(false); var scope = SkillValidation.IsSkillClaim(claimsIdentity.Claims) ? JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims) : _toChannelFromBotOAuthScope; var callerId = await GenerateCallerIdAsync(_credentialFactory, claimsIdentity, cancellationToken).ConfigureAwait(false); var appId = BuiltinBotFrameworkAuthentication.GetAppId(claimsIdentity); var credentials = await _credentialFactory.CreateCredentialsAsync(appId, scope, _toChannelFromBotLoginUrl, _validateAuthority, cancellationToken).ConfigureAwait(false); return new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, Credentials = credentials, Scope = scope, CallerId = callerId }; } public override Task<ServiceClientCredentials> GetProactiveCredentialsAsync(ClaimsIdentity claimsIdentity, string audience, CancellationToken cancellationToken) { throw new NotImplementedException(); } private async Task<string> GenerateCallerIdAsync(ServiceClientCredentialsFactory credentialFactory, ClaimsIdentity claimsIdentity, CancellationToken cancellationToken) { // Is the bot accepting all incoming messages? if (await credentialFactory.IsAuthenticationDisabledAsync(cancellationToken).ConfigureAwait(false)) { // Return null so that the callerId is cleared. return null; } // Is the activity from another bot? if (SkillValidation.IsSkillClaim(claimsIdentity.Claims)) { return $"{CallerIdConstants.BotToBotPrefix}{JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims)}"; } return _callerId; } // The following code is based on JwtTokenValidation.AuthenticateRequest private async Task<ClaimsIdentity> JwtTokenValidation_AuthenticateRequestAsync(Activity activity, string authHeader, ServiceClientCredentialsFactory credentialFactory, AuthenticationConfiguration authConfiguration, HttpClient httpClient, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(authHeader)) { var isAuthDisabled = await credentialFactory.IsAuthenticationDisabledAsync(cancellationToken).ConfigureAwait(false); if (isAuthDisabled) { // In the scenario where Auth is disabled, we still want to have the // IsAuthenticated flag set in the ClaimsIdentity. To do this requires // adding in an empty claim. return new ClaimsIdentity(new List<Claim>(), "anonymous"); } // No Auth Header. Auth is required. Request is not authorized. throw new UnauthorizedAccessException(); } var claimsIdentity = await JwtTokenValidation_ValidateAuthHeaderAsync(authHeader, credentialFactory, activity.ChannelId, authConfiguration, activity.ServiceUrl, httpClient, cancellationToken).ConfigureAwait(false); AppCredentials.TrustServiceUrl(activity.ServiceUrl); return claimsIdentity; } private async Task<ClaimsIdentity> JwtTokenValidation_ValidateAuthHeaderAsync(string authHeader, ServiceClientCredentialsFactory credentialFactory, string channelId, AuthenticationConfiguration authConfiguration, string serviceUrl, HttpClient httpClient, CancellationToken cancellationToken) { var identity = await JwtTokenValidation_AuthenticateTokenAsync(authHeader, credentialFactory, channelId, authConfiguration, serviceUrl, httpClient, cancellationToken).ConfigureAwait(false); await JwtTokenValidation_ValidateClaimsAsync(authConfiguration, identity.Claims).ConfigureAwait(false); return identity; } private async Task JwtTokenValidation_ValidateClaimsAsync(AuthenticationConfiguration authConfig, IEnumerable<Claim> claims) { if (authConfig.ClaimsValidator != null) { // Call the validation method if defined (it should throw an exception if the validation fails) var claimsList = claims as IList<Claim> ?? claims.ToList(); await authConfig.ClaimsValidator.ValidateClaimsAsync(claimsList).ConfigureAwait(false); } else if (SkillValidation.IsSkillClaim(claims)) { throw new UnauthorizedAccessException("ClaimsValidator is required for validation of Skill Host calls."); } } private async Task<ClaimsIdentity> JwtTokenValidation_AuthenticateTokenAsync(string authHeader, ServiceClientCredentialsFactory credentialFactory, string channelId, AuthenticationConfiguration authConfiguration, string serviceUrl, HttpClient httpClient, CancellationToken cancellationToken) { if (SkillValidation.IsSkillToken(authHeader)) { return await SkillValidation_AuthenticateChannelTokenAsync(authHeader, credentialFactory, httpClient, channelId, authConfiguration, cancellationToken).ConfigureAwait(false); } if (EmulatorValidation.IsTokenFromEmulator(authHeader)) { return await EmulatorValidation_AuthenticateEmulatorTokenAsync(authHeader, credentialFactory, httpClient, channelId, authConfiguration, cancellationToken).ConfigureAwait(false); } return await GovernmentChannelValidation_AuthenticateChannelTokenAsync(authHeader, credentialFactory, serviceUrl, httpClient, channelId, authConfiguration, cancellationToken).ConfigureAwait(false); } // The following code is based on SkillValidation.AuthenticateChannelToken private async Task<ClaimsIdentity> SkillValidation_AuthenticateChannelTokenAsync(string authHeader, ServiceClientCredentialsFactory credentialFactory, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfiguration, CancellationToken cancellationToken) { var tokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuers = new[] { "https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/", // Auth v3.1, 1.0 token "https://login.microsoftonline.com/d6d49420-f39b-4df7-a1dc-d59a935871db/v2.0", // Auth v3.1, 2.0 token "https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/", // Auth v3.2, 1.0 token "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0", // Auth v3.2, 2.0 token "https://sts.windows.net/cab8a31a-1906-4287-a0d8-4eef66b95f6e/", // Auth for US Gov, 1.0 token "https://login.microsoftonline.us/cab8a31a-1906-4287-a0d8-4eef66b95f6e/v2.0" // Auth for US Gov, 2.0 token }, ValidateAudience = false, // Audience validation takes place manually in code. ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5), RequireSignedTokens = true }; // TODO: what should the openIdMetadataUrl be here? var tokenExtractor = new JwtTokenExtractor( httpClient, tokenValidationParameters, _toBotFromEmulatorOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfiguration.RequiredEndorsements).ConfigureAwait(false); await SkillValidation_ValidateIdentityAsync(identity, credentialFactory, cancellationToken).ConfigureAwait(false); return identity; } private async Task SkillValidation_ValidateIdentityAsync(ClaimsIdentity identity, ServiceClientCredentialsFactory credentialFactory, CancellationToken cancellationToken) { if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException("Invalid Identity"); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException("Token Not Authenticated"); } var versionClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.VersionClaim); if (versionClaim == null) { // No version claim throw new UnauthorizedAccessException($"'{AuthenticationConstants.VersionClaim}' claim is required on skill Tokens."); } // Look for the "aud" claim, but only if issued from the Bot Framework var audienceClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AudienceClaim)?.Value; if (string.IsNullOrWhiteSpace(audienceClaim)) { // Claim is not present or doesn't have a value. Not Authorized. throw new UnauthorizedAccessException($"'{AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens."); } if (!await credentialFactory.IsValidAppIdAsync(audienceClaim, cancellationToken).ConfigureAwait(false)) { // The AppId is not valid. Not Authorized. throw new UnauthorizedAccessException("Invalid audience."); } var appId = JwtTokenValidation.GetAppIdFromClaims(identity.Claims); if (string.IsNullOrWhiteSpace(appId)) { // Invalid appId throw new UnauthorizedAccessException("Invalid appId."); } } // The following code is based on EmulatorValidation.AuthenticateEmulatorToken private async Task<ClaimsIdentity> EmulatorValidation_AuthenticateEmulatorTokenAsync(string authHeader, ServiceClientCredentialsFactory credentialFactory, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfiguration, CancellationToken cancellationToken) { var toBotFromEmulatorTokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuers = new[] { "https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/", // Auth v3.1, 1.0 token "https://login.microsoftonline.com/d6d49420-f39b-4df7-a1dc-d59a935871db/v2.0", // Auth v3.1, 2.0 token "https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/", // Auth v3.2, 1.0 token "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0", // Auth v3.2, 2.0 token "https://sts.windows.net/cab8a31a-1906-4287-a0d8-4eef66b95f6e/", // Auth for US Gov, 1.0 token "https://login.microsoftonline.us/cab8a31a-1906-4287-a0d8-4eef66b95f6e/v2.0", // Auth for US Gov, 2.0 token }, ValidateAudience = false, // Audience validation takes place manually in code. ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5), RequireSignedTokens = true, }; var tokenExtractor = new JwtTokenExtractor( httpClient, toBotFromEmulatorTokenValidationParameters, _toBotFromEmulatorOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfiguration.RequiredEndorsements).ConfigureAwait(false); if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException("Invalid Identity"); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException("Token Not Authenticated"); } // Now check that the AppID in the claimset matches // what we're looking for. Note that in a multi-tenant bot, this value // comes from developer code that may be reaching out to a service, hence the // Async validation. Claim versionClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.VersionClaim); if (versionClaim == null) { throw new UnauthorizedAccessException("'ver' claim is required on Emulator Tokens."); } string tokenVersion = versionClaim.Value; string appID = string.Empty; // The Emulator, depending on Version, sends the AppId via either the // appid claim (Version 1) or the Authorized Party claim (Version 2). if (string.IsNullOrWhiteSpace(tokenVersion) || tokenVersion == "1.0") { // either no Version or a version of "1.0" means we should look for // the claim in the "appid" claim. Claim appIdClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AppIdClaim); if (appIdClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'appid' claim is required on Emulator Token version '1.0'."); } appID = appIdClaim.Value; } else if (tokenVersion == "2.0") { // Emulator, "2.0" puts the AppId in the "azp" claim. Claim appZClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AuthorizedParty); if (appZClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'azp' claim is required on Emulator Token version '2.0'."); } appID = appZClaim.Value; } else { // Unknown Version. Not Authorized. throw new UnauthorizedAccessException($"Unknown Emulator Token version '{tokenVersion}'."); } if (!await credentialFactory.IsValidAppIdAsync(appID, cancellationToken).ConfigureAwait(false)) { throw new UnauthorizedAccessException($"Invalid AppId passed on token: {appID}"); } return identity; } // The following code is based on GovernmentChannelValidation.AuthenticateChannelToken private async Task<ClaimsIdentity> GovernmentChannelValidation_AuthenticateChannelTokenAsync(string authHeader, ServiceClientCredentialsFactory credentialFactory, string serviceUrl, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig, CancellationToken cancellationToken) { var tokenValidationParameters = GovernmentChannelValidation_GetTokenValidationParameters(); var tokenExtractor = new JwtTokenExtractor( httpClient, tokenValidationParameters, _toBotFromChannelOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false); await GovernmentChannelValidation_ValidateIdentityAsync(identity, credentialFactory, serviceUrl, cancellationToken).ConfigureAwait(false); return identity; } private TokenValidationParameters GovernmentChannelValidation_GetTokenValidationParameters() { return new TokenValidationParameters() { ValidateIssuer = true, ValidIssuers = new[] { _toBotFromChannelTokenIssuer }, // Audience validation takes place in JwtTokenExtractor ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5), RequireSignedTokens = true, ValidateIssuerSigningKey = true, }; } private async Task GovernmentChannelValidation_ValidateIdentityAsync(ClaimsIdentity identity, ServiceClientCredentialsFactory credentialFactory, string serviceUrl, CancellationToken cancellationToken) { if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException(); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException(); } // Now check that the AppID in the claimset matches // what we're looking for. Note that in a multi-tenant bot, this value // comes from developer code that may be reaching out to a service, hence the // Async validation. // Look for the "aud" claim, but only if issued from the Bot Framework var audienceClaim = identity.Claims.FirstOrDefault( c => c.Issuer == _toBotFromChannelTokenIssuer && c.Type == AuthenticationConstants.AudienceClaim); if (audienceClaim == null) { // The relevant audience Claim MUST be present. Not Authorized. throw new UnauthorizedAccessException(); } // The AppId from the claim in the token must match the AppId specified by the developer. // In this case, the token is destined for the app, so we find the app ID in the audience claim. var appIdFromClaim = audienceClaim.Value; if (string.IsNullOrWhiteSpace(appIdFromClaim)) { // Claim is present, but doesn't have a value. Not Authorized. throw new UnauthorizedAccessException(); } if (!await credentialFactory.IsValidAppIdAsync(appIdFromClaim, cancellationToken).ConfigureAwait(false)) { // The AppId is not valid. Not Authorized. throw new UnauthorizedAccessException($"Invalid AppId passed on token: {appIdFromClaim}"); } if (serviceUrl != null) { var serviceUrlClaim = identity.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.ServiceUrlClaim)?.Value; if (string.IsNullOrWhiteSpace(serviceUrlClaim)) { // Claim must be present. Not Authorized. throw new UnauthorizedAccessException(); } if (!string.Equals(serviceUrlClaim, serviceUrl, StringComparison.OrdinalIgnoreCase)) { // Claim must match. Not Authorized. throw new UnauthorizedAccessException(); } } } } }
51.97931
307
0.649816
[ "MIT" ]
HainanZhao/botbuilder-dotnet
libraries/Microsoft.Bot.Connector/Authentication/ParameterizedBotFrameworkAuthentication.cs
22,613
C#
#pragma checksum "C:\Users\veget\source\repos\FilmCatalog\FilmCatalog\Views\Movie\NotFound.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a21af20fa90f4bf76ec0ef21211f40d04d4aeed8" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Movie_NotFound), @"mvc.1.0.view", @"/Views/Movie/NotFound.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\veget\source\repos\FilmCatalog\FilmCatalog\Views\_ViewImports.cshtml" using FilmCatalog.Models; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\veget\source\repos\FilmCatalog\FilmCatalog\Views\_ViewImports.cshtml" using FilmCatalog.ViewModel; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\veget\source\repos\FilmCatalog\FilmCatalog\Views\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a21af20fa90f4bf76ec0ef21211f40d04d4aeed8", @"/Views/Movie/NotFound.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b28716dd884164fcf2c46c1411fc873b18591489", @"/Views/_ViewImports.cshtml")] public class Views_Movie_NotFound : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("<div class=\"container\">\r\n <div class=\"text-center\">\r\n <h2>Такого фильма не найдено.</h2>\r\n </div>\r\n</div>"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
50.135593
182
0.760649
[ "Unlicense" ]
evilvegetarian/FilmCatalog
FilmCatalog/obj/Debug/net5.0/Razor/Views/Movie/NotFound.cshtml.g.cs
2,979
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.TestSupport.Configuration; using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration; using Microsoft.Practices.EnterpriseLibrary.Validation.Tests.Properties; using Microsoft.Practices.EnterpriseLibrary.Validation.TestSupport.Configuration; using Microsoft.Practices.EnterpriseLibrary.Validation.TestSupport.TestClasses; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.EnterpriseLibrary.Validation.Tests.Configuration { [TestClass] public class ValidatorDataFixture { [TestMethod] public void CanDeserializeSerializedInstanceWithNameAndType() { MockValidationSettings rwSettings = new MockValidationSettings(); ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwSettings.Validators.Add(rwValidatorData); IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>(); sections[ValidationSettings.SectionName] = rwSettings; using (ConfigurationFileHelper configurationFileHelper = new ConfigurationFileHelper(sections)) { IConfigurationSource configurationSource = configurationFileHelper.ConfigurationSource; MockValidationSettings roSettings = configurationSource.GetSection(ValidationSettings.SectionName) as MockValidationSettings; Assert.IsNotNull(roSettings); Assert.AreEqual(1, roSettings.Validators.Count); Assert.AreEqual("validator1", roSettings.Validators.Get(0).Name); Assert.AreSame(typeof(MockValidator), roSettings.Validators.Get(0).Type); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplate); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceTypeName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).Tag); } } [TestMethod] public void CanDeserializeSerializedInstanceWithNameAndTypeAndMessageTemplate() { MockValidationSettings rwSettings = new MockValidationSettings(); ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwSettings.Validators.Add(rwValidatorData); rwValidatorData.MessageTemplate = "message template"; IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>(); sections[ValidationSettings.SectionName] = rwSettings; using (ConfigurationFileHelper configurationFileHelper = new ConfigurationFileHelper(sections)) { IConfigurationSource configurationSource = configurationFileHelper.ConfigurationSource; MockValidationSettings roSettings = configurationSource.GetSection(ValidationSettings.SectionName) as MockValidationSettings; Assert.IsNotNull(roSettings); Assert.AreEqual(1, roSettings.Validators.Count); Assert.AreEqual("validator1", roSettings.Validators.Get(0).Name); Assert.AreSame(typeof(MockValidator), roSettings.Validators.Get(0).Type); Assert.AreEqual("message template", roSettings.Validators.Get(0).MessageTemplate); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceTypeName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).Tag); } } [TestMethod] public void CanDeserializeSerializedInstanceWithNameAndTypeAndResourceMessageTemplateInformation() { MockValidationSettings rwSettings = new MockValidationSettings(); ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwSettings.Validators.Add(rwValidatorData); rwValidatorData.MessageTemplateResourceName = "message template name"; rwValidatorData.MessageTemplateResourceTypeName = "my type"; IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>(); sections[ValidationSettings.SectionName] = rwSettings; using (ConfigurationFileHelper configurationFileHelper = new ConfigurationFileHelper(sections)) { IConfigurationSource configurationSource = configurationFileHelper.ConfigurationSource; MockValidationSettings roSettings = configurationSource.GetSection(ValidationSettings.SectionName) as MockValidationSettings; Assert.IsNotNull(roSettings); Assert.AreEqual(1, roSettings.Validators.Count); Assert.AreEqual("validator1", roSettings.Validators.Get(0).Name); Assert.AreSame(typeof(MockValidator), roSettings.Validators.Get(0).Type); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplate); Assert.AreEqual("message template name", roSettings.Validators.Get(0).MessageTemplateResourceName); Assert.AreEqual("my type", roSettings.Validators.Get(0).MessageTemplateResourceTypeName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).Tag); } } [TestMethod] public void CanDeserializeSerializedInstanceWithNameAndTypeAndTag() { MockValidationSettings rwSettings = new MockValidationSettings(); ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwSettings.Validators.Add(rwValidatorData); rwValidatorData.Tag = "tag"; IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>(); sections[ValidationSettings.SectionName] = rwSettings; using (ConfigurationFileHelper configurationFileHelper = new ConfigurationFileHelper(sections)) { IConfigurationSource configurationSource = configurationFileHelper.ConfigurationSource; MockValidationSettings roSettings = configurationSource.GetSection(ValidationSettings.SectionName) as MockValidationSettings; Assert.IsNotNull(roSettings); Assert.AreEqual(1, roSettings.Validators.Count); Assert.AreEqual("validator1", roSettings.Validators.Get(0).Name); Assert.AreSame(typeof(MockValidator), roSettings.Validators.Get(0).Type); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplate); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceName); Assert.AreEqual(string.Empty, roSettings.Validators.Get(0).MessageTemplateResourceTypeName); Assert.AreEqual("tag", roSettings.Validators.Get(0).Tag); } } [TestMethod] public void GetsNullForMessageTemplateIfNeitherLiteralOrResourceTemplateIsSet() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); Assert.AreEqual(null, rwValidatorData.GetMessageTemplate()); } [TestMethod] public void GetsLiteralTemplateForMessageTemplateIfLiteralTemplateIsSet() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwValidatorData.MessageTemplate = "message template"; Assert.AreEqual("message template", rwValidatorData.GetMessageTemplate()); } [TestMethod] public void GetsResourceBasedTemplateForMessageTemplateIfResourceBasedTemplateTypeAndNameAreSet() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwValidatorData.MessageTemplateResourceName = "TestMessageTemplate"; rwValidatorData.MessageTemplateResourceTypeName = typeof(Resources).AssemblyQualifiedName; Assert.AreEqual(Resources.TestMessageTemplate, rwValidatorData.GetMessageTemplate()); } [TestMethod] public void GetsLiteralTemplateForMessageTemplateIfBothLiteralOrResourceTemplateAreSet() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwValidatorData.MessageTemplate = "message template"; rwValidatorData.MessageTemplateResourceName = "TestMessageTemplate"; rwValidatorData.MessageTemplateResourceTypeName = typeof(Resources).AssemblyQualifiedName; Assert.AreEqual("message template", rwValidatorData.GetMessageTemplate()); } [TestMethod] public void CreatesValidatorWithNullTagIfTagNotSet() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); Validator validator = ((IValidatorDescriptor)rwValidatorData).CreateValidator(null, null, null, null); Assert.AreEqual(string.Empty, rwValidatorData.Tag); Assert.IsNotNull(validator); Assert.IsNull(validator.Tag); } [TestMethod] public void CreatesValidatorWithTagIfTagSet() { string tag = new string(new char[] { 'a', 'b', 'c' }); ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwValidatorData.Tag = tag; Validator validator = ((IValidatorDescriptor)rwValidatorData).CreateValidator(null, null, null, null); Assert.IsNotNull(validator); Assert.AreSame(tag, validator.Tag); } [TestMethod] public void CreatesValidatorWithSpecifiedTemplate() { ValidatorData rwValidatorData = new MockValidatorData("validator1", false); rwValidatorData.MessageTemplateResourceName = "TestMessageTemplate"; rwValidatorData.MessageTemplateResourceTypeName = typeof(Resources).AssemblyQualifiedName; Validator validator = ((IValidatorDescriptor)rwValidatorData).CreateValidator(null, null, null, null); Assert.IsNotNull(validator); Assert.AreEqual(Resources.TestMessageTemplate, validator.MessageTemplate); } } }
51.990338
141
0.702565
[ "Apache-2.0" ]
EnterpriseLibrary/validation-application-block
source/Tests/Validation.Tests/Configuration/ValidatorDataFixture.cs
10,762
C#
// Copyright (c) 2010-2014 SharpDX - 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. using System; namespace SharpDX.Direct3D11 { public partial class ResourceView { /// <summary> /// <p>Get the resource that is accessed through this view.</p> /// </summary> /// <remarks> /// <p>This function increments the reference count of the resource by one, so it is necessary to call <strong>Release</strong> on the returned reference when the application is done with it. Destroying (or losing) the returned reference before <strong>Release</strong> is called will result in a memory leak.</p> /// </remarks> /// <msdn-id>ff476643</msdn-id> /// <unmanaged>GetResource</unmanaged> /// <unmanaged-short>GetResource</unmanaged-short> /// <unmanaged>void ID3D11View::GetResource([Out] ID3D11Resource** ppResource)</unmanaged> public SharpDX.Direct3D11.Resource Resource { get { IntPtr __output__; GetResource(out __output__); return new Resource(__output__); } } /// <summary> /// <p>Get the resource that is accessed through this view.</p> /// </summary> /// <remarks> /// <p>This function increments the reference count of the resource by one, so it is necessary to call <strong>Dispose</strong> on the returned reference when the application is done with it. Destroying (or losing) the returned reference before <strong>Release</strong> is called will result in a memory leak.</p> /// </remarks> /// <msdn-id>ff476643</msdn-id> /// <unmanaged>GetResource</unmanaged> /// <unmanaged-short>GetResource</unmanaged-short> /// <unmanaged>void ID3D11View::GetResource([Out] ID3D11Resource** ppResource)</unmanaged> public T ResourceAs<T>() where T : Resource { IntPtr resourcePtr; GetResource(out resourcePtr); return As<T>(resourcePtr); } } }
49.046875
322
0.664861
[ "MIT" ]
Altair7610/SharpDX
Source/SharpDX.Direct3D11/ResourceView.cs
3,141
C#
using System.Net.Http; using CoreLayer.Citrix.Adc.NitroClient.Interfaces; namespace CoreLayer.Citrix.Adc.NitroClient.Api.Configuration.System.SystemFile { public class SystemFileAddRequestConfiguration : NitroRequestConfiguration { public override HttpMethod Method => HttpMethod.Post; public override string ResourcePath => "/nitro/v1/config/systemfile"; public override INitroRequestOptions Options => new SystemFileAddRequestOptions(); public override INitroRequestDataRoot DataRoot { get; } public SystemFileAddRequestConfiguration(SystemFileAddRequestDataRoot dataRoot) { DataRoot = dataRoot; } } }
38.055556
90
0.741606
[ "Apache-2.0" ]
CoreLayer/CoreLayer.Citrix.Adc.Nitro
src/CoreLayer.Citrix.Adc.NitroClient/Api/Configuration/System/SystemFile/SystemFileAddRequestConfiguration.cs
685
C#
using UnityEngine; using TMPro; namespace Voxels.Game { public sealed class PlayerNamePresenter : MonoBehaviour { public TMP_Text NameLabel = null; public PlayerMovement Owner = null; void Start() { NameLabel.text = Owner.PlayerName; } } }
17.733333
58
0.703008
[ "MIT" ]
TxN/VoxelLand
Assets/Scripts/ClientOnly/Game/PlayerNamePresenter.cs
266
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using OmniSharp.Helpers; using OmniSharp.Models.Diagnostics; using OmniSharp.Options; using OmniSharp.Roslyn.CSharp.Services.Diagnostics; namespace OmniSharp.Roslyn.CSharp.Workers.Diagnostics { public class CSharpDiagnosticWorker: ICsDiagnosticWorker, IDisposable { private readonly ILogger _logger; private readonly OmniSharpWorkspace _workspace; private readonly DiagnosticEventForwarder _forwarder; private readonly OmniSharpOptions _options; private readonly IObserver<string> _openDocuments; private readonly IDisposable _disposable; public CSharpDiagnosticWorker(OmniSharpWorkspace workspace, DiagnosticEventForwarder forwarder, ILoggerFactory loggerFactory, OmniSharpOptions options) { _workspace = workspace; _forwarder = forwarder; _logger = loggerFactory.CreateLogger<CSharpDiagnosticWorker>(); _options = options; var openDocumentsSubject = new Subject<string>(); _openDocuments = openDocumentsSubject; _workspace.WorkspaceChanged += OnWorkspaceChanged; _workspace.DocumentOpened += OnDocumentOpened; _workspace.DocumentClosed += OnDocumentOpened; _disposable = openDocumentsSubject .Buffer(() => Observable.Amb( openDocumentsSubject.Skip(99).Select(z => Unit.Default), Observable.Timer(TimeSpan.FromMilliseconds(100)).Select(z => Unit.Default) )) .SubscribeOn(TaskPoolScheduler.Default) .Select(ProcessQueue) .Merge() .Subscribe(); } private void OnDocumentOpened(object sender, DocumentEventArgs args) { if (!_forwarder.IsEnabled) { return; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs changeEvent) { if (!_forwarder.IsEnabled) { return; } if (changeEvent.Kind == WorkspaceChangeKind.DocumentAdded || changeEvent.Kind == WorkspaceChangeKind.DocumentChanged || changeEvent.Kind == WorkspaceChangeKind.DocumentReloaded) { var newDocument = changeEvent.NewSolution.GetDocument(changeEvent.DocumentId); EmitDiagnostics(new [] {newDocument.Id}.Union(_workspace.GetOpenDocumentIds()).Select(x => _workspace.CurrentSolution.GetDocument(x).FilePath).ToArray()); } else if (changeEvent.Kind == WorkspaceChangeKind.ProjectAdded || changeEvent.Kind == WorkspaceChangeKind.ProjectReloaded) { EmitDiagnostics(changeEvent.NewSolution.GetProject(changeEvent.ProjectId).Documents.Select(x => x.FilePath).ToArray()); } } public void QueueDiagnostics(params string[] documents) { if (!_forwarder.IsEnabled) { return; } this.EmitDiagnostics(documents); } private void EmitDiagnostics(params string[] documents) { if (!_forwarder.IsEnabled) { return; } foreach (var document in documents) { _openDocuments.OnNext(document); } } private IObservable<Unit> ProcessQueue(IEnumerable<string> filePaths) { return Observable.FromAsync(async () => { var results = await Task.WhenAll(filePaths.Distinct().Select(ProcessNextItem)); var message = new DiagnosticMessage() { Results = results }; _forwarder.Forward(message); }); } private async Task<DiagnosticResult> ProcessNextItem(string filePath) { var documents = _workspace.GetDocuments(filePath); var semanticModels = await Task.WhenAll(documents.Select(doc => doc.GetSemanticModelAsync())); var items = semanticModels .SelectMany(sm => sm.GetDiagnostics()); return new DiagnosticResult() { FileName = filePath, QuickFixes = items.Select(x => x.ToDiagnosticLocation()).Distinct().ToArray() }; } public ImmutableArray<DocumentId> QueueForDiagnosis(ImmutableArray<string> documentPaths) { this.EmitDiagnostics(documentPaths.ToArray()); return ImmutableArray<DocumentId>.Empty; } public async Task<ImmutableArray<DocumentDiagnostics>> GetDiagnostics(ImmutableArray<string> documentPaths) { if (!documentPaths.Any()) return ImmutableArray<DocumentDiagnostics>.Empty; var results = ImmutableList<DocumentDiagnostics>.Empty; var documents = (await Task.WhenAll( documentPaths .Select(docPath => _workspace.GetDocumentsFromFullProjectModelAsync(docPath))) ).SelectMany(s => s); var diagnosticTasks = new List<Task>(); var throttler = new SemaphoreSlim(_options.RoslynExtensionsOptions.DiagnosticWorkersThreadCount); foreach (var document in documents) { if(document?.Project?.Name == null) continue; var projectName = document.Project.Name; await throttler.WaitAsync(); diagnosticTasks.Add( Task.Run(async () => { try { var diagnostics = await GetDiagnosticsForDocument(document, projectName); var documentDiagnostics = new DocumentDiagnostics(document.Id, document.FilePath, document.Project.Id, document.Project.Name, diagnostics); ImmutableInterlocked.Update(ref results, currentResults => currentResults.Add(documentDiagnostics)); } finally { throttler.Release(); } } ) ); } await Task.WhenAll(diagnosticTasks); return results.ToImmutableArray(); } private static async Task<ImmutableArray<Diagnostic>> GetDiagnosticsForDocument(Document document, string projectName) { // Only basic syntax check is available if file is miscellanous like orphan .cs file. // Those projects are on hard coded virtual project if (projectName == $"{Configuration.OmniSharpMiscProjectName}.csproj") { var syntaxTree = await document.GetSyntaxTreeAsync(); return syntaxTree.GetDiagnostics().ToImmutableArray(); } else { var semanticModel = await document.GetSemanticModelAsync(); return semanticModel.GetDiagnostics(); } } public ImmutableArray<DocumentId> QueueDocumentsForDiagnostics() { var documents = _workspace.CurrentSolution.Projects.SelectMany(x => x.Documents); QueueForDiagnosis(documents.Select(x => x.FilePath).ToImmutableArray()); return documents.Select(x => x.Id).ToImmutableArray(); } public ImmutableArray<DocumentId> QueueDocumentsForDiagnostics(ImmutableArray<ProjectId> projectIds) { var documents = projectIds.SelectMany(projectId => _workspace.CurrentSolution.GetProject(projectId).Documents); QueueForDiagnosis(documents.Select(x => x.FilePath).ToImmutableArray()); return documents.Select(x => x.Id).ToImmutableArray(); } public Task<ImmutableArray<DocumentDiagnostics>> GetAllDiagnosticsAsync() { var documents = _workspace.CurrentSolution.Projects.SelectMany(x => x.Documents).Select(x => x.FilePath).ToImmutableArray(); return GetDiagnostics(documents); } public void Dispose() { _workspace.WorkspaceChanged -= OnWorkspaceChanged; _workspace.DocumentOpened -= OnDocumentOpened; _workspace.DocumentClosed -= OnDocumentOpened; _disposable.Dispose(); } public async Task<IEnumerable<Diagnostic>> AnalyzeDocumentAsync(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await GetDiagnosticsForDocument(document, document.Project.Name); } public async Task<IEnumerable<Diagnostic>> AnalyzeProjectsAsync(Project project, CancellationToken cancellationToken) { var diagnostics = new List<Diagnostic>(); foreach (var document in project.Documents) { cancellationToken.ThrowIfCancellationRequested(); diagnostics.AddRange(await GetDiagnosticsForDocument(document, project.Name)); } return diagnostics; } } }
39.369919
189
0.603304
[ "MIT" ]
ScriptBox99/omnisharp-roslyn
src/OmniSharp.Roslyn.CSharp/Workers/Diagnostics/CSharpDiagnosticWorker.cs
9,685
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.ResourceManager.DigitalTwins.Models { /// <summary> A list of DigitalTwinsInstance Endpoints with a next link. </summary> public partial class DigitalTwinsEndpointResourceListResult { /// <summary> Initializes a new instance of DigitalTwinsEndpointResourceListResult. </summary> internal DigitalTwinsEndpointResourceListResult() { } /// <summary> Initializes a new instance of DigitalTwinsEndpointResourceListResult. </summary> /// <param name="nextLink"> The link used to get the next page of DigitalTwinsInstance Endpoints. </param> /// <param name="value"> A list of DigitalTwinsInstance Endpoints. </param> internal DigitalTwinsEndpointResourceListResult(string nextLink, IReadOnlyList<DigitalTwinsEndpointResource> value) { NextLink = nextLink; Value = value; } /// <summary> The link used to get the next page of DigitalTwinsInstance Endpoints. </summary> public string NextLink { get; } /// <summary> A list of DigitalTwinsInstance Endpoints. </summary> public IReadOnlyList<DigitalTwinsEndpointResource> Value { get; } } }
39.257143
123
0.700873
[ "MIT" ]
Expensya/azure-sdk-for-net
sdk/digitaltwins/Azure.ResourceManager.DigitalTwins/src/Generated/Models/DigitalTwinsEndpointResourceListResult.cs
1,374
C#
// <copyright file="Stability.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2010 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; #if !NOSYSNUMERICS using System.Numerics; #endif // ReSharper disable CheckNamespace namespace MathNet.Numerics // ReSharper restore CheckNamespace { public partial class SpecialFunctions { /// <summary> /// Numerically stable exponential minus one, i.e. <code>x -> exp(x)-1</code> /// </summary> /// <param name="power">A number specifying a power.</param> /// <returns>Returns <code>exp(power)-1</code>.</returns> public static double ExponentialMinusOne(double power) { double x = Math.Abs(power); if (x > 0.1) { return Math.Exp(power) - 1.0; } if (x < x.PositiveEpsilonOf()) { return x; } // Series Expansion to x^k / k! int k = 0; double term = 1.0; return Evaluate.Series( () => { k++; term *= power; term /= k; return term; }); } /// <summary> /// Numerically stable hypotenuse of a right angle triangle, i.e. <code>(a,b) -> sqrt(a^2 + b^2)</code> /// </summary> /// <param name="a">The length of side a of the triangle.</param> /// <param name="b">The length of side b of the triangle.</param> /// <returns>Returns <code>sqrt(a<sup>2</sup> + b<sup>2</sup>)</code> without underflow/overflow.</returns> public static Complex Hypotenuse(Complex a, Complex b) { if (a.Magnitude > b.Magnitude) { var r = b.Magnitude/a.Magnitude; return a.Magnitude*Math.Sqrt(1 + (r*r)); } if (b != 0.0) { // NOTE (ruegg): not "!b.AlmostZero()" to avoid convergence issues (e.g. in SVD algorithm) var r = a.Magnitude/b.Magnitude; return b.Magnitude*Math.Sqrt(1 + (r*r)); } return 0d; } /// <summary> /// Numerically stable hypotenuse of a right angle triangle, i.e. <code>(a,b) -> sqrt(a^2 + b^2)</code> /// </summary> /// <param name="a">The length of side a of the triangle.</param> /// <param name="b">The length of side b of the triangle.</param> /// <returns>Returns <code>sqrt(a<sup>2</sup> + b<sup>2</sup>)</code> without underflow/overflow.</returns> public static Complex32 Hypotenuse(Complex32 a, Complex32 b) { if (a.Magnitude > b.Magnitude) { var r = b.Magnitude/a.Magnitude; return a.Magnitude*(float)Math.Sqrt(1 + (r*r)); } if (b != 0.0f) { // NOTE (ruegg): not "!b.AlmostZero()" to avoid convergence issues (e.g. in SVD algorithm) var r = a.Magnitude/b.Magnitude; return b.Magnitude*(float)Math.Sqrt(1 + (r*r)); } return 0f; } /// <summary> /// Numerically stable hypotenuse of a right angle triangle, i.e. <code>(a,b) -> sqrt(a^2 + b^2)</code> /// </summary> /// <param name="a">The length of side a of the triangle.</param> /// <param name="b">The length of side b of the triangle.</param> /// <returns>Returns <code>sqrt(a<sup>2</sup> + b<sup>2</sup>)</code> without underflow/overflow.</returns> public static double Hypotenuse(double a, double b) { if (Math.Abs(a) > Math.Abs(b)) { double r = b/a; return Math.Abs(a)*Math.Sqrt(1 + (r*r)); } if (b != 0.0) { // NOTE (ruegg): not "!b.AlmostZero()" to avoid convergence issues (e.g. in SVD algorithm) double r = a/b; return Math.Abs(b)*Math.Sqrt(1 + (r*r)); } return 0d; } /// <summary> /// Numerically stable hypotenuse of a right angle triangle, i.e. <code>(a,b) -> sqrt(a^2 + b^2)</code> /// </summary> /// <param name="a">The length of side a of the triangle.</param> /// <param name="b">The length of side b of the triangle.</param> /// <returns>Returns <code>sqrt(a<sup>2</sup> + b<sup>2</sup>)</code> without underflow/overflow.</returns> public static float Hypotenuse(float a, float b) { if (Math.Abs(a) > Math.Abs(b)) { float r = b/a; return Math.Abs(a)*(float)Math.Sqrt(1 + (r*r)); } if (b != 0.0) { // NOTE (ruegg): not "!b.AlmostZero()" to avoid convergence issues (e.g. in SVD algorithm) float r = a/b; return Math.Abs(b)*(float)Math.Sqrt(1 + (r*r)); } return 0f; } } }
37.093567
115
0.541384
[ "MIT" ]
MattHeffron/mathnet-numerics
src/Numerics/SpecialFunctions/Stability.cs
6,343
C#
using System; using System.Collections.Generic; using System.Windows.Forms; namespace truckersmplauncher { public partial class Settings : Form { Dictionary<string, string> ETS2Config = new Dictionary<string, string>(); Dictionary<string, string> ATSConfig = new Dictionary<string, string>(); public Settings() { InitializeComponent(); this.FormClosed += new FormClosedEventHandler(Done_btn_Click); ETS2Config = Game.getConfig("ETS2"); ATSConfig = Game.getConfig("ATS"); //Launcher LauncherClose_chkbox.Checked = Properties.Settings.Default.closeLauncher; closeDelay_numeric.Value = Properties.Settings.Default.closeDelay; AutoUpdate_chkbox.Checked = Properties.Settings.Default.AutoUpdateLauncher; StartSteam_chkbox.Checked = Properties.Settings.Default.StartSteam; if (Properties.Settings.Default.mode.Equals("advanced")) advancedLauncher_btn.Checked = true; else if (Properties.Settings.Default.mode.Equals("simple")) simpleLauncher_btn.Checked = true; //ETS2 ets2sin_chkbox.Checked = Properties.Settings.Default.ETS2NoIntro; ets2_launchargs.Text = Properties.Settings.Default.ETS2LaunchArguments; if (ETS2Config != null) { ets2_gameoptions.Visible = true; ets_save_format.Text = ETS2Config["g_save_format"]; ets2_console.Checked = Convert.ToBoolean(Convert.ToInt32(ETS2Config["g_console"])); ets2_online_loading.Checked = Convert.ToBoolean(Convert.ToInt32(ETS2Config["g_online_loading_screens"])); ets2_traffic.Checked = Convert.ToBoolean(Convert.ToInt32(ETS2Config["g_traffic"].Replace(".0", ""))); ets2_show_fps.Checked = Convert.ToBoolean(Convert.ToInt32(ETS2Config["g_fps"])); } else { ets2_gameoptions.Visible = false; } //ATS atssin_chkbox.Checked = Properties.Settings.Default.ATSNoIntro; ats_launchargs.Text = Properties.Settings.Default.ATSLaunchArguments; if (ATSConfig != null) { ats_gameoptions.Visible = true; ats_save_format.Text = ATSConfig["g_save_format"]; ats_console.Checked = Convert.ToBoolean(Convert.ToInt32(ATSConfig["g_console"])); ats_online_loading.Checked = Convert.ToBoolean(Convert.ToInt32(ATSConfig["g_online_loading_screens"])); ats_traffic.Checked = Convert.ToBoolean(Convert.ToInt32(ATSConfig["g_traffic"].Replace(".0", ""))); ats_show_fps.Checked = Convert.ToBoolean(Convert.ToInt32(ATSConfig["g_fps"])); } else { ats_gameoptions.Visible = false; } } // // Buttons // private void UpdateCheck_btn_Click(object sender, EventArgs e) { checkForUpdates(); } private void Done_btn_Click(object sender, EventArgs e) { //Launcher Properties.Settings.Default.closeLauncher = LauncherClose_chkbox.Checked; Properties.Settings.Default.closeDelay = closeDelay_numeric.Value; Properties.Settings.Default.AutoUpdateLauncher = AutoUpdate_chkbox.Checked; Properties.Settings.Default.StartSteam = StartSteam_chkbox.Checked; if (advancedLauncher_btn.Checked) Properties.Settings.Default.mode = "advanced"; else if (simpleLauncher_btn.Checked) Properties.Settings.Default.mode = "simple"; //ETS2 Properties.Settings.Default.ETS2NoIntro = ets2sin_chkbox.Checked; Properties.Settings.Default.ETS2LaunchArguments = ets2_launchargs.Text; if (ETS2Config != null) { ETS2Config["g_save_format"] = ets_save_format.Text; ETS2Config["g_console"] = (Convert.ToInt32(ets2_console.Checked)).ToString(); ETS2Config["g_developer"] = (Convert.ToInt32(ets2_console.Checked)).ToString(); ETS2Config["g_online_loading_screens"] = (Convert.ToInt32(ets2_online_loading.Checked)).ToString(); ETS2Config["g_traffic"] = (Convert.ToInt32(ets2_traffic.Checked)).ToString(); ETS2Config["g_fps"] = (Convert.ToInt32(ets2_show_fps.Checked)).ToString(); } //ATS Properties.Settings.Default.ATSNoIntro = atssin_chkbox.Checked; Properties.Settings.Default.ATSLaunchArguments = ats_launchargs.Text; if (ATSConfig != null) { ATSConfig["g_save_format"] = ats_save_format.Text; ATSConfig["g_console"] = (Convert.ToInt32(ats_console.Checked)).ToString(); ATSConfig["g_developer"] = (Convert.ToInt32(ats_console.Checked)).ToString(); ATSConfig["g_online_loading_screens"] = (Convert.ToInt32(ats_online_loading.Checked)).ToString(); ATSConfig["g_traffic"] = (Convert.ToInt32(ats_traffic.Checked)).ToString(); ATSConfig["g_fps"] = (Convert.ToInt32(ats_show_fps.Checked)).ToString(); } if (ETS2Config != null) Game.writeConfig("ETS2", ETS2Config); if (ATSConfig != null) Game.writeConfig("ATS", ATSConfig); Properties.Settings.Default.Save(); this.Close(); } // // Functions // private void checkForUpdates() { string latest = Launcher.latestVersion(); string local = Properties.Settings.Default.LauncherVersion; if (latest == "0") { MessageBox.Show("Unable to connect to API.\n\nPlease check your internet connection and try again.", "TruckersMP Launcher", MessageBoxButtons.YesNo, MessageBoxIcon.Error); return; } if ( !(string.Compare(latest, local, true) > 0)) { MessageBox.Show("Current version is: " + local + "\nLatest version is: " + latest + "\n\nYou already have the newest version!\nThere is no need for you to update!", "TruckersMP Launcher", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { Launcher.update(); } } } }
45.360544
255
0.595381
[ "MIT" ]
TheUnknownKiller/ETS2MPLauncher
Source/Settings.cs
6,670
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 Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Microsoft.EntityFrameworkCore { public class SqlServerOptionsExtensionTest { [ConditionalFact] public void ApplyServices_adds_SQL_server_services() { var services = new ServiceCollection(); new SqlServerOptionsExtension().ApplyServices(services); Assert.True(services.Any(sd => sd.ServiceType == typeof(ISqlServerConnection))); } [ConditionalFact] public void Changing_RowNumberPagingEnabled_causes_new_service_provider_to_be_built() { ISqlServerOptions singletonOptions; using (var context = new ChangedRowNumberContext(rowNumberPagingEnabled: false, setInternalServiceProvider: false)) { _ = context.Model; singletonOptions = context.GetService<ISqlServerOptions>(); Assert.False(singletonOptions.RowNumberPagingEnabled); } using (var context = new ChangedRowNumberContext(rowNumberPagingEnabled: true, setInternalServiceProvider: false)) { _ = context.Model; var newOptions = context.GetService<ISqlServerOptions>(); Assert.True(newOptions.RowNumberPagingEnabled); Assert.NotSame(newOptions, singletonOptions); } } [ConditionalFact] public void Changing_RowNumberPagingEnabled_when_UseInternalServiceProvider_throws() { using (var context = new ChangedRowNumberContext(rowNumberPagingEnabled: false, setInternalServiceProvider: true)) { _ = context.Model; } using (var context = new ChangedRowNumberContext(rowNumberPagingEnabled: true, setInternalServiceProvider: true)) { Assert.Equal( CoreStrings.SingletonOptionChanged( nameof(SqlServerDbContextOptionsBuilder.UseRowNumberForPaging), nameof(DbContextOptionsBuilder.UseInternalServiceProvider)), Assert.Throws<InvalidOperationException>(() => context.Model).Message); } } private class ChangedRowNumberContext : DbContext { private static readonly IServiceProvider _serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .BuildServiceProvider(); private readonly bool _rowNumberPagingEnabled; private readonly bool _setInternalServiceProvider; public ChangedRowNumberContext(bool rowNumberPagingEnabled, bool setInternalServiceProvider) { _rowNumberPagingEnabled = rowNumberPagingEnabled; _setInternalServiceProvider = setInternalServiceProvider; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (_setInternalServiceProvider) { optionsBuilder.UseInternalServiceProvider(_serviceProvider); } optionsBuilder .UseSqlServer( "Database=Maltesers", b => { if (_rowNumberPagingEnabled) { b.UseRowNumberForPaging(); } }); } } } }
39.105769
127
0.619621
[ "Apache-2.0" ]
CharlieRoseMarie/EntityFrameworkCore
test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs
4,067
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bar = TradingClient.Data.Contracts.Bar; using TradingClient.Data.Contracts; using TradingClient.DataProvider.TradingService; namespace TradingClient.DataProvider { internal class HistoryRequest { public HistoryRequest() { Bars = new List<Bar>(); } public int Interval { get; set; } public Timeframe Periodicity { get; set; } public int BarsCount { get; set; } public DateTime From { get; set; } public DateTime To { get; set; } public int Level { get; set; } public bool? IncludeWeekendData { get; set; } public List<Bar> Bars { get; } } }
21.216216
53
0.638217
[ "MPL-2.0" ]
NominalNimbus/ClientNimbus
TradingClient.DataProvider/HistoryRequest.cs
787
C#
using UnityEngine; using System.Collections; using UnityEditor; public class SpriteProcessor : AssetPostprocessor { void OnPostprocessTexture(Texture2D texture) { string lowerCaseAssetPath = assetPath.ToLower(); bool isInSpritesDirectory = true; if (isInSpritesDirectory) { TextureImporter textureImporter = (TextureImporter)assetImporter; textureImporter.textureType = TextureImporterType.Sprite; textureImporter.isReadable = true; } AssetDatabase.Refresh(); } }
26.809524
77
0.685613
[ "Apache-2.0" ]
taylordigital13/ARjs_Unity
Editor/SpriteProcessor.cs
565
C#
using System.Collections.Generic; namespace Jerrycurl.Mvc.Test.Project.Accessors { public class MiscAccessor : Accessor { public IList<int> TemplatedQuery() => this.Query<int>(); public IList<int> PartialedQuery() => this.Query<int>(); } }
24.545455
64
0.67037
[ "MIT" ]
rhodosaur/jerrycurl
test/unit/src/Mvc/Jerrycurl.Mvc.Test/Project/Accessors/MiscAccessor.cs
272
C#
using System; using System.IO; using System.Linq; using System.Collections.Generic; using Microsoft.Office.Interop.PowerPoint; using Microsoft.Office.Core; using SoftUniConverterCommon; using static SoftUniConverterCommon.ConverterUtils; using Shape = Microsoft.Office.Interop.PowerPoint.Shape; public class SoftUniPowerPointConverter { static readonly string pptTemplateFileName = Path.GetFullPath(Directory.GetCurrentDirectory() + @"\..\..\..\Document-Templates\SoftUni-Creative-PowerPoint-Template-Nov-2019.pptx"); static readonly string pptSourceFileName = Path.GetFullPath(Directory.GetCurrentDirectory() + @"\..\..\..\Sample-Docs\test3.pptx"); static readonly string pptDestFileName = Directory.GetCurrentDirectory() + @"\converted.pptx"; static void Main() { ConvertAndFixPresentation(pptSourceFileName, pptDestFileName, pptTemplateFileName, true); } public static void ConvertAndFixPresentation(string pptSourceFileName, string pptDestFileName, string pptTemplateFileName, bool appWindowVisible) { if (KillAllProcesses("POWERPNT")) Console.WriteLine("MS PowerPoint (POWERPNT.EXE) is still running -> process terminated."); MsoTriState pptAppWindowsVisible = appWindowVisible ? MsoTriState.msoTrue : MsoTriState.msoFalse; Application pptApp = new Application(); try { Console.WriteLine("Processing input presentation: {0}", pptSourceFileName); Presentation pptSource = pptApp.Presentations.Open( pptSourceFileName, WithWindow: pptAppWindowsVisible); Console.WriteLine("Copying the PPTX template '{0}' as output presentation '{1}'", pptTemplateFileName, pptDestFileName); File.Copy(pptTemplateFileName, pptDestFileName, true); Console.WriteLine($"Opening the output presentation: {pptDestFileName}..."); Presentation pptDestination = pptApp.Presentations.Open( pptDestFileName, WithWindow: pptAppWindowsVisible); List<string> pptTemplateSlideTitles = ExtractSlideTitles(pptDestination); RemoveAllSectionsAndSlides(pptDestination); CopyDocumentProperties(pptSource, pptDestination); CopySlidesAndSections(pptSource, pptDestination); FixCodeBoxes(pptSource, pptDestination); pptSource.Close(); Language lang = DetectPresentationLanguage(pptDestination); FixQuestionsSlide(pptDestination, pptTemplateFileName, pptTemplateSlideTitles, lang); FixLicenseSlide(pptDestination, pptTemplateFileName, pptTemplateSlideTitles, lang); FixAboutSoftUniSlide(pptDestination, pptTemplateFileName, pptTemplateSlideTitles, lang); FixInvalidSlideLayouts(pptDestination); FixSectionTitleSlides(pptDestination); ReplaceIncorrectHyperlinks(pptDestination); FixSlideTitles(pptDestination); FixSlideNumbers(pptDestination); FixSlideNotesPages(pptDestination); pptDestination.Save(); if (!appWindowVisible) pptDestination.Close(); } finally { if (!appWindowVisible) { // Quit the MS Word application pptApp.Quit(); // Release any associated .NET proxies for the COM objects, which are not in use // Intentionally we call the garbace collector twice GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } } static List<Shape> ExtractSlideTitleShapes(Presentation presentation, bool includeSubtitles = false) { List<Shape> slideTitleShapes = new List<Shape>(); foreach (Slide slide in presentation.Slides) { Shape slideTitleShape = null; foreach (Shape shape in slide.Shapes.Placeholders) { if (shape.Type == MsoShapeType.msoPlaceholder) if (shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderTitle) if (shape.HasTextFrame == MsoTriState.msoTrue) slideTitleShape = shape; } if (slideTitleShape == null) { if (slide.Shapes.Placeholders.Count > 0) { Shape firstShape = slide.Shapes.Placeholders[1]; if (firstShape?.HasTextFrame == MsoTriState.msoTrue) slideTitleShape = firstShape; } } slideTitleShapes.Add(slideTitleShape); if (includeSubtitles) { // Extract also subtitles foreach (Shape shape in slide.Shapes.Placeholders) { if (shape.Type == MsoShapeType.msoPlaceholder) if (shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderSubtitle) if (shape.HasTextFrame == MsoTriState.msoTrue) slideTitleShapes.Add(shape); } } } return slideTitleShapes; } static List<string> ExtractSlideTitles(Presentation presentation) { List<Shape> slideTitleShapes = ExtractSlideTitleShapes(presentation); List<string> slideTitles = slideTitleShapes .Select(shape => shape?.TextFrame.TextRange.Text) .ToList(); return slideTitles; } static void RemoveAllSectionsAndSlides(Presentation presentation) { Console.WriteLine("Removing all sections and slides from the template..."); while (presentation.SectionProperties.Count > 0) presentation.SectionProperties.Delete(1, true); } static void CopySlidesAndSections(Presentation pptSource, Presentation pptDestination) { Console.WriteLine("Copying all slides and sections from the source presentation..."); // Copy all slides from the source presentation Console.WriteLine(" Copying all slides from the source presentation..."); pptDestination.Slides.InsertFromFile(pptSource.FullName, 0); // Copy all sections from the source presentation Console.WriteLine(" Copying all sections from the source presentation..."); int sectionSlideIndex = 1; for (int sectNum = 1; sectNum <= pptSource.SectionProperties.Count; sectNum++) { string sectionName = pptSource.SectionProperties.Name(sectNum); sectionName = FixEnglishTitleCharacterCasing(sectionName); if (sectionSlideIndex <= pptDestination.Slides.Count) pptDestination.SectionProperties.AddBeforeSlide(sectionSlideIndex, sectionName); else pptDestination.SectionProperties.AddSection(sectNum, sectionName); sectionSlideIndex += pptSource.SectionProperties.SlidesCount(sectNum); } } static void FixCodeBoxes(Presentation pptSource, Presentation pptDestination) { Console.WriteLine("Fixing source code boxes..."); int slidesCount = pptSource.Slides.Count; for (int slideNum = 1; slideNum <= slidesCount; slideNum++) { Slide newSlide = pptDestination.Slides[slideNum]; if (newSlide.CustomLayout.Name == "Source Code Example") { Slide oldSlide = pptSource.Slides[slideNum]; for (int shapeNum = 1; shapeNum <= newSlide.Shapes.Placeholders.Count; shapeNum++) { Shape newShape = newSlide.Shapes.Placeholders[shapeNum]; if (newShape.HasTextFrame == MsoTriState.msoTrue && newShape.TextFrame.HasText == MsoTriState.msoTrue) { // Found [Code Box] -> copy the paragraph formatting from the original shape Shape oldShape = oldSlide.Shapes.Placeholders[shapeNum]; newShape.TextFrame.TextRange.ParagraphFormat.SpaceBefore = Math.Max(0, oldShape.TextFrame.TextRange.ParagraphFormat.SpaceBefore); newShape.TextFrame.TextRange.ParagraphFormat.SpaceAfter = Math.Max(0, oldShape.TextFrame.TextRange.ParagraphFormat.SpaceAfter); newShape.TextFrame.TextRange.ParagraphFormat.SpaceWithin = Math.Max(0, oldShape.TextFrame.TextRange.ParagraphFormat.SpaceWithin); newShape.TextFrame.TextRange.LanguageID = MsoLanguageID.msoLanguageIDEnglishUS; // newShape.TextFrame.TextRange.NoProofing = MsoTriState.msoTrue; } } Console.WriteLine($" Fixed the code box styling at slide #{slideNum}"); } } } static void CopyDocumentProperties(Presentation pptSource, Presentation pptDestination) { Console.WriteLine("Copying document properties (metadata)..."); object srcDocProperties = pptSource.BuiltInDocumentProperties; string title = GetObjectProperty(srcDocProperties, "Title") ?.ToString()?.Replace(',', ';'); string subject = GetObjectProperty(srcDocProperties, "Subject") ?.ToString()?.Replace(',', ';'); string category = GetObjectProperty(srcDocProperties, "Category") ?.ToString()?.Replace(',', ';'); string keywords = GetObjectProperty(srcDocProperties, "Keywords") ?.ToString()?.Replace(',', ';'); object destDocProperties = pptDestination.BuiltInDocumentProperties; if (!string.IsNullOrWhiteSpace(title)) SetObjectProperty(destDocProperties, "Title", title); if (!string.IsNullOrWhiteSpace(subject)) SetObjectProperty(destDocProperties, "Subject", subject); if (!string.IsNullOrWhiteSpace(category)) SetObjectProperty(destDocProperties, "Category", category); if (!string.IsNullOrWhiteSpace(keywords)) SetObjectProperty(destDocProperties, "Keywords", keywords); } static void FixInvalidSlideLayouts(Presentation presentation) { Console.WriteLine("Fixing the invalid slide layouts..."); var layoutMappings = new Dictionary<string, string> { { "Presentation Title Slide", "Presentation Title Slide" }, { "Section Title Slide", "Section Title Slide" }, { "Section Slide", "Section Title Slide" }, { "Title Slide", "Section Title Slide" }, { "Заглавен слайд", "Section Title Slide" }, { "Demo Slide", "Demo Slide" }, { "Live Exercise Slide", "Section Title Slide" }, { "Background Slide", "Section Title Slide" }, { "Important Concept", "Important Concept" }, { "Important Example", "Important Example" }, { "Table of Content", "Table of Contents" }, { "Table of Contents", "Table of Contents" }, { "Comparison Slide", "Comparison Slide" }, { "Title and Content", "Title and Content" }, { "Заглавие и съдържание", "Title and Content" }, { "Source Code Example", "Source Code Example" }, { "Image and Content", "Image and Content" }, { "Questions Slide", "Questions Slide" }, { "Blank Slide", "Blank Slide" }, { "Block scheme", "Blank Slide" }, { "About Slide", "About Slide" }, { "Last", "About Slide" }, { "Comparison Slide Dark", "Comparison Slide" }, { "", "" }, }; // Add layout names like "1_Section Title Slide", "2_Demo Slide" foreach (string layoutName in layoutMappings.Keys.ToArray()) { var mappedName = layoutMappings[layoutName]; for (int i = 1; i < 99; i++) layoutMappings["" + i + "_" + layoutName] = mappedName; } const string defaultLayoutName = "Title and Content"; var customLayoutsByName = new Dictionary<string, CustomLayout>(); foreach (CustomLayout layout in presentation.SlideMaster.CustomLayouts) customLayoutsByName[layout.Name] = layout; var layoutsForDeleting = new HashSet<string>(); // Replace the incorrect layouts with the correct ones for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { Slide slide = presentation.Slides[slideNum]; string oldLayoutName = slide.CustomLayout.Name; string newLayoutName = defaultLayoutName; if (layoutMappings.ContainsKey(oldLayoutName)) newLayoutName = layoutMappings[oldLayoutName]; if (newLayoutName != oldLayoutName) { Console.WriteLine($" Replacing invalid slide layout \"{oldLayoutName}\" on slide #{slideNum} with \"{newLayoutName}\""); // Replace the old layout with the new layout if (customLayoutsByName.ContainsKey(newLayoutName)) { slide.CustomLayout = customLayoutsByName[newLayoutName]; } else { slide.CustomLayout = customLayoutsByName[defaultLayoutName]; Console.WriteLine($" Cannot find layout [{newLayoutName}] --> using [{defaultLayoutName}] instead"); } layoutsForDeleting.Add(oldLayoutName); } } // Delete all old (and no longer used) layouts foreach (var layoutName in layoutsForDeleting) { Console.WriteLine($" Deleting unused layout \"{layoutName}\""); CustomLayout layout = customLayoutsByName[layoutName]; layout.Delete(); } } static void ReplaceIncorrectHyperlinks(Presentation presentation) { Console.WriteLine("Replacing incorrect hyperlinks in the slides..."); var hyperlinksToReplace = new Dictionary<string, string> { { "http://softuni.bg", "https://softuni.bg" }, { "http://softuni.foundation/", "https://softuni.foundation" }, }; for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { Slide slide = presentation.Slides[slideNum]; foreach (Hyperlink link in slide.Hyperlinks) { try { string linkText = link.TextToDisplay; if (hyperlinksToReplace.ContainsKey(linkText)) { string newText = hyperlinksToReplace[linkText]; link.TextToDisplay = newText; link.Address = newText; } } catch (Exception) { // Ignore silently: cannot change the link for some reason } } } } static void FixSectionTitleSlides(Presentation presentation) { Console.WriteLine("Fixing broken section title slides..."); var sectionTitleSlides = presentation.Slides.Cast<Slide>() .Where(slide => slide.CustomLayout.Name == "Section Title Slide"); foreach (Slide slide in sectionTitleSlides) { // Collect the texts from the slide (expecting title and subtitle) List<string> slideTexts = new List<string>(); foreach (Shape shape in slide.Shapes) { try { if (shape.HasTextFrame == MsoTriState.msoTrue && (shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderTitle || shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderSubtitle || shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderBody) && shape.TextFrame.TextRange.Text != "") { slideTexts.Add(shape.TextFrame.TextRange.Text); shape.Delete(); } } catch (Exception) { // Silently ignore --> the shape is not a placeholder } } // Put the slide texts into the placeholders (and delete the empty placeholders) for (int i = 0; i < slide.Shapes.Placeholders.Count; i++) { Shape placeholder = slide.Shapes.Placeholders[i+1]; if (i < slideTexts.Count) placeholder.TextFrame.TextRange.Text = slideTexts[i]; else placeholder.Delete(); } Console.WriteLine($" Fixed slide #{slide.SlideNumber}: {slideTexts.FirstOrDefault()}"); } } static void FixSlideTitles(Presentation presentation) { Console.WriteLine("Fixing incorrect slide titles..."); var titleMappings = new Dictionary<string, string> { { "Table of Content", "Table of Contents" } }; List<Shape> slideTitleShapes = ExtractSlideTitleShapes(presentation, includeSubtitles: true); List<string> slideTitles = slideTitleShapes .Select(shape => shape?.TextFrame.TextRange.Text) .ToList(); for (int i = 0; i < slideTitleShapes.Count; i++) { string newTitle = FixEnglishTitleCharacterCasing(slideTitles[i]); if (newTitle != null && titleMappings.ContainsKey(newTitle)) newTitle = titleMappings[newTitle]; if (newTitle != slideTitles[i]) { Console.WriteLine($" Replaced slide #{i} title: [{slideTitles[i]}] -> [{newTitle}]"); slideTitleShapes[i].TextFrame.TextRange.Text = newTitle; } } } static Language DetectPresentationLanguage(Presentation presentation) { Console.WriteLine("Detecting presentation language..."); var englishLettersCount = 0; var bulgarianLettersCount = 0; var slideTitles = ExtractSlideTitles(presentation); foreach (string title in slideTitles) if (title != null) foreach (char ch in title.ToLower()) if (ch >= 'a' && ch <= 'z') englishLettersCount++; else if (ch >= 'а' && ch <= 'я') bulgarianLettersCount++; Language lang = (bulgarianLettersCount > englishLettersCount / 2) ? Language.BG : Language.EN; Console.WriteLine($" Language detected: {lang}"); return lang; } static void FixQuestionsSlide(Presentation presentation, string pptTemplateFileName, List<string> pptTemplateSlideTitles, Language lang) { Console.WriteLine("Fixing the [Questions] slide..."); int questionsSlideIndexInTemplate = pptTemplateSlideTitles.LastIndexOf("Questions?"); if (lang == Language.BG || questionsSlideIndexInTemplate == -1) { int questionsSlideIndexBG = pptTemplateSlideTitles.LastIndexOf("Въпроси?"); if (questionsSlideIndexBG != -1) questionsSlideIndexInTemplate = questionsSlideIndexBG; } if (questionsSlideIndexInTemplate == -1) { Console.WriteLine($" Cannot find the [Questions] slide --> operation skipped"); return; } for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { Slide slide = presentation.Slides[slideNum]; if (slide.CustomLayout.Name == "Questions Slide" || slide.CustomLayout.Name == "1_Questions Slide") { Console.WriteLine($" Found the [Questions] slide #{slideNum} --> replacing it from the template"); presentation.Slides[slideNum].Delete(); presentation.Slides.InsertFromFile(pptTemplateFileName, slideNum - 1, questionsSlideIndexInTemplate + 1, questionsSlideIndexInTemplate + 1); } } } static void FixLicenseSlide(Presentation presentation, string pptTemplateFileName, List<string> pptTemplateSlideTitles, Language lang) { Console.WriteLine("Fixing the [License] slide..."); int licenseSlideIndexInTemplate = pptTemplateSlideTitles.LastIndexOf("License"); if (lang == Language.BG || licenseSlideIndexInTemplate == -1) { int licenseSlideIndexBG = pptTemplateSlideTitles.LastIndexOf("Лиценз"); if (licenseSlideIndexBG != -1) licenseSlideIndexInTemplate = licenseSlideIndexBG; } if (licenseSlideIndexInTemplate == -1) { Console.WriteLine($" Cannot find the [License] slide --> operation skipped"); return; } var slideTitles = ExtractSlideTitles(presentation); for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { if (slideTitles[slideNum - 1] == "License" || slideTitles[slideNum - 1] == "Лиценз") { Console.WriteLine($" Found the [License] slide #{slideNum} --> replacing it from the template"); presentation.Slides[slideNum].Delete(); presentation.Slides.InsertFromFile(pptTemplateFileName, slideNum - 1, licenseSlideIndexInTemplate + 1, licenseSlideIndexInTemplate + 1); } } } static void FixAboutSoftUniSlide(Presentation presentation, string pptTemplateFileName, List<string> pptTemplateSlideTitles, Language lang) { Console.WriteLine("Fixing the [About] slide..."); var aboutSlidePossibleTitles = new List<(string, Language)>() { ("Trainings @ Software University (SoftUni)", Language.EN), ("About SoftUni Digital", Language.EN), ("About SoftUni Creative", Language.EN), ("About SoftUni Kids", Language.EN), ("Обучения в СофтУни", Language.BG), ("Обучения в Софтуерен университет (СофтУни)", Language.BG), }; // Find the replacement slide index from the template // for the [About] slide in the current language int aboutSlideReplacementIndexInTemplate = -1; foreach (var title in aboutSlidePossibleTitles.Where(t => t.Item2 == lang)) aboutSlideReplacementIndexInTemplate = Math.Max( aboutSlideReplacementIndexInTemplate, pptTemplateSlideTitles.LastIndexOf(title.Item1)); // Remove the language filter if the [About] slide is not found if (aboutSlideReplacementIndexInTemplate == -1) foreach (var title in aboutSlidePossibleTitles) aboutSlideReplacementIndexInTemplate = Math.Max( aboutSlideReplacementIndexInTemplate, pptTemplateSlideTitles.LastIndexOf(title.Item1)); if (aboutSlideReplacementIndexInTemplate == -1) { Console.WriteLine($" Cannot find the [About] slide --> operation skipped"); return; } // Replace the [About] slides from the presentation // with the [About] slide from the template HashSet<string> slideTitlesToReplace = new HashSet<string>( aboutSlidePossibleTitles.Select(t => t.Item1)); var slideTitles = ExtractSlideTitles(presentation); for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { if (slideTitlesToReplace.Contains(slideTitles[slideNum - 1])) { Console.WriteLine($" Found the [About] slide #{slideNum} --> replacing it from the template"); presentation.Slides[slideNum].Delete(); presentation.Slides.InsertFromFile(pptTemplateFileName, slideNum - 1, aboutSlideReplacementIndexInTemplate + 1, aboutSlideReplacementIndexInTemplate + 1); } } } static void FixSlideNumbers(Presentation presentation) { Shape FindFirstSlideNumberShape() { CustomLayout layout = presentation.SlideMaster.CustomLayouts.OfType<CustomLayout>() .Where(l => l.Name == "Title and Content").First(); foreach (Shape shape in layout.Shapes) if (shape.Type == MsoShapeType.msoPlaceholder) if (shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderSlideNumber) return shape; return null; } Console.Write("Fixing slide numbering..."); var layoutsWithoutNumbering = new HashSet<string>() { "Presentation Title Slide", "Section Title Slide", "Questions Slide" }; Shape slideNumberShape = FindFirstSlideNumberShape(); slideNumberShape.Copy(); // Delete the [slide number] box in each slide, then put it again if needed for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { Slide slide = presentation.Slides[slideNum]; string layoutName = slide.CustomLayout.Name; foreach (Shape shape in slide.Shapes) { bool isSlideNumberTextBox = shape.Type == MsoShapeType.msoTextBox && shape.Name.Contains("Slide Number"); bool isSlideNumberPlaceholder = shape.Type == MsoShapeType.msoPlaceholder && shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderSlideNumber; if (isSlideNumberTextBox || isSlideNumberPlaceholder) { // Found a "slide number" shape --> delete it shape.Delete(); } } if (!layoutsWithoutNumbering.Contains(layoutName)) { // The slide should have [slide number] box --> insert it slide.Shapes.Paste(); } Console.Write("."); // Display progress of the current operation } Console.WriteLine(); } static void FixSlideNotesPages(Presentation presentation) { Shape FindNotesFooter() { var footerShape = presentation.NotesMaster.Shapes.OfType<Shape>().Where( shape => shape.Type == MsoShapeType.msoPlaceholder && shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderFooter) .FirstOrDefault(); return footerShape; } Console.WriteLine("Fixing slide notes pages..."); Shape footerFromNotesMaster = FindNotesFooter(); footerFromNotesMaster.Copy(); for (int slideNum = 1; slideNum <= presentation.Slides.Count; slideNum++) { Slide slide = presentation.Slides[slideNum]; if (slide.HasNotesPage == MsoTriState.msoTrue) { var slideNotesFooter = slide.NotesPage.Shapes.OfType<Shape>().Where( shape => shape.Type == MsoShapeType.msoPlaceholder && shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderFooter) .FirstOrDefault(); if (slideNotesFooter != null) slideNotesFooter.Delete(); slide.NotesPage.Shapes.Paste(); } } } }
42.966102
137
0.593832
[ "MIT" ]
SoftUni/SoftUni-Course-Converter
SoftUni-PowerPoint-Converter/SoftUniPowerPointConverter.cs
27,992
C#
using System.ComponentModel.DataAnnotations; using Abp.Authorization.Users; namespace DFF.Freedom.Models.TokenAuth { /// <summary> /// 外部认证 模型 /// </summary> public class ExternalAuthenticateModel { /// <summary> /// 认证提供字符串 /// </summary> [Required] [MaxLength(UserLogin.MaxLoginProviderLength)] public string AuthProvider { get; set; } /// <summary> /// 提供的键字符串 /// </summary> [Required] [MaxLength(UserLogin.MaxProviderKeyLength)] public string ProviderKey { get; set; } /// <summary> /// 提供的访问代码字符串 /// </summary> [Required] public string ProviderAccessCode { get; set; } } }
23.25
54
0.563172
[ "MIT" ]
dafeifei0218/DFF.Freedom
aspnet-core/src/DFF.Freedom.Web.Core/Models/TokenAuth/ExternalAuthenticateModel.cs
806
C#
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" namespace HtmlRenderer.PdfSharp.Adapters { #if NETCOREAPP2_2 using PdfSharpCore.Drawing; #else using global::PdfSharp.Drawing; #endif using System; using HtmlRenderer.Core.Adapters; using HtmlRenderer.Core.Adapters.Entities; using HtmlRenderer.Core.Core.Utils; using HtmlRenderer.PdfSharp.Utilities; /// <summary> /// Adapter for WinForms Graphics for core. /// </summary> internal sealed class GraphicsAdapter : RGraphics { #region Fields and Consts /// <summary> /// The wrapped WinForms graphics object /// </summary> private readonly XGraphics _g; /// <summary> /// if to release the graphics object on dispose /// </summary> private readonly bool _releaseGraphics; /// <summary> /// Used to measure and draw strings /// </summary> private static readonly XStringFormat _stringFormat; #endregion static GraphicsAdapter() { _stringFormat = new XStringFormat(); _stringFormat.Alignment = XStringAlignment.Near; _stringFormat.LineAlignment = XLineAlignment.Near; } /// <summary> /// Init. /// </summary> /// <param name="g">the win forms graphics object to use</param> /// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param> public GraphicsAdapter(XGraphics g, bool releaseGraphics = false) : base(PdfSharpAdapter.Instance, new RRect(0, 0, double.MaxValue, double.MaxValue)) { ArgChecker.AssertArgNotNull(g, "g"); this._g = g; this._releaseGraphics = releaseGraphics; } public override void PopClip() { this._clipStack.Pop(); this._g.Restore(); } public override void PushClip(RRect rect) { this._clipStack.Push(rect); this._g.Save(); this._g.IntersectClip(Utils.Convert(rect)); } public override void PushClipExclude(RRect rect) { } public override Object SetAntiAliasSmoothingMode() { var prevMode = this._g.SmoothingMode; this._g.SmoothingMode = XSmoothingMode.AntiAlias; return prevMode; } public override void ReturnPreviousSmoothingMode(Object prevMode) { if (prevMode != null) { this._g.SmoothingMode = (XSmoothingMode)prevMode; } } public override RSize MeasureString(string str, RFont font) { var fontAdapter = (FontAdapter)font; var realFont = fontAdapter.Font; var size = this._g.MeasureString(str, realFont, _stringFormat); if (font.Height < 0) { var height = realFont.Height; var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style); fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + 1f))); } return Utils.Convert(size); } public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth) { // there is no need for it - used for text selection throw new NotSupportedException(); } public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl) { var xBrush = ((BrushAdapter)this._adapter.GetSolidBrush(color)).Brush; this._g.DrawString(str, ((FontAdapter)font).Font, (XBrush)xBrush, point.X, point.Y, _stringFormat); } public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation) { return new BrushAdapter(new XTextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect), Utils.Convert(translateTransformLocation))); } public override RGraphicsPath GetGraphicsPath() { return new GraphicsPathAdapter(); } public override void Dispose() { if (this._releaseGraphics) this._g.Dispose(); } #region Delegate graphics methods public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2) { this._g.DrawLine(((PenAdapter)pen).Pen, x1, y1, x2, y2); } public override void DrawRectangle(RPen pen, double x, double y, double width, double height) { this._g.DrawRectangle(((PenAdapter)pen).Pen, x, y, width, height); } public override void DrawRectangle(RBrush brush, double x, double y, double width, double height) { var xBrush = ((BrushAdapter)brush).Brush; var xTextureBrush = xBrush as XTextureBrush; if (xTextureBrush != null) { xTextureBrush.DrawRectangle(this._g, x, y, width, height); } else { this._g.DrawRectangle((XBrush)xBrush, x, y, width, height); // handle bug in PdfSharp that keeps the brush color for next string draw if (xBrush is XLinearGradientBrush) this._g.DrawRectangle(XBrushes.White, 0, 0, 0.1, 0.1); } } public override void DrawImage(RImage image, RRect destRect, RRect srcRect) { this._g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), XGraphicsUnit.Point); } public override void DrawImage(RImage image, RRect destRect) { this._g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect)); } public override void DrawPath(RPen pen, RGraphicsPath path) { this._g.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPath(RBrush brush, RGraphicsPath path) { this._g.DrawPath((XBrush)((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPolygon(RBrush brush, RPoint[] points) { if (points != null && points.Length > 0) { this._g.DrawPolygon((XBrush)((BrushAdapter)brush).Brush, Utils.Convert(points), XFillMode.Winding); } } #endregion } }
33.038095
151
0.597146
[ "MIT" ]
gpcaretti/libraries
Kongrevsky.Libraries/Infrastructure/HtmlRenderer/HtmlRenderer.PdfSharp/Adapters/GraphicsAdapter.cs
6,938
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Windows.Controls { public delegate void TextChangedEventHandler(object sender, TextChangedEventArgs e); public class TextChangedEventArgs : RoutedEventArgs { public TextChangedEventArgs(RoutedEvent routedEvent, object originalSource) : base(routedEvent, originalSource) { // } public override void InvokeEventHandler(Delegate handler, object target) { if (handler is TextChangedEventHandler) { ((TextChangedEventHandler)handler)(target, this); } else { base.InvokeEventHandler(handler, target); } } } }
26.83871
89
0.592548
[ "Apache-2.0" ]
bridgedotnet/Granular
Granular.Presentation/Controls/TextChangedEventArgs.cs
834
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Tasks { public class D { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var N = Scanner.Scan<int>(); var H = new long[N]; var S = new long[N]; for (var i = 0; i < N; i++) { (H[i], S[i]) = Scanner.Scan<long, long>(); } var l = H.Max() - 1; var r = (long)1e18; while (r - l > 1) { var m = l + (r - l) / 2; var memo = new int[N]; var ok = true; for (var i = 0; i < N; i++) { var t = Math.Min(N - 1, (m - H[i]) / S[i]); memo[t]++; } var sum = 0L; for (var i = 0; i < N && ok; i++) { sum += memo[i]; if (sum > i + 1) ok = false; } if (ok) r = m; else l = m; } Console.WriteLine(r); } public static class Scanner { private static Queue<string> queue = new Queue<string>(); public static T Next<T>() { if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item); return (T)Convert.ChangeType(queue.Dequeue(), typeof(T)); } public static T Scan<T>() => Next<T>(); public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>()); public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>()); public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>()); public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>()); } } }
31.458333
138
0.405298
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC023/Tasks/D.cs
2,265
C#
using Newtonsoft.Json; namespace ZendeskApi_v2.Models.Tickets { public class Options { [JsonProperty("timezone")] public string Timezone { get; set; } [JsonProperty("hour_offset")] public string HourOffset { get; set; } } }
19.285714
46
0.625926
[ "Apache-2.0" ]
APErebus/ZendeskApi_v2
src/ZendeskApi_v2/Models/Tickets/Options.cs
270
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.AppMesh")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS App Mesh. AWS App Mesh is a service mesh that makes it easy to monitor and control communications between microservices of an application. AWS App Mesh APIs are available for preview in eu-west-1, us-east-1, us-east-2, and us-west-2 regions.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.111.11")]
49.9375
325
0.749687
[ "Apache-2.0" ]
alefranz/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/AppMesh/Properties/AssemblyInfo.cs
1,598
C#
using System.Web.Http; using System.Web.Mvc; namespace MAASoft.HomeBanking.Areas.HelpPage { public class HelpPageAreaRegistration : AreaRegistration { public override string AreaName { get { return "HelpPage"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "HelpPage_Default", "Help/{action}/{apiId}", new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); HelpPageConfig.Register(GlobalConfiguration.Configuration); } } }
26.038462
94
0.567208
[ "MIT" ]
Roque27/MutualApi
MAASoft.HomeBanking/Areas/HelpPage/HelpPageAreaRegistration.cs
677
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.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal static class MetadataNameHelpers { private static void AppendNamespace(INamespaceSymbol namespaceSymbol, StringBuilder builder) => builder.Append(namespaceSymbol.Name); private static void AppendNamedType(INamedTypeSymbol namedTypeSymbol, StringBuilder builder) { builder.Append(namedTypeSymbol.Name); if (namedTypeSymbol.Arity > 0) { var typeArguments = namedTypeSymbol.TypeArguments; builder.Append('`'); builder.Append(typeArguments.Length); // Append generic arguments builder.Append('['); for (var i = 0; i < typeArguments.Length; i++) { if (i > 0) { builder.Append(','); } builder.Append(GetMetadataName(typeArguments[i])); } builder.Append(']'); } } private static void AppendArrayType(IArrayTypeSymbol symbol, StringBuilder builder) { builder.Append(GetMetadataName(symbol.ElementType)); builder.Append('['); builder.Append(',', symbol.Rank - 1); builder.Append(']'); } private static void AppendPointerType(IPointerTypeSymbol symbol, StringBuilder builder) { builder.Append(GetMetadataName(symbol.PointedAtType)); builder.Append('*'); } public static string GetMetadataName(ITypeSymbol typeSymbol) { if (typeSymbol.Kind == SymbolKind.TypeParameter) { throw new ArgumentException("Type parameters are not suppported", nameof(typeSymbol)); } var parts = new Stack<ISymbol>(); ISymbol symbol = typeSymbol; while (symbol != null) { parts.Push(symbol); symbol = symbol.ContainingSymbol; } var builder = new StringBuilder(); while (parts.Count > 0) { symbol = parts.Pop(); if (builder.Length > 0) { if (symbol.ContainingSymbol is ITypeSymbol) { builder.Append('+'); } else { builder.Append('.'); } } switch (symbol.Kind) { case SymbolKind.Namespace: var namespaceSymbol = (INamespaceSymbol)symbol; if (!namespaceSymbol.IsGlobalNamespace) { AppendNamespace(namespaceSymbol, builder); } break; case SymbolKind.NamedType: AppendNamedType((INamedTypeSymbol)symbol, builder); break; case SymbolKind.ArrayType: AppendArrayType((IArrayTypeSymbol)symbol, builder); break; case SymbolKind.PointerType: AppendPointerType((IPointerTypeSymbol)symbol, builder); break; } } return builder.ToString(); } } }
31.129032
102
0.501036
[ "MIT" ]
06needhamt/roslyn
src/VisualStudio/Core/Impl/CodeModel/MetadataNameHelpers.cs
3,862
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 marketplacecommerceanalytics-2015-07-01.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.AWSMarketplaceCommerceAnalytics.Model { ///<summary> /// AWSMarketplaceCommerceAnalytics exception /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public class MarketplaceCommerceAnalyticsException : AmazonAWSMarketplaceCommerceAnalyticsException { /// <summary> /// Constructs a new MarketplaceCommerceAnalyticsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public MarketplaceCommerceAnalyticsException(string message) : base(message) {} /// <summary> /// Construct instance of MarketplaceCommerceAnalyticsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public MarketplaceCommerceAnalyticsException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of MarketplaceCommerceAnalyticsException /// </summary> /// <param name="innerException"></param> public MarketplaceCommerceAnalyticsException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of MarketplaceCommerceAnalyticsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public MarketplaceCommerceAnalyticsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of MarketplaceCommerceAnalyticsException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public MarketplaceCommerceAnalyticsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !NETSTANDARD /// <summary> /// Constructs a new instance of the MarketplaceCommerceAnalyticsException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected MarketplaceCommerceAnalyticsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
45.639175
179
0.669302
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/AWSMarketplaceCommerceAnalytics/Generated/Model/MarketplaceCommerceAnalyticsException.cs
4,427
C#
using System; namespace _03.ShoppingSpree { public class Product { private string name; private decimal cost; public Product(string name, decimal cost) { this.Name = name; this.Cost = cost; } public string Name { get { return this.name; } private set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Name cannot be empty"); } this.name = value; } } public decimal Cost { get { return this.cost; } private set { if (value < 0) { throw new ArgumentException("Money cannot be negative"); } this.cost = value; } } } }
18.962963
76
0.37793
[ "MIT" ]
LyubomirRashkov/Software-University-SoftUni
C#OOP/ProjectsAndSolutionsFromLecturesAndExercises/02ex-Encapsulation/03.ShoppingSpree/Product.cs
1,026
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.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Security; using System.Diagnostics; #if !NET_NATIVE namespace System.Runtime.Serialization { internal class CodeGenerator { /// <SecurityNote> /// Critical - Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> [SecurityCritical] private static MethodInfo s_getTypeFromHandle; private static MethodInfo GetTypeFromHandle { /// <SecurityNote> /// Critical - fetches the critical getTypeFromHandle field /// Safe - get-only properties only needs to be protected for write; initialized in getter if null. /// </SecurityNote> [SecuritySafeCritical] get { if (s_getTypeFromHandle == null) { s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle"); Debug.Assert(s_getTypeFromHandle != null); } return s_getTypeFromHandle; } } /// <SecurityNote> /// Critical - Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> [SecurityCritical] private static MethodInfo s_objectEquals; private static MethodInfo ObjectEquals { /// <SecurityNote> /// Critical - fetches the critical objectEquals field /// Safe - get-only properties only needs to be protected for write; initialized in getter if null. /// </SecurityNote> [SecuritySafeCritical] get { if (s_objectEquals == null) { s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static); Debug.Assert(s_objectEquals != null); } return s_objectEquals; } } /// <SecurityNote> /// Critical - Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> [SecurityCritical] private static MethodInfo s_arraySetValue; private static MethodInfo ArraySetValue { /// <SecurityNote> /// Critical - fetches the critical arraySetValue field /// Safe - get-only properties only needs to be protected for write; initialized in getter if null. /// </SecurityNote> [SecuritySafeCritical] get { if (s_arraySetValue == null) { s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }); Debug.Assert(s_arraySetValue != null); } return s_arraySetValue; } } #if !NET_NATIVE [SecurityCritical] private static MethodInfo s_objectToString; private static MethodInfo ObjectToString { [SecuritySafeCritical] get { if (s_objectToString == null) { s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>()); Debug.Assert(s_objectToString != null); } return s_objectToString; } } private static MethodInfo s_stringFormat; private static MethodInfo StringFormat { [SecuritySafeCritical] get { if (s_stringFormat == null) { s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }); Debug.Assert(s_stringFormat != null); } return s_stringFormat; } } #endif private Type _delegateType; #if USE_REFEMIT AssemblyBuilder assemblyBuilder; ModuleBuilder moduleBuilder; TypeBuilder typeBuilder; static int typeCounter; MethodBuilder methodBuilder; #else /// <SecurityNote> /// Critical - Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> [SecurityCritical] private static Module s_serializationModule; private static Module SerializationModule { /// <SecurityNote> /// Critical - fetches the critical serializationModule field /// Safe - get-only properties only needs to be protected for write; initialized in getter if null. /// </SecurityNote> [SecuritySafeCritical] get { if (s_serializationModule == null) { s_serializationModule = typeof(CodeGenerator).GetTypeInfo().Module; // could to be replaced by different dll that has SkipVerification set to false } return s_serializationModule; } } private DynamicMethod _dynamicMethod; #endif private ILGenerator _ilGen; private List<ArgBuilder> _argList; private Stack<object> _blockStack; private Label _methodEndLabel; private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>(); private enum CodeGenTrace { None, Save, Tron }; private CodeGenTrace _codeGenTrace; #if !NET_NATIVE private LocalBuilder _stringFormatArray; #endif internal CodeGenerator() { //Defaulting to None as thats the default value in WCF _codeGenTrace = CodeGenTrace.None; } #if !USE_REFEMIT internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { _dynamicMethod = dynamicMethod; _ilGen = _dynamicMethod.GetILGenerator(); _delegateType = delegateType; InitILGeneration(methodName, argTypes); } #endif internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess); _delegateType = delegateType; } [SecuritySafeCritical] private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { #if USE_REFEMIT string typeName = "Type" + (typeCounter++); InitAssemblyBuilder(typeName + "." + methodName); this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public); this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes); this.ilGen = this.methodBuilder.GetILGenerator(); #else _dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess); _ilGen = _dynamicMethod.GetILGenerator(); #endif InitILGeneration(methodName, argTypes); } private void InitILGeneration(string methodName, Type[] argTypes) { _methodEndLabel = _ilGen.DefineLabel(); _blockStack = new Stack<object>(); _argList = new List<ArgBuilder>(); for (int i = 0; i < argTypes.Length; i++) _argList.Add(new ArgBuilder(i, argTypes[i])); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("Begin method " + methodName + " {"); } internal Delegate EndMethod() { MarkLabel(_methodEndLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("} End method"); Ret(); Delegate retVal = null; #if USE_REFEMIT Type type = typeBuilder.CreateType(); MethodInfo method = type.GetMethod(methodBuilder.Name); retVal = Delegate.CreateDelegate(delegateType, method); methodBuilder = null; #else retVal = _dynamicMethod.CreateDelegate(_delegateType); _dynamicMethod = null; #endif _delegateType = null; _ilGen = null; _blockStack = null; _argList = null; return retVal; } internal MethodInfo CurrentMethod { get { #if USE_REFEMIT return methodBuilder; #else return _dynamicMethod; #endif } } internal ArgBuilder GetArg(int index) { return (ArgBuilder)_argList[index]; } internal Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; else if (var is LocalBuilder) return ((LocalBuilder)var).LocalType; else return var.GetType(); } internal LocalBuilder DeclareLocal(Type type, string name, object initialValue) { LocalBuilder local = DeclareLocal(type, name); Load(initialValue); Store(local); return local; } internal LocalBuilder DeclareLocal(Type type, string name) { return DeclareLocal(type, name, false); } internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned) { LocalBuilder local = _ilGen.DeclareLocal(type, isPinned); if (_codeGenTrace != CodeGenTrace.None) { _localNames[local] = name; EmitSourceComment("Declare local '" + name + "' of type " + type); } return local; } internal void Set(LocalBuilder local, object value) { Load(value); Store(local); } internal object For(LocalBuilder local, object start, object end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) { Load(start); Stloc(forState.Index); Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); _blockStack.Push(forState); return forState; } internal void EndFor() { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); if (forState.Index != null) { Ldloc(forState.Index); Ldc(1); Add(); Stloc(forState.Index); MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); if (GetVariableType(forState.End).IsArray) Ldlen(); Blt(forState.BeginLabel); } else Br(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void Break(object forState) { InternalBreakFor(forState, OpCodes.Br); } internal void IfFalseBreak(object forState) { InternalBreakFor(forState, OpCodes.Brfalse); } internal void InternalBreakFor(object userForState, OpCode branchInstruction) { foreach (object block in _blockStack) { ForState forState = block as ForState; if (forState != null && (object)forState == userForState) { if (!forState.RequiresEndLabel) { forState.EndLabel = DefineLabel(); forState.RequiresEndLabel = true; } if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode()); _ilGen.Emit(branchInstruction, forState.EndLabel); break; } } } internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType, LocalBuilder enumerator, MethodInfo getCurrentMethod) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator); Br(forState.TestLabel); MarkLabel(forState.BeginLabel); Call(enumerator, getCurrentMethod); ConvertValue(elementType, GetVariableType(local)); Stloc(local); _blockStack.Push(forState); } internal void EndForEach(MethodInfo moveNextMethod) { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); MarkLabel(forState.TestLabel); object enumerator = forState.End; Call(enumerator, moveNextMethod); Brtrue(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void IfNotDefaultValue(object value) { Type type = GetVariableType(value); TypeCode typeCode = type.GetTypeCode(); if ((typeCode == TypeCode.Object && type.GetTypeInfo().IsValueType) || typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal) { LoadDefaultValue(type); ConvertValue(type, Globals.TypeOfObject); Load(value); ConvertValue(type, Globals.TypeOfObject); Call(ObjectEquals); IfNot(); } else { LoadDefaultValue(type); Load(value); If(Cmp.NotEqualTo); } } internal void If() { InternalIf(false); } internal void IfNot() { InternalIf(true); } private OpCode GetBranchCode(Cmp cmp) { switch (cmp) { case Cmp.LessThan: return OpCodes.Bge; case Cmp.EqualTo: return OpCodes.Bne_Un; case Cmp.LessThanOrEqualTo: return OpCodes.Bgt; case Cmp.GreaterThan: return OpCodes.Ble; case Cmp.NotEqualTo: return OpCodes.Beq; default: DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp"); return OpCodes.Blt; } } internal void If(Cmp cmpOp) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void If(object value1, Cmp cmpOp, object value2) { Load(value1); Load(value2); If(cmpOp); } internal void Else() { IfState ifState = PopIfState(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; _blockStack.Push(ifState); } internal void ElseIf(object value1, Cmp cmpOp, object value2) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(value1); Load(value2); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void EndIf() { IfState ifState = PopIfState(); if (!ifState.ElseBegin.Equals(ifState.EndIf)) MarkLabel(ifState.ElseBegin); MarkLabel(ifState.EndIf); } internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) { if (methodInfo.GetParameters().Length != expectedCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount))); } internal void Call(object thisObj, MethodInfo methodInfo) { VerifyParameterCount(methodInfo, 0); LoadThis(thisObj, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1) { VerifyParameterCount(methodInfo, 1); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2) { VerifyParameterCount(methodInfo, 2); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3) { VerifyParameterCount(methodInfo, 3); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4) { VerifyParameterCount(methodInfo, 4); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5) { VerifyParameterCount(methodInfo, 5); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6) { VerifyParameterCount(methodInfo, 6); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); LoadParam(param6, 6, methodInfo); Call(methodInfo); } internal void Call(MethodInfo methodInfo) { if (methodInfo.IsVirtual && !methodInfo.DeclaringType.GetTypeInfo().IsValueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Callvirt, methodInfo); } else if (methodInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } } internal void Call(ConstructorInfo ctor) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Initobj " + valueType); _ilGen.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newarr " + elementType); _ilGen.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { Type objType = GetVariableType(obj).GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) { Ldelema(objType); Ldobj(objType); } else Ldelem(objType); } internal void StoreArrayElement(object obj, object arrayIndex, object value) { Type arrayType = GetVariableType(obj); if (arrayType == Globals.TypeOfArray) { Call(obj, ArraySetValue, value, arrayIndex); } else { Type objType = arrayType.GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) Ldelema(objType); Load(value); ConvertValue(GetVariableType(value), objType); if (IsStruct(objType)) Stobj(objType); else Stelem(objType); } } private static bool IsStruct(Type objType) { return objType.GetTypeInfo().IsValueType && !objType.GetTypeInfo().IsPrimitive; } internal Type LoadMember(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property))); Call(getMethod); } } else if (memberInfo is MethodInfo) { MethodInfo method = (MethodInfo)memberInfo; memberType = method.ReturnType; Call(method); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name))); EmitStackTop(memberType); return memberType; } internal void StoreMember(MemberInfo memberInfo) { if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; if (property != null) { MethodInfo setMethod = property.SetMethod; if (setMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property))); Call(setMethod); } } else if (memberInfo is MethodInfo) Call((MethodInfo)memberInfo); else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown"))); } internal void LoadDefaultValue(Type type) { if (type.GetTypeInfo().IsValueType) { switch (type.GetTypeCode()) { case TypeCode.Boolean: Ldc(false); break; case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: Ldc(0); break; case TypeCode.Int64: case TypeCode.UInt64: Ldc(0L); break; case TypeCode.Single: Ldc(0.0F); break; case TypeCode.Double: Ldc(0.0); break; case TypeCode.Decimal: case TypeCode.DateTime: default: LocalBuilder zero = DeclareLocal(type, "zero"); LoadAddress(zero); InitObj(type); Load(zero); break; } } else Load(null); } internal void Load(object obj) { if (obj == null) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldnull"); _ilGen.Emit(OpCodes.Ldnull); } else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) Ldloc((LocalBuilder)obj); else Ldc(obj); } internal void Store(object var) { if (var is ArgBuilder) Starg((ArgBuilder)var); else if (var is LocalBuilder) Stloc((LocalBuilder)var); else { DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder."); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType())))); } } internal void Dec(object var) { Load(var); Load(1); Subtract(); Store(var); } internal void LoadAddress(object obj) { if (obj is ArgBuilder) LdargAddress((ArgBuilder)obj); else if (obj is LocalBuilder) LdlocAddress((LocalBuilder)obj); else Load(obj); } internal void ConvertAddress(Type source, Type target) { InternalConvert(source, target, true); } internal void ConvertValue(Type source, Type target) { InternalConvert(source, target, false); } internal void Castclass(Type target) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Castclass " + target); _ilGen.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Box " + type); _ilGen.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Unbox " + type); _ilGen.Emit(OpCodes.Unbox, type); } private OpCode GetLdindOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Ldind_I1; // TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldind_I2; // TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldind_I1; // TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldind_U1; // TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldind_I2; // TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldind_U2; // TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldind_I4; // TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldind_U4; // TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldind_I8; // TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldind_I8; // TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldind_R4; // TypeCode.Single: case TypeCode.Double: return OpCodes.Ldind_R8; // TypeCode.Double: case TypeCode.String: return OpCodes.Ldind_Ref; // TypeCode.String: default: return OpCodes.Nop; } } internal void Ldobj(Type type) { OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldobj " + type); _ilGen.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stobj " + type); _ilGen.Emit(OpCodes.Stobj, type); } internal void Ceq() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ceq"); _ilGen.Emit(OpCodes.Ceq); } internal void Throw() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Throw"); _ilGen.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldtoken " + t); _ilGen.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) { Type valueType = o.GetType(); if (o is Type) { Ldtoken((Type)o); Call(GetTypeFromHandle); } else if (valueType.GetTypeInfo().IsEnum) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceComment("Ldc " + o.GetType() + "." + o); Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null)); } else { switch (valueType.GetTypeCode()) { case TypeCode.Boolean: Ldc((bool)o); break; case TypeCode.Char: DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract"); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.CharIsInvalidPrimitive))); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture)); break; case TypeCode.Int32: Ldc((int)o); break; case TypeCode.UInt32: Ldc((int)(uint)o); break; case TypeCode.UInt64: Ldc((long)(ulong)o); break; case TypeCode.Int64: Ldc((long)o); break; case TypeCode.Single: Ldc((float)o); break; case TypeCode.Double: Ldc((double)o); break; case TypeCode.String: Ldstr((string)o); break; case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.Empty: default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType)))); } } } internal void Ldc(bool boolVar) { if (boolVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 1"); _ilGen.Emit(OpCodes.Ldc_I4_1); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 0"); _ilGen.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 " + intVar); switch (intVar) { case -1: _ilGen.Emit(OpCodes.Ldc_I4_M1); break; case 0: _ilGen.Emit(OpCodes.Ldc_I4_0); break; case 1: _ilGen.Emit(OpCodes.Ldc_I4_1); break; case 2: _ilGen.Emit(OpCodes.Ldc_I4_2); break; case 3: _ilGen.Emit(OpCodes.Ldc_I4_3); break; case 4: _ilGen.Emit(OpCodes.Ldc_I4_4); break; case 5: _ilGen.Emit(OpCodes.Ldc_I4_5); break; case 6: _ilGen.Emit(OpCodes.Ldc_I4_6); break; case 7: _ilGen.Emit(OpCodes.Ldc_I4_7); break; case 8: _ilGen.Emit(OpCodes.Ldc_I4_8); break; default: _ilGen.Emit(OpCodes.Ldc_I4, intVar); break; } } internal void Ldc(long l) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i8 " + l); _ilGen.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r4 " + f); _ilGen.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r8 " + d); _ilGen.Emit(OpCodes.Ldc_R8, d); } internal void Ldstr(string strVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldstr " + strVar); _ilGen.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) { if (localBuilder.LocalType.GetTypeInfo().IsValueType) Ldloca(localBuilder); else Ldloc(localBuilder); } internal void Ldloc(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloc " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloc, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void Stloc(LocalBuilder local) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stloc " + _localNames[local]); EmitStackTop(local.LocalType); _ilGen.Emit(OpCodes.Stloc, local); } internal void Ldloca(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloca " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloca, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void LdargAddress(ArgBuilder argBuilder) { if (argBuilder.ArgType.GetTypeInfo().IsValueType) Ldarga(argBuilder); else Ldarg(argBuilder); } internal void Ldarg(ArgBuilder arg) { Ldarg(arg.Index); } internal void Starg(ArgBuilder arg) { Starg(arg.Index); } internal void Ldarg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarg " + slot); switch (slot) { case 0: _ilGen.Emit(OpCodes.Ldarg_0); break; case 1: _ilGen.Emit(OpCodes.Ldarg_1); break; case 2: _ilGen.Emit(OpCodes.Ldarg_2); break; case 3: _ilGen.Emit(OpCodes.Ldarg_3); break; default: if (slot <= 255) _ilGen.Emit(OpCodes.Ldarg_S, slot); else _ilGen.Emit(OpCodes.Ldarg, slot); break; } } internal void Starg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Starg " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Starg_S, slot); else _ilGen.Emit(OpCodes.Starg, slot); } internal void Ldarga(ArgBuilder argBuilder) { Ldarga(argBuilder.Index); } internal void Ldarga(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarga " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Ldarga_S, slot); else _ilGen.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldlen"); _ilGen.Emit(OpCodes.Ldlen); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Conv.i4"); _ilGen.Emit(OpCodes.Conv_I4); } private OpCode GetLdelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Ldelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Ldelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldelem_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldelem_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldelem_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Ldelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Ldelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Ldelem(Type arrayElementType) { if (arrayElementType.GetTypeInfo().IsEnum) { Ldelem(Enum.GetUnderlyingType(arrayElementType)); } else { OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); EmitStackTop(arrayElementType); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode, arrayElementType); EmitStackTop(arrayElementType); } private OpCode GetStelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Stelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Stelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Stelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Stelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Stelem_I1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Stelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Stelem_I2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Stelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Stelem_I4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Stelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Stelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Stelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Stelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Stelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Stelem(Type arrayElementType) { if (arrayElementType.GetTypeInfo().IsEnum) Stelem(Enum.GetUnderlyingType(arrayElementType)); else { OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); EmitStackTop(arrayElementType); _ilGen.Emit(opCode); } } internal Label DefineLabel() { return _ilGen.DefineLabel(); } internal void MarkLabel(Label label) { _ilGen.MarkLabel(label); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel(label.GetHashCode() + ":"); } internal void Add() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Add"); _ilGen.Emit(OpCodes.Add); } internal void Subtract() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Sub"); _ilGen.Emit(OpCodes.Sub); } internal void And() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("And"); _ilGen.Emit(OpCodes.And); } internal void Or() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Or"); _ilGen.Emit(OpCodes.Or); } internal void Not() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Not"); _ilGen.Emit(OpCodes.Not); } internal void Ret() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ret"); _ilGen.Emit(OpCodes.Ret); } internal void Br(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Br " + label.GetHashCode()); _ilGen.Emit(OpCodes.Br, label); } internal void Blt(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Blt " + label.GetHashCode()); _ilGen.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brfalse " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brtrue " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brtrue, label); } internal void Pop() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Pop"); _ilGen.Emit(OpCodes.Pop); } internal void Dup() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Dup"); _ilGen.Emit(OpCodes.Dup); } private void LoadThis(object thisObj, MethodInfo methodInfo) { if (thisObj != null && !methodInfo.IsStatic) { LoadAddress(thisObj); ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType); } } private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo) { Load(arg); if (arg != null) ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType); } private void InternalIf(bool negate) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); if (negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); _blockStack.Push(ifState); } private OpCode GetConvOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Conv_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Conv_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Conv_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Conv_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Conv_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Conv_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Conv_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Conv_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Conv_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Conv_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Conv_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Conv_R8;// TypeCode.Double: default: return OpCodes.Nop; } } private void InternalConvert(Type source, Type target, bool isAddress) { if (target == source) return; if (target.GetTypeInfo().IsValueType) { if (source.GetTypeInfo().IsValueType) { OpCode opCode = GetConvOpCode(target.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target)))); else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } } else if (source.IsAssignableFrom(target)) { Unbox(target); if (!isAddress) Ldobj(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } else if (target.IsAssignableFrom(source)) { if (source.GetTypeInfo().IsValueType) { if (isAddress) Ldobj(source); Box(source); } } else if (source.IsAssignableFrom(target)) { Castclass(target); } else if (target.GetTypeInfo().IsInterface || source.GetTypeInfo().IsInterface) { Castclass(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState ifState = stackTop as IfState; if (ifState == null) ThrowMismatchException(stackTop); return ifState; } #if USE_REFEMIT [SecuritySafeCritical] void InitAssemblyBuilder(string methodName) { AssemblyName name = new AssemblyName(); name.Name = "Microsoft.GeneratedCode."+methodName; //Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false); } #endif private void ThrowMismatchException(object expected) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString()))); } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceInstruction(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceLabel(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceComment(string comment) { } internal void EmitStackTop(Type stackTopType) { if (_codeGenTrace != CodeGenTrace.Tron) return; } internal Label[] Switch(int labelCount) { SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel()); Label[] caseLabels = new Label[labelCount]; for (int i = 0; i < caseLabels.Length; i++) caseLabels[i] = DefineLabel(); _ilGen.Emit(OpCodes.Switch, caseLabels); Br(switchState.DefaultLabel); _blockStack.Push(switchState); return caseLabels; } internal void Case(Label caseLabel1, string caseLabelName) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("case " + caseLabelName + "{"); MarkLabel(caseLabel1); } internal void EndCase() { object stackTop = _blockStack.Peek(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); Br(switchState.EndOfSwitchLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end case "); } internal void EndSwitch() { object stackTop = _blockStack.Pop(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end switch"); if (!switchState.DefaultDefined) MarkLabel(switchState.DefaultLabel); MarkLabel(switchState.EndOfSwitchLabel); } private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod; internal void ElseIfIsEmptyString(LocalBuilder strLocal) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(strLocal); Call(s_stringLength); Load(0); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin); _blockStack.Push(ifState); } internal void IfNotIsEmptyString(LocalBuilder strLocal) { Load(strLocal); Call(s_stringLength); Load(0); If(Cmp.NotEqualTo); } #if !NET_NATIVE internal void BeginWhileCondition() { Label startWhile = DefineLabel(); MarkLabel(startWhile); _blockStack.Push(startWhile); } internal void BeginWhileBody(Cmp cmpOp) { Label startWhile = (Label)_blockStack.Pop(); If(cmpOp); _blockStack.Push(startWhile); } internal void EndWhile() { Label startWhile = (Label)_blockStack.Pop(); Br(startWhile); EndIf(); } internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); if (_stringFormatArray == null) _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray"); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) StoreArrayElement(_stringFormatArray, i, values[i]); Load(msg); Load(_stringFormatArray); Call(StringFormat); } internal void ToString(Type type) { if (type != Globals.TypeOfString) { if (type.GetTypeInfo().IsValueType) { Box(type); } Call(ObjectToString); } } #endif } internal class ArgBuilder { internal int Index; internal Type ArgType; internal ArgBuilder(int index, Type argType) { this.Index = index; this.ArgType = argType; } } internal class ForState { private LocalBuilder _indexVar; private Label _beginLabel; private Label _testLabel; private Label _endLabel; private bool _requiresEndLabel; private object _end; internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) { _indexVar = indexVar; _beginLabel = beginLabel; _testLabel = testLabel; _end = end; } internal LocalBuilder Index { get { return _indexVar; } } internal Label BeginLabel { get { return _beginLabel; } } internal Label TestLabel { get { return _testLabel; } } internal Label EndLabel { get { return _endLabel; } set { _endLabel = value; } } internal bool RequiresEndLabel { get { return _requiresEndLabel; } set { _requiresEndLabel = value; } } internal object End { get { return _end; } } } internal enum Cmp { LessThan, EqualTo, LessThanOrEqualTo, GreaterThan, NotEqualTo, GreaterThanOrEqualTo } internal class IfState { private Label _elseBegin; private Label _endIf; internal Label EndIf { get { return _endIf; } set { _endIf = value; } } internal Label ElseBegin { get { return _elseBegin; } set { _elseBegin = value; } } } internal class SwitchState { private Label _defaultLabel; private Label _endOfSwitchLabel; private bool _defaultDefined; internal SwitchState(Label defaultLabel, Label endOfSwitchLabel) { _defaultLabel = defaultLabel; _endOfSwitchLabel = endOfSwitchLabel; _defaultDefined = false; } internal Label DefaultLabel { get { return _defaultLabel; } } internal Label EndOfSwitchLabel { get { return _endOfSwitchLabel; } } internal bool DefaultDefined { get { return _defaultDefined; } set { _defaultDefined = value; } } } } #endif
34.388535
274
0.523538
[ "MIT" ]
OceanYan/corefx
src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs
64,788
C#
#nullable enable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using OmniSharp.DotNetTest.Models; using OmniSharp.Eventing; using OmniSharp.Mef; using OmniSharp.Services; namespace OmniSharp.DotNetTest.Services { [Shared] [OmniSharpHandler(OmniSharpEndpoints.V2.DebugTestsInContextGetStartInfo, LanguageNames.CSharp)] internal class DebugTestsInContextService : BaseTestService, IRequestHandler<DebugTestsInContextGetStartInfoRequest, DebugTestGetStartInfoResponse> { private readonly DebugSessionManager _debugSessionManager; [ImportingConstructor] public DebugTestsInContextService(DebugSessionManager debugSessionManager, OmniSharpWorkspace workspace, IDotNetCliService dotNetCli, IEventEmitter eventEmitter, ILoggerFactory loggerFactory) : base(workspace, dotNetCli, eventEmitter, loggerFactory) { _debugSessionManager = debugSessionManager; } public async Task<DebugTestGetStartInfoResponse> Handle(DebugTestsInContextGetStartInfoRequest request) { var document = Workspace.GetDocument(request.FileName); if (document is null) { return new DebugTestGetStartInfoResponse { Succeeded = false, FailureReason = "File is not part of a C# project in the loaded solution.", ContextHadNoTests = true, }; } var testManager = TestManager.Create(document.Project, DotNetCli, EventEmitter, LoggerFactory); var (methodNames, testFramework) = await testManager.GetContextTestMethodNames(request.Line, request.Column, document, CancellationToken.None); if (methodNames is null) { return new DebugTestGetStartInfoResponse { Succeeded = false, FailureReason = "Could not find any tests to run", ContextHadNoTests = true, }; } testManager.Connect(); if (testManager.IsConnected) { _debugSessionManager.StartSession(testManager); return await _debugSessionManager.DebugGetStartInfoAsync(methodNames, request.RunSettings, testFramework, request.TargetFrameworkVersion, CancellationToken.None); } return new DebugTestGetStartInfoResponse { FailureReason = "Failed to connect to the 'dotnet test' process", Succeeded = false }; } } }
36.891892
199
0.654945
[ "MIT" ]
int3rrupt/omnisharp-roslyn
src/OmniSharp.DotNetTest/Services/DebugTestsInContextService.cs
2,730
C#
using System; namespace UnityEngine { [AttributeUsage (AttributeTargets.Struct)] internal class IL2CPPStructAlignmentAttribute : Attribute { // // Fields // public int Align; // // Constructors // public IL2CPPStructAlignmentAttribute () { this.Align = 1; } } }
13.857143
58
0.676976
[ "MIT" ]
NathanWarden/unity-godot-compat
UnityEngine/Attributes/IL2CPPStructAlignmentAttribute.cs
293
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Stride.Core; using Stride.Core.Serialization; using Stride.Core.Serialization.Serializers; using Stride.Rendering; namespace Stride.Shaders.Compiler { /// <summary> /// Parameters used for compilation. /// </summary> [DataSerializer(typeof(DictionaryAllSerializer<CompilerParameters, ParameterKey, object>))] public sealed class CompilerParameters : ParameterCollection, IDictionary<ParameterKey, object> { /// <summary> /// Initializes a new instance of the <see cref="CompilerParameters"/> class. /// </summary> public CompilerParameters() { } public CompilerParameters(CompilerParameters compilerParameters) : base(compilerParameters) { EffectParameters = compilerParameters.EffectParameters; } [DataMemberIgnore] public EffectCompilerParameters EffectParameters = EffectCompilerParameters.Default; #region IDictionary<ParameterKey, object> implementation public void Add(ParameterKey key, object value) { SetObject(key, value); } public bool Contains(KeyValuePair<ParameterKey, object> item) { var accessor = GetObjectParameterHelper(item.Key); if (accessor.Offset == -1) return false; return ObjectValues[accessor.Offset].Equals(item.Value); } public void CopyTo(KeyValuePair<ParameterKey, object>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count { get { var count = 0; foreach (var parameterKeyInfo in ParameterKeyInfos) { if (parameterKeyInfo.Key.Type == ParameterKeyType.Permutation) count++; } return count; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<KeyValuePair<ParameterKey, object>> GetEnumerator() { foreach (var parameterKeyInfo in ParameterKeyInfos) { if (parameterKeyInfo.Key.Type != ParameterKeyType.Permutation) continue; yield return new KeyValuePair<ParameterKey, object>(parameterKeyInfo.Key, ObjectValues[parameterKeyInfo.BindingSlot]); } } public bool IsReadOnly => false; public object this[ParameterKey key] { get { return GetObject(key); } set { SetObject(key, value); } } public ICollection<ParameterKey> Keys { get { throw new NotImplementedException(); } } public ICollection<object> Values { get { throw new NotImplementedException(); } } public bool TryGetValue(ParameterKey key, out object value) { foreach (var parameterKeyInfo in ParameterKeyInfos) { if (parameterKeyInfo.Key.Type != ParameterKeyType.Permutation) continue; if (parameterKeyInfo.Key == key) { value = ObjectValues[parameterKeyInfo.BindingSlot]; return true; } } value = null; return false; } public void Add(KeyValuePair<ParameterKey, object> item) { throw new NotImplementedException(); } public bool Remove(KeyValuePair<ParameterKey, object> item) { throw new NotImplementedException(); } #endregion } }
31.286822
163
0.594896
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Shaders/Compiler/CompilerParameters.cs
4,036
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using Xamarin.Forms; using ItsEarth.Models; using ItsEarth.Services; namespace ItsEarth.ViewModels { public class BaseViewModel : INotifyPropertyChanged { public IDataStore<Item> DataStore => DependencyService.Get<IDataStore<Item>>() ?? new MockDataStore(); bool isBusy = false; public bool IsBusy { get { return isBusy; } set { SetProperty(ref isBusy, value); } } string title = string.Empty; public string Title { get { return title; } set { SetProperty(ref title, value); } } protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { var changed = PropertyChanged; if (changed == null) return; changed.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
27.526316
110
0.603569
[ "MIT" ]
ItsEarth/ItsEarth
ItsEarth/ItsEarth/ItsEarth/ViewModels/BaseViewModel.cs
1,571
C#
using System; using System.IO; namespace Knapcode.ExplorePackages { public class TempStreamResult : IDisposable { private readonly Stream _stream; private readonly byte[] _hash; private TempStreamResult(TempStreamResultType type, Stream stream, byte[] hash) { Type = type; _stream = stream; _hash = hash; } public TempStreamResultType Type { get; } public Stream Stream => Type == TempStreamResultType.Success ? _stream : throw new InvalidOperationException($"No stream available. Result type is {Type}."); public byte[] Hash => Type == TempStreamResultType.Success ? _hash : throw new InvalidOperationException($"No hash available. Result type is {Type}."); public static TempStreamResult Success(Stream stream, byte[] hash) { return new TempStreamResult(TempStreamResultType.Success, stream, hash); } public static TempStreamResult NeedNewStream() { return new TempStreamResult(TempStreamResultType.NeedNewStream, stream: null, hash: null); } public static TempStreamResult SemaphoreNotAvailable() { return new TempStreamResult(TempStreamResultType.SemaphoreNotAvailable, stream: null, hash: null); } public void Dispose() { _stream?.Dispose(); } } }
32.953488
165
0.642202
[ "MIT" ]
loic-sharma/ExplorePackages
src/ExplorePackages.Logic/TempStream/TempStreamResult.cs
1,419
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageTake : MonoBehaviour { Health health; Armor armor; [Range(0,1)] float armorAbsobtionRatio; // Start is called before the first frame update private void Start() { armor = GetComponent<Armor>(); health = GetComponent<Health>(); } void takeDamage(int damage) { if (armor.getArmor() > 0) { armor.reduceWith((int)(armorAbsobtionRatio * damage)); health.reduceWith((int)((1 - armorAbsobtionRatio) * damage)); } else { health.reduceWith(damage); } } }
27.44
74
0.593294
[ "MIT" ]
Ivan-Vankov/GameDevCourse
Kamen/Coding Practice/Assets/Scripts/DamageTake.cs
688
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.Gaap.V20180529.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ModifyGroupDomainConfigResponse : AbstractModel { /// <summary> /// The unique request ID, which is returned for each request. RequestId is required for locating a problem. /// </summary> [JsonProperty("RequestId")] public string RequestId{ 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 + "RequestId", this.RequestId); } } }
31.863636
116
0.671184
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Gaap/V20180529/Models/ModifyGroupDomainConfigResponse.cs
1,402
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System; using WinRT.SourceGenerator; namespace Generator { public partial class WinRTComponentScanner { public WinRTComponentScanner(GeneratorExecutionContext context, string assemblyName) { _assemblyName = assemblyName; _context = context; _flag = false; } private readonly string _assemblyName; private readonly GeneratorExecutionContext _context; private bool _flag; public bool Found() { return _flag; } /// <summary> /// Gather information on all classes, interfaces and structs /// Perform code analysis to find scenarios that are erroneous in Windows Runtime</summary> public void FindDiagnostics() { WinRTSyntaxReciever syntaxReciever = (WinRTSyntaxReciever)_context.SyntaxReceiver; if (!syntaxReciever.Declarations.Any()) { Report(WinRTRules.NoPublicTypesRule, null); return; } CheckNamespaces(); CheckDeclarations(); } private void CheckNamespaces() { WinRTSyntaxReciever syntaxReciever = (WinRTSyntaxReciever)_context.SyntaxReceiver; // Used to check for conflicitng namespace names HashSet<string> namespaceNames = new(); foreach (var @namespace in syntaxReciever.Namespaces) { var model = _context.Compilation.GetSemanticModel(@namespace.SyntaxTree); var namespaceSymbol = model.GetDeclaredSymbol(@namespace); string namespaceString = namespaceSymbol.ToString(); bool newNamespaceDeclaration = true; // Because modules could have a namespace defined in different places (i.e. defines a partial class) // we can't rely on `Contains` so we manually check that namespace names cannot differ by case only foreach (var usedNamespaceName in namespaceNames) { if (String.Equals(namespaceString, usedNamespaceName, StringComparison.OrdinalIgnoreCase) && !String.Equals(namespaceString, usedNamespaceName, StringComparison.Ordinal)) { newNamespaceDeclaration = false; Report(WinRTRules.NamespacesDifferByCase, namespaceSymbol.Locations.First(), namespaceString); } } if (newNamespaceDeclaration) { namespaceNames.Add(namespaceString); } if (IsInvalidNamespace(namespaceSymbol, _assemblyName)) { Report(WinRTRules.DisjointNamespaceRule, namespaceSymbol.Locations.First(), _assemblyName, namespaceString); } } } private void CheckDeclarations() { WinRTSyntaxReciever syntaxReciever = (WinRTSyntaxReciever)_context.SyntaxReceiver; foreach (var declaration in syntaxReciever.Declarations) { var model = _context.Compilation.GetSemanticModel(declaration.SyntaxTree); // Check symbol information for whether it is public to properly detect partial types // which can leave out modifier. if (model.GetDeclaredSymbol(declaration).DeclaredAccessibility != Accessibility.Public) { continue; } if (declaration is ClassDeclarationSyntax @class) { var classId = @class.Identifier; var classSymbol = model.GetDeclaredSymbol(@class); var publicMethods = @class.ChildNodes().OfType<MethodDeclarationSyntax>().Where(IsPublic); var props = @class.DescendantNodes().OfType<PropertyDeclarationSyntax>().Where(IsPublic); // filter out methods and properties that will be replaced with our custom type mappings IgnoreCustomTypeMappings(classSymbol, ref publicMethods, ref props); if (!classSymbol.IsSealed && !classSymbol.IsStatic) { Report(WinRTRules.UnsealedClassRule, @class.GetLocation(), classId); } OverloadsOperator(@class); HasMultipleConstructorsOfSameArity(@class); if (classSymbol.IsGenericType) { Report(WinRTRules.GenericTypeRule, @class.GetLocation(), classId); } // check for things in nonWindowsRuntimeInterfaces ImplementsInvalidInterface(classSymbol, @class); CheckProperties(props, classId); // check types -- todo: check for !valid types CheckMethods(publicMethods, classId); } else if (declaration is InterfaceDeclarationSyntax @interface) { var interfaceSym = model.GetDeclaredSymbol(@interface); var methods = @interface.DescendantNodes().OfType<MethodDeclarationSyntax>(); var props = @interface.DescendantNodes().OfType<PropertyDeclarationSyntax>().Where(IsPublic); // filter out methods and properties that will be replaced with our custom type mappings IgnoreCustomTypeMappings(interfaceSym, ref methods, ref props); if (interfaceSym.IsGenericType) { Report(WinRTRules.GenericTypeRule, @interface.GetLocation(), @interface.Identifier); } ImplementsInvalidInterface(interfaceSym, @interface); CheckProperties(props, @interface.Identifier); CheckMethods(methods, @interface.Identifier); } else if (declaration is StructDeclarationSyntax @struct) { CheckStructFields(@struct); } } } private void IgnoreCustomTypeMappings(INamedTypeSymbol typeSymbol, ref IEnumerable<MethodDeclarationSyntax> methods, ref IEnumerable<PropertyDeclarationSyntax> properties) { string QualifiedName(INamedTypeSymbol sym) { return sym.OriginalDefinition.ContainingNamespace + "." + sym.OriginalDefinition.MetadataName; } HashSet<ISymbol> classMethods = new(); foreach (var @interface in typeSymbol.AllInterfaces. Where(symbol => WinRTTypeWriter.MappedCSharpTypes.ContainsKey(QualifiedName(symbol)) || WinRTTypeWriter.ImplementedInterfacesWithoutMapping.Contains(QualifiedName(symbol)))) { foreach (var interfaceMember in @interface.GetMembers()) { classMethods.Add(typeSymbol.FindImplementationForInterfaceMember(interfaceMember)); } } methods = methods.Where(m => !classMethods.Contains(GetModel(m.SyntaxTree).GetDeclaredSymbol(m))); properties = properties.Where(p => !classMethods.Contains(GetModel(p.SyntaxTree).GetDeclaredSymbol(p))); } /// <summary>Checks to see if the class declares any operators (overloading them)</summary> ///<param name="classDeclaration">Class to check</param> /// Class to check for operator declarations /// operator declarations are just like method declarations except they use the `operator` keyword</param> /// <returns>True iff an operator is overloaded by the given class</returns> private void OverloadsOperator(ClassDeclarationSyntax classDeclaration) { var operatorDeclarations = classDeclaration.DescendantNodes().OfType<OperatorDeclarationSyntax>(); foreach (var op in operatorDeclarations) { Report(WinRTRules.OperatorOverloadedRule, op.GetLocation(), op.OperatorToken); } } /// <summary> /// Raises a diagnostic when multiple constructors for a class are defined with the same arity.</summary> /// <param name="classDeclaration">Look at constructors of this class</param> private void HasMultipleConstructorsOfSameArity(ClassDeclarationSyntax classDeclaration) { IEnumerable<ConstructorDeclarationSyntax> constructors = classDeclaration.ChildNodes().OfType<ConstructorDeclarationSyntax>().Where(IsPublic); HashSet<int> aritiesSeenSoFar = new(); foreach (ConstructorDeclarationSyntax constructor in constructors) { int arity = constructor.ParameterList.Parameters.Count; if (aritiesSeenSoFar.Contains(arity)) { Report(WinRTRules.ClassConstructorRule, constructor.GetLocation(), classDeclaration.Identifier, arity); } else { aritiesSeenSoFar.Add(arity); } } } /// <summary> /// The code generation process makes functions with output param `__retval`, /// we will shadow a user variable named the same thing -- so raise a diagnostic instead</summary> /// <param name="method">the method whose parameteres we are inspecting</param> private void HasConflictingParameterName(MethodDeclarationSyntax method) { // check if the identifier is our special name GeneratedReturnValueName bool IsInvalidParameterName(ParameterSyntax stx) { return stx.Identifier.Value.Equals(GeneratedReturnValueName); } var hasInvalidParams = method.ParameterList.Parameters.Any(IsInvalidParameterName); if (hasInvalidParams) { Report(WinRTRules.ParameterNamedValueRule, method.GetLocation(), method.Identifier); } } /// <summary> /// Look for overloads/defaultoverload attribute, conflicting parameter names, /// parameter attribute errors, invalid types</summary> /// <param name="methodDeclarations">Collection of methods</param><param name="typeId">Containing class or interface</param> private void CheckMethods(IEnumerable<MethodDeclarationSyntax> methodDeclarations, SyntaxToken typeId) { Dictionary<string, bool> methodsHasAttributeMap = new(); Dictionary<string, Diagnostic> overloadsWithoutAttributeMap = new Dictionary<string, Diagnostic>(); // var methodDeclarations = interfaceDeclaration.DescendantNodes().OfType<MethodDeclarationSyntax>(); foreach (MethodDeclarationSyntax method in methodDeclarations) { /* Gather information on which methods have overloads, and if any method has the DefaultOverload attribute */ CheckOverloadAttributes(method, methodsHasAttributeMap, overloadsWithoutAttributeMap, typeId); /* Has parameter named __retval */ HasConflictingParameterName(method); /* Check signature for invalid types */ ParameterHasAttributeErrors(method); var methodSym = GetModel(method.SyntaxTree).GetDeclaredSymbol(method); ReportIfInvalidType(methodSym.ReturnType, method.GetLocation(), method.Identifier, typeId); foreach (var arg in methodSym.Parameters) { ReportIfInvalidType(arg.Type, method.GetLocation(), method.Identifier, typeId); } } /* Finishes up the work started by `CheckOverloadAttributes` */ foreach (var thing in overloadsWithoutAttributeMap) { ReportDiagnostic(thing.Value); } } /// <summary>Looks at all the properties of the given class and checks them for improper array types (System.Array instances, multidimensional, jagged)</summary> ///<param name="props">collection of properties</param><param name="typeId">containing class/interface</param> /// <returns>True iff any of the invalid array types are used in any of the propertyy signatures in the given class</returns> private void CheckProperties(IEnumerable<PropertyDeclarationSyntax> props, SyntaxToken typeId) { foreach (var prop in props) { var propSym = GetModel(prop.SyntaxTree).GetDeclaredSymbol(prop); var loc = prop.GetLocation(); if (propSym.GetMethod == null || !propSym.GetMethod.DeclaredAccessibility.Equals(Accessibility.Public)) { Report(WinRTRules.PrivateGetterRule, loc, prop.Identifier); } ReportIfInvalidType(propSym.Type, loc, prop.Identifier, typeId); foreach (var arg in propSym.Parameters) { ReportIfInvalidType(arg.Type, loc, prop.Identifier, typeId); } } } /// <summary>All struct fields must be public, of basic types, and not const</summary> /// <param name="struct">struct declaration</param> private void CheckStructFields(StructDeclarationSyntax @struct) { // delegates not allowed if (@struct.DescendantNodes().OfType<DelegateDeclarationSyntax>().Any()) { Report(WinRTRules.StructHasInvalidFieldRule, @struct.GetLocation(), @struct.Identifier, SimplifySyntaxTypeString(typeof(DelegateDeclarationSyntax).Name)); } // methods not allowed if (@struct.DescendantNodes().OfType<MethodDeclarationSyntax>().Any()) { Report(WinRTRules.StructHasInvalidFieldRule, @struct.GetLocation(), @struct.Identifier, SimplifySyntaxTypeString(typeof(MethodDeclarationSyntax).Name)); } var structSym = GetModel(@struct.SyntaxTree).GetDeclaredSymbol(@struct); // constructors not allowed if (structSym.Constructors.Length > 1) { Report(WinRTRules.StructHasInvalidFieldRule, @struct.GetLocation(), @struct.Identifier, SimplifySyntaxTypeString(typeof(ConstructorDeclarationSyntax).Name)); } var fields = @struct.DescendantNodes().OfType<FieldDeclarationSyntax>(); foreach (var field in fields) { // all fields must be public if (!IsPublic(field)) { Report(WinRTRules.StructHasPrivateFieldRule, field.GetLocation(), @struct.Identifier); } // const fields not allowed if (field.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.ConstKeyword))) { Report(WinRTRules.StructHasConstFieldRule, field.GetLocation(), @struct.Identifier); } // see what type the field is, it must be an allowed type or another struct foreach (var variable in field.Declaration.Variables) { IFieldSymbol varFieldSym = (IFieldSymbol)GetModel(variable.SyntaxTree).GetDeclaredSymbol(variable); if (ValidStructFieldTypes.Contains(varFieldSym.Type.SpecialType) || varFieldSym.Type.TypeKind == TypeKind.Struct) { break; } else { Report(WinRTRules.StructHasInvalidFieldRule, variable.GetLocation(), @struct.Identifier, varFieldSym.Name); } } } // Structs must have some public fields if (!fields.Any()) { Report(WinRTRules.StructWithNoFieldsRule, @struct.GetLocation(), @struct.Identifier); } } /// <summary>Make sure any namespace defined is the same as the winmd or a subnamespace of it /// If component is A.B, e.g. A.B.winmd , then D.Class1 is invalid, as well as A.C.Class2 /// </summary> /// <param name="namespace">the authored namespace to check</param><param name="assemblyName">the name of the component/winmd</param> /// <returns>True iff namespace is disjoint from the assembly name</returns> private bool IsInvalidNamespace(INamespaceSymbol @namespace, string assemblyName) { if (@namespace.ToString() == assemblyName) { return false; } var topLevel = @namespace; while (!topLevel.ContainingNamespace.IsGlobalNamespace) { if (topLevel.ToString() == assemblyName) { return false; } topLevel = topLevel.ContainingNamespace; } return topLevel.ToString() != assemblyName; } ///<summary>Array types can only be one dimensional and not System.Array, ///and there are some types not usable in the Windows Runtime, like KeyValuePair</summary> ///<param name="typeSymbol">The type to check</param><param name="loc">where the type is</param> ///<param name="memberId">The method or property with this type in its signature</param> /// <param name="typeId">the type this member (method/prop) lives in</param> private void ReportIfInvalidType(ITypeSymbol typeSymbol, Location loc, SyntaxToken memberId, SyntaxToken typeId) { // If it's of the form int[], it has to be one dimensional if (typeSymbol.TypeKind == TypeKind.Array) { IArrayTypeSymbol arrTypeSym = (IArrayTypeSymbol)typeSymbol; // [,,]? if (arrTypeSym.Rank > 1) { Report(WinRTRules.MultiDimensionalArrayRule, loc, memberId, typeId); return; } // [][]? if (arrTypeSym.ElementType.TypeKind == TypeKind.Array) { Report(WinRTRules.JaggedArrayRule, loc, memberId, typeId); return; } } // NotValidTypes is an array of types that don't exist in Windows Runtime, so can't be passed between functions in Windows Runtime foreach (var typeName in NotValidTypes) { var notValidTypeSym = GetTypeByMetadataName(typeName); if (SymEq(typeSymbol.OriginalDefinition, notValidTypeSym)) { Report(WinRTRules.UnsupportedTypeRule, loc, memberId, typeName, SuggestType(typeName)); return; } } // construct the qualified name for this type string qualifiedName = ""; if (typeSymbol.ContainingNamespace != null && !typeSymbol.ContainingNamespace.IsGlobalNamespace) { // ContainingNamespace for Enumerable is just System, but we need System.Linq which is the ContainingSymbol qualifiedName += typeSymbol.ContainingSymbol + "."; } // instead of TypeName<int>, TypeName`1 qualifiedName += typeSymbol.MetadataName; // GetTypeByMetadataName fails on "System.Linq.Enumerable" & "System.Collections.ObjectModel.ReadOnlyDictionary`2" // Would be fixed by issue #678 on the dotnet/roslyn-sdk repo foreach (var notValidType in WIPNotValidTypes) { if (qualifiedName == notValidType) { Report(WinRTRules.UnsupportedTypeRule, loc, memberId, notValidType, SuggestType(notValidType)); return; } } } } }
47.138249
173
0.595366
[ "MIT" ]
QPC-database/CsWinRT
src/Authoring/WinRT.SourceGenerator/DiagnosticUtils.cs
20,460
C#
namespace Lykke.Job.TradeDataAggregator.Models { public class ErrorResponse { public string ErrorMessage { get; set; } } }
20.428571
48
0.671329
[ "MIT" ]
LykkeCity/Lykke.Job.TradeDataAggregator
src/Lykke.Job.TradeDataAggregator/Models/ErrorResponse.cs
145
C#
using System; using System.Collections; using UltimaOnline; using UltimaOnline.Commands; namespace UltimaOnline.Items { public class StealableArtifactsSpawner : Item { public class StealableEntry { private Map m_Map; private Point3D m_Location; private int m_MinDelay; private int m_MaxDelay; private Type m_Type; private int m_Hue; public Map Map { get { return m_Map; } } public Point3D Location { get { return m_Location; } } public int MinDelay { get { return m_MinDelay; } } public int MaxDelay { get { return m_MaxDelay; } } public Type Type { get { return m_Type; } } public int Hue { get { return m_Hue; } } public StealableEntry(Map map, Point3D location, int minDelay, int maxDelay, Type type) : this(map, location, minDelay, maxDelay, type, 0) { } public StealableEntry(Map map, Point3D location, int minDelay, int maxDelay, Type type, int hue) { m_Map = map; m_Location = location; m_MinDelay = minDelay; m_MaxDelay = maxDelay; m_Type = type; m_Hue = hue; } public Item CreateInstance() { Item item = (Item)Activator.CreateInstance(m_Type); if (m_Hue > 0) item.Hue = m_Hue; item.Movable = false; item.MoveToWorld(this.Location, this.Map); return item; } } private static StealableEntry[] m_Entries = new StealableEntry[] { // Doom - Artifact rarity 1 new StealableEntry( Map.Malas, new Point3D( 317, 56, -1 ), 72, 108, typeof( RockArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 360, 31, 8 ), 72, 108, typeof( SkullCandleArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 369, 372, -1 ), 72, 108, typeof( BottleArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 378, 372, 0 ), 72, 108, typeof( DamagedBooksArtifact ) ), // Doom - Artifact rarity 2 new StealableEntry( Map.Malas, new Point3D( 432, 16, -1 ), 144, 216, typeof( StretchedHideArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 489, 9, 0 ), 144, 216, typeof( BrazierArtifact ) ), // Doom - Artifact rarity 3 new StealableEntry( Map.Malas, new Point3D( 471, 96, -1 ), 288, 432, typeof( LampPostArtifact ), GetLampPostHue() ), new StealableEntry( Map.Malas, new Point3D( 421, 198, 2 ), 288, 432, typeof( BooksNorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 431, 189, -1 ), 288, 432, typeof( BooksWestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 435, 196, -1 ), 288, 432, typeof( BooksFaceDownArtifact ) ), // Doom - Artifact rarity 5 new StealableEntry( Map.Malas, new Point3D( 447, 9, 8 ), 1152, 1728, typeof( StuddedLeggingsArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 423, 28, 0 ), 1152, 1728, typeof( EggCaseArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 347, 44, 4 ), 1152, 1728, typeof( SkinnedGoatArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 497, 57, -1 ), 1152, 1728, typeof( GruesomeStandardArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 381, 375, 11 ), 1152, 1728, typeof( BloodyWaterArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 489, 369, 2 ), 1152, 1728, typeof( TarotCardsArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 497, 369, 5 ), 1152, 1728, typeof( BackpackArtifact ) ), // Doom - Artifact rarity 7 new StealableEntry( Map.Malas, new Point3D( 475, 23, 4 ), 4608, 6912, typeof( StuddedTunicArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 423, 28, 0 ), 4608, 6912, typeof( CocoonArtifact ) ), // Doom - Artifact rarity 8 new StealableEntry( Map.Malas, new Point3D( 354, 36, -1 ), 9216, 13824, typeof( SkinnedDeerArtifact ) ), // Doom - Artifact rarity 9 new StealableEntry( Map.Malas, new Point3D( 433, 11, -1 ), 18432, 27648, typeof( SaddleArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 403, 31, 4 ), 18432, 27648, typeof( LeatherTunicArtifact ) ), // Doom - Artifact rarity 10 new StealableEntry( Map.Malas, new Point3D( 257, 70, -2 ), 36864, 55296, typeof( ZyronicClaw ) ), new StealableEntry( Map.Malas, new Point3D( 354, 176, 7 ), 36864, 55296, typeof( TitansHammer ) ), new StealableEntry( Map.Malas, new Point3D( 369, 389, -1 ), 36864, 55296, typeof( BladeOfTheRighteous ) ), new StealableEntry( Map.Malas, new Point3D( 467, 92, 4 ), 36864, 55296, typeof( InquisitorsResolution ) ), // Doom - Artifact rarity 12 new StealableEntry( Map.Malas, new Point3D( 487, 364, -1 ), 147456, 221184, typeof( RuinedPaintingArtifact ) ), // Yomotsu Mines - Artifact rarity 1 new StealableEntry( Map.Malas, new Point3D( 18, 110, -1 ), 72, 108, typeof( Basket1Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 66, 114, -1 ), 72, 108, typeof( Basket2Artifact ) ), // Yomotsu Mines - Artifact rarity 2 new StealableEntry( Map.Malas, new Point3D( 63, 12, 11 ), 144, 216, typeof( Basket4Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 5, 29, -1 ), 144, 216, typeof( Basket5NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 30, 81, 3 ), 144, 216, typeof( Basket5WestArtifact ) ), // Yomotsu Mines - Artifact rarity 3 new StealableEntry( Map.Malas, new Point3D( 115, 7, -1 ), 288, 432, typeof( Urn1Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 85, 13, -1 ), 288, 432, typeof( Urn2Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 110, 53, -1 ), 288, 432, typeof( Sculpture1Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 108, 37, -1 ), 288, 432, typeof( Sculpture2Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 121, 14, -1 ), 288, 432, typeof( TeapotNorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 121, 115, -1 ), 288, 432, typeof( TeapotWestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 84, 40, -1 ), 288, 432, typeof( TowerLanternArtifact ) ), // Yomotsu Mines - Artifact rarity 9 new StealableEntry( Map.Malas, new Point3D( 94, 7, -1 ), 18432, 27648, typeof( ManStatuetteSouthArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 1 new StealableEntry( Map.Malas, new Point3D( 113, 640, -2 ), 72, 108, typeof( Basket3NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 102, 355, -1 ), 72, 108, typeof( Basket3WestArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 2 new StealableEntry( Map.Malas, new Point3D( 99, 370, -1 ), 144, 216, typeof( Basket6Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 100, 357, -1 ), 144, 216, typeof( ZenRock1Artifact ) ), // Fan Dancer's Dojo - Artifact rarity 3 new StealableEntry( Map.Malas, new Point3D( 73, 473, -1 ), 288, 432, typeof( FanNorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 99, 372, -1 ), 288, 432, typeof( FanWestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 92, 326, -1 ), 288, 432, typeof( BowlsVerticalArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 97, 470, -1 ), 288, 432, typeof( ZenRock2Artifact ) ), new StealableEntry( Map.Malas, new Point3D( 103, 691, -1 ), 288, 432, typeof( ZenRock3Artifact ) ), // Fan Dancer's Dojo - Artifact rarity 4 new StealableEntry( Map.Malas, new Point3D( 103, 336, 4 ), 576, 864, typeof( Painting1NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 59, 381, 4 ), 576, 864, typeof( Painting1WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 84, 401, 2 ), 576, 864, typeof( Painting2NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 59, 392, 2 ), 576, 864, typeof( Painting2WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 107, 483, -1 ), 576, 864, typeof( TripleFanNorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 50, 475, -1 ), 576, 864, typeof( TripleFanWestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 107, 460, -1 ), 576, 864, typeof( BowlArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 90, 502, -1 ), 576, 864, typeof( CupsArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 107, 688, -1 ), 576, 864, typeof( BowlsHorizontalArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 112, 676, -1 ), 576, 864, typeof( SakeArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 5 new StealableEntry( Map.Malas, new Point3D( 135, 614, -1 ), 1152, 1728, typeof( SwordDisplay1NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 50, 482, -1 ), 1152, 1728, typeof( SwordDisplay1WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 119, 672, -1 ), 1152, 1728, typeof( Painting3Artifact ) ), // Fan Dancer's Dojo - Artifact rarity 6 new StealableEntry( Map.Malas, new Point3D( 90, 326, -1 ), 2304, 3456, typeof( Painting4NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 99, 354, -1 ), 2304, 3456, typeof( Painting4WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 179, 652, -1 ), 2304, 3456, typeof( SwordDisplay2NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 118, 627, -1 ), 2304, 3456, typeof( SwordDisplay2WestArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 7 new StealableEntry( Map.Malas, new Point3D( 90, 483, -1 ), 4608, 6912, typeof( FlowersArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 8 new StealableEntry( Map.Malas, new Point3D( 71, 562, -1 ), 9216, 13824, typeof( DolphinLeftArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 102, 677, -1 ), 9216, 13824, typeof( DolphinRightArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 61, 499, 0 ), 9216, 13824, typeof( SwordDisplay3SouthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 182, 669, -1 ), 9216, 13824, typeof( SwordDisplay3EastArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 162, 647, -1 ), 9216, 13824, typeof( SwordDisplay4WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 124, 624, 0 ), 9216, 13824, typeof( Painting5NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 146, 649, 2 ), 9216, 13824, typeof( Painting5WestArtifact ) ), // Fan Dancer's Dojo - Artifact rarity 9 new StealableEntry( Map.Malas, new Point3D( 100, 488, -1 ), 18432, 27648, typeof( SwordDisplay4NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 175, 606, 0 ), 18432, 27648, typeof( SwordDisplay5NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 157, 608, -1 ), 18432, 27648, typeof( SwordDisplay5WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 187, 643, 1 ), 18432, 27648, typeof( Painting6NorthArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 146, 623, 1 ), 18432, 27648, typeof( Painting6WestArtifact ) ), new StealableEntry( Map.Malas, new Point3D( 178, 629, -1 ), 18432, 27648, typeof( ManStatuetteEastArtifact ) ) }; public static StealableEntry[] Entries { get { return m_Entries; } } private static Type[] m_TypesOfEntries = null; public static Type[] TypesOfEntires { get { if (m_TypesOfEntries == null) { m_TypesOfEntries = new Type[m_Entries.Length]; for (int i = 0; i < m_Entries.Length; i++) m_TypesOfEntries[i] = m_Entries[i].Type; } return m_TypesOfEntries; } } private static StealableArtifactsSpawner m_Instance; public static StealableArtifactsSpawner Instance { get { return m_Instance; } } private static int GetLampPostHue() { if (0.9 > Utility.RandomDouble()) return 0; return Utility.RandomList(0x455, 0x47E, 0x482, 0x486, 0x48F, 0x4F2, 0x58C, 0x66C); } public static void Initialize() { CommandSystem.Register("GenStealArties", AccessLevel.Administrator, new CommandEventHandler(GenStealArties_OnCommand)); CommandSystem.Register("RemoveStealArties", AccessLevel.Administrator, new CommandEventHandler(RemoveStealArties_OnCommand)); } [Usage("GenStealArties")] [Description("Generates the stealable artifacts spawner.")] private static void GenStealArties_OnCommand(CommandEventArgs args) { Mobile from = args.Mobile; if (Create()) from.SendMessage("Stealable artifacts spawner generated."); else from.SendMessage("Stealable artifacts spawner already present."); } [Usage("RemoveStealArties")] [Description("Removes the stealable artifacts spawner and every not yet stolen stealable artifacts.")] private static void RemoveStealArties_OnCommand(CommandEventArgs args) { Mobile from = args.Mobile; if (Remove()) from.SendMessage("Stealable artifacts spawner removed."); else from.SendMessage("Stealable artifacts spawner not present."); } public static bool Create() { if (m_Instance != null && !m_Instance.Deleted) return false; m_Instance = new StealableArtifactsSpawner(); return true; } public static bool Remove() { if (m_Instance == null) return false; m_Instance.Delete(); m_Instance = null; return true; } public static StealableInstance GetStealableInstance(Item item) { if (Instance == null) return null; return (StealableInstance)Instance.m_Table[item]; } public class StealableInstance { private StealableEntry m_Entry; private Item m_Item; private DateTime m_NextRespawn; public StealableEntry Entry { get { return m_Entry; } } public Item Item { get { return m_Item; } set { if (m_Item != null && value == null) { int delay = Utility.RandomMinMax(this.Entry.MinDelay, this.Entry.MaxDelay); this.NextRespawn = DateTime.UtcNow + TimeSpan.FromMinutes(delay); } if (Instance != null) { if (m_Item != null) Instance.m_Table.Remove(m_Item); if (value != null) Instance.m_Table[value] = this; } m_Item = value; } } public DateTime NextRespawn { get { return m_NextRespawn; } set { m_NextRespawn = value; } } public StealableInstance(StealableEntry entry) : this(entry, null, DateTime.UtcNow) { } public StealableInstance(StealableEntry entry, Item item, DateTime nextRespawn) { m_Item = item; m_NextRespawn = nextRespawn; m_Entry = entry; } public void CheckRespawn() { if (this.Item != null && (this.Item.Deleted || this.Item.Movable || this.Item.Parent != null)) this.Item = null; if (this.Item == null && DateTime.UtcNow >= this.NextRespawn) { this.Item = this.Entry.CreateInstance(); } } } private Timer m_RespawnTimer; private StealableInstance[] m_Artifacts; private Hashtable m_Table; public override string DefaultName { get { return "Stealable Artifacts Spawner - Internal"; } } private StealableArtifactsSpawner() : base(1) { Movable = false; m_Artifacts = new StealableInstance[m_Entries.Length]; m_Table = new Hashtable(m_Entries.Length); for (int i = 0; i < m_Entries.Length; i++) { m_Artifacts[i] = new StealableInstance(m_Entries[i]); } m_RespawnTimer = Timer.DelayCall(TimeSpan.Zero, TimeSpan.FromMinutes(15.0), new TimerCallback(CheckRespawn)); } public override void OnDelete() { base.OnDelete(); if (m_RespawnTimer != null) { m_RespawnTimer.Stop(); m_RespawnTimer = null; } foreach (StealableInstance si in m_Artifacts) { if (si.Item != null) si.Item.Delete(); } m_Instance = null; } public void CheckRespawn() { foreach (StealableInstance si in m_Artifacts) { si.CheckRespawn(); } } public StealableArtifactsSpawner(Serial serial) : base(serial) { m_Instance = this; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version writer.WriteEncodedInt(m_Artifacts.Length); for (int i = 0; i < m_Artifacts.Length; i++) { StealableInstance si = m_Artifacts[i]; writer.Write((Item)si.Item); writer.WriteDeltaTime((DateTime)si.NextRespawn); } } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); m_Artifacts = new StealableInstance[m_Entries.Length]; m_Table = new Hashtable(m_Entries.Length); int length = reader.ReadEncodedInt(); for (int i = 0; i < length; i++) { Item item = reader.ReadItem(); DateTime nextRespawn = reader.ReadDeltaTime(); if (i < m_Artifacts.Length) { StealableInstance si = new StealableInstance(m_Entries[i], item, nextRespawn); m_Artifacts[i] = si; if (si.Item != null) m_Table[si.Item] = si; } } for (int i = length; i < m_Entries.Length; i++) { m_Artifacts[i] = new StealableInstance(m_Entries[i]); } m_RespawnTimer = Timer.DelayCall(TimeSpan.Zero, TimeSpan.FromMinutes(15.0), new TimerCallback(CheckRespawn)); } } }
48.397619
151
0.561913
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Decoration Artifacts/StealableArtifactsSpawner.cs
20,327
C#
using System.Threading.Tasks; namespace Automaton.Runner.Core.Services { public interface IHubService { Task Connect(JsonWebToken token, string runnerName); Task Disconnect(); Task Ping(string runnerName); } }
20.666667
60
0.681452
[ "Apache-2.0" ]
lulzzz/automaton-studio
Automaton.Runner.Core/Services/Interface/IHubService.cs
250
C#
/* Copyright (c) Citrix Systems, Inc. * 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. * * 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.Threading; using System.Windows.Forms; using NUnit.Framework; using XenAdmin.Wizards.NewPolicyWizard; namespace XenAdminTests.WizardTests.cowleyPolicies_xml { [TestFixture, Category(TestCategories.UICategoryB)] class NewPolicyWizardTest : WizardTest<NewPolicyWizardSpecific<XenAPI.VMPP>> { public NewPolicyWizardTest() : base(new string[] { "Policy Name", "Protected VMs", "Snapshot Type", "Snapshot schedule","Archive Options","Email Alerts","Finish" } , true, false) { } protected override NewPolicyWizardSpecific<XenAPI.VMPP> NewWizard() { return new NewPolicyWizardSpecific<XenAPI.VMPP>(base.GetAnyPool()); } protected override void TestPage(string pageName) { if (pageName == "Policy Name") { MW(() => (TestUtils.GetTextBox(wizard, "xenTabPagePolicy.textBoxName")).Text = "policy"); } } } }
39.903226
147
0.679871
[ "BSD-2-Clause" ]
GaborApatiNagy/xenadmin
XenAdminTests/WizardTests/NewPolicyWizardTest.cs
2,476
C#
// Copyright (c) Justin Fouts All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Xunit; namespace Clearly.Crud.Test.Unit; public class FormatTokenizedStringTests { [Fact] public void ItParses_SingleToken() { // Arrange var replacements = new Dictionary<string, string?> { { "Key", "Example" } }; var pattern = "[Key]"; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("Example", result); } [Fact] public void ItParses_BackToBackTokens() { // Arrange var replacements = new Dictionary<string, string?> { { "1", "back to " }, { "2", "back" } }; var pattern = "These are [1][2]."; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("These are back to back.", result); } [Fact] public void ItParses_EscapesInTokens() { // Arrange var replacements = new Dictionary<string, string?> { { "An[Odd]Key", "is" } }; var pattern = "This [An[[Odd]]Key] escaped."; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("This is escaped.", result); } [Fact] public void ItParses_EscapesInTokens_ImmediatelyAfterAToken() { // Arrange var replacements = new Dictionary<string, string?> { { "First", "a " }, { "Second]Key", "test" } }; var pattern = "This is [First][Second]]Key] of sorts."; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("This is a test of sorts.", result); } [Fact] public void ItParses_EscapesInTokens_AtEnds() { // Arrange var replacements = new Dictionary<string, string?> { { "Odd", "is" } }; var pattern = "This [[[Odd]]] escaped."; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("This [is] escaped.", result); } [Fact] public void ItParses_RouteLikeTokens() { // Arrange var replacements = new Dictionary<string, string?> { { "Part1", "api" }, { "Part2", "controller" }, { "Part3", "action" } }; var pattern = "[Part1]/[Part2]/[Part3]"; // Act var result = pattern.FormatTokenizedString(replacements); // Assert Assert.Equal("api/controller/action", result); } [Fact] public void ItThrowsOn_UnclosedBrackets() { // Arrange var replacements = new Dictionary<string, string?>(); var pattern = "This has an [ unclosed bracket!"; // Act void Act() => pattern.FormatTokenizedString(replacements!); // Assert Assert.Throws<InvalidOperationException>(Act); } [Fact] public void ItThrowsOn_UnclosedBrackets_AtEnd() { // Arrange var replacements = new Dictionary<string, string?>(); var pattern = "This has an unclosed bracket!["; // Act void Act() => pattern.FormatTokenizedString(replacements!); // Assert Assert.Throws<InvalidOperationException>(Act); } [Fact] public void ItThrowsOn_UnMatchedClosingBracket() { // Arrange var replacements = new Dictionary<string, string?>(); var pattern = "This has an unclosed bracket!]"; // Act void Act() => pattern.FormatTokenizedString(replacements!); // Assert Assert.Throws<InvalidOperationException>(Act); } [Fact] public void ItThrowsOn_OpeningBracketInToken() { // Arrange var replacements = new Dictionary<string, string?>(); var pattern = "This has [Brackets [in] a token]!"; // Act void Act() => pattern.FormatTokenizedString(replacements!); // Assert Assert.Throws<InvalidOperationException>(Act); } [Fact] public void ItThrowsOn_KeyNotFound() { // Arrange var replacements = new Dictionary<string, string?> { { "OtherKey", "Example" } }; var pattern = "[Key]"; // Act void Act() => pattern.FormatTokenizedString(replacements!); // Assert Assert.Throws<InvalidOperationException>(Act); } }
26.993902
132
0.586176
[ "MIT" ]
JFouts/clearly
test/Clearly.Crud.Test.Unit/FormatTokenizedStringTests.cs
4,427
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; using UnityEngine.SceneManagement; public class leaderboardBehavior : MonoBehaviour { public Transform entryContainer; public Transform entryTemplate; public TextMeshProUGUI posText; public TextMeshProUGUI nameText; public TextMeshProUGUI scoreText; private List<Transform> highscoreEntryTransformList; void Start() { entryTemplate.gameObject.SetActive(false); /*highscoreEntryList = new List<HighscoreEntry>() { new HighscoreEntry { name = "xxx", score = 2}, new HighscoreEntry { name = "xxx", score = 3}, new HighscoreEntry { name = "xxx", score = 1}, new HighscoreEntry { name = "xxx", score = 4}, new HighscoreEntry { name = "xxx", score = 8}, new HighscoreEntry { name = "xxx", score = 6}, new HighscoreEntry { name = "xxx", score = 7}, new HighscoreEntry { name = "xxx", score = 5}, new HighscoreEntry { name = "xxx", score = 9888888}, }; */ string jsonString = PlayerPrefs.GetString("public"); Highscores highscores = JsonUtility.FromJson<Highscores>(jsonString); jsonString = PlayerPrefs.GetString("public"); highscores = JsonUtility.FromJson<Highscores>(jsonString); for (int i = 0; i < highscores.highscoreEntryList.Count; i++) { for (int j = 0; j < highscores.highscoreEntryList.Count; j++) { if (highscores.highscoreEntryList[j].score < highscores.highscoreEntryList[i].score) { HighscoreEntry tmp = highscores.highscoreEntryList[i]; highscores.highscoreEntryList[i] = highscores.highscoreEntryList[j]; highscores.highscoreEntryList[j] = tmp; } } } /* for (int i = 0; i < highscores.highscoreEntryList.Count; i++) { { Debug.Log(PlayerPrefs.GetString("leaderboard2")); highscores.highscoreEntryList.RemoveAt((highscores.highscoreEntryList.Count -1)); } } */ highscoreEntryTransformList = new List<Transform>(); foreach (HighscoreEntry highscoreEntry in highscores.highscoreEntryList) { CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList); } } void CreateHighscoreEntryTransform(HighscoreEntry highscoreEntry, Transform container, List<Transform> transformList) { Transform entryTransform = Instantiate(entryTemplate, container); RectTransform entryRectTransform = entryTransform.GetComponent<RectTransform>(); entryRectTransform.anchoredPosition = new Vector2(0, -50f * (transformList.Count - 1)); entryTransform.gameObject.SetActive(true); int rank = transformList.Count + 1; string rankString; switch (rank) { default: rankString = rank + "th"; break; case 1: rankString = "1st"; break; case 2: rankString = "2nd"; break; case 3: rankString = "3rd"; break; } posText.text = rankString; string name = highscoreEntry.name; nameText.text = highscoreEntry.name; float score = highscoreEntry.score; scoreText.text = score.ToString(); transformList.Add(entryTransform); } public static void AddHighscoreEntry(string name, float score) { HighscoreEntry highscoreEntry = new HighscoreEntry { name = name, score = score }; string jsonString = PlayerPrefs.GetString("public"); Highscores highscores = JsonUtility.FromJson<Highscores>(jsonString); if (highscores == null) { highscores = new Highscores() { highscoreEntryList = new List<HighscoreEntry>() }; } highscores.highscoreEntryList.Add(highscoreEntry); string json = JsonUtility.ToJson(highscores); PlayerPrefs.SetString("public", json); PlayerPrefs.Save(); } private class Highscores { public List<HighscoreEntry> highscoreEntryList; } [System.Serializable] private class HighscoreEntry { public string name; public float score; } public void BackToMainMenu() { SceneManager.LoadScene("MainMenu"); } void Update() { if ((Input.GetKey("escape"))) { BackToMainMenu(); } } }
32.033784
121
0.601139
[ "MIT" ]
kan2k/1885.
Assets/BehaviorScript/leaderboardBehavior.cs
4,743
C#
/* PftConditionalLiteral.cs */ #region Using directives using System; #endregion namespace ManagedClient.Pft.Ast { /// <summary> /// Условный литерал. /// </summary> [Serializable] public sealed class PftConditionalLiteral : PftAst { #region Properties #endregion #region Construction public PftConditionalLiteral() { } public PftConditionalLiteral ( string text ) { if (ReferenceEquals(text, null)) { throw new ArgumentNullException("text"); } Text = text; } public PftConditionalLiteral ( PftParser.ConditionalLiteralContext context ) { string text = context.GetText(); Text = PftUtility.PrepareLiteral(text); } #endregion #region Private members #endregion #region Public methods #endregion #region PftAst members #endregion } }
17.015385
59
0.513562
[ "MIT" ]
amironov73/ManagedClient.3
ManagedClient/Pft/Ast/PftConditionalLiteral.cs
1,123
C#
using UnityEngine; using System.Collections; public class FaceDirection : AbstractBehavior { // Use this for initialization void Start() { } // Update is called once per frame void Update() { var right = inputState.GetButtonValue(inputButtons[0]); var left = inputState.GetButtonValue(inputButtons[1]); if (right) { inputState.direction = Directions.Right; } else if (left) { inputState.direction = Directions.Left; } transform.localScale = new Vector3((float)inputState.direction, 1, 1); } }
24.44
78
0.613748
[ "Apache-2.0" ]
emilmannfeldt/Thor-Game
Asatruth/Assets/Scripts/Behaviors/FaceDirection.cs
613
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 braket-2019-09-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Braket.Model { /// <summary> /// Container for the parameters to the CreateQuantumTask operation. /// Creates a quantum task. /// </summary> public partial class CreateQuantumTaskRequest : AmazonBraketRequest { private string _action; private string _clientToken; private string _deviceArn; private string _deviceParameters; private string _outputs3Bucket; private string _outputs3KeyPrefix; private long? _shots; private Dictionary<string, string> _tags = new Dictionary<string, string>(); /// <summary> /// Gets and sets the property Action. /// <para> /// The action associated with the task. /// </para> /// </summary> [AWSProperty(Required=true)] public string Action { get { return this._action; } set { this._action = value; } } // Check to see if Action property is set internal bool IsSetAction() { return this._action != null; } /// <summary> /// Gets and sets the property ClientToken. /// <para> /// The client token associated with the request. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string ClientToken { get { return this._clientToken; } set { this._clientToken = value; } } // Check to see if ClientToken property is set internal bool IsSetClientToken() { return this._clientToken != null; } /// <summary> /// Gets and sets the property DeviceArn. /// <para> /// The ARN of the device to run the task on. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=256)] public string DeviceArn { get { return this._deviceArn; } set { this._deviceArn = value; } } // Check to see if DeviceArn property is set internal bool IsSetDeviceArn() { return this._deviceArn != null; } /// <summary> /// Gets and sets the property DeviceParameters. /// <para> /// The parameters for the device to run the task on. /// </para> /// </summary> [AWSProperty(Min=1, Max=48000)] public string DeviceParameters { get { return this._deviceParameters; } set { this._deviceParameters = value; } } // Check to see if DeviceParameters property is set internal bool IsSetDeviceParameters() { return this._deviceParameters != null; } /// <summary> /// Gets and sets the property OutputS3Bucket. /// <para> /// The S3 bucket to store task result files in. /// </para> /// </summary> [AWSProperty(Required=true, Min=3, Max=63)] public string OutputS3Bucket { get { return this._outputs3Bucket; } set { this._outputs3Bucket = value; } } // Check to see if OutputS3Bucket property is set internal bool IsSetOutputS3Bucket() { return this._outputs3Bucket != null; } /// <summary> /// Gets and sets the property OutputS3KeyPrefix. /// <para> /// The key prefix for the location in the S3 bucket to store task results in. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1024)] public string OutputS3KeyPrefix { get { return this._outputs3KeyPrefix; } set { this._outputs3KeyPrefix = value; } } // Check to see if OutputS3KeyPrefix property is set internal bool IsSetOutputS3KeyPrefix() { return this._outputs3KeyPrefix != null; } /// <summary> /// Gets and sets the property Shots. /// <para> /// The number of shots to use for the task. /// </para> /// </summary> [AWSProperty(Required=true, Min=0)] public long Shots { get { return this._shots.GetValueOrDefault(); } set { this._shots = value; } } // Check to see if Shots property is set internal bool IsSetShots() { return this._shots.HasValue; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Tags to be added to the quantum task you're creating. /// </para> /// </summary> public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
29.767677
104
0.56074
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Braket/Generated/Model/CreateQuantumTaskRequest.cs
5,894
C#
using System.Web; using System.Web.Optimization; namespace GraphWebhooks { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.84375
112
0.574417
[ "MIT" ]
OfficeDev/TrainingContent-Archive
O3653/O3653-19 WebHooks/Completed Projects/Exercise 2/GraphWebhooks/GraphWebhooks/App_Start/BundleConfig.cs
1,245
C#
/************************************************************************ AvalonDock Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at https://opensource.org/licenses/MS-PL ************************************************************************/ using System; namespace AvalonDock { /// <summary> /// Implements a class that provides mathematical helper methods. /// </summary> internal static class MathHelper { /// <summary> /// Ensures that <paramref name="min"/> is greater <paramref name="max"/> via Exception (if not) /// and returns a valid value inside the given bounds. /// /// That is, (<paramref name="min"/> or <paramref name="max"/> is returned if /// <paramref name="value"/> is out of bounds, <paramref name="value"/> is returned otherwise. /// </summary> /// <param name="value"></param> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static double MinMax(double value, double min, double max) { if (min > max) throw new ArgumentException("The minimum should not be greater then the maximum", nameof(min)); if (value < min) return min; return value > max ? max : value; } /// <summary> /// Throw an exception if <paramref name="value"/> is smaller than 0. /// </summary> /// <param name="value"></param> public static void AssertIsPositiveOrZero(double value) { if (value < 0.0) throw new ArgumentException("Invalid value, must be a positive number or equal to zero", nameof(value)); } } }
34.702128
124
0.605763
[ "MIT" ]
Tech305/AvalonDock
source/Components/AvalonDock/MathHelper.cs
1,633
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MarginTrading.MarketMaker.Contracts.Enums; using MarginTrading.MarketMaker.Contracts.Messages; using MarginTrading.MarketMaker.Enums; namespace MarginTrading.MarketMaker.Services.SpotPrices.Implementation { internal class SpotOrderCommandsGeneratorService : ISpotOrderCommandsGeneratorService { private static readonly Dictionary<string, AssetPairRate> _pendingBuyRates = new Dictionary<string, AssetPairRate>(); private static readonly Dictionary<string, AssetPairRate> _pendingSellRates = new Dictionary<string, AssetPairRate>(); private readonly Dictionary<string, AssetPairBidAsk> _quotes = new Dictionary<string, AssetPairBidAsk>(); private readonly ConcurrentDictionary<string, object> _locksByAssetPairId = new ConcurrentDictionary<string, object>(); public IReadOnlyList<OrderCommand> GenerateOrderCommands(string assetPairId, bool isBuy, decimal newBestPrice, decimal ordersVolume) { lock (_locksByAssetPairId.GetOrAdd(assetPairId, k => new object())) { return FixNegativeSpreadAndCreateOrderCommands(ordersVolume, assetPairId, isBuy, newBestPrice) ?? Array.Empty<OrderCommand>(); } } [CanBeNull] private IReadOnlyList<OrderCommand> FixNegativeSpreadAndCreateOrderCommands(decimal ordersVolume, string assetPairId, bool isBuy, decimal newBestPrice) { AssetPairRate feedData = new AssetPairRate { BestPrice = newBestPrice, AssetPairId = assetPairId, IsBuy = isBuy, }; AssetPairRate pendingFeedData; decimal bid; decimal ask; _quotes.TryGetValue(assetPairId, out var bestBidAsk); if (isBuy) { bid = newBestPrice; ask = bestBidAsk?.Ask ?? decimal.MaxValue; _pendingSellRates.TryGetValue(assetPairId, out pendingFeedData); if (bid >= ask) { if (pendingFeedData != null) { if (bid >= pendingFeedData.BestPrice) { _pendingBuyRates[assetPairId] = feedData; return null; } } else { _pendingBuyRates[assetPairId] = feedData; return null; } } if (pendingFeedData != null) { _pendingSellRates.Remove(assetPairId); } } else { bid = bestBidAsk?.Bid ?? decimal.MinValue; ask = newBestPrice; _pendingBuyRates.TryGetValue(assetPairId, out pendingFeedData); if (bid >= ask) { if (pendingFeedData != null) { if (bid >= pendingFeedData.BestPrice) { _pendingSellRates[assetPairId] = feedData; return null; } } else { _pendingSellRates[assetPairId] = feedData; return null; } } if (pendingFeedData != null) { _pendingBuyRates.Remove(assetPairId); } } _quotes[assetPairId] = new AssetPairBidAsk { Ask = ask, Bid = bid, }; var orders = new[] {feedData, pendingFeedData}.Where(d => d != null) .Select(rate => CreateCommand(rate, ordersVolume)).ToList(); AppendDeleteCommands(orders); return orders; } private static void AppendDeleteCommands(List<OrderCommand> orders) { var orderDirections = orders.Where(o => o.Direction != null).Select(o => o.Direction).Distinct().ToList(); foreach (var orderDirection in orderDirections) { orders.Add(new OrderCommand { CommandType = OrderCommandTypeEnum.DeleteOrder, Direction = orderDirection, }); } } private static OrderCommand CreateCommand(AssetPairRate feedData, decimal volume) { return new OrderCommand { Price = feedData.BestPrice, Volume = volume, CommandType = OrderCommandTypeEnum.SetOrder, Direction = feedData.IsBuy ? OrderDirectionEnum.Buy : OrderDirectionEnum.Sell, }; } private class AssetPairBidAsk { public decimal Bid { get; set; } public decimal Ask { get; set; } } private class AssetPairRate { public string AssetPairId { get; set; } public bool IsBuy { get; set; } public decimal BestPrice { get; set; } } } }
34.031056
159
0.519073
[ "MIT" ]
LykkeCity/MT.MarketMaker
src/MarginTrading.MarketMaker/Services/SpotPrices/Implementation/SpotOrderCommandsGeneratorService.cs
5,481
C#
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Http; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Configuration; using Gigya.Microdot.Configuration.Objects; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Orleans.Hosting; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; using Ninject; using Ninject.Activation; using Ninject.Extensions.Factory; using Ninject.Modules; using ConsulClient = Gigya.Microdot.ServiceDiscovery.ConsulClient; using IConsulClient = Gigya.Microdot.ServiceDiscovery.IConsulClient; namespace Gigya.Microdot.Ninject { /// <inheritdoc /> /// <summary> /// Contains all binding except hosting layer /// </summary> public class MicrodotModule : NinjectModule { private readonly Type[] NonSingletonBaseTypes = { typeof(ConsulDiscoverySource), typeof(RemoteHostPool), typeof(LoadBalancer), typeof(ConfigDiscoverySource), typeof(HttpServiceListener), typeof(GigyaSiloHost) }; public override void Load() { //Need to be initialized before using any regex! new RegexTimeoutInitializer().Init(); Kernel.Bind(typeof(DisposableCollection<,>)).ToSelf().InSingletonScope(); if (Kernel.CanResolve<Func<long, DateTime>>() == false) Kernel.Load<FuncModule>(); this.BindClassesAsSingleton( NonSingletonBaseTypes, typeof(ConfigurationAssembly), typeof(ServiceProxyAssembly)); this.BindInterfacesAsSingleton( NonSingletonBaseTypes, new List<Type>{typeof(ILog)}, typeof(ConfigurationAssembly), typeof(ServiceProxyAssembly), typeof(SharedLogicAssembly), typeof(ServiceDiscoveryAssembly)); Bind<IRemoteHostPoolFactory>().ToFactory(); Kernel.BindPerKey<string, ReportingStrategy, IPassiveAggregatingHealthCheck, PassiveAggregatingHealthCheck>(); Kernel.BindPerKey<string, ReachabilityCheck, IMultiEnvironmentServiceDiscovery, MultiEnvironmentServiceDiscovery>(); Kernel.BindPerKey<string, ReachabilityChecker, IServiceDiscovery, ServiceDiscovery.ServiceDiscovery>(); Kernel.Bind<Func<HttpClientConfiguration, HttpMessageHandler>>().ToMethod(c => HttpClientConfiguration => { var clientHandler = new HttpClientHandler(); if (HttpClientConfiguration.UseHttps) { var httpAuthenticator = c.Kernel.Get<IHttpsAuthenticator>(); httpAuthenticator.AddHttpMessageHandlerAuthentication(clientHandler, HttpClientConfiguration); } return clientHandler; }); Kernel.BindPerString<IServiceProxyProvider, ServiceProxyProvider>(); Kernel.BindPerString<AggregatingHealthStatus>(); Rebind<MetricsContext>() .ToMethod(c => Metric.Context(GetTypeOfTarget(c).Name)) .InScope(GetTypeOfTarget); Rebind<IServiceDiscoverySource>().To<ConsulDiscoverySource>().InTransientScope(); Bind<IServiceDiscoverySource>().To<LocalDiscoverySource>().InTransientScope(); Bind<IServiceDiscoverySource>().To<ConfigDiscoverySource>().InTransientScope(); Bind<INodeSourceFactory>().To<ConsulNodeSourceFactory>().InTransientScope(); Rebind<ILoadBalancer>().To<LoadBalancer>().InTransientScope(); Rebind<NodeMonitoringState>().ToSelf().InTransientScope(); Bind<IDiscovery>().To<Discovery>().InSingletonScope(); Rebind<ServiceDiscovery.Rewrite.ConsulClient, ServiceDiscovery.Rewrite.IConsulClient>() .To<ServiceDiscovery.Rewrite.ConsulClient>().InSingletonScope(); Kernel.Rebind<IConsulClient>().To<ConsulClient>().InTransientScope(); Kernel.Load<ServiceProxyModule>(); Kernel.Rebind<IConfigObjectsCache>().To<ConfigObjectsCache>().InSingletonScope(); Kernel.Rebind<IConfigObjectCreator>().To<ConfigObjectCreator>().InTransientScope(); Kernel.Bind<IConfigEventFactory>().To<ConfigEventFactory>(); Kernel.Bind<IConfigFuncFactory>().ToFactory(); // ServiceSchema is at ServiceContracts, and cannot be depended on IServiceInterfaceMapper, which belongs to Microdot Kernel.Rebind<ServiceSchema>() .ToMethod(c =>new ServiceSchema(c.Kernel.Get<IServiceInterfaceMapper>().ServiceInterfaceTypes.ToArray())).InSingletonScope(); Kernel.Rebind<SystemInitializer.SystemInitializer>().ToSelf().InSingletonScope(); } protected static Type GetTypeOfTarget(IContext context) { var type = context.Request.Target?.Member.DeclaringType; return type ?? typeof(MicrodotModule); } } }
43.848684
141
0.689122
[ "Apache-2.0" ]
myarichuk/microdot
Gigya.Microdot.Ninject/MicrodotModule.cs
6,667
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; namespace Steeltoe.Common.Contexts { public interface IApplicationContext { IConfiguration Configuration { get; } IServiceProvider ServiceProvider { get; } object GetService(string name, Type serviceType); T GetService<T>(string name); T GetService<T>(); object GetService(Type serviceType); IEnumerable<T> GetServices<T>(); bool ContainsService(string name, Type serviceType); bool ContainsService<T>(string name); void Register(string name, object instance); object Deregister(string name); } }
25.277778
78
0.695604
[ "Apache-2.0" ]
Hawxy/Steeltoe
src/Common/src/Abstractions/Contexts/IApplicationContext.cs
912
C#
using Microsoft.Xna.Framework; using Requiem.Scenes; namespace Requiem.Entities.Enemy.AI { public sealed class GuardBehavior : Behavior { public GuardBehavior(FiniteStateMachine fsm, string next = null) : base(fsm, next) { } public override void Start() { } public override void Update(GameTime time) { } } }
18.043478
72
0.571084
[ "MIT" ]
DanCuccia/Requiem_Engine
Requiem/Requiem/Entities/Enemy/AI/GuardBehavior.cs
417
C#
using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace ExtendIOSConcepts { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private readonly MyCustomView m_view1; private readonly PanningView m_panningView; public MainPage() { InitializeComponent(); m_panningView = new PanningView(); Workspace.Children.Add(m_panningView.View); m_panningView.SetMargin(1300, 1300); m_panningView.SetSize(1700, 1600); m_view1 = new MyCustomView(); Workspace.Children.Add(m_view1.View); //m_panningView.ParentForChildren.Children.Add(m_view1.View); m_view1.SetMargin(100, 200); m_view1.SetSize(100, 45); //for (int i = 0; i < 10; i++) //{ // for (int j = 0; j < 10; j++) // { // MyCustomView view = new MyCustomView(); // m_panningView.ParentForChildren.Children.Add(view.View); // view.SetMargin(100 * i, 100 * j); // view.SetSize(100, 45); // } //} } private void MovePanel_OnClick(object sender, RoutedEventArgs e) { m_view1.SetMargin(300, 500); m_view1.RequestNewLayout(); m_view1.RequestNewLayout(); } private void ExpandPanel_OnClick(object sender, RoutedEventArgs e) { m_view1.SetSize(600, 300); m_view1.RequestNewLayout(); m_view1.RequestNewLayout(); } private void ComplexMove_OnClick(object sender, RoutedEventArgs e) { m_view1.SetMargin(100, 200); m_view1.SetSize(100, 100); m_view1.View.InvalidateArrange(); m_view1.SetMargin(100, 400); m_view1.SetSize(200, 500); m_view1.View.InvalidateMeasure(); m_view1.SetMargin(300, 500); m_view1.SetSize(250, 300); m_view1.View.InvalidateMeasure(); m_view1.View.InvalidateMeasure(); m_view1.View.InvalidateMeasure(); m_view1.SetSize(600, 300); m_view1.View.InvalidateMeasure(); m_view1.SetSize(60, 350); m_view1.SetSize(65, 400); } } }
26.696203
107
0.697961
[ "MIT" ]
cghersi/UWPExamples
ExtendIOSConcepts/ExtendIOSConcepts/MainPage.xaml.cs
2,111
C#
using System; using System.Collections.Generic; using System.Linq; using Nop.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Vendors; using Nop.Plugin.Api.DataStructures; using Nop.Plugin.Api.Infrastructure; using Nop.Services.Stores; using System.Threading.Tasks; namespace Nop.Plugin.Api.Services { public class ProductApiService : IProductApiService { private readonly IRepository<ProductCategory> _productCategoryMappingRepository; private readonly IRepository<Product> _productRepository; private readonly IStoreMappingService _storeMappingService; private readonly IRepository<Vendor> _vendorRepository; public ProductApiService( IRepository<Product> productRepository, IRepository<ProductCategory> productCategoryMappingRepository, IRepository<Vendor> vendorRepository, IStoreMappingService storeMappingService) { _productRepository = productRepository; _productCategoryMappingRepository = productCategoryMappingRepository; _vendorRepository = vendorRepository; _storeMappingService = storeMappingService; } public IList<Product> GetProducts( IList<int> ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, int? limit = null, int? page = null, int? sinceId = null, int? categoryId = null, string vendorName = null, bool? publishedStatus = null, IList<string> manufacturerPartNumbers = null, bool? isDownload = null) { var query = GetProductsQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, vendorName, publishedStatus, ids, categoryId, manufacturerPartNumbers, isDownload); if (sinceId > 0) { query = query.Where(c => c.Id > sinceId); } return new ApiList<Product>(query, (page ?? Constants.Configurations.DefaultPageValue) - 1, (limit ?? Constants.Configurations.DefaultLimit)); } public async Task<int> GetProductsCountAsync( DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, string vendorName = null, int? categoryId = null, IList<string> manufacturerPartNumbers = null, bool? isDownload = null) { var query = GetProductsQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, vendorName, publishedStatus, ids: null, categoryId, manufacturerPartNumbers, isDownload); return await query.WhereAwait(async p => await _storeMappingService.AuthorizeAsync(p)).CountAsync(); } public Product GetProductById(int productId) { if (productId == 0) { return null; } return _productRepository.Table.FirstOrDefault(product => product.Id == productId && !product.Deleted); } public Product GetProductByIdNoTracking(int productId) { if (productId == 0) { return null; } return _productRepository.Table.FirstOrDefault(product => product.Id == productId && !product.Deleted); } private IQueryable<Product> GetProductsQuery( DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, string vendorName = null, bool? publishedStatus = null, IList<int> ids = null, int? categoryId = null, IList<string> manufacturerPartNumbers = null, bool? isDownload = null) { var query = _productRepository.Table; if (ids != null && ids.Count > 0) { query = query.Where(p => ids.Contains(p.Id)); } if (manufacturerPartNumbers != null && manufacturerPartNumbers.Count > 0) { query = query.Where(p => manufacturerPartNumbers.Contains(p.ManufacturerPartNumber)); } if (publishedStatus != null) { query = query.Where(p => p.Published == publishedStatus.Value); } if (isDownload != null) { query = query.Where(p => p.IsDownload == isDownload.Value); } // always return products that are not deleted!!! query = query.Where(p => !p.Deleted); if (createdAtMin != null) { query = query.Where(p => p.CreatedOnUtc > createdAtMin.Value); } if (createdAtMax != null) { query = query.Where(p => p.CreatedOnUtc < createdAtMax.Value); } if (updatedAtMin != null) { query = query.Where(p => p.UpdatedOnUtc > updatedAtMin.Value); } if (updatedAtMax != null) { query = query.Where(p => p.UpdatedOnUtc < updatedAtMax.Value); } if (!string.IsNullOrEmpty(vendorName)) { query = from vendor in _vendorRepository.Table join product in _productRepository.Table on vendor.Id equals product.VendorId where vendor.Name == vendorName && !vendor.Deleted && vendor.Active select product; } if (categoryId != null) { var categoryMappingsForProduct = from productCategoryMapping in _productCategoryMappingRepository.Table where productCategoryMapping.CategoryId == categoryId select productCategoryMapping; query = from product in query join productCategoryMapping in categoryMappingsForProduct on product.Id equals productCategoryMapping.ProductId select product; } query = query.OrderBy(product => product.Id); return query; } } }
41.019108
181
0.579814
[ "MIT" ]
DataplaceDevs/api-for-nopcommerce
Nop.Plugin.Api/Services/ProductApiService.cs
6,442
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Vapor Store")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Vapor Store")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cf47c1bd-aeb2-4639-be7e-ef073b92ab6d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.741981
[ "MIT" ]
ginkogrudev/Softuni-Work
CSharp BasicsMore Exercises/02. Vapor Store/Properties/AssemblyInfo.cs
1,406
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; namespace MonsterSwap { public class Character: GameObject { public Character(int x, int y, int width, int height) :base(x, y, width, height) { } } }
23.5
61
0.72147
[ "MIT" ]
maegico/Monster-Swap
MonsterSwap/Character.cs
519
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mono.Options; namespace LOGGING { class Program { public static string todefpath; public static string loggingBIN; public static bool help; public static string fname = "null"; public static int loglevel = -10; public static string writeby = "null"; public static string log = "null"; public static List<string> anotherarg = new List<string>(); static void Main(string[] args) { try { todefpath = Environment.GetEnvironmentVariable("toolsonpath", EnvironmentVariableTarget.Machine); loggingBIN = todefpath + "\\LOGSERVICE.tologservexec"; } catch (ArgumentNullException) { Console.Write("CANT LOAD TOOLSON SYSTEM FRAME"); return; } OptionSet options = new OptionSet() { { "h|help=", "Show command list", v => help = v != null }, { "r=|read=", "Read Logfile", v => fname = v }, { "l=|level=", "Log Level (more of -9 less of 9)", (int v) => loglevel = v }, { "a=|apps=", "Writed apps(or Session) name", v => writeby = v }, { "s=|string=", "Log", v => log = v }, }; anotherarg = options.Parse(args); if (help) { helpscr(options); } if (fname != "null") { readlog(fname); } if (loglevel != -10) { writelog(loglevel,writeby,log); ; } } static void writelog(int llev,string uan,string lstr) { //Write by (<TIME>)|[<Writer>][<FRAME>]|{<Agent>}|*<LogLevel>*|:<Log> string logsrc = "\n("+ DateTime.Now+ ")|[LOGSRV1][TOOLSON]|{" + uan + "}|*" + llev.ToString() + "*|:" + lstr; System.IO.File.AppendAllText(loggingBIN, logsrc, Encoding.GetEncoding("utf-8")); } static void readlog(string fname) { string[] srclog = System.IO.File.ReadAllLines(fname, Encoding.GetEncoding("utf-8")); foreach (string logtxt in srclog) { if (logtxt == "") { continue; } try{ string[] cutbyent = logtxt.Split('|'); if(writeby!="null"){if(cutbyent[2]!='{'+writeby+'}'){continue;}} if(loglevel!=-10){if(cutbyent[3]!='*'+loglevel.ToString()+'*'){continue;}} Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(cutbyent[0]); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(cutbyent[1]); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write(cutbyent[2]); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(cutbyent[3]); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(cutbyent[4]); }catch(Exception){Console.ForegroundColor=ConsoleColor.Red;Console.WriteLine("File Error");Console.ResetColor();Environment.Exit(1);} Console.ResetColor(); } } static void helpscr(OptionSet options) { Console.WriteLine("Toolson LOGGING FRAME :"); options.WriteOptionDescriptions(Console.Out); } } }
39.228261
149
0.527016
[ "MIT" ]
Jetgame0906/Toolson
Toolson/LOGGING/Program.cs
3,611
C#
// Copyright 2015-2017 Directive Games Limited - All Rights Reserved using UnrealBuildTool; using System.IO; public class DriftGooglePlay : ModuleRules { public DriftGooglePlay(ReadOnlyTargetRules TargetRules) : base(TargetRules) { bEnableShadowVariableWarnings = false; PCHUsage = PCHUsageMode.NoSharedPCHs; PublicIncludePaths.AddRange( new string[] { "DriftGooglePlay/Public", } ); PrivateIncludePaths.AddRange( new string[] { "DriftGooglePlay/Private", } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "Projects", } ); PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Engine", "OnlineSubsystem", "OnlineSubsystemUtils", "Drift", } ); } }
19.804348
76
0.580681
[ "MIT" ]
dgnorth/drift-ue4-plugin
Plugins/Drift/DriftGooglePlay/Source/DriftGooglePlay.Build.cs
911
C#
using Assistant.Net.Abstractions; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Assistant.Net.Core.Tests.Internal { public class TypeEncoderTests { [TestCaseSource(nameof(ValidCases))] public void Encode_returnsName(string name, Type type) { var encoder = new ServiceCollection() .AddTypeEncoder() .BuildServiceProvider() .GetRequiredService<ITypeEncoder>(); encoder.Encode(type).Should().Be(name); } [TestCaseSource(nameof(ValidCases))] public void Decode_returnsType(string name, Type type) { var encoder = new ServiceCollection() .AddTypeEncoder() .BuildServiceProvider() .GetRequiredService<ITypeEncoder>(); encoder.Decode(name).Should().Be(type); } [TestCaseSource(nameof(InvalidCases))] public void Encode_returnsNull(Type type) { var encoder = new ServiceCollection() .AddTypeEncoder() .BuildServiceProvider() .GetRequiredService<ITypeEncoder>(); encoder.Encode(type).Should().BeNull(); } public static IEnumerable<TestCaseData> ValidCases() => validTypes.Select(x => new TestCaseData(x.Key, x.Value)); private static Type[] InvalidCases() => new[] {new {X = 1}.GetType()}; private static readonly Dictionary<string, Type> validTypes = new() { ["String"] = typeof(string), ["Int32"] = typeof(int), ["DateTime"] = typeof(DateTime), ["DateTimeOffset"] = typeof(DateTimeOffset), ["String[]"] = typeof(string[]), ["Int32[,]"] = typeof(int[,]), ["IEnumerable`1[Int32]"] = typeof(IEnumerable<int>), ["Dictionary`2[Type,Object]"] = typeof(Dictionary<Type, object>), ["List`1[IList`1[String]]"] = typeof(List<IList<string>>), ["ImmutableArray`1[ImmutableArray`1[String]]"] = typeof(ImmutableArray<ImmutableArray<string>>), ["IEnumerable`1"] = typeof(IEnumerable<>) }; } }
35.545455
121
0.58994
[ "Apache-2.0" ]
iotbusters/assistant.net
tests/Core.Tests/Internal/TypeEncoderTests.cs
2,348
C#
using System; using System.Collections.Generic; using System.Text; using FluentAssertions; using Xunit; namespace ShoppingCart.Tests { public class DiscountTest { [Fact] public void Ctor_ShouldCreate() { var arrange = new Discount(DiscountType.Amount, 10.5); arrange.DiscountType.Should().Be(DiscountType.Amount); arrange.Value.Should().Be(10.5); } [Fact] public void Ctor_When_discountValue_entry_less_than_zero_should_throw_exception() { Action action = () => new Discount(DiscountType.Amount, -1); action.Should().Throw<Exception>().WithMessage("Discount value must be greather than zero"); } [Fact] public void CalculateDiscountPrice_when_productPrice_less_than_zero_throw_exception() { double price = -1; var discount = new Discount(DiscountType.Amount,5); Action action = () => discount.CalculateDiscountPrice(price); action.Should().Throw<Exception>().WithMessage("Product price must be greather than zero"); } [Fact] public void CalculateDiscountPrice_when_discountRate_less_or_equal_zero_throw_exception() { double price = -1; var discount = new Discount(DiscountType.Rate, 5); Action action = () => discount.CalculateDiscountPrice(price); action.Should().Throw<Exception>().WithMessage("Product price must be greather than zero"); } [Fact] public void CalculateDiscountPrice_With_Rate() { double productPrice = 10; var discount = new Discount(DiscountType.Rate, 1); var act = discount.CalculateDiscountPrice(productPrice); act.Should().Be(0.1); } [Fact] public void CalculateDiscountPrice_With_Amount() { double productPrice = 10; var discount = new Discount(DiscountType.Amount,5); double act = discount.CalculateDiscountPrice(productPrice); act.Should().Be(5); } } }
35.081967
104
0.618224
[ "MIT" ]
Ferhatcandas/ShoppingCart
test/ShoppingCart.Tests/DiscountTest.cs
2,142
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Threading.Tasks; using Elastic.Elasticsearch.Xunit.XunitPlumbing; using Nest; using Tests.Framework.EndpointTests; using static Tests.Framework.EndpointTests.UrlTester; namespace Tests.Modules.Scripting.ExecutePainlessScript { public class ExecutePainlessScriptUrlTests { [U] public async Task Urls() { var painless = "1 + 1"; var request = new ExecutePainlessScriptRequest { Script = new InlineScript(painless) }; await POST("/_scripts/painless/_execute") .Fluent(c => c.ExecutePainlessScript<string>(f => f.Script(s => s.Source(painless)))) .Request(c => c.ExecutePainlessScript<string>(request)) .FluentAsync(c => c.ExecutePainlessScriptAsync<string>(f => f.Script(s => s.Source(painless)))) .RequestAsync(c => c.ExecutePainlessScriptAsync<string>(request)) ; } } }
32.59375
100
0.73442
[ "Apache-2.0" ]
Brightspace/elasticsearch-net
tests/Tests/Modules/Scripting/ExecutePainlessScript/ExecutePainlessScriptUrlTests.cs
1,045
C#
namespace ContractHttpTests { using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using ContractHttp; /// <summary> /// Defines a test service with retry. /// </summary> [Retry(RetryCount = 3, HttpStatusCodesToRetry = new[] { HttpStatusCode.BadGateway, (HttpStatusCode)429 })] [HttpClientContract(Route = "api")] public interface ITestServiceWithRetry { /// <summary> /// Get async. /// </summary> /// <param name="status">The status.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> [Get("{status}")] Task<HttpResponseMessage> GetAsync(int status); /// <summary> /// Get async. /// </summary> /// <param name="status">The status.</param> /// <param name="responseFunc">A function to build the return data from the response.</param> /// <returns>A value.</returns> [Get("{status}")] Task<bool> GetAsync(int status, Func<HttpResponseMessage, bool> responseFunc); /// <summary> /// Post async /// </summary> /// <param name="responseFunc">A response function.</param> /// <returns>True or false.</returns> [Post] Task<bool> PostAsync(Func<HttpResponseMessage, bool> responseFunc); } }
33.341463
110
0.588881
[ "MIT" ]
PCOL/ContractHttp
tests/ContractHttpTests/Resources/ITestServiceWithRetry.cs
1,367
C#
// // Community Forums // Copyright (c) 2013-2021 // by DNN Community // // 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; using System.Collections.Generic; using System.Data; using System.ComponentModel; using System.Web.UI; using System.Web; namespace DotNetNuke.Modules.ActiveForums.Controls { public class ControlsBase : ForumBase { private string _template; private string _templateFile; private string _currentView = "forumview"; private bool _parseTemplate = false; [Description("Template for display"), PersistenceMode(PersistenceMode.InnerProperty)] public string DisplayTemplate { get { if (string.IsNullOrEmpty(_template) && ! (string.IsNullOrEmpty(TemplateFile))) { if (! (string.IsNullOrEmpty(ControlConfig.TemplatePath))) { _template = ControlConfig.TemplatePath + TemplateFile; } else { _template = TemplateFile; } _template = Utilities.GetTemplate(Page.ResolveUrl(_template)); _template = Utilities.ParseTokenConfig(_template, "default", ControlConfig); } return _template; } set { _template = value; } } public string CurrentView { get { return _currentView; } set { _currentView = value; } } public bool ParseTemplateFile { get { return _parseTemplate; } set { _parseTemplate = value; } } public int DataPageId { get { if (HttpContext.Current.Request.QueryString[ParamKeys.PageId] == null) { return 1; } else { return int.Parse(HttpContext.Current.Request.QueryString[ParamKeys.PageId].ToString()); } } } protected override void OnInit(EventArgs e) { base.OnInit(e); if (ParseTemplateFile) { if (! (string.IsNullOrEmpty(DisplayTemplate))) { Control ctl = Page.ParseControl(DisplayTemplate); LinkControls(ctl.Controls); this.Controls.Add(ctl); } } } private void LinkControls(ControlCollection ctrls) { foreach (Control ctrl in ctrls) { if (ctrl is Controls.ForumRow) { ((Controls.ForumRow)ctrl).UserRoles = ForumUser.UserRoles; } if (ctrl is Controls.ControlsBase) { ((Controls.ControlsBase)ctrl).ControlConfig = this.ControlConfig; ((Controls.ControlsBase)ctrl).ForumData = ForumData; ((Controls.ControlsBase)ctrl).ForumInfo = ForumInfo; } if (ctrl.Controls.Count > 0) { LinkControls(ctrl.Controls); } } } } }
26.631579
116
0.693676
[ "MIT" ]
DNNCommunity/Dnn.CommunityForums
components/Controls/ControlsBase.cs
3,544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class libx_Assets_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(libx.Assets); args = new Type[]{typeof(System.String), typeof(System.Boolean)}; method = type.GetMethod("LoadSceneAsync", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LoadSceneAsync_0); } static StackObject* LoadSceneAsync_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @additive = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @path = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = libx.Assets.LoadSceneAsync(@path, @additive); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
36.459016
147
0.695144
[ "MIT" ]
tuita520/JEngine
UnityProject/Assets/Dependencies/ILRuntime/Generated/libx_Assets_Binding.cs
2,224
C#
// Copyright (c) Microsoft. All rights reserved. using System; namespace Microsoft.Azure.IoTSolutions.IoTStreamAnalytics.StreamingAgent.Runtime { public interface IStreamingConfig { string ConsumerGroup { get; } int ReceiveBatchSize { get; } TimeSpan ReceiveTimeout { get; } } public class StreamingConfig : IStreamingConfig { public string ConsumerGroup { get; set; } public int ReceiveBatchSize { get; set; } public TimeSpan ReceiveTimeout { get; set; } } }
26.75
80
0.671028
[ "MIT" ]
VSChina/pcs-telemetry-agent
StreamingAgent/Runtime/StreamingConfig.cs
537
C#
using Cosmos.Conversions.Common; using Cosmos.Conversions.Common.Core; using Cosmos.Exceptions; namespace Cosmos.Conversions.Determiners; /// <summary> /// Internal core conversion helper from string to long /// </summary> public static class StringLongDeterminer { // ReSharper disable once InconsistentNaming internal static bool IS(string str) => Is(str); // ReSharper disable once InconsistentNaming private const NumberStyles NUMBER_STYLES = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent; /// <summary> /// Is /// </summary> /// <param name="text"></param> /// <param name="style"></param> /// <param name="formatProvider"></param> /// <param name="matchedCallback"></param> /// <returns></returns> public static bool Is( string text, NumberStyles style = NUMBER_STYLES, IFormatProvider formatProvider = null, Action<long> matchedCallback = null) { if (string.IsNullOrWhiteSpace(text)) return false; return long.TryParse(text, style, formatProvider.SafeNumber(), out var number) .IfFalseThenInvoke(ValueDeterminer.IsXxxAgain<long>, text) .IfTrueThenInvoke(matchedCallback, number); } /// <summary> /// Is /// </summary> /// <param name="text"></param> /// <param name="tries"></param> /// <param name="style"></param> /// <param name="formatProvider"></param> /// <param name="matchedCallback"></param> /// <returns></returns> public static bool Is( string text, IEnumerable<IConversionTry<string, long>> tries, NumberStyles style = NUMBER_STYLES, IFormatProvider formatProvider = null, Action<long> matchedCallback = null) { return ValueDeterminer.IsXXX(text, string.IsNullOrWhiteSpace, (s, act) => Is(s, style, formatProvider.SafeNumber(), act), tries, matchedCallback); } /// <summary> /// To /// </summary> /// <param name="text"></param> /// <param name="defaultVal"></param> /// <param name="style"></param> /// <param name="formatProvider"></param> /// <returns></returns> public static long To( string text, long defaultVal = default, NumberStyles style = NUMBER_STYLES, IFormatProvider formatProvider = null) { if (text is null) return defaultVal; if (long.TryParse(text, style, formatProvider.SafeNumber(), out var number)) return number; return Try.Create(() => Convert.ToInt64(Convert.ToDecimal(text))) .Recover(_ => ValueConverter.ToXxxAgain(text, defaultVal)) .Value; } /// <summary> /// To /// </summary> /// <param name="text"></param> /// <param name="impls"></param> /// <param name="style"></param> /// <param name="formatProvider"></param> /// <returns></returns> public static long To( string text, IEnumerable<IConversionImpl<string, long>> impls, NumberStyles style = NUMBER_STYLES, IFormatProvider formatProvider = null) { return ValueConverter.ToXxx(text, (s, act) => Is(s, style, formatProvider.SafeNumber(), act), impls); } }
34.386792
109
0.583539
[ "Apache-2.0" ]
cosmos-loops/Cosmos.Standard
src/Cosmos.Extensions.Conversions/Cosmos/Conversions/Determiners/StringLongDeterminer.cs
3,645
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.Data; using System.Data.Common; using Microsoft.Data.Sqlite.Properties; using static SQLitePCL.raw; namespace Microsoft.Data.Sqlite { /// <summary> /// Represents a transaction made against a SQLite database. /// </summary> public class SqliteTransaction : DbTransaction { private SqliteConnection _connection; private readonly IsolationLevel _isolationLevel; private bool _completed; internal SqliteTransaction(SqliteConnection connection, IsolationLevel isolationLevel) { if ((isolationLevel == IsolationLevel.ReadUncommitted && connection.ConnectionOptions.Cache != SqliteCacheMode.Shared) || isolationLevel == IsolationLevel.ReadCommitted || isolationLevel == IsolationLevel.RepeatableRead) { isolationLevel = IsolationLevel.Serializable; } _connection = connection; _isolationLevel = isolationLevel; if (isolationLevel == IsolationLevel.ReadUncommitted) { connection.ExecuteNonQuery("PRAGMA read_uncommitted = 1;"); } else if (isolationLevel == IsolationLevel.Serializable) { connection.ExecuteNonQuery("PRAGMA read_uncommitted = 0;"); } else if (isolationLevel != IsolationLevel.Unspecified) { throw new ArgumentException(Resources.InvalidIsolationLevel(isolationLevel)); } connection.ExecuteNonQuery( IsolationLevel == IsolationLevel.Serializable ? "BEGIN IMMEDIATE;" : "BEGIN;"); sqlite3_rollback_hook(connection.Handle, RollbackExternal, null); } /// <summary> /// Gets the connection associated with the transaction. /// </summary> /// <value>The connection associated with the transaction.</value> public new virtual SqliteConnection Connection => _connection; /// <summary> /// Gets the connection associated with the transaction. /// </summary> /// <value>The connection associated with the transaction.</value> protected override DbConnection DbConnection => Connection; internal bool ExternalRollback { get; private set; } /// <summary> /// Gets the isolation level for the transaction. This cannot be changed if the transaction is completed or /// closed. /// </summary> /// <value>The isolation level for the transaction.</value> public override IsolationLevel IsolationLevel => _completed || _connection.State != ConnectionState.Open ? throw new InvalidOperationException(Resources.TransactionCompleted) : _isolationLevel != IsolationLevel.Unspecified ? _isolationLevel : (_connection.ConnectionOptions.Cache == SqliteCacheMode.Shared && _connection.ExecuteScalar<long>("PRAGMA read_uncommitted;") != 0) ? IsolationLevel.ReadUncommitted : IsolationLevel.Serializable; /// <summary> /// Applies the changes made in the transaction. /// </summary> public override void Commit() { if (ExternalRollback || _completed || _connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.TransactionCompleted); } sqlite3_rollback_hook(_connection.Handle, null, null); _connection.ExecuteNonQuery("COMMIT;"); Complete(); } /// <summary> /// Reverts the changes made in the transaction. /// </summary> public override void Rollback() { if (_completed || _connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.TransactionCompleted); } RollbackInternal(); } /// <summary> /// Releases any resources used by the transaction and rolls it back. /// </summary> /// <param name="disposing"> /// true to release managed and unmanaged resources; false to release only unmanaged resources. /// </param> protected override void Dispose(bool disposing) { if (disposing && !_completed && _connection.State == ConnectionState.Open) { RollbackInternal(); } } private void Complete() { _connection.Transaction = null; _connection = null; _completed = true; } private void RollbackInternal() { if (!ExternalRollback) { sqlite3_rollback_hook(_connection.Handle, null, null); _connection.ExecuteNonQuery("ROLLBACK;"); } Complete(); } private void RollbackExternal(object userData) { sqlite3_rollback_hook(_connection.Handle, null, null); ExternalRollback = true; } } }
35.705128
119
0.577379
[ "Apache-2.0" ]
Pankraty/EntityFrameworkCore
src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs
5,570
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyCBA.Core.ViewModels { public class AddNewUserViewModel { [Required, MinLength(6)] [RegularExpression(@"^[ a-zA-Z0-9]+$", ErrorMessage = "Username should only characters and numbers"), MaxLength(40)] public string Username { get; set; } [Required(ErrorMessage = "Please enter the First Name")] [RegularExpression(@"^[ a-zA-Z]+$", ErrorMessage = "First name should only characters and white spaces"), MaxLength(40)] [Display(Name = "First name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter the Last Name")] [RegularExpression(@"^[ a-zA-Z]+$", ErrorMessage = "Last name should only characters and white spaces"), MaxLength(40)] [Display(Name = "Last name")] public string LastName { get; set; } [Required] [Display(Name = "Email Address")] [DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid email address"), MaxLength(100)] public string Email { get; set; } [Required] [Display(Name = "Phone Number")] [DataType(DataType.PhoneNumber, ErrorMessage = "Please enter a valid Phone Number")] [RegularExpression(@"^[0-9+]+$", ErrorMessage = "Please enter a valid phone number"), MinLength(11), MaxLength(16)] public string PhoneNumber { get; set; } [Required(ErrorMessage = "Please select a branch")] [Display(Name = "Branch")] public int BranchId { get; set; } [Required(ErrorMessage = "Please select a role")] [Display(Name = "Role")] public int RoleId { get; set; } } }
38.765957
129
0.639407
[ "MIT" ]
Sulzmido/Core-Banking-Application-NHibernate
MyCBA.Core/ViewModels/UserViewModels/AddNewUserViewModel.cs
1,824
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; namespace Amazon.PowerShell.Cmdlets.CGIP { /// <summary> /// Creates a new user in the specified user pool. /// /// /// <para> /// If <code>MessageAction</code> is not set, the default is to send a welcome message /// via email or phone (SMS). /// </para><para> /// This message is based on a template that you configured in your call to create or /// update a user pool. This template includes your custom sign-up instructions and placeholders /// for user name and temporary password. /// </para><para> /// Alternatively, you can call <code>AdminCreateUser</code> with “SUPPRESS” for the <code>MessageAction</code> /// parameter, and Amazon Cognito will not send any email. /// </para><para> /// In either case, the user will be in the <code>FORCE_CHANGE_PASSWORD</code> state until /// they sign in and change their password. /// </para><para><code>AdminCreateUser</code> requires developer credentials. /// </para> /// </summary> [Cmdlet("New", "CGIPUserAdmin", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.CognitoIdentityProvider.Model.UserType")] [AWSCmdlet("Calls the Amazon Cognito Identity Provider AdminCreateUser API operation.", Operation = new[] {"AdminCreateUser"}, SelectReturnType = typeof(Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse))] [AWSCmdletOutput("Amazon.CognitoIdentityProvider.Model.UserType or Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse", "This cmdlet returns an Amazon.CognitoIdentityProvider.Model.UserType object.", "The service call response (type Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class NewCGIPUserAdminCmdlet : AmazonCognitoIdentityProviderClientCmdlet, IExecutor { #region Parameter ClientMetadata /// <summary> /// <para> /// <para>A map of custom key-value pairs that you can provide as input for any custom workflows /// that this action triggers. </para><para>You create custom workflows by assigning AWS Lambda functions to user pool triggers. /// When you use the AdminCreateUser API action, Amazon Cognito invokes the function that /// is assigned to the <i>pre sign-up</i> trigger. When Amazon Cognito invokes this function, /// it passes a JSON payload, which the function receives as input. This payload contains /// a <code>clientMetadata</code> attribute, which provides the data that you assigned /// to the ClientMetadata parameter in your AdminCreateUser request. In your function /// code in AWS Lambda, you can process the <code>clientMetadata</code> value to enhance /// your workflow for your specific needs.</para><para>For more information, see <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html">Customizing /// User Pool Workflows with Lambda Triggers</a> in the <i>Amazon Cognito Developer Guide</i>.</para><note><para>Take the following limitations into consideration when you use the ClientMetadata /// parameter:</para><ul><li><para>Amazon Cognito does not store the ClientMetadata value. This data is available only /// to AWS Lambda triggers that are assigned to a user pool to support custom workflows. /// If your user pool configuration does not include triggers, the ClientMetadata parameter /// serves no purpose.</para></li><li><para>Amazon Cognito does not validate the ClientMetadata value.</para></li><li><para>Amazon Cognito does not encrypt the the ClientMetadata value, so don't use it to provide /// sensitive information.</para></li></ul></note> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Collections.Hashtable ClientMetadata { get; set; } #endregion #region Parameter DesiredDeliveryMedium /// <summary> /// <para> /// <para>Specify <code>"EMAIL"</code> if email will be used to send the welcome message. Specify /// <code>"SMS"</code> if the phone number will be used. The default value is <code>"SMS"</code>. /// More than one value can be specified.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("DesiredDeliveryMediums")] public System.String[] DesiredDeliveryMedium { get; set; } #endregion #region Parameter ForceAliasCreation /// <summary> /// <para> /// <para>This parameter is only used if the <code>phone_number_verified</code> or <code>email_verified</code> /// attribute is set to <code>True</code>. Otherwise, it is ignored.</para><para>If this parameter is set to <code>True</code> and the phone number or email address /// specified in the UserAttributes parameter already exists as an alias with a different /// user, the API call will migrate the alias from the previous user to the newly created /// user. The previous user will no longer be able to log in using that alias.</para><para>If this parameter is set to <code>False</code>, the API throws an <code>AliasExistsException</code> /// error if the alias already exists. The default value is <code>False</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? ForceAliasCreation { get; set; } #endregion #region Parameter MessageAction /// <summary> /// <para> /// <para>Set to <code>"RESEND"</code> to resend the invitation message to a user that already /// exists and reset the expiration limit on the user's account. Set to <code>"SUPPRESS"</code> /// to suppress sending the message. Only one value can be specified.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [AWSConstantClassSource("Amazon.CognitoIdentityProvider.MessageActionType")] public Amazon.CognitoIdentityProvider.MessageActionType MessageAction { get; set; } #endregion #region Parameter TemporaryPassword /// <summary> /// <para> /// <para>The user's temporary password. This password must conform to the password policy that /// you specified when you created the user pool.</para><para>The temporary password is valid only once. To complete the Admin Create User flow, /// the user must enter the temporary password in the sign-in page along with a new password /// to be used in all future sign-ins.</para><para>This parameter is not required. If you do not specify a value, Amazon Cognito generates /// one for you.</para><para>The temporary password can only be used until the user account expiration limit that /// you specified when you created the user pool. To reset the account after that time /// limit, you must call <code>AdminCreateUser</code> again, specifying <code>"RESEND"</code> /// for the <code>MessageAction</code> parameter.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String TemporaryPassword { get; set; } #endregion #region Parameter UserAttribute /// <summary> /// <para> /// <para>An array of name-value pairs that contain user attributes and attribute values to /// be set for the user to be created. You can create a user without specifying any attributes /// other than <code>Username</code>. However, any attributes that you specify as required /// (when creating a user pool or in the <b>Attributes</b> tab of the console) must be /// supplied either by you (in your call to <code>AdminCreateUser</code>) or by the user /// (when he or she signs up in response to your welcome message).</para><para>For custom attributes, you must prepend the <code>custom:</code> prefix to the attribute /// name.</para><para>To send a message inviting the user to sign up, you must specify the user's email /// address or phone number. This can be done in your call to AdminCreateUser or in the /// <b>Users</b> tab of the Amazon Cognito console for managing your user pools.</para><para>In your call to <code>AdminCreateUser</code>, you can set the <code>email_verified</code> /// attribute to <code>True</code>, and you can set the <code>phone_number_verified</code> /// attribute to <code>True</code>. (You can also do this by calling <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html">AdminUpdateUserAttributes</a>.)</para><ul><li><para><b>email</b>: The email address of the user to whom the message that contains the /// code and username will be sent. Required if the <code>email_verified</code> attribute /// is set to <code>True</code>, or if <code>"EMAIL"</code> is specified in the <code>DesiredDeliveryMediums</code> /// parameter.</para></li><li><para><b>phone_number</b>: The phone number of the user to whom the message that contains /// the code and username will be sent. Required if the <code>phone_number_verified</code> /// attribute is set to <code>True</code>, or if <code>"SMS"</code> is specified in the /// <code>DesiredDeliveryMediums</code> parameter.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("UserAttributes")] public Amazon.CognitoIdentityProvider.Model.AttributeType[] UserAttribute { get; set; } #endregion #region Parameter Username /// <summary> /// <para> /// <para>The username for the user. Must be unique within the user pool. Must be a UTF-8 string /// between 1 and 128 characters. After the user is created, the username cannot be changed.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String Username { get; set; } #endregion #region Parameter UserPoolId /// <summary> /// <para> /// <para>The user pool ID for the user pool where the user will be created.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String UserPoolId { get; set; } #endregion #region Parameter ValidationData /// <summary> /// <para> /// <para>The user's validation data. This is an array of name-value pairs that contain user /// attributes and attribute values that you can use for custom validation, such as restricting /// the types of user accounts that can be registered. For example, you might choose to /// allow or disallow user sign-up based on the user's domain.</para><para>To configure custom validation, you must create a Pre Sign-up Lambda trigger for the /// user pool as described in the Amazon Cognito Developer Guide. The Lambda trigger receives /// the validation data and uses it in the validation process.</para><para>The user's validation data is not persisted.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public Amazon.CognitoIdentityProvider.Model.AttributeType[] ValidationData { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'User'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse). /// Specifying the name of a property of type Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "User"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the UserPoolId parameter. /// The -PassThru parameter is deprecated, use -Select '^UserPoolId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^UserPoolId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.UserPoolId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-CGIPUserAdmin (AdminCreateUser)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse, NewCGIPUserAdminCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.UserPoolId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute if (this.ClientMetadata != null) { context.ClientMetadata = new Dictionary<System.String, System.String>(StringComparer.Ordinal); foreach (var hashKey in this.ClientMetadata.Keys) { context.ClientMetadata.Add((String)hashKey, (String)(this.ClientMetadata[hashKey])); } } if (this.DesiredDeliveryMedium != null) { context.DesiredDeliveryMedium = new List<System.String>(this.DesiredDeliveryMedium); } context.ForceAliasCreation = this.ForceAliasCreation; context.MessageAction = this.MessageAction; context.TemporaryPassword = this.TemporaryPassword; if (this.UserAttribute != null) { context.UserAttribute = new List<Amazon.CognitoIdentityProvider.Model.AttributeType>(this.UserAttribute); } context.Username = this.Username; #if MODULAR if (this.Username == null && ParameterWasBound(nameof(this.Username))) { WriteWarning("You are passing $null as a value for parameter Username which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.UserPoolId = this.UserPoolId; #if MODULAR if (this.UserPoolId == null && ParameterWasBound(nameof(this.UserPoolId))) { WriteWarning("You are passing $null as a value for parameter UserPoolId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.ValidationData != null) { context.ValidationData = new List<Amazon.CognitoIdentityProvider.Model.AttributeType>(this.ValidationData); } // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.CognitoIdentityProvider.Model.AdminCreateUserRequest(); if (cmdletContext.ClientMetadata != null) { request.ClientMetadata = cmdletContext.ClientMetadata; } if (cmdletContext.DesiredDeliveryMedium != null) { request.DesiredDeliveryMediums = cmdletContext.DesiredDeliveryMedium; } if (cmdletContext.ForceAliasCreation != null) { request.ForceAliasCreation = cmdletContext.ForceAliasCreation.Value; } if (cmdletContext.MessageAction != null) { request.MessageAction = cmdletContext.MessageAction; } if (cmdletContext.TemporaryPassword != null) { request.TemporaryPassword = cmdletContext.TemporaryPassword; } if (cmdletContext.UserAttribute != null) { request.UserAttributes = cmdletContext.UserAttribute; } if (cmdletContext.Username != null) { request.Username = cmdletContext.Username; } if (cmdletContext.UserPoolId != null) { request.UserPoolId = cmdletContext.UserPoolId; } if (cmdletContext.ValidationData != null) { request.ValidationData = cmdletContext.ValidationData; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse CallAWSServiceOperation(IAmazonCognitoIdentityProvider client, Amazon.CognitoIdentityProvider.Model.AdminCreateUserRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Cognito Identity Provider", "AdminCreateUser"); try { #if DESKTOP return client.AdminCreateUser(request); #elif CORECLR return client.AdminCreateUserAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public Dictionary<System.String, System.String> ClientMetadata { get; set; } public List<System.String> DesiredDeliveryMedium { get; set; } public System.Boolean? ForceAliasCreation { get; set; } public Amazon.CognitoIdentityProvider.MessageActionType MessageAction { get; set; } public System.String TemporaryPassword { get; set; } public List<Amazon.CognitoIdentityProvider.Model.AttributeType> UserAttribute { get; set; } public System.String Username { get; set; } public System.String UserPoolId { get; set; } public List<Amazon.CognitoIdentityProvider.Model.AttributeType> ValidationData { get; set; } public System.Func<Amazon.CognitoIdentityProvider.Model.AdminCreateUserResponse, NewCGIPUserAdminCmdlet, object> Select { get; set; } = (response, cmdlet) => response.User; } } }
55.213483
331
0.640497
[ "Apache-2.0" ]
hevaldez07/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/CognitoIdentityProvider/Basic/New-CGIPUserAdmin-Cmdlet.cs
24,574
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Fomusa.Client.Modules.Official { public partial class OfficialListGroup { /// <summary> /// Image1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image Image1; /// <summary> /// title_cate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal title_cate; /// <summary> /// title_name control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal title_name; /// <summary> /// DataList1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DataList DataList1; /// <summary> /// hddGroupCate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField hddGroupCate; } }
33.983607
84
0.522431
[ "MIT" ]
khiem2/quanlyhocsinh
cms_form/Web_CMS/Formosa/Client/Modules/Official/OfficialListGroup.ascx.designer.cs
2,075
C#
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; using System.Security.Claims; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace Backend { public class Startup { private readonly TokenValidationParameters _tokenValidadtionParameters; private readonly TokenProviderOptions _tokenProviderOptions; private readonly SymmetricSecurityKey _signingKey; public IConfigurationRoot Configuration { get; } public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); _signingKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value)); _tokenValidadtionParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = _signingKey, ValidateIssuer = true, ValidIssuer = Configuration.GetSection("TokenAuthentication:Issuer").Value, ValidateAudience = true, ValidAudience = Configuration.GetSection("TokenAuthentication:Audience").Value, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; _tokenProviderOptions = new TokenProviderOptions { Path = Configuration.GetSection("TokenAuthentication:TokenPath").Value, Audience = Configuration.GetSection("TokenAuthentication:Audience").Value, Issuer = Configuration.GetSection("TokenAuthentication:Issuer").Value, SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256), IdentityResolver = GetIdentity }; } public void ConfigureServices(IServiceCollection services) { services.AddGrpc(options => { options.EnableDetailedErrors = true; }); ConfigureAuth(services); var connection = "Data Source=usersContext.db"; services.AddDbContext<UsersContext> (options => options.UseSqlite(connection)); } public void ConfigureAuth(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = _tokenValidadtionParameters; }) .AddCookie(options => { options.Cookie.Name = Configuration.GetSection("TokenAuthentication:CookieName").Value; options.TicketDataFormat = new CustomJwtDataFormat( SecurityAlgorithms.HmacSha256, _tokenValidadtionParameters); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMiddleware<TokenProviderMiddleware>(Options.Create(_tokenProviderOptions)); app.UseAuthentication(); app.UseRouting(routes => { routes.MapGrpcService<AuthenticationService>(); }); } private async Task<ClaimsIdentity> GetIdentity(string username,string password, UsersContext usersContext) { Console.WriteLine("identity"); var result = await usersContext.Users.AnyAsync(x => x.Username == username && x.Password == password); if (!result && username != "test") { return null; } return new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }); } } }
39.975
115
0.619762
[ "MIT" ]
SzymonWelter/Authentication-and-Authorization
Backend/Startup.cs
4,797
C#
using FluentAssertions; using RoadCaptain.App.Runner.Views; using RoadCaptain.GameStates; using Serilog.Events; using Serilog.Sinks.InMemory.Assertions; using Xunit; namespace RoadCaptain.App.Runner.Tests.Unit.Engine { public class WhenWaitingForConnectionStateIsReceived : EngineTest { [Fact] public void MessageIsLogged() { GivenConnectedToZwiftStateReceived(); InMemorySink .Should() .HaveMessage("Waiting for connection from Zwift") .Appearing() .Once() .WithLevel(LogEventLevel.Information); } // TODO: Re-enable this test //[Fact] public void GivenRouteIsLoadedAndMainWindowIsActive_MainWindowIsClosed() { GivenLoadedRoute(); WindowService.ShowMainWindow(); GivenConnectedToZwiftStateReceived(); WindowService .ClosedWindows .Should() .Contain(typeof(MainWindow)) .And .HaveCount(1); } [Fact] public void GivenNoWindowIsActive_CloseIsNotCalled() { GivenConnectedToZwiftStateReceived(); WindowService .ClosedWindows .Should() .BeEmpty(); } [Fact] public void GivenRouteIsLoaded_InGameWindowIsShown() { GivenLoadedRoute(); WindowService.ShowMainWindow(); GivenConnectedToZwiftStateReceived(); WindowService .ShownWindows .Should() .Contain(typeof(InGameNavigationWindow)); } [Fact] public void GivenNoRouteIsLoaded_InGameWindowIsNotShown() { GivenConnectedToZwiftStateReceived(); WindowService .ShownWindows .Should() .BeEmpty(); } private void GivenConnectedToZwiftStateReceived() { ReceiveGameState(new WaitingForConnectionState()); } private void GivenLoadedRoute() { var plannedRoute = new PlannedRoute { Name = "test", World = new World { Id = "watopia" } }; plannedRoute.RouteSegmentSequence.Add(new SegmentSequence { Direction = SegmentDirection.AtoB, SegmentId = "watopia-beach-island-loop-001" }); SetFieldValueByName("_loadedRoute", plannedRoute); } } }
26.958333
154
0.553323
[ "Artistic-2.0" ]
sandermvanvliet/RoadCaptain
test/RoadCaptain.App.Runner.Tests.Unit/Engine/WhenWaitingForConnectionStateIsReceived.cs
2,590
C#
using System.Threading.Tasks; using Application.Profiles; using Microsoft.AspNetCore.Mvc; namespace API.Controllers { public class ProfilesController : BaseController { [HttpGet("{username}")] public async Task<ActionResult<Profile>> Get(string username) { return await Mediator.Send(new Details.Query{Username = username}); } } }
25.8
79
0.677003
[ "MIT" ]
NissanGoldberg/Reactivities
API/Controllers/ProfilesController.cs
387
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt321() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt321 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt321 testClass) { var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftRightLogical( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt321(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(firstOp[0] >> 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(firstOp[i] >> 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
38.684478
185
0.580543
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/X86/Sse2/ShiftRightLogical.Int32.1.cs
15,203
C#
namespace RobloxFiles.DataTypes { /// <summary> /// Content is a type used by most url-based XML properties. /// Here, it only exists as a wrapper class for strings. /// </summary> public class Content { public readonly string Url; public override string ToString() => Url; public Content(string url) { Url = url; } public static implicit operator string(Content content) { return content?.Url; } public static implicit operator Content(string url) { return new Content(url); } public override int GetHashCode() { return Url.GetHashCode(); } public override bool Equals(object obj) { if (!(obj is Content content)) return false; return Url.Equals(content.Url); } } }
22.585366
64
0.533477
[ "MIT" ]
CloneTrooper1019/Roblox-File-Format
DataTypes/Content.cs
928
C#
using MihaZupan; namespace ITMOSchedule.Telegram { public static class TelegramSettings { public static string Key { get; } public static HttpToSocks5Proxy Proxy { get; } } }
21.3
55
0.643192
[ "MIT" ]
riiji/ITMOScheduleBot
ITMOSchedule/Telegram/TelegramSettings.cs
215
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(ICarController))] [RequireComponent(typeof(Rigidbody))] public class WheelVehicleVr : MonoBehaviour { [Header("Inputs")] // If isPlayer is false inputs are ignored [SerializeField] bool isPlayer = true; public bool IsPlayer { get { return isPlayer; } set { isPlayer = value; } } private ICarController _carController; // Input names to read using GetAxis [SerializeField] string throttleInput = "Throttle"; [SerializeField] string brakeInput = "Brake"; [SerializeField] string turnInput = "Horizontal"; [SerializeField] string jumpInput = "Jump"; [SerializeField] string driftInput = "Drift"; [SerializeField] string boostInput = "Boost"; /* * Turn input curve: x real input, y value used * My advice (-1, -1) tangent x, (0, 0) tangent 0 and (1, 1) tangent x */ [SerializeField] AnimationCurve turnInputCurve = AnimationCurve.Linear(-1.0f, -1.0f, 1.0f, 1.0f); [Header("Wheels")] [SerializeField] WheelCollider[] driveWheel; public WheelCollider[] DriveWheel { get { return driveWheel; } } [SerializeField] WheelCollider[] turnWheel; public WheelCollider[] TurnWheel { get { return turnWheel; } } // This code checks if the car is grounded only when needed and the data is old enough bool isGrounded = false; int lastGroundCheck = 0; public bool IsGrounded { get { if (lastGroundCheck == Time.frameCount) return isGrounded; lastGroundCheck = Time.frameCount; isGrounded = true; foreach (WheelCollider wheel in wheels) { if (!wheel.gameObject.activeSelf || !wheel.isGrounded) isGrounded = false; } return isGrounded; } } [Header("Behaviour")] /* * Motor torque represent the torque sent to the wheels by the motor with x: speed in km/h and y: torque * The curve should start at x=0 and y>0 and should end with x>topspeed and y<0 * The higher the torque the faster it accelerate * the longer the curve the faster it gets */ [SerializeField] AnimationCurve motorTorque = new AnimationCurve(new Keyframe(0, 200), new Keyframe(50, 300), new Keyframe(200, 0)); // Differential gearing ratio [Range(2, 16)] [SerializeField] float diffGearing = 4.0f; public float DiffGearing { get { return diffGearing; } set { diffGearing = value; } } // Basicaly how hard it brakes [SerializeField] float brakeForce = 1500.0f; public float BrakeForce { get { return brakeForce; } set { brakeForce = value; } } // Max steering hangle, usualy higher for drift car [Range(0f, 50.0f)] [SerializeField] float steerAngle = 30.0f; public float SteerAngle { get { return steerAngle; } set { steerAngle = Mathf.Clamp(value, 0.0f, 50.0f); } } // The value used in the steering Lerp, 1 is instant (Strong power steering), and 0 is not turning at all [Range(0.001f, 1.0f)] [SerializeField] float steerSpeed = 0.2f; public float SteerSpeed { get { return steerSpeed; } set { steerSpeed = Mathf.Clamp(value, 0.001f, 1.0f); } } // How hight do you want to jump? [Range(1f, 1.5f)] [SerializeField] float jumpVel = 1.3f; public float JumpVel { get { return jumpVel; } set { jumpVel = Mathf.Clamp(value, 1.0f, 1.5f); } } // How hard do you want to drift? [Range(0.0f, 2f)] [SerializeField] float driftIntensity = 1f; public float DriftIntensity { get { return driftIntensity; } set { driftIntensity = Mathf.Clamp(value, 0.0f, 2.0f); } } // Reset Values Vector3 spawnPosition; Quaternion spawnRotation; /* * The center of mass is set at the start and changes the car behavior A LOT * I recomment having it between the center of the wheels and the bottom of the car's body * Move it a bit to the from or bottom according to where the engine is */ [SerializeField] Transform centerOfMass; // Force aplied downwards on the car, proportional to the car speed [Range(0.5f, 10f)] [SerializeField] float downforce = 1.0f; public float Downforce { get { return downforce; } set { downforce = Mathf.Clamp(value, 0, 5); } } // When IsPlayer is false you can use this to control the steering float steering; public float Steering { get { return steering; } set { steering = Mathf.Clamp(value, -1f, 1f); } } // When IsPlayer is false you can use this to control the throttle float throttle; public float Throttle { get { return throttle; } set { throttle = Mathf.Clamp(value, -1f, 1f); } } // Like your own car handbrake, if it's true the car will not move [SerializeField] bool handbrake; public bool Handbrake { get { return handbrake; } set { handbrake = value; } } // Use this to disable drifting [HideInInspector] public bool allowDrift = true; bool drift; public bool Drift { get { return drift; } set { drift = value; } } // Use this to read the current car speed (you'll need this to make a speedometer) [SerializeField] float speed = 0.0f; public float Speed { get { return speed; } } [Header("Particles")] // Exhaust fumes [SerializeField] ParticleSystem[] gasParticles; [Header("Boost")] // Disable boost [HideInInspector] public bool allowBoost = true; // Maximum boost available [SerializeField] float maxBoost = 10f; public float MaxBoost { get { return maxBoost; } set { maxBoost = value; } } // Current boost available [SerializeField] float boost = 10f; public float Boost { get { return boost; } set { boost = Mathf.Clamp(value, 0f, maxBoost); } } // Regen boostRegen per second until it's back to maxBoost [Range(0f, 1f)] [SerializeField] float boostRegen = 0.2f; public float BoostRegen { get { return boostRegen; } set { boostRegen = Mathf.Clamp01(value); } } /* * The force applied to the car when boosting * NOTE: the boost does not care if the car is grounded or not */ [SerializeField] float boostForce = 5000; public float BoostForce { get { return boostForce; } set { boostForce = value; } } // Use this to boost when IsPlayer is set to false public bool boosting = false; // Use this to jump when IsPlayer is set to false public bool jumping = false; // Boost particles and sound [SerializeField] ParticleSystem[] boostParticles; [SerializeField] AudioClip boostClip; [SerializeField] AudioSource boostSource; // Private variables set at the start Rigidbody _rb; WheelCollider[] wheels; // Init rigidbody, center of mass, wheels and more void Start() { #if MULTIOSCONTROLS Debug.Log("[ACP] Using MultiOSControls"); #endif if (boostClip != null) { boostSource.clip = boostClip; } boost = maxBoost; _carController = GetComponent<ICarController>(); _rb = GetComponent<Rigidbody>(); spawnPosition = transform.position; spawnRotation = transform.rotation; if (_rb != null && centerOfMass != null) { _rb.centerOfMass = centerOfMass.localPosition; } wheels = GetComponentsInChildren<WheelCollider>(); // Set the motor torque to a non null value because 0 means the wheels won't turn no matter what foreach (WheelCollider wheel in wheels) { wheel.motorTorque = 0.0001f; } } // Visual feedbacks and boost regen void Update() { foreach (ParticleSystem gasParticle in gasParticles) { gasParticle.Play(); ParticleSystem.EmissionModule em = gasParticle.emission; em.rateOverTime = handbrake ? 0 : Mathf.Lerp(em.rateOverTime.constant, Mathf.Clamp(150.0f * throttle, 30.0f, 100.0f), 0.1f); } if (isPlayer && allowBoost) { boost += Time.deltaTime * boostRegen; if (boost > maxBoost) { boost = maxBoost; } } } // Update everything void FixedUpdate() { // Mesure current speed speed = transform.InverseTransformDirection(_rb.velocity).z * 3.6f; // Get all the inputs! if (isPlayer) { Vector3 _inputs = Vector3.zero; _inputs = _carController.GetInputs(); // Accelerate & brake throttle = _inputs.z * 1; // Boost //boosting = (GetInput(boostInput) > 0.5f); // Turn steering = turnInputCurve.Evaluate(_inputs.x) * steerAngle; // Drift //drift = GetInput(driftInput) > 0 && _rb.velocity.sqrMagnitude > 100; // Jump //jumping = _inputs.z != 0; } // Direction foreach (WheelCollider wheel in turnWheel) { wheel.steerAngle = Mathf.Lerp(wheel.steerAngle, steering, steerSpeed); } foreach (WheelCollider wheel in wheels) { wheel.brakeTorque = 0; } // Handbrake if (handbrake) { foreach (WheelCollider wheel in wheels) { // Don't zero out this value or the wheel completly lock up wheel.motorTorque = 0.0001f; wheel.brakeTorque = brakeForce; } } else if (Mathf.Abs(speed) < 4 || Mathf.Sign(speed) == Mathf.Sign(throttle)) { foreach (WheelCollider wheel in driveWheel) { float torque = throttle * motorTorque.Evaluate(speed) * diffGearing / driveWheel.Length; wheel.motorTorque = torque; } } else { foreach (WheelCollider wheel in wheels) { wheel.brakeTorque = Mathf.Abs(throttle) * brakeForce; } } // Jump if (jumping && isPlayer) { if (!IsGrounded) return; _rb.velocity += transform.up * jumpVel; } // Boost if (boosting && allowBoost && boost > 0.1f) { _rb.AddForce(transform.forward * boostForce); boost -= Time.fixedDeltaTime; if (boost < 0f) { boost = 0f; } if (boostParticles.Length > 0 && !boostParticles[0].isPlaying) { foreach (ParticleSystem boostParticle in boostParticles) { boostParticle.Play(); } } if (boostSource != null && !boostSource.isPlaying) { boostSource.Play(); } } else { if (boostParticles.Length > 0 && boostParticles[0].isPlaying) { foreach (ParticleSystem boostParticle in boostParticles) { boostParticle.Stop(); } } if (boostSource != null && boostSource.isPlaying) { boostSource.Stop(); } } // Drift if (drift && allowDrift) { Vector3 driftForce = -transform.right; driftForce.y = 0.0f; driftForce.Normalize(); if (steering != 0) driftForce *= _rb.mass * speed / 7f * throttle * steering / steerAngle; Vector3 driftTorque = transform.up * 0.1f * steering / steerAngle; _rb.AddForce(driftForce * driftIntensity, ForceMode.Force); _rb.AddTorque(driftTorque * driftIntensity, ForceMode.VelocityChange); } // Downforce _rb.AddForce(-transform.up * speed * downforce); } // Reposition the car to the start position public void ResetPos() { transform.position = spawnPosition; transform.rotation = spawnRotation; _rb.velocity = Vector3.zero; _rb.angularVelocity = Vector3.zero; } public void toogleHandbrake(bool h) { handbrake = h; } // MULTIOSCONTROLS is another package I'm working on ignore it I don't know if it will get a release. #if MULTIOSCONTROLS private static MultiOSControls _controls; #endif // Use this method if you want to use your own input manager private float GetInput(string input) { #if MULTIOSCONTROLS return MultiOSControls.GetValue(input, playerId); #else return Input.GetAxis(input); #endif } }
32.271574
136
0.599449
[ "MIT" ]
robinpipirs/VrMicroRacer
Assets/Scripts/WheelVehicleVr.cs
12,717
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace InControl { public class InControlManager : MonoBehaviour { private static InControlManager manager; public bool logDebugInfo = false; public bool invertYAxis = false; public bool enableXInput = false; public bool useFixedUpdate = false; public bool dontDestroyOnLoad = false; public List<string> customProfiles = new List<string>(); public void OnEnable() { if (manager) { Destroy(gameObject); return; } else { manager = this; } if (logDebugInfo) { Debug.Log( "InControl (version " + InputManager.Version + ")" ); Logger.OnLogMessage += HandleOnLogMessage; } InputManager.InvertYAxis = invertYAxis; InputManager.EnableXInput = enableXInput; InputManager.SetupInternal(); foreach (var className in customProfiles) { var classType = Type.GetType( className ); if (classType == null) { Debug.LogError( "Cannot find class for custom profile: " + className ); } else { var customProfileInstance = Activator.CreateInstance( classType ) as UnityInputDeviceProfile; InputManager.AttachDevice( new UnityInputDevice( customProfileInstance ) ); } } if (dontDestroyOnLoad) { DontDestroyOnLoad( this ); } } //void OnDisable() //{ // InputManager.ResetInternal(); //} #if UNITY_ANDROID && INCONTROL_OUYA && !UNITY_EDITOR void Start() { StartCoroutine( CheckForOuyaEverywhereSupport() ); } IEnumerator CheckForOuyaEverywhereSupport() { while (!OuyaSDK.isIAPInitComplete()) { yield return null; } OuyaEverywhereDeviceManager.Enable(); } #endif private void Start() { InputManager.SetupInternal(); } void Update() { if (!useFixedUpdate || Mathf.Approximately( Time.timeScale, 0.0f )) { InputManager.UpdateInternal(); } } void FixedUpdate() { if (useFixedUpdate) { InputManager.UpdateInternal(); } } void OnApplicationFocus( bool focusState ) { InputManager.OnApplicationFocus( focusState ); } void OnApplicationPause( bool pauseState ) { InputManager.OnApplicationPause( pauseState ); } void OnApplicationQuit() { InputManager.OnApplicationQuit(); } void HandleOnLogMessage( LogMessage logMessage ) { switch (logMessage.type) { case LogMessageType.Info: Debug.Log( logMessage.text ); break; case LogMessageType.Warning: Debug.LogWarning( logMessage.text ); break; case LogMessageType.Error: Debug.LogError( logMessage.text ); break; } } } }
19.959732
99
0.611298
[ "Unlicense" ]
Ehwhat/BetaArcadeGame
Assets/Plugins/InControl-1.4.4/Assets/InControl/Source/Components/InControlManager.cs
2,974
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ClientCommandSystem : MonoBehaviour { [SerializeField] NetworkManager_Client client; private void Start() { client.OnTcpMessageReceived += ReceivedServerCommand; } void ReceivedServerCommand(byte[] data) { string s = NetworkManagerBase.encoding.GetString(data); } public void SendNotify_StartingContent() { client.SendTcpPacket("Started"); } public void SendNotify_EndContent() { client.SendTcpPacket("Started"); } }
20.758621
63
0.684385
[ "Apache-2.0" ]
SCL-1-Carpe/Spatial-History
Assets/Networking/ExampleScripts/ClientCommandSystem.cs
604
C#
using AspectCore.DynamicProxy; using AspectCore.Injector; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace JadeFramework.Cache { public class CachingInterceptor : AbstractInterceptor { [FromContainer] public ICachingProvider CacheProvider { get; set; } private char _linkChar = ':'; /// <summary> /// Invoke the specified context and next. /// </summary> /// <returns>The invoke.</returns> /// <param name="context">Context.</param> /// <param name="next">Next.</param> public async override Task Invoke(AspectContext context, AspectDelegate next) { var qCachingAttribute = GetQCachingAttributeInfo(context.ServiceMethod); if (qCachingAttribute != null) { await ProceedCaching(context, next, qCachingAttribute); } else { await next(context); } } /// <summary> /// Gets the QC aching attribute info. /// </summary> /// <returns>The QC aching attribute info.</returns> /// <param name="method">Method.</param> private CachingAttribute GetQCachingAttributeInfo(MethodInfo method) { return method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; } /// <summary> /// Proceeds the caching. /// </summary> /// <returns>The caching.</returns> /// <param name="context">Context.</param> /// <param name="next">Next.</param> /// <param name="attribute">Attribute.</param> private async Task ProceedCaching(AspectContext context, AspectDelegate next, CachingAttribute attribute) { var cacheKey = GenerateCacheKey(context); var cacheValue = CacheProvider.Get(cacheKey); if (cacheValue != null) { context.ReturnValue = cacheValue; return; } await next(context); if (!string.IsNullOrWhiteSpace(cacheKey)) { CacheProvider.Set(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(attribute.AbsoluteExpiration)); } } /// <summary> /// Generates the cache key. /// </summary> /// <returns>The cache key.</returns> /// <param name="context">Context.</param> private string GenerateCacheKey(AspectContext context) { var typeName = context.ServiceMethod.DeclaringType.Name; var methodName = context.ServiceMethod.Name; var methodArguments = this.FormatArgumentsToPartOfCacheKey(context.ServiceMethod.GetParameters()); return this.GenerateCacheKey(typeName, methodName, methodArguments); } /// <summary> /// Generates the cache key. /// </summary> /// <returns>The cache key.</returns> /// <param name="typeName">Type name.</param> /// <param name="methodName">Method name.</param> /// <param name="parameters">Parameters.</param> private string GenerateCacheKey(string typeName, string methodName, IList<string> parameters) { var builder = new StringBuilder(); builder.Append(typeName); builder.Append(_linkChar); builder.Append(methodName); builder.Append(_linkChar); foreach (var param in parameters) { builder.Append(param); builder.Append(_linkChar); } return builder.ToString().TrimEnd(_linkChar); } /// <summary> /// Formats the arguments to part of cache key. /// </summary> /// <returns>The arguments to part of cache key.</returns> /// <param name="methodArguments">Method arguments.</param> /// <param name="maxCount">Max count.</param> private IList<string> FormatArgumentsToPartOfCacheKey(IList<ParameterInfo> methodArguments, int maxCount = 5) { return methodArguments.Select(this.GetArgumentValue).Take(maxCount).ToList(); } /// <summary> /// Gets the argument value. /// </summary> /// <returns>The argument value.</returns> /// <param name="arg">Argument.</param> private string GetArgumentValue(object arg) { if (arg is int || arg is long || arg is string) return arg.ToString(); if (arg is DateTime) return ((DateTime)arg).ToString("yyyyMMddHHmmss"); if (arg is ICachable) return ((ICachable)arg).CacheKey; return null; } } }
33.678082
133
0.576978
[ "Apache-2.0" ]
wangmaosheng/JadeFramework
JadeFramework.Cache/CachingInterceptor.cs
4,919
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Zen.App.Data.Log; using Zen.Base.Module; using Zen.Base.Module.Data; using Zen.Base.Module.Data.Adapter; using Zen.Base.Module.Data.Connection; namespace Zen.App.Data.Pipeline.SetVersioning { public class SetVersion<T> : Data<SetVersion<T>>, IStorageCollectionResolver where T : Data<T> { private const string CollectionSuffix = "set"; [Key] public string Id { get; set; } = Guid.NewGuid().ToString(); public string Code { get; set; } public string Name { get; set; } public string Description { get; set; } public bool IsPublic { get; set; } public bool IsLocked { get; set; } public bool IsCurrent { get; set; } public long ItemCount { get; set; } public DateTime TimeStamp { get; set; } = DateTime.Now; public string OperatorLocator { get; set; } = Current.Orchestrator?.Person?.Locator; public static SetVersioningPrimitiveAttribute Configuration { get; } = typeof(T).GetCustomAttributes(typeof(SetVersioningPrimitiveAttribute), true).FirstOrDefault() as SetVersioningPrimitiveAttribute; // public override void OnRemove() { LocalCache.Delete(GetItemCacheKey()); } public string SetTag => Id == Constants.CURRENT_LIVE_WORKSET_TAG ? null : $"{CollectionSuffix}:{Id}"; public string GetStorageCollectionName() => $"{Info<T>.Settings.StorageCollectionName}#{CollectionSuffix}"; public new static DataAdapterPrimitive<T> GetDataAdapter() => Info<T>.Settings.Adapter; public override void BeforeSave() { var isNew = IsNew(); var action = isNew ? "Created" : "Updated"; if (Current.Orchestrator?.Person!= null) action += " by " + Current.Orchestrator?.Person.Name + " (" + Current.Orchestrator?.Person.Locator + ")"; var log = new Log<T> { ReferenceId = Id, AuthorLocator = Current.Orchestrator?.Person?.Locator, Action = isNew ? "CREATE" : "UPDATE", Type = Log.Constants.Type.VERSIONING, Message = $"Version [{Code}] ({Name}) {action}" }; log.Save(); } public override void BeforeRemove() { Info<T>.Settings.Adapter.DropSet(Id); var action = "Dropped"; var person = Current.Orchestrator?.Person; if (person!= null) action += " by " + person.Name + " (" + person.Locator + ")"; var log = new Log<T> { ReferenceId = Id, AuthorLocator = person?.Locator, Action = "DROP", Type = Log.Constants.Type.VERSIONING, Message = $"Version [{Code}] ({Name}) {action}" }; log.Save(); } private static string CollectionTag(string id) { return $"{CollectionSuffix}:{id}"; } private IEnumerable<T> VersionGetAll() { var set = Code == Constants.CURRENT_LIVE_WORKSET_TAG ? "" : CollectionTag(Id); Base.Log.Add<T>($"VersionGetAll {set ?? "(none)"}"); var mutator = new Mutator {SetCode = set}; return Data<T>.Query(mutator); } public static SetVersion<T> PushFromWorkset(string id) { var isNew = id == "new" || id == Constants.CURRENT_LIVE_WORKSET_TAG; SetVersion<T> probe; if (isNew) { var code = DateTime.Now.ToString("yyyyMMdd-HHmmss"); probe = new SetVersion<T> {Code = "BKP" + code, Name = "Backup:" + code}; } else { probe = Get(id); if (probe == null) throw new Exception($"Version {id} not found."); } try { probe.ItemCount = Data<T>.Count(); probe.Save(); Info<T>.Settings.Adapter.CopySet(Constants.CURRENT_LIVE_WORKSET_TAG, CollectionTag(probe.Id), true); var log = new Log<T> { ReferenceId = probe.Id, AuthorLocator = Current.Orchestrator?.Person?.Locator, Action = "PUSH", Type = Log.Constants.Type.VERSIONING, Message = $"Workset pushed to Version [{probe.Code}] ({probe.Name}): {probe.ItemCount} items copied" }; log.Save(); return probe; } catch (Exception e) { throw e; } } public Payload GetPackage() { var ret = new Payload { Content = Info<T>.Configuration.Description ?? typeof(T).FullName, Descriptor = this, Items = VersionGetAll() }; return ret; } public static Payload GetPackage(string code) { var package = GetByCode(code).GetPackage(); return package; } public void PullToWorkset() { Info<T>.Settings.Adapter.CopySet(CollectionTag(Id), Constants.CURRENT_LIVE_WORKSET_TAG, true); new Log<T> { ReferenceId = Id, AuthorLocator = Current.Orchestrator?.Person?.Locator, Action = "PULL", Type = Log.Constants.Type.VERSIONING, Message = $"Version [{Code}] ({Name}) pulled to Workset" }.Save(); } public static SetVersion<T> GetByCode(string code) { return string.IsNullOrEmpty(code) || code == Constants.CURRENT_LIVE_WORKSET_TAG ? new SetVersion<T> {Id = Constants.CURRENT_LIVE_WORKSET_TAG, Code = Constants.CURRENT_LIVE_WORKSET_TAG} : Where(i => i.Code == code).FirstOrDefault(); } public static bool CanModify() { return Configuration.CanModify(); } public static bool CanBrowse() { return Configuration.CanBrowse(); } public class Payload { public string Content { get; set; } public SetVersion<T> Descriptor { get; set; } public IEnumerable<object> Items { get; set; } } } }
35.745763
243
0.553027
[ "MIT" ]
bucknellu/zen
Zen.App/Data/Pipeline/SetVersioning/SetVersion.cs
6,329
C#