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
/******************************************************************************* * 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.CodePipeline; using Amazon.CodePipeline.Model; namespace Amazon.PowerShell.Cmdlets.CP { /// <summary> /// Gets a listing of all the webhooks in this AWS Region for this account. The output /// lists all webhooks and includes the webhook URL and ARN and the configuration for /// each webhook.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "CPWebhookList")] [OutputType("Amazon.CodePipeline.Model.ListWebhookItem")] [AWSCmdlet("Calls the AWS CodePipeline ListWebhooks API operation.", Operation = new[] {"ListWebhooks"}, SelectReturnType = typeof(Amazon.CodePipeline.Model.ListWebhooksResponse))] [AWSCmdletOutput("Amazon.CodePipeline.Model.ListWebhookItem or Amazon.CodePipeline.Model.ListWebhooksResponse", "This cmdlet returns a collection of Amazon.CodePipeline.Model.ListWebhookItem objects.", "The service call response (type Amazon.CodePipeline.Model.ListWebhooksResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetCPWebhookListCmdlet : AmazonCodePipelineClientCmdlet, IExecutor { #region Parameter MaxResult /// <summary> /// <para> /// <para>The maximum number of results to return in a single call. To retrieve the remaining /// results, make another call with the returned nextToken value.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] [Alias("MaxResults")] public System.Int32? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <para>The token that was returned from the previous ListWebhooks call, which can be used /// to return the next set of webhooks in the list.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Webhooks'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CodePipeline.Model.ListWebhooksResponse). /// Specifying the name of a property of type Amazon.CodePipeline.Model.ListWebhooksResponse 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; } = "Webhooks"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the MaxResult parameter. /// The -PassThru parameter is deprecated, use -Select '^MaxResult' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^MaxResult' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CodePipeline.Model.ListWebhooksResponse, GetCPWebhookListCmdlet>(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.MaxResult; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.MaxResult = this.MaxResult; context.NextToken = this.NextToken; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.CodePipeline.Model.ListWebhooksRequest(); if (cmdletContext.MaxResult != null) { request.MaxResults = cmdletContext.MaxResult.Value; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CodePipeline.Model.ListWebhooksResponse CallAWSServiceOperation(IAmazonCodePipeline client, Amazon.CodePipeline.Model.ListWebhooksRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CodePipeline", "ListWebhooks"); try { #if DESKTOP return client.ListWebhooks(request); #elif CORECLR return client.ListWebhooksAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.Int32? MaxResult { get; set; } public System.String NextToken { get; set; } public System.Func<Amazon.CodePipeline.Model.ListWebhooksResponse, GetCPWebhookListCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Webhooks; } } }
46.158537
253
0.602818
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/CodePipeline/Basic/Get-CPWebhookList-Cmdlet.cs
11,355
C#
using System; using System.Drawing; using FlaUI.Core.AutomationElements; using FlaUI.Core.Conditions; using FlaUI.Core.Definitions; using FlaUI.Core.EventHandlers; using FlaUI.Core.Identifiers; using FlaUI.Core.Overlay; namespace FlaUI.Core { /// <summary> /// Base class for the native automation object. /// </summary> public abstract class AutomationBase : IDisposable { /// <summary> /// Creates a new <see cref="AutomationBase"/> instance. /// </summary> /// <param name="propertyLibrary">The property library to use.</param> /// <param name="eventLibrary">The event library to use.</param> /// <param name="patternLibrary">The pattern library to use.</param> /// <param name="textAttributeLibrary">The text attribute library to use.</param> protected AutomationBase(IPropertyLibrary propertyLibrary, IEventLibrary eventLibrary, IPatternLibrary patternLibrary, ITextAttributeLibrary textAttributeLibrary) { PropertyLibrary = propertyLibrary; EventLibrary = eventLibrary; PatternLibrary = patternLibrary; TextAttributeLibrary = textAttributeLibrary; ConditionFactory = new ConditionFactory(propertyLibrary); #if NETSTANDARD OverlayManager = new NullOverlayManager(); #else OverlayManager = new WinFormsOverlayManager(); #endif // Make sure all pattern ids are initialized var unused = PatternLibrary.AllForCurrentFramework; } /// <summary> /// Provides a library with the existing <see cref="PropertyId"/>s. /// </summary> public IPropertyLibrary PropertyLibrary { get; } /// <summary> /// Provides a library with the existing <see cref="EventId"/>s. /// </summary> public IEventLibrary EventLibrary { get; } /// <summary> /// Provides a library with the existing <see cref="PatternId"/>s. /// </summary> public IPatternLibrary PatternLibrary { get; } /// <summary> /// Provides a library with the existing <see cref="TextAttributeId"/>s. /// </summary> public ITextAttributeLibrary TextAttributeLibrary { get; } /// <summary> /// Provides a factory to create conditions for searching. /// </summary> public ConditionFactory ConditionFactory { get; } /// <summary> /// Provides a manager for displaying overlays. /// </summary> public IOverlayManager OverlayManager { get; } /// <summary> /// Provides a factory to create <see cref="ITreeWalker"/>s. /// </summary> public abstract ITreeWalkerFactory TreeWalkerFactory { get; } /// <summary> /// The <see cref="AutomationType"/> of the automation implementation. /// </summary> public abstract AutomationType AutomationType { get; } /// <summary> /// Object which represents the "Not Supported" value. /// </summary> public abstract object NotSupportedValue { get; } /// <summary> /// Specifies the length of time that UI Automation will wait for a provider to respond to a client request for information about an automation element. /// The default is 20 seconds. /// </summary> public abstract TimeSpan TransactionTimeout { get; set; } /// <summary> /// Specifies the length of time that UI Automation will wait for a provider to respond to a client request for an automation element. /// The default is two seconds. /// </summary> public abstract TimeSpan ConnectionTimeout { get; set; } /// <summary> /// Indicates whether an accessible technology client adjusts provider request timeouts when the provider is non-responsive. /// </summary> public abstract ConnectionRecoveryBehaviorOptions ConnectionRecoveryBehavior { get; set; } /// <summary> /// Gets or sets whether an accessible technology client receives all events, or a subset where duplicate events are detected and filtered. /// </summary> public abstract CoalesceEventsOptions CoalesceEvents { get; set; } /// <summary> /// Gets the desktop (root) element. /// </summary> public abstract AutomationElement GetDesktop(); /// <summary> /// Creates an <see cref="AutomationElement" /> from a given point. /// </summary> public abstract AutomationElement FromPoint(Point point); /// <summary> /// Creates an <see cref="AutomationElement" /> from a given windows handle (HWND). /// </summary> public abstract AutomationElement FromHandle(IntPtr hwnd); /// <summary> /// Gets the currently focused element as an <see cref="AutomationElement"/>. /// </summary> /// <returns></returns> public abstract AutomationElement FocusedElement(); /// <summary> /// Registers for a focus changed event. /// </summary> public abstract FocusChangedEventHandlerBase RegisterFocusChangedEvent(Action<AutomationElement> action); /// <summary> /// Unregisters the given focus changed event handler. /// </summary> public abstract void UnregisterFocusChangedEvent(FocusChangedEventHandlerBase eventHandler); /// <summary> /// Removes all registered event handlers. /// </summary> public abstract void UnregisterAllEvents(); /// <summary> /// Compares two automation elements for equality. /// </summary> public abstract bool Compare(AutomationElement element1, AutomationElement element2); /// <summary> /// Cleans up the resources. /// </summary> public void Dispose() { UnregisterAllEvents(); OverlayManager.Dispose(); } } }
38.132911
170
0.627884
[ "MIT" ]
ChrisZhang95/FlaUI
src/FlaUI.Core/AutomationBase.cs
6,027
C#
namespace Microsoft.Extensions.DependencyInjection { using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Interfaces; using Microsoft.AspNet.OData.Routing; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using System; using System.Linq; using static Microsoft.AspNetCore.Mvc.Versioning.ApiVersionParameterLocation; using static ServiceDescriptor; /// <summary> /// Provides extension methods for the <see cref="IODataBuilder"/> interface. /// </summary> [CLSCompliant( false )] public static partial class IODataBuilderExtensions { /// <summary> /// Enables service API versioning for the specified OData configuration. /// </summary> /// <param name="builder">The <see cref="IODataBuilder">OData builder</see> available in the application.</param> /// <returns>The original <paramref name="builder"/> object.</returns> public static IODataBuilder EnableApiVersioning( this IODataBuilder builder ) { if ( builder == null ) { throw new ArgumentNullException( nameof( builder ) ); } AddODataServices( builder.Services ); return builder; } /// <summary> /// Enables service API versioning for the specified OData configuration. /// </summary> /// <param name="builder">The <see cref="IODataBuilder">OData builder</see> available in the application.</param> /// <param name="setupAction">An <see cref="Action{T}">action</see> used to configure the provided options.</param> /// <returns>The original <paramref name="builder"/> object.</returns> public static IODataBuilder EnableApiVersioning( this IODataBuilder builder, Action<ODataApiVersioningOptions> setupAction ) { if ( builder == null ) { throw new ArgumentNullException( nameof( builder ) ); } var services = builder.Services; AddODataServices( services ); services.Configure( setupAction ); return builder; } static void AddODataServices( IServiceCollection services ) { var partManager = services.GetService<ApplicationPartManager>(); if ( partManager == null ) { partManager = new ApplicationPartManager(); services.TryAddSingleton( partManager ); } partManager.ApplicationParts.Add( new AssemblyPart( typeof( IODataBuilderExtensions ).Assembly ) ); ConfigureDefaultFeatureProviders( partManager ); services.Replace( Singleton<IActionSelector, ODataApiVersionActionSelector>() ); services.TryAdd( Transient<VersionedODataModelBuilder, VersionedODataModelBuilder>() ); services.TryAdd( Singleton<IODataRouteCollectionProvider, ODataRouteCollectionProvider>() ); services.AddTransient<IApplicationModelProvider, ODataApplicationModelProvider>(); services.AddTransient<IActionDescriptorProvider, ODataActionDescriptorProvider>(); services.AddSingleton<IActionDescriptorChangeProvider>( ODataActionDescriptorChangeProvider.Instance ); services.TryAddEnumerable( Transient<IApiControllerSpecification, ODataControllerSpecification>() ); services.AddTransient<IStartupFilter, RaiseVersionedODataRoutesMapped>(); services.AddModelConfigurationsAsServices( partManager ); services.TryReplace( WithLinkGeneratorDecorator( services ) ); } static T GetService<T>( this IServiceCollection services ) => (T) services.LastOrDefault( d => d.ServiceType == typeof( T ) )?.ImplementationInstance!; static void AddModelConfigurationsAsServices( this IServiceCollection services, ApplicationPartManager partManager ) { var feature = new ModelConfigurationFeature(); var modelConfigurationType = typeof( IModelConfiguration ); partManager.PopulateFeature( feature ); foreach ( var modelConfiguration in feature.ModelConfigurations.Select( t => t.AsType() ) ) { services.TryAddEnumerable( Transient( modelConfigurationType, modelConfiguration ) ); } } static IServiceCollection TryReplace( this IServiceCollection services, ServiceDescriptor? descriptor ) { if ( descriptor != null ) { services.Replace( descriptor ); } return services; } static void ConfigureDefaultFeatureProviders( ApplicationPartManager partManager ) { if ( !partManager.FeatureProviders.OfType<ModelConfigurationFeatureProvider>().Any() ) { partManager.FeatureProviders.Add( new ModelConfigurationFeatureProvider() ); } } static ServiceDescriptor? WithLinkGeneratorDecorator( IServiceCollection services ) { // HACK: even though the core api versioning services decorate the default LinkGenerator, we need to get in front of the odata // implementation in order to add the necessary route values when versioning by url segment. // // REF: https://github.com/OData/WebApi/blob/master/src/Microsoft.AspNetCore.OData/Extensions/ODataServiceCollectionExtensions.cs#L99 // REF: https://github.com/OData/WebApi/blob/master/src/Microsoft.AspNetCore.OData/Extensions/Endpoint/ODataEndpointLinkGenerator.cs var descriptor = services.FirstOrDefault( sd => sd.ServiceType == typeof( LinkGenerator ) ); if ( descriptor == null ) { return default; } var lifetime = descriptor.Lifetime; var factory = descriptor.ImplementationFactory; if ( factory == null ) { throw new InvalidOperationException( LocalSR.MissingLinkGenerator ); } LinkGenerator NewFactory( IServiceProvider serviceProvider ) { var instance = (LinkGenerator) factory( serviceProvider ); var source = serviceProvider.GetRequiredService<IApiVersionParameterSource>(); var context = new UrlSegmentDescriptionContext(); source.AddParameters( context ); if ( context.HasPathApiVersion ) { instance = new ApiVersionLinkGenerator( instance ); } return instance; } return Describe( typeof( LinkGenerator ), NewFactory, lifetime ); } sealed class UrlSegmentDescriptionContext : IApiVersionParameterDescriptionContext { internal bool HasPathApiVersion { get; private set; } public void AddParameter( string name, ApiVersionParameterLocation location ) => HasPathApiVersion |= location == Path; } } }
44.035088
159
0.652855
[ "MIT" ]
Bhekinkosi12/aspnet-api-versioning
src/Microsoft.AspNetCore.OData.Versioning/Extensions.DependencyInjection/IODataBuilderExtensions.cs
7,532
C#
using BoDi; using PossumLabs.Specflow.Core.Validations; using System; using System.Collections.Generic; using System.Text; using TechTalk.SpecFlow; namespace PossumLabs.Specflow.Selenium.Integration { [Binding] public class LogSteps: WebDriverStepBase { public LogSteps(IObjectContainer objectContainer) : base(objectContainer) { } [Then(@"the Browser Logs has the value '(.*)'")] public void ThenTheBrowserLogsHasTheValue(Validation validation) => Executor.Execute(() => WebDriver.BrowserLogs.Validate(validation)); } }
25.478261
82
0.711604
[ "MIT" ]
BasHamer/PossumLabs.Specflow.Selenium
PossumLabs.Specflow.Selenium.UnitTests/LogSteps.cs
588
C#
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using ClientDependency.Core; namespace umbraco.uicontrols { public class Pane : System.Web.UI.WebControls.Panel { public Pane() { } private string m_Text = string.Empty; public string Text { get { return m_Text; } set { m_Text = value; } } private string m_title = string.Empty; public string Title { get { return m_title; } set { m_title = value; } } public void addProperty(string Caption, Control C, params BaseValidator[] validators) { PropertyPanel pp = new PropertyPanel(); pp.Controls.Add(C); foreach (var validator in validators) { validator.Display = ValidatorDisplay.Dynamic; pp.Controls.Add(validator); } pp.Text = Caption; this.Controls.Add(pp); } public void addProperty(string Caption, Control C) { PropertyPanel pp = new PropertyPanel(); pp.Controls.Add(C); pp.Text = Caption; this.Controls.Add(pp); } public void addProperty(Control ctrl) { PropertyPanel pp = new PropertyPanel(); pp.Controls.Add(ctrl); this.Controls.Add(pp); } protected override void OnLoad(System.EventArgs EventArguments) { } protected override void Render(System.Web.UI.HtmlTextWriter writer) { this.ViewStateMode = ViewStateMode.Disabled; this.CreateChildControls(); string styleString = ""; foreach (string key in this.Style.Keys) { styleString += key + ":" + this.Style[key] + ";"; } writer.WriteLine("<div class=\"umb-pane " + this.CssClass + "\" style='" + styleString + "'>"); if (!string.IsNullOrEmpty(m_title)) writer.WriteLine("<h5 class='umb-pane-title'>" + m_title + "</h5>"); writer.WriteLine("<div class=\"control-group umb-control-group\" style='" + styleString + "'>"); if (!string.IsNullOrEmpty(m_Text)) writer.WriteLine("<p class=\"umb-abstract\">" + m_Text + "</p>"); try { this.RenderChildren(writer); } catch (Exception ex) { writer.WriteLine("Error creating control <br />"); writer.WriteLine(ex.ToString()); } writer.WriteLine("</div>"); writer.WriteLine("</div>"); } } }
26.213675
109
0.509292
[ "MIT" ]
Abhith/Umbraco-CMS
src/umbraco.controls/pane.cs
3,067
C#
using System; using System.Text; namespace StackExchange.Redis { internal struct RawResult { public static readonly RawResult EmptyArray = new RawResult(new RawResult[0]); public static readonly RawResult Nil = new RawResult(); private static readonly byte[] emptyBlob = new byte[0]; private readonly int offset, count; private Array arr; public RawResult(ResultType resultType, byte[] buffer, int offset, int count) { switch (resultType) { case ResultType.SimpleString: case ResultType.Error: case ResultType.Integer: case ResultType.BulkString: break; default: throw new ArgumentOutOfRangeException(nameof(resultType)); } Type = resultType; arr = buffer; this.offset = offset; this.count = count; } public RawResult(RawResult[] arr) { if (arr == null) throw new ArgumentNullException(nameof(arr)); Type = ResultType.MultiBulk; offset = 0; count = arr.Length; this.arr = arr; } public bool HasValue => Type != ResultType.None; public bool IsError => Type == ResultType.Error; public ResultType Type { get; } internal bool IsNull => arr == null; public override string ToString() { if (arr == null) { return "(null)"; } switch (Type) { case ResultType.SimpleString: case ResultType.Integer: case ResultType.Error: return $"{Type}: {GetString()}"; case ResultType.BulkString: return $"{Type}: {count} bytes"; case ResultType.MultiBulk: return $"{Type}: {count} items"; default: return "(unknown)"; } } internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode) { switch (Type) { case ResultType.SimpleString: case ResultType.BulkString: if (channelPrefix == null) { return new RedisChannel(GetBlob(), mode); } if (AssertStarts(channelPrefix)) { var src = (byte[])arr; byte[] copy = new byte[count - channelPrefix.Length]; Buffer.BlockCopy(src, offset + channelPrefix.Length, copy, 0, copy.Length); return new RedisChannel(copy, mode); } return default(RedisChannel); default: throw new InvalidCastException("Cannot convert to RedisChannel: " + Type); } } internal RedisKey AsRedisKey() { switch (Type) { case ResultType.SimpleString: case ResultType.BulkString: return (RedisKey)GetBlob(); default: throw new InvalidCastException("Cannot convert to RedisKey: " + Type); } } internal RedisValue AsRedisValue() { switch (Type) { case ResultType.Integer: long i64; if (TryGetInt64(out i64)) return (RedisValue)i64; break; case ResultType.SimpleString: case ResultType.BulkString: return (RedisValue)GetBlob(); } throw new InvalidCastException("Cannot convert to RedisValue: " + Type); } internal unsafe bool IsEqual(byte[] expected) { if (expected == null) throw new ArgumentNullException(nameof(expected)); if (expected.Length != count) return false; var actual = arr as byte[]; if (actual == null) return false; int octets = count / 8, spare = count % 8; fixed (byte* actual8 = &actual[offset]) fixed (byte* expected8 = expected) { long* actual64 = (long*)actual8; long* expected64 = (long*)expected8; for (int i = 0; i < octets; i++) { if (actual64[i] != expected64[i]) return false; } int index = count - spare; while (spare-- != 0) { if (actual8[index] != expected8[index]) return false; } } return true; } internal bool AssertStarts(byte[] expected) { if (expected == null) throw new ArgumentNullException(nameof(expected)); if (expected.Length > count) return false; var actual = arr as byte[]; if (actual == null) return false; for (int i = 0; i < expected.Length; i++) { if (expected[i] != actual[offset + i]) return false; } return true; } internal byte[] GetBlob() { var src = (byte[])arr; if (src == null) return null; if (count == 0) return emptyBlob; byte[] copy = new byte[count]; Buffer.BlockCopy(src, offset, copy, 0, count); return copy; } internal bool GetBoolean() { if (count != 1) throw new InvalidCastException(); byte[] actual = arr as byte[]; if (actual == null) throw new InvalidCastException(); switch (actual[offset]) { case (byte)'1': return true; case (byte)'0': return false; default: throw new InvalidCastException(); } } internal RawResult[] GetItems() { return (RawResult[])arr; } internal RedisKey[] GetItemsAsKeys() { RawResult[] items = GetItems(); if (items == null) { return null; } else if (items.Length == 0) { return RedisKey.EmptyArray; } else { var arr = new RedisKey[items.Length]; for (int i = 0; i < arr.Length; i++) { arr[i] = items[i].AsRedisKey(); } return arr; } } internal RedisValue[] GetItemsAsValues() { RawResult[] items = GetItems(); if (items == null) { return null; } else if (items.Length == 0) { return RedisValue.EmptyArray; } else { var arr = new RedisValue[items.Length]; for (int i = 0; i < arr.Length; i++) { arr[i] = items[i].AsRedisValue(); } return arr; } } static readonly string[] NilStrings = new string[0]; internal string[] GetItemsAsStrings() { RawResult[] items = GetItems(); if (items == null) { return null; } else if (items.Length == 0) { return NilStrings; } else { var arr = new string[items.Length]; for (int i = 0; i < arr.Length; i++) { arr[i] = (string)(items[i].AsRedisValue()); } return arr; } } internal GeoPosition? GetItemsAsGeoPosition() { RawResult[] items = GetItems(); if (items == null || items.Length == 0) { return null; } var coords = items[0].GetArrayOfRawResults(); if (coords == null) { return null; } return new GeoPosition((double)coords[0].AsRedisValue(), (double)coords[1].AsRedisValue()); } internal GeoPosition?[] GetItemsAsGeoPositionArray() { RawResult[] items = GetItems(); if (items == null) { return null; } else if (items.Length == 0) { return new GeoPosition?[0]; } else { var arr = new GeoPosition?[items.Length]; for (int i = 0; i < arr.Length; i++) { RawResult[] item = items[i].GetArrayOfRawResults(); if (item == null) { arr[i] = null; } else { arr[i] = new GeoPosition((double)item[0].AsRedisValue(), (double)item[1].AsRedisValue()); } } return arr; } } internal RawResult[] GetItemsAsRawResults() { return GetItems(); } // returns an array of RawResults internal RawResult[] GetArrayOfRawResults() { if (arr == null) { return null; } else if (arr.Length == 0) { return new RawResult[0]; } else { var rawResultArray = new RawResult[arr.Length]; for (int i = 0; i < arr.Length; i++) { var rawResult = (RawResult)arr.GetValue(i); rawResultArray.SetValue(rawResult, i); } return rawResultArray; } } internal string GetString() { if (arr == null) return null; var blob = (byte[])arr; if (blob.Length == 0) return ""; return Encoding.UTF8.GetString(blob, offset, count); } internal bool TryGetDouble(out double val) { if (arr == null) { val = 0; return false; } long i64; if (TryGetInt64(out i64)) { val = i64; return true; } return Format.TryParseDouble(GetString(), out val); } internal bool TryGetInt64(out long value) { if (arr == null) { value = 0; return false; } return RedisValue.TryParseInt64(arr as byte[], offset, count, out value); } } }
30.515068
113
0.432663
[ "Apache-2.0" ]
952208166/StackExchange.Redis
StackExchange.Redis/StackExchange/Redis/RawResult.cs
11,140
C#
using Machine.Specifications; namespace FeatureSwitcher.Configuration.Specs.Contexts { public class WithCleanUp { Cleanup clean = () => Features.Are.HandledByDefault(); } }
21.444444
62
0.709845
[ "Apache-2.0" ]
mexx/FeatureSwitcher.Configuration
Source/FeatureSwitcher.Configuration.Specs/Contexts/WithCleanUp.cs
193
C#
// <copyright file="WorkforceIntegration.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Models.RequestModels { using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models; using Newtonsoft.Json; /// <summary> /// This class models the request object to be forwarding to Graph API. /// </summary> public class WorkforceIntegration { /// <summary> /// Gets or sets the displayName. /// </summary> [JsonProperty("displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the apiVersion. /// </summary> [JsonProperty("apiVersion")] public int ApiVersion { get; set; } = 1; /// <summary> /// Gets or sets a value indicating whether or not a workforce integration is active. /// </summary> [JsonProperty("isActive")] public bool IsActive { get; set; } /// <summary> /// Gets or sets the encryption. /// </summary> [JsonProperty("encryption")] public Encryption Encryption { get; set; } /// <summary> /// Gets or sets the url. /// </summary> [JsonProperty("url")] #pragma warning disable CA1056 // Uri properties should not be strings public string Url { get; set; } #pragma warning restore CA1056 // Uri properties should not be strings /// <summary> /// Gets or sets the functionalities supported for the outbound sync (from Shifts to the WFM provider). /// </summary> [JsonProperty("supportedEntities")] public string SupportedEntities { get; set; } /// <summary> /// Gets or sets the eligibility functionalities supported for the outbound sync (from Shifts to the WFM provider). /// </summary> [JsonProperty("eligibilityFilteringEnabledEntities")] public string EligibilityFilteringEnabledEntities { get; set; } } }
34.433333
123
0.618587
[ "MIT" ]
Andy65/Microsoft-Teams-Shifts-WFM-Connectors
Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Models/RequestModels/WorkforceIntegration.cs
2,068
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Security.Cryptography.X509Certificates; using JetBrains.Annotations; using Newtonsoft.Json; namespace dotAPNS { public class ApplePush { public string Token { get; private set; } public string VoipToken { get; private set; } public int Priority => CustomPriority ?? (Type == ApplePushType.Background ? 5 : 10); // 5 for background, 10 for everything else public ApplePushType Type { get; } /// <summary> /// If specified, this value will be used as a `apns- /// </summary> public int? CustomPriority { get; private set; } [CanBeNull] public ApplePushAlert Alert { get; private set; } [CanBeNull] public ApplePushLocalizedAlert LocalizedAlert { get; private set; } public int? Badge { get; private set; } [CanBeNull] public string Sound { get; private set; } /// <summary> /// See <a href="https://developer.apple.com/documentation/usernotifications/unnotificationcontent/1649866-categoryidentifier">official documentation</a> for reference. /// </summary> [CanBeNull] public string Category { get; private set; } public bool IsContentAvailable { get; private set; } public bool IsMutableContent { get; private set; } /// <summary> /// The date at which the notification is no longer valid. /// If set to <i>null</i> (default) then <i>apns-expiration</i> header is not sent and expiration time is undefined (<seealso href="https://stackoverflow.com/questions/44630196/what-is-the-default-value-of-the-apns-expiration-field">but is probably large</seealso>). /// </summary> public DateTimeOffset? Expiration { get; private set; } /// <summary> /// User-defined properties that will be attached to the root payload dictionary. /// </summary> public Dictionary<string, object> CustomProperties { get; set; } /// <summary> /// User-defined properties that will be attached to the <i>aps</i> payload dictionary. /// </summary> public IDictionary<string, object> CustomApsProperties { get; set; } /// <summary> /// Indicates whether alert must be sent as a string. /// </summary> bool _sendAlertAsText; public ApplePush(ApplePushType pushType) { Type = pushType; } /// <summary> /// /// </summary> /// <param name="sendAsVoipType">True if push must be sent with 'voip' type rather than 'background'.</param> /// <returns></returns> [Obsolete("Please use " + nameof(AddContentAvailable) + " instead.")] public static ApplePush CreateContentAvailable(bool sendAsVoipType = false) => new ApplePush(sendAsVoipType ? ApplePushType.Voip : ApplePushType.Background) { IsContentAvailable = true }; /// <summary> /// /// </summary> /// <param name="alert"></param> /// <param name="sendAsVoipType">True if push must be sent with 'voip' type rather than 'alert'.</param> /// <returns></returns> [Obsolete("Please use " + nameof(AddAlert) + " instead.")] public static ApplePush CreateAlert(ApplePushAlert alert, bool sendAsVoipType = false) => new ApplePush(sendAsVoipType ? ApplePushType.Voip : ApplePushType.Alert) { Alert = alert }; /// <summary> /// Send alert push with alert as string. /// </summary> /// <param name="alert"></param> /// <param name="sendAsVoipType">True if push must be sent with 'voip' type rather than 'alert'.</param> /// <returns></returns> [Obsolete("Please use " + nameof(AddAlert) + " instead.")] public static ApplePush CreateAlert(string alert, bool sendAsVoipType = false) { var push = CreateAlert(new ApplePushAlert(null, alert), sendAsVoipType); push._sendAlertAsText = true; return push; } /// <summary> /// Add `content-available: 1` to the payload. /// </summary> public ApplePush AddContentAvailable() { IsContentAvailable = true; return this; } /// <summary> /// Add `mutable-content: 1` to the payload. /// </summary> /// <returns></returns> public ApplePush AddMutableContent() { IsMutableContent = true; return this; } /// <summary> /// Add alert to the payload. /// </summary> /// <param name="title">Alert title. Can be null.</param> /// <param name="subtitle">Alert subtitle. Can be null.</param> /// <param name="body">Alert body. <b>Cannot be null.</b></param> /// <returns></returns> public ApplePush AddAlert([CanBeNull] string title, [CanBeNull] string subtitle, [NotNull] string body) { Alert = new ApplePushAlert(title, subtitle, body); if (title == null) _sendAlertAsText = true; return this; } /// <summary> /// Add alert to the payload. /// </summary> /// <param name="title">Alert title. Can be null.</param> /// <param name="body">Alert body. <b>Cannot be null.</b></param> /// <returns></returns> public ApplePush AddAlert([CanBeNull] string title, [NotNull] string body) { Alert = new ApplePushAlert(title, body); if (title == null) _sendAlertAsText = true; return this; } /// <summary> /// Add alert to the payload. /// </summary> /// <param name="body">Alert body. <b>Cannot be null.</b></param> /// <returns></returns> public ApplePush AddAlert([NotNull] string body) { return AddAlert(null, body); } /// <summary> /// Add localized alert to the payload. When alert is already present, localized alert will be omitted when generating payload. /// </summary> /// <param name="locKey">Key to an alert-message string in a Localizable.strings file for the current localization. <b>Cannot be null.</b></param> /// <param name="locArgs">Variable string values to appear in place of the format specifiers in loc-key. <b>Cannot be null.</b></param> /// <param name="titleLocKey">The key to a title string in the Localizable.strings file for the current localization. Can be null.</param> /// <param name="tittleLocArgs">Variable string values to appear in place of the format specifiers in title-loc-key. Can be null.</param> /// <param name="actionLocKey">The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View". Can be null.</param> /// <returns></returns> public ApplePush AddLocalizedAlert([CanBeNull] string titleLocKey, [CanBeNull] string[] tittleLocArgs, [NotNull] string locKey, [NotNull] string[] locArgs, [CanBeNull] string actionLocKey) { LocalizedAlert = new ApplePushLocalizedAlert(titleLocKey, tittleLocArgs, locKey, locArgs, actionLocKey); return this; } /// <summary> /// Add localized alert to the payload. When alert is already present, localized alert will be omitted when generating payload. /// </summary> /// <param name="locKey">Key to an alert-message string in a Localizable.strings file for the current localization. <b>Cannot be null.</b></param> /// <param name="locArgs">Variable string values to appear in place of the format specifiers in loc-key. <b>Cannot be null.</b></param> /// <returns></returns> public ApplePush AddLocalizedAlert([NotNull] string locKey, [NotNull] string[] locArgs) { return AddLocalizedAlert(null, null, locKey, locArgs, null); } public ApplePush SetPriority(int priority) { if(priority < 0 || priority > 10) throw new ArgumentOutOfRangeException(nameof(priority), priority, "Priority must be between 0 and 10."); CustomPriority = priority; return this; } public ApplePush AddBadge(int badge) { IsContentAvailableGuard(); if (Badge != null) throw new InvalidOperationException("Badge already exists"); Badge = badge; return this; } public ApplePush AddSound([NotNull] string sound = "default") { if (string.IsNullOrWhiteSpace(sound)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(sound)); IsContentAvailableGuard(); if (Sound != null) throw new InvalidOperationException("Sound already exists"); Sound = sound; return this; } public ApplePush AddCategory([NotNull] string category) { if (string.IsNullOrWhiteSpace(category)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(category)); if (Category != null) throw new InvalidOperationException($"{nameof(Category)} already exists."); Category = category; return this; } /// <summary> /// APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed until the specified date. /// </summary> /// <param name="expirationDate">The date at which the notification is no longer valid.</param> /// public ApplePush AddExpiration(DateTimeOffset expirationDate) { Expiration = expirationDate; return this; } /// <summary> /// APNs attempts to deliver the notification only once and doesn’t store it. /// </summary> /// <seealso cref="AddExpiration"/> public ApplePush AddImmediateExpiration() { Expiration = DateTimeOffset.MinValue; return this; } public ApplePush AddToken([NotNull] string token) { if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(token)); EnsureTokensNotExistGuard(); if (Type == ApplePushType.Voip) throw new InvalidOperationException($"Please use AddVoipToken() when sending {nameof(ApplePushType.Voip)} pushes."); Token = token; return this; } public ApplePush AddVoipToken([NotNull] string voipToken) { if (string.IsNullOrWhiteSpace(voipToken)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(voipToken)); EnsureTokensNotExistGuard(); if(Type != ApplePushType.Voip) throw new InvalidOperationException($"VoIP token may only be used with {nameof(ApplePushType.Voip)} pushes."); VoipToken = voipToken; return this; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="addToApsDict">If <b>true</b>, property will be added to the <i>aps</i> dictionary, otherwise to the root dictionary. Default: <b>false</b>.</param> /// <returns></returns> public ApplePush AddCustomProperty(string key, object value, bool addToApsDict = false) { if (addToApsDict) { CustomApsProperties ??= new Dictionary<string, object>(); CustomApsProperties.Add(key, value); } else { CustomProperties ??= new Dictionary<string, object>(); CustomProperties.Add(key, value); } return this; } void EnsureTokensNotExistGuard() { if (!(string.IsNullOrEmpty(Token) && string.IsNullOrEmpty(VoipToken))) throw new InvalidOperationException("Notification already has token"); } void IsContentAvailableGuard() { if (IsContentAvailable) throw new InvalidOperationException("Cannot add fields to a push with content-available"); } public object GeneratePayload() { dynamic payload = new ExpandoObject(); payload.aps = new ExpandoObject(); IDictionary<string, object> apsAsDict = payload.aps; if (IsContentAvailable) apsAsDict["content-available"] = "1"; if(IsMutableContent) apsAsDict["mutable-content"] = "1"; if (Alert != null) { object alert; if (_sendAlertAsText) alert = Alert.Body; else if (Alert.Subtitle == null) alert = new { title = Alert.Title, body = Alert.Body }; else alert = new { title = Alert.Title, subtitle = Alert.Subtitle, body = Alert.Body }; payload.aps.alert = alert; } else if (LocalizedAlert != null) { object localizedAlert = LocalizedAlert; payload.aps.alert = localizedAlert; } if (Badge != null) payload.aps.badge = Badge.Value; if (Sound != null) payload.aps.sound = Sound; if (Category != null) payload.aps.category = Category; if (CustomProperties != null) { IDictionary<string, object> payloadAsDict = payload; foreach (var customProperty in CustomProperties) payloadAsDict[customProperty.Key] = customProperty.Value; } if (CustomApsProperties != null) { foreach (var customApsProperty in CustomApsProperties) apsAsDict[customApsProperty.Key] = customApsProperty.Value; } return payload; } } public class ApplePushAlert { public string Title { get; } public string Subtitle { get; } public string Body { get; } public ApplePushAlert([CanBeNull] string title, [NotNull] string body) { Title = title; Body = body ?? throw new ArgumentNullException(nameof(body)); } public ApplePushAlert([CanBeNull] string title, [CanBeNull] string subtitle, [NotNull] string body) { Title = title; Subtitle = subtitle; Body = body ?? throw new ArgumentNullException(nameof(body)); } } [JsonObject(MemberSerialization.OptIn)] public class ApplePushLocalizedAlert { [JsonProperty("title-loc-key")] public string TitleLocKey { get; } [JsonProperty("title-loc-args")] public string[] TitleLocArgs { get; } [JsonProperty("loc-key")] public string LocKey { get; } [JsonProperty("loc-args")] public string[] LocArgs { get; } [JsonProperty("action-loc-key")] public string ActionLocKey { get; } public ApplePushLocalizedAlert([NotNull] string locKey, [NotNull] string[] locArgs) { LocKey = locKey ?? throw new ArgumentNullException(nameof(locKey)); LocArgs = locArgs ?? throw new ArgumentNullException(nameof(locArgs)); } public ApplePushLocalizedAlert(string titleLocKey, string[] titleLocArgs, string locKey, string[] locArgs, string actionLocKey) { TitleLocKey = titleLocKey; TitleLocArgs = titleLocArgs; LocKey = locKey ?? throw new ArgumentNullException(nameof(locKey));; LocArgs = locArgs ?? throw new ArgumentNullException(nameof(locArgs)); ActionLocKey = actionLocKey; } } }
39.735437
274
0.582493
[ "Apache-2.0" ]
mtalaga/dotAPNS
dotAPNS/ApplePush.cs
16,379
C#
using BulletSharp; using System; using System.Collections.Generic; namespace Dissonance.Engine.Physics { public sealed partial class PhysicsEngine : EngineModule { internal static DbvtBroadphase broadphase; internal static CollisionConfiguration collisionConf; protected override void Init() { collisionConf = new DefaultCollisionConfiguration(); broadphase = new DbvtBroadphase(); // ManifoldPoint.ContactAdded += Callback_ContactAdded; // PersistentManifold.ContactProcessed += Callback_ContactProcessed; // PersistentManifold.ContactDestroyed += Callback_ContactDestroyed; } protected override void OnDispose() { broadphase?.Dispose(); /*if (rigidbodies != null) { for (int i = 0; i < rigidbodies.Count; i++) { rigidbodies[i].Dispose(); } rigidbodies.Clear(); }*/ } /*public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hit, float range = 100000f, Func<ulong, ulong> mask = null, Func<GameObject, bool?> customFilter = null, bool debug = false) { direction.Normalize(); ulong layerMask = ulong.MaxValue; if (mask != null) { layerMask = mask(layerMask); } BulletSharp.Math.Vector3 rayEnd = (origin + direction * range); BulletSharp.Math.Vector3 origin2 = origin; var callback = new RaycastCallback(ref origin2, ref rayEnd, layerMask, customFilter); world.RayTest(origin, rayEnd, callback); if (!callback.HasHit) { hit = new RaycastHit { triangleIndex = -1, }; return false; } hit = new RaycastHit { point = callback.HitPointWorld, triangleIndex = callback.triangleIndex, collider = callback.collider, gameObject = callback.collider?.gameObject }; return true; }*/ internal static CollisionShape GetSubShape(CollisionShape shape, int subIndex) { if (shape is CompoundShape compoundShape && compoundShape.NumChildShapes > 0) { return compoundShape.GetChildShape(subIndex >= 0 ? subIndex : 0); } return shape; } } }
25.2625
205
0.703612
[ "MIT" ]
ExterminatorX99/DissonanceEngine
Src/Physics/PhysicsEngine.cs
2,021
C#
using System.Collections.Generic; using UnityEngine; using EnemyAI; // The NPC patrol action. [CreateAssetMenu(menuName = "Enemy AI/Actions/Patrol")] public class PatrolAction : Action { // The act function, called on Update() (State controller - current state - action). public override void Act(StateController controller) { Patrol(controller); } // The action on enable function, triggered once after a FSM state transition. public override void OnEnableAction(StateController controller) { // Setup initial values for the action. controller.enemyAnimation.AbortPendingAim(); controller.enemyAnimation.anim.SetBool("Crouch", false); controller.personalTarget = Vector3.positiveInfinity; controller.CoverSpot = Vector3.positiveInfinity; } // NPC patrolling function. private void Patrol(StateController controller) { // No patrol waypoints, stand idle. if (controller.patrolWayPoints.Count == 0) return; // Set navigation parameters. controller.focusSight = false; controller.nav.speed = controller.generalStats.patrolSpeed; // Reached waypoint, wait for a moment before keep patrolling. if (controller.nav.remainingDistance <= controller.nav.stoppingDistance && !controller.nav.pathPending) { controller.variables.patrolTimer += Time.deltaTime; if (controller.variables.patrolTimer >= controller.generalStats.patrolWaitTime) { controller.waypointIndex = (controller.waypointIndex + 1) % controller.patrolWayPoints.Count; controller.variables.patrolTimer = 0f; } } // Set next patrol waypoint. try { controller.nav.destination = controller.patrolWayPoints[controller.waypointIndex].position; } catch (UnassignedReferenceException) { // Suggest patrol waypoints for NPC, if none. Debug.LogWarning("No waypoints assigned for " + controller.transform.name+", enemy will remain idle"); // No waypoints, create single position to stand still. controller.patrolWayPoints = new List<Transform> { controller.transform }; controller.nav.destination = controller.transform.position; } } }
34.278689
105
0.754663
[ "MIT" ]
screat100/Project-SS
ex/Assets/TPS Bundle/EnemyAI/Scripts/ScriptableObjects/Actions/PatrolAction.cs
2,093
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.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Xunit { internal class ForegroundTestCase : XunitTestCase { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Called by the de-serializer", error: true)] public ForegroundTestCase() { } public ForegroundTestCase(IMessageSink diagnosticMessageSink, TestMethodDisplay defaultMethodDisplay, TestMethodDisplayOptions defaultMethodDisplayOptions, ITestMethod testMethod, object[] testMethodArguments = null) : base(diagnosticMessageSink, defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments) { } public override Task<RunSummary> RunAsync( IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var tcs = new TaskCompletionSource<RunSummary>(); var thread = new Thread(() => { try { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); var worker = base.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource); Exception caught = null; var frame = new DispatcherFrame(); Task.Run(async () => { try { await worker; } catch (Exception ex) { caught = ex; } finally { frame.Continue = false; } }); Dispatcher.PushFrame(frame); if (caught == null) { tcs.SetResult(worker.Result); } else { tcs.SetException(caught); } } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; } } }
33.682353
224
0.5124
[ "Apache-2.0" ]
ajaybhargavb/AspNetCore-Tooling
src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test.Common/Xunit/ForegroundTestCase.cs
2,865
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("OneCog.Io.Spark.Ninject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OneCog.Io.Spark.Ninject")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9cde5827-9f15-4e4a-a872-7b160ff7c288")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.351351
84
0.744891
[ "MIT" ]
ibebbs/OneCog.Io.Spark
src/OneCog.Io.Spark.Ninject/Properties/AssemblyInfo.cs
1,422
C#
using UnityEngine; using System.Collections; using Sirenix.OdinInspector; public class WwiseEventEmitter : MonoBehaviour { [FoldoutGroup("Main Sound"), Tooltip("nom du son exacte à jouer"), SerializeField] private string nameSoundToPlay = ""; [FoldoutGroup("Main Sound"), Tooltip("lien de l'ak (dans le même gameObject)"), SerializeField] private AkAmbient soundToPlay; [FoldoutGroup("Stop Sound"), Tooltip("nom du son exacte à stopper"), SerializeField] public string nameSoundToStop = ""; [FoldoutGroup("Stop Sound"), Tooltip("lien de l'ak (dans le même gameObject)"), SerializeField] public AkAmbient soundToPlayStop; [FoldoutGroup("Spacialisation"), Tooltip("le son est-il spacialisé ?"), SerializeField] public bool spacialisationEnabled = false; [FoldoutGroup("Spacialisation"), EnableIf("spacialisationEnabled"), Tooltip("le lien de l'objet parent d'ou on appelle les sons..."), SerializeField] public Transform mainParent; void Start() { //AkSoundEngine.PostEvent("Play_music_placeholder"); //AkSoundEngine.PostEvent("Play_music_placeholder", this.gameObject); //emitter = gameObject.GetComponent<AkAmbient>(); //init l'emitter SoundManager.Instance.AddKey(GetNameId(), this); if (nameSoundToStop != "") SoundManager.Instance.AddKey(GetNameStopId(), this); } private string GetNameId() { //string addParent = (addIdEvent) ? soundToPlay.eventID.ToString() : ""; string addParent = (spacialisationEnabled) ? mainParent.GetInstanceID().ToString() : ""; return (nameSoundToPlay + addParent); } private string GetNameStopId() { //string addParent = (addIdEvent) ? soundToPlayStop.eventID.ToString() : ""; string addParent = (spacialisationEnabled) ? mainParent.GetInstanceID().ToString() : ""; return (nameSoundToStop + addParent); } /// <summary> /// play l'emmiter /// </summary> [Button("play")] public void Play() { if (!gameObject || !soundToPlay) return; //SendMessage("Play"); AkSoundEngine.PostEvent(nameSoundToPlay, this.gameObject); } /// <summary> /// stop l'emmiter /// </summary> [Button("stop")] public void Stop() { if (!gameObject || !soundToPlayStop) return; AkSoundEngine.PostEvent(nameSoundToStop, this.gameObject); } /// <summary> /// AkSoundEngine.SetState("MainStateGroup", "Movement"); /// </summary> public void SetStateValue(string paramState, string paramName) { if (!gameObject || !soundToPlay) return; //emitter.SetParameter(paramName, value); AkSoundEngine.SetState(paramState, paramName); } /// <summary> /// exemple: paramName: Pitch /// </summary> public void SetRTPCValue(string paramName, float value) { if (!gameObject || !soundToPlay) return; AkSoundEngine.SetRTPCValue(paramName, value, gameObject); } private void OnDestroy() { Debug.Log("on destroy ??"); return; //string addParent = (addIdOfObject) ? addIdOfObject.GetInstanceID().ToString() : ""; //if (emitter && emitter.Event != "" && SoundManager.GetSingleton) SoundManager.Instance.DeleteKey(GetNameId(), this); if (nameSoundToStop != "") SoundManager.Instance.DeleteKey(GetNameStopId(), this); } }
35.294118
154
0.622778
[ "MIT" ]
usernameHed/BackHome
Assets/_Scripts/Core/_Main/WwiseEventEmitter.cs
3,607
C#
using System.Security.Cryptography; using Anreton.RabbitMq.HashGenerator.Abstractions; namespace Anreton.RabbitMq.HashGenerator { /// <summary> /// Represents an implementation of the SHA512 generator. /// </summary> public sealed class SHA512Generator : Generator { /// <summary> /// Initializes a new instance of the <see cref="SHA512Generator"/> class. /// </summary> public SHA512Generator() : base(SHA512.Create()) { } } }
22.45
76
0.712695
[ "MIT" ]
anreton/Anreton.RabbitMq
Anreton.RabbitMq.HashGenerator/SHA512Generator.cs
451
C#
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ using global::SharpDX; using System; using System.Collections.Generic; #if !NETFX_CORE namespace HelixToolkit.Wpf.SharpDX #else #if CORE namespace HelixToolkit.SharpDX.Core #else namespace HelixToolkit.UWP #endif #endif { using Utilities; #if !NETFX_CORE [Serializable] #endif public class LineGeometry3D : Geometry3D { public IEnumerable<Line> Lines { get { for (int i = 0; i < Indices.Count; i += 2) { yield return new Line { P0 = Positions[Indices[i]], P1 = Positions[Indices[i + 1]], }; } } } protected override IOctreeBasic CreateOctree(OctreeBuildParameter parameter) { return new StaticLineGeometryOctree(Positions, Indices, parameter); } protected override bool CanCreateOctree() { return Positions != null && Positions.Count > 0 && Indices != null && Indices.Count > 0; } public virtual bool HitTest(IRenderMatrices context, Matrix modelMatrix, ref Ray rayWS, ref List<HitTestResult> hits, object originalSource, float hitTestThickness) { if (Positions == null || Positions.Count == 0 || Indices == null || Indices.Count == 0) { return false; } if(Octree != null) { return Octree.HitTest(context, originalSource, this, modelMatrix, rayWS, ref hits, hitTestThickness); } else { var result = new LineHitTestResult { IsValid = false, Distance = double.MaxValue }; var lastDist = double.MaxValue; var lineIndex = 0; foreach (var line in Lines) { var t0 = Vector3.TransformCoordinate(line.P0, modelMatrix); var t1 = Vector3.TransformCoordinate(line.P1, modelMatrix); var rayToLineDistance = LineBuilder.GetRayToLineDistance(rayWS, t0, t1, out Vector3 sp, out Vector3 tp, out float sc, out float tc); var svpm = context.ScreenViewProjectionMatrix; Vector3.TransformCoordinate(ref sp, ref svpm, out var sp3); Vector3.TransformCoordinate(ref tp, ref svpm, out var tp3); var tv2 = new Vector2(tp3.X - sp3.X, tp3.Y - sp3.Y); var dist = tv2.Length() / context.DpiScale; if (dist < lastDist && dist <= hitTestThickness) { lastDist = dist; result.PointHit = sp; result.NormalAtHit = sp - tp; // not normalized to get length result.Distance = (rayWS.Position - sp).Length(); result.RayToLineDistance = rayToLineDistance; result.ModelHit = originalSource; result.IsValid = true; result.Tag = lineIndex; // For compatibility result.LineIndex = lineIndex; result.TriangleIndices = null; // Since triangles are shader-generated result.RayHitPointScalar = sc; result.LineHitPointScalar = tc; result.Geometry = this; } lineIndex++; } if (result.IsValid) { hits.Add(result); } return result.IsValid; } } public override void UpdateBounds() { base.UpdateBounds(); if (Bound.Size.LengthSquared() < 1e-1f) { var off = new Vector3(0.5f); Bound = new BoundingBox(Bound.Minimum - off, Bound.Maximum + off); } if (BoundingSphere.Radius < 1e-1f) { BoundingSphere = new BoundingSphere(BoundingSphere.Center, 0.5f); } } } }
36.486957
172
0.513584
[ "MIT" ]
Kaos1105/PointCloudViewer-HelixToolkit
Source/HelixToolkit.SharpDX.Shared/Model/Geometry/LineGeometry3D.cs
4,198
C#
/******************************************************************************* * 命名空间: SF.Data.Repository * * 功 能: N/A * 类 名: IRoleRepository * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2016/11/11 15:18:03 疯狂蚂蚁 初版 * * Copyright (c) 2016 SF 版权所有 * Description: SF快速开发平台 * Website:http://www.mayisite.com *********************************************************************************/ using SF.Core.EFCore.UoW; using SF.Entitys; namespace SF.Data.Repository { /// <summary> /// /// </summary> public interface ISettingRepository : IEFCoreQueryableRepository<SettingEntity, long> { } }
21.9
82
0.444444
[ "Apache-2.0" ]
blueskybcl/SF-Boilerplate
SF.Data/Repository/ISettingRepository.cs
805
C#
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using Alexa.NET.Request; using MartinCostello.LondonTravel.Skill.Intents; using Microsoft.Extensions.DependencyInjection; namespace MartinCostello.LondonTravel.Skill; /// <summary> /// A class representing a factory for <see cref="IIntent"/> instances. This class cannot be inherited. /// </summary> internal sealed class IntentFactory { /// <summary> /// Initializes a new instance of the <see cref="IntentFactory"/> class. /// </summary> /// <param name="serviceProvider">The <see cref="IServiceProvider"/> to use.</param> public IntentFactory(IServiceProvider serviceProvider) { ServiceProvider = serviceProvider; } /// <summary> /// Gets the <see cref="IServiceProvider"/> to use. /// </summary> private IServiceProvider ServiceProvider { get; } /// <summary> /// Creates an intent responder for the specified intent. /// </summary> /// <param name="intent">The intent to create a responder for.</param> /// <returns> /// The <see cref="IIntent"/> to use to generate a response for the intent. /// </returns> public IIntent Create(Intent intent) { switch (intent.Name) { case "AMAZON.CancelIntent": case "AMAZON.StopIntent": return ServiceProvider.GetRequiredService<EmptyIntent>(); case "AMAZON.HelpIntent": return ServiceProvider.GetRequiredService<HelpIntent>(); case "CommuteIntent": return ServiceProvider.GetRequiredService<CommuteIntent>(); case "DisruptionIntent": return ServiceProvider.GetRequiredService<DisruptionIntent>(); case "StatusIntent": return ServiceProvider.GetRequiredService<StatusIntent>(); default: return ServiceProvider.GetRequiredService<UnknownIntent>(); } } }
34.016393
112
0.653012
[ "Apache-2.0" ]
martincostello/alexa-london-travel
src/LondonTravel.Skill/IntentFactory.cs
2,075
C#
namespace DynamicAttribute { partial class Form1 { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード private void InitializeComponent() { this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.controlListBox = new System.Windows.Forms.ListBox(); this.hideButton = new System.Windows.Forms.Button(); this.hidePropertyListBox = new System.Windows.Forms.ListBox(); this.showButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // propertyGrid1 // this.propertyGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.propertyGrid1.Font = new System.Drawing.Font("メイリオ", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.propertyGrid1.Location = new System.Drawing.Point(514, 12); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(323, 431); this.propertyGrid1.TabIndex = 0; // // controlListBox // this.controlListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.controlListBox.Font = new System.Drawing.Font("メイリオ", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.controlListBox.FormattingEnabled = true; this.controlListBox.ItemHeight = 24; this.controlListBox.Location = new System.Drawing.Point(12, 12); this.controlListBox.Name = "controlListBox"; this.controlListBox.Size = new System.Drawing.Size(215, 436); this.controlListBox.TabIndex = 1; this.controlListBox.SelectedIndexChanged += new System.EventHandler(this.ControlListBox_SelectedIndexChanged); // // hideButton // this.hideButton.Location = new System.Drawing.Point(463, 87); this.hideButton.Name = "hideButton"; this.hideButton.Size = new System.Drawing.Size(45, 47); this.hideButton.TabIndex = 2; this.hideButton.Text = "←\r\nDel"; this.hideButton.UseVisualStyleBackColor = true; this.hideButton.Click += new System.EventHandler(this.HideButton_Click); // // hidePropertyListBox // this.hidePropertyListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.hidePropertyListBox.Font = new System.Drawing.Font("メイリオ", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.hidePropertyListBox.FormattingEnabled = true; this.hidePropertyListBox.ItemHeight = 24; this.hidePropertyListBox.Location = new System.Drawing.Point(233, 12); this.hidePropertyListBox.Name = "hidePropertyListBox"; this.hidePropertyListBox.Size = new System.Drawing.Size(224, 436); this.hidePropertyListBox.TabIndex = 3; // // showButton // this.showButton.Location = new System.Drawing.Point(463, 201); this.showButton.Name = "showButton"; this.showButton.Size = new System.Drawing.Size(45, 51); this.showButton.TabIndex = 4; this.showButton.Text = "→\r\nAdd"; this.showButton.UseVisualStyleBackColor = true; this.showButton.Click += new System.EventHandler(this.ShowButton_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(849, 455); this.Controls.Add(this.showButton); this.Controls.Add(this.hidePropertyListBox); this.Controls.Add(this.hideButton); this.Controls.Add(this.controlListBox); this.Controls.Add(this.propertyGrid1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.PropertyGrid propertyGrid1; private System.Windows.Forms.ListBox controlListBox; private System.Windows.Forms.Button hideButton; private System.Windows.Forms.ListBox hidePropertyListBox; private System.Windows.Forms.Button showButton; } }
48.688073
167
0.622762
[ "CC0-1.0" ]
TN8001/DynamicAttribute
DynamicAttribute/Form1.Designer.cs
5,373
C#
namespace Zuehlke.Hades.Test { internal static class AppSettings { public static string ConnectionString => ""; } }
17.125
52
0.649635
[ "MIT" ]
DaveSenn/Zuehlke.Hades
Zuehlke.Hades.Test/AppSettings.cs
139
C#
using System; using System.Activities; using OpenRPA.Interfaces; using System.Activities.Presentation.PropertyEditing; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Runtime.ExceptionServices; using System.Reflection; using System.CodeDom.Compiler; using System.Management.Automation.Runspaces; using System.Collections; using System.Collections.ObjectModel; using Python.Runtime; namespace OpenRPA.Script.Activities { [System.ComponentModel.Designer(typeof(InvokeCodeDesigner), typeof(System.ComponentModel.Design.IDesigner))] [System.Drawing.ToolboxBitmap(typeof(ResFinder2), "Resources.toolbox.comment.png")] [LocalizedToolboxTooltip("activity_invokecode_tooltip", typeof(Resources.strings))] [LocalizedDisplayName("activity_invokecode", typeof(Resources.strings))] public class InvokeCode : CodeActivity { public InvokeCode() { } [RequiredArgument] public InArgument<string> Code { get; set; } [RequiredArgument] public InArgument<string> Language { get; set; } = "VB"; public OutArgument<Collection<System.Management.Automation.PSObject>> PipelineOutput { get; set; } [Browsable(false)] public string[] namespaces { get; set; } public static RunspacePool pool { get; set; } = null; public static Runspace runspace = null; public static void ExecuteNewAppDomain(Action action) { AppDomain domain = null; try { domain = AppDomain.CreateDomain("New App Domain: " + Guid.NewGuid()); var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap( typeof(AppDomainDelegate).Assembly.FullName, typeof(AppDomainDelegate).FullName); domainDelegate.Execute(action); } finally { if (domain != null) AppDomain.Unload(domain); } } public static void ExecuteNewAppDomain(string code, Action<string> action) { AppDomain domain = null; try { domain = AppDomain.CreateDomain("New App Domain: " + Guid.NewGuid()); var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap( typeof(AppDomainDelegate).Assembly.FullName, typeof(AppDomainDelegate).FullName); domainDelegate.Execute<string>(code, action); } finally { if (domain != null) AppDomain.Unload(domain); } } protected override void Execute(CodeActivityContext context) { string currentdir = System.IO.Directory.GetCurrentDirectory(); try { System.IO.Directory.SetCurrentDirectory(Interfaces.Extensions.ProjectsDirectory); var code = Code.Get(context); var language = Language.Get(context); var variables = new Dictionary<string, Type>(); var variablevalues = new Dictionary<string, object>(); var vars = context.DataContext.GetProperties(); foreach (dynamic v in vars) { Type rtype = v.PropertyType as Type; var value = v.GetValue(context.DataContext); if (rtype == null && value != null) rtype = value.GetType(); if (rtype == null) continue; variables.Add(v.DisplayName, rtype); variablevalues.Add(v.DisplayName, value); } string sourcecode = code; if (namespaces == null) { throw new Exception("InvokeCode is missing namespaces, please open workflow in designer and save changes"); } if (language == "VB") { var header = GetVBHeaderText(variables, "Expression", namespaces); sourcecode = header + code + GetVBFooterText(); int numLines = header.Split('\n').Length; Log.Debug("Header (add to line numbers): " + numLines); } if (language == "C#") { var header = GetCSharpHeaderText(variables, "Expression", namespaces); sourcecode = header + code + GetCSharpFooterText(); int numLines = header.Split('\n').Length; Log.Debug("Header (add to line numbers): " + numLines); } if (language == "PowerShell") { if (runspace == null) { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); } using (var pipeline = runspace.CreatePipeline()) { Command cmd = new Command(sourcecode, true); foreach (var parameter in variablevalues) { // cmd.Parameters.Add(parameter.Key, parameter.Value); runspace.SessionStateProxy.SetVariable(parameter.Key, parameter.Value); } pipeline.Commands.Add(cmd); var res = pipeline.Invoke(); foreach (var o in res) { if (o != null) Log.Output(o.ToString()); } foreach (dynamic v in vars) { var value = runspace.SessionStateProxy.GetVariable(v.DisplayName); var myVar = context.DataContext.GetProperties().Find(v.DisplayName, true); try { if (myVar != null && value != null) { //var myValue = myVar.GetValue(context.DataContext); myVar.SetValue(context.DataContext, value); } } catch (Exception ex) { Log.Error(ex.ToString()); } } PipelineOutput.Set(context, res); } return; } if (language == "AutoHotkey") { AppDomain Temporary = null; try { AppDomainSetup domaininfo = new AppDomainSetup(); domaininfo.ApplicationBase = global.CurrentDirectory; System.Security.Policy.Evidence adevidence = AppDomain.CurrentDomain.Evidence; Temporary = AppDomain.CreateDomain("Temporary", adevidence, domaininfo); Temporary.AssemblyResolve += AHKProxy.CurrentDomain_AssemblyResolve; //var ahk = (AutoHotkey.Interop.AutoHotkeyEngine)Temporary.CreateInstanceAndUnwrap("sharpAHK, Version=1.0.0.5, Culture=neutral, PublicKeyToken=null", "AutoHotkey.Interop.AutoHotkeyEngine"); Type type = typeof(AHKProxy); var ahk = (AHKProxy)Temporary.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName); foreach (var parameter in variablevalues) { if (parameter.Value == null) continue; ahk.SetVar(parameter.Key, parameter.Value.ToString()); } ahk.ExecRaw(code); foreach (dynamic v in vars) { var value = ahk.GetVar(v.DisplayName); PropertyDescriptor myVar = context.DataContext.GetProperties().Find(v.DisplayName, true); if (myVar != null && value != null) { if (myVar.PropertyType == typeof(string)) myVar.SetValue(context.DataContext, value); else if (myVar.PropertyType == typeof(int)) myVar.SetValue(context.DataContext, int.Parse(value.ToString())); else if (myVar.PropertyType == typeof(bool)) myVar.SetValue(context.DataContext, bool.Parse(value.ToString())); else Log.Information("Ignorering variable " + v.DisplayName + " of type " + myVar.PropertyType.FullName); } } } catch (Exception ex) { Log.Error(ex.ToString()); throw; } finally { if (Temporary != null) AppDomain.Unload(Temporary); } return; } if (language == "Python") { try { GenericTools.RunUI(() => { if (PluginConfig.use_embedded_python) { System.IO.Directory.SetCurrentDirectory(Python.Included.Installer.EmbeddedPythonHome); } IntPtr lck = IntPtr.Zero; try { lck = PythonEngine.AcquireLock(); using (var scope = Py.CreateScope()) { foreach (var parameter in variablevalues) { PyObject pyobj = parameter.Value.ToPython(); scope.Set(parameter.Key, pyobj); } try { PythonOutput output = new PythonOutput(); dynamic sys = Py.Import("sys"); sys.stdout = output; sys.stderr = output; // PythonEngine.RunSimpleString(@" //import sys //from System import Console //class output(object): // def write(self, msg): // Console.Out.Write(msg) // def writelines(self, msgs): // for msg in msgs: // Console.Out.Write(msg) // def flush(self): // pass // def close(self): // pass //sys.stdout = sys.stderr = output() //"); } catch (Exception ex) { Log.Debug(ex.ToString()); } scope.Exec(code); foreach (var parameter in variablevalues) { PyObject pyobj = scope.Get(parameter.Key); if (pyobj == null) continue; PropertyDescriptor myVar = context.DataContext.GetProperties().Find(parameter.Key, true); if (myVar.PropertyType == typeof(string)) myVar.SetValue(context.DataContext, pyobj.ToString()); else if (myVar.PropertyType == typeof(int)) myVar.SetValue(context.DataContext, int.Parse(pyobj.ToString())); else if (myVar.PropertyType == typeof(bool)) myVar.SetValue(context.DataContext, bool.Parse(pyobj.ToString())); else { try { var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(pyobj.ToString(), myVar.PropertyType); myVar.SetValue(context.DataContext, obj); } catch (Exception ex) { Log.Information("Failed variable " + parameter.Key + " of type " + myVar.PropertyType.FullName + " " + ex.Message); } } } } //lck = PythonEngine.AcquireLock(); //PythonEngine.Exec(code); } catch (Exception) { //Log.Error(ex.ToString()); throw; } finally { PythonEngine.ReleaseLock(lck); } }); //using (Python.Runtime.Py.GIL()) //{ // IntPtr lck = Python.Runtime.PythonEngine.AcquireLock(); // Python.Runtime.PythonEngine.Exec(code); // Python.Runtime.PythonEngine.ReleaseLock(lck); // //// create a Python scope // //using (var scope = Python.Runtime.Py.CreateScope()) // //{ // // //// convert the Person object to a PyObject // // //PyObject pyPerson = person.ToPython(); // // // create a Python variable "person" // // // scope.Set("person", pyPerson); // // // the person object may now be used in Python // // // string code = "fullName = person.FirstName + ' ' + person.LastName"; // // scope.Exec(code); // //} //} } catch (Exception) { throw; } finally { try { // Python.Runtime.PythonEngine.Shutdown(); } catch (Exception ex) { Log.Error(ex.ToString()); } } return; } var assemblyLocations = GetAssemblyLocations(); CompileAndRun(language, sourcecode, assemblyLocations.ToArray(), variablevalues, context); } finally { System.IO.Directory.SetCurrentDirectory(currentdir); } } public static string[] GetAssemblyLocations() { var names = new List<string>(); var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); var assemblyLocations = new List<string>(); foreach (var asm in assemblies) { try { //var a = Assembly.ReflectionOnlyLoad(asm.FullName); //var a = Assembly.Load(asm.FullName); //if(!assemblyLocations.Contains(a.Location)) assemblyLocations.Add(a.Location); if (!asm.IsDynamic) { // if (asm.Location.Contains("Microsoft.Office.Interop")) continue; if (string.IsNullOrEmpty(asm.Location)) continue; if (asm.Location.Contains("System.Numerics.Vectors")) { continue; } if (!assemblyLocations.Contains(asm.Location) && !names.Contains(asm.FullName)) { names.Add(asm.FullName); assemblyLocations.Add(asm.Location); } } //else //{ // Console.WriteLine(asm.FullName ); // + " " + asm.Location //} } catch (Exception ex) { Log.Error(ex.ToString()); } } return assemblyLocations.ToArray(); } private static Dictionary<string, CompilerResults> cache = new Dictionary<string, CompilerResults>(); public void CompileAndRun(string language, string code, string[] references, Dictionary<string, object> variablevalues, CodeActivityContext context) { CompilerResults compile = null; if (!cache.ContainsKey(code)) { CompilerParameters CompilerParams = new CompilerParameters(); string outputDirectory = System.IO.Directory.GetCurrentDirectory(); //CompilerParams.GenerateInMemory = true; CompilerParams.TreatWarningsAsErrors = false; CompilerParams.GenerateExecutable = false; CompilerParams.CompilerOptions = "/optimize /d:DEBUG"; CompilerParams.IncludeDebugInformation = true; CompilerParams.GenerateInMemory = false; CompilerParams.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString().Replace("-", "") + ".dll"); CompilerParams.ReferencedAssemblies.AddRange(references); // CompilerParams.ReferencedAssemblies.Add(@"C:\code\openrpa\bin\Microsoft.Office.Tools.Excel.dll"); CodeDomProvider provider = null; if (language == "VB") { provider = new Microsoft.VisualBasic.VBCodeProvider(); } else { provider = new Microsoft.CSharp.CSharpCodeProvider(); } compile = provider.CompileAssemblyFromSource(CompilerParams, new[] { code }); if (compile.Errors.HasErrors) { string text = ""; foreach (CompilerError ce in compile.Errors) { if (!ce.IsWarning) { text += ce.ToString(); Log.Error(ce.ToString()); } } throw new Exception(text); } cache.Add(code, compile); } else { compile = cache[code]; } //ExpoloreAssembly(compile.CompiledAssembly); Module module = compile.CompiledAssembly.GetModules()[0]; Type mt = null; MethodInfo methInfo = null; if (module != null) { mt = module.GetType("Expression"); } if (module != null && mt == null) { mt = module.GetType("SomeNamespace.Expression"); } if (mt != null) { methInfo = mt.GetMethod("ExpressionValue"); foreach (var v in variablevalues) { var p = mt.GetField(v.Key); if (p != null) { p.SetValue(mt, v.Value); } } } if (methInfo != null) { ExceptionDispatchInfo exceptionDispatchInfo = null; try { methInfo.Invoke(null, new object[] { }); } catch (Exception ex) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } if (exceptionDispatchInfo != null) exceptionDispatchInfo.Throw(); var vars = context.DataContext.GetProperties(); foreach (dynamic v in vars) { var p = mt.GetField(v.DisplayName); if (p == null) continue; var value = p.GetValue(mt); v.SetValue(context.DataContext, value); } } } private static string GetVBHeaderText(Dictionary<string, Type> variables, string moduleName, string[] namespaces) { // Inject namespace imports //var headerText = new StringBuilder("Imports System\r\nImports System.Collections\r\nImports System.Collections.Generic\r\nImports System.Linq\r\n"); var headerText = new StringBuilder(); foreach (var n in namespaces) { headerText.AppendLine("Imports " + n + "\r\n"); } // NOTE: Automated IntelliPrompt will only show for namespaces and types that are within the imported namespaces... // Add other namespace imports here if types from other namespaces should be accessible // Inject a Class and Sub wrapper headerText.Append("\r\nModule " + moduleName + "\r\n"); //headerText.Append("\r\nClass Expression\r\nShared Sub ExpressionValue\r\n"); if (variables != null) { foreach (var var in variables) { // Build a VB representation of the variable's type name var variableTypeName = new StringBuilder(); AppendVBTypeName(variableTypeName, var.Value); headerText.Append("Public "); headerText.Append(var.Key); headerText.Append(" As "); headerText.Append(variableTypeName.Replace("[", "(").Replace("]", ")")); headerText.AppendLine(); } } headerText.Append("Sub ExpressionValue\r\n"); //// Since the document text is an expression, inject a Return statement start at the end of the header text //headerText.Append("\r\nReturn "); headerText.AppendLine(); return headerText.ToString(); } private static string GetVBFooterText() { // Close out the Sub and Class in the footer return "\r\nEnd Sub\r\nEnd Module"; } private static void AppendVBTypeName(StringBuilder typeName, Type type) { var typeFullName = type.FullName; if (type.IsGenericType) { var tickIndex = typeFullName.IndexOf('`'); if (tickIndex != -1) { typeName.Append(typeFullName.Substring(0, tickIndex)); typeName.Append("(Of "); var genericArgumentIndex = 0; foreach (var genericArgument in type.GetGenericArguments()) { if (genericArgumentIndex++ > 0) typeName.Append(", "); AppendVBTypeName(typeName, genericArgument); } typeName.Append(")"); return; } } typeName.Append(typeFullName); } public static string GetCSharpHeaderText(Dictionary<string, Type> variables, string moduleName, string[] namespaces) { var headerText = new StringBuilder(); foreach (var n in namespaces) { headerText.AppendLine("using " + n + ";\r\n"); } headerText.Append("\r\n namespace SomeNamespace { public class " + moduleName + " { \r\n"); headerText.AppendLine(); if (variables != null) { foreach (var var in variables) { // Build a VB representation of the variable's type name var variableTypeName = new StringBuilder(); AppendCSharpTypeName(variableTypeName, var.Value); headerText.Append("public static " + variableTypeName + " " + var.Key + " = default(" + variableTypeName + ");"); headerText.AppendLine(); } } headerText.AppendLine("public static void ExpressionValue() { "); return headerText.ToString(); } public static string GetCSharpFooterText() { return " } } }"; } public static void AppendCSharpTypeName(StringBuilder typeName, Type type) { var typeFullName = type.FullName; if (type.IsGenericType) { var tickIndex = typeFullName.IndexOf('`'); if (tickIndex != -1) { typeName.Append(typeFullName.Substring(0, tickIndex)); typeName.Append("<"); var genericArgumentIndex = 0; foreach (var genericArgument in type.GetGenericArguments()) { if (genericArgumentIndex++ > 0) typeName.Append(", "); AppendCSharpTypeName(typeName, genericArgument); } typeName.Append(">"); return; } } typeName.Append(typeFullName); } public new string DisplayName { get { var displayName = base.DisplayName; if (displayName == this.GetType().Name) { var displayNameAttribute = this.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), true).FirstOrDefault() as DisplayNameAttribute; if (displayNameAttribute != null) displayName = displayNameAttribute.DisplayName; } return displayName; } set { base.DisplayName = value; } } } public class AssemblyLoader { private Dictionary<string, Assembly> loadedAssemblies; public AssemblyLoader() { loadedAssemblies = new Dictionary<string, Assembly>(); AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string shortName = args.Name.Split(',')[0]; string resourceName = $"{shortName}.dll"; if (loadedAssemblies.ContainsKey(resourceName)) { return loadedAssemblies[resourceName]; } // looks for the assembly from the resources and load it using (System.IO.Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { if (stream != null) { var assemblyData = new byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); Assembly assembly = Assembly.Load(assemblyData); loadedAssemblies[resourceName] = assembly; return assembly; } } return null; }; } } //public class AppDomainDelegate : MarshalByRefObject //{ // public void Execute(Action action) // { // action(); // } //} public class AppDomainDelegate : MarshalByRefObject { public void Execute(Action action) { action(); } public void Execute<T>(T parameter, Action<T> action) { action(parameter); } } }
43.233918
213
0.444711
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
IBM/openrpa
OpenRPA.Script/Activities/InvokeCode.cs
29,574
C#
namespace Calopsite { partial class Alimentacao { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(101, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(130, 25); this.label1.TabIndex = 0; this.label1.Text = "Alimentação"; // // comboBox1 // this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(25, 92); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(121, 21); this.comboBox1.TabIndex = 9; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(21, 58); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(55, 20); this.label2.TabIndex = 10; this.label2.Text = "Gaiola"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(187, 58); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 20); this.label3.TabIndex = 11; this.label3.Text = "Ração"; // // comboBox2 // this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(182, 92); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(121, 21); this.comboBox2.TabIndex = 12; // // textBox1 // this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.Location = new System.Drawing.Point(91, 154); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 29); this.textBox1.TabIndex = 13; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(27, 154); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(58, 24); this.label4.TabIndex = 14; this.label4.Text = "Peso:"; // // button1 // this.button1.Location = new System.Drawing.Point(125, 245); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 15; this.button1.Text = "Alimentar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Alimentacao // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(352, 293); this.Controls.Add(this.button1); this.Controls.Add(this.label4); this.Controls.Add(this.textBox1); this.Controls.Add(this.comboBox2); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.comboBox1); this.Controls.Add(this.label1); this.Name = "Alimentacao"; this.Text = "Aimentacao"; this.Load += new System.EventHandler(this.Aimentacao_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; protected System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; protected System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button1; } }
44.92
171
0.579252
[ "MIT" ]
igoreira0/CalopsiteDesktop
form/Alimentacao.Designer.cs
6,744
C#
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Letscode.Signal { /// <summary> /// Complete subscriber delegate. /// </summary> public delegate void CallbackSubscriberWithSenderAndArgs(object sender, Dictionary<string, object> args); /// <summary> /// Minimal subscriber delegate with sender. /// </summary> public delegate void CallbackSubscriberWithSender(object sender); /// <summary> /// Minimal subscriber delegate with arguments. /// </summary> public delegate void CallbackSubscriberWithArgs(Dictionary<string, object> args); /// <summary> /// Minimal subscriber delegate. /// </summary> public delegate void CallbackSubscriber(); /// <summary> /// Mediator is a communication interface for components. /// /// The class implements the singleton pattern, make usage of getter Mediator.Instance to catch the active instance. /// /// Objects can subscribe and publish messages to it. Additionally the mediator has a "per frame state", /// messages within the same frame will be consumed even if the event was fired before the subscriber /// subscribed. /// </summary> public class Mediator { /// <summary> /// Instance of Mediator. /// </summary> private static Mediator instance = null; /// <summary> /// The frame number from the last interaction. /// </summary> int lastFrame = 0; /// <summary> /// Dictionary containing a list of all events that have been /// published during this frame /// </summary> Dictionary<string, List<Dictionary<string, object>>> frameEvents; /// <summary> /// Direct subscribers call the ISubscriber SignalDispatcher method on the subscribed object. /// </summary> Dictionary<string, List<ISubscriber>> directSubscribers; /// <summary> /// Callback subscribers use the native delegate approach to handle callbacks on, for the handler anonymous, objects. /// </summary> Dictionary<string, CallbackSubscriberWithSenderAndArgs> callbackSubscribersWithSenderAndArgs; /// <summary> /// The callback subscribers with arguments. /// </summary> Dictionary<string, CallbackSubscriberWithArgs> callbackSubscribersWithArgs; /// <summary> /// The minimal callback subscribers. /// </summary> Dictionary<string, CallbackSubscriber> callbackSubscribers; protected Mediator() { //Init directSubscribers = new Dictionary<string, List<ISubscriber>> (); callbackSubscribersWithSenderAndArgs = new Dictionary<string, CallbackSubscriberWithSenderAndArgs> (); callbackSubscribersWithArgs = new Dictionary<string, CallbackSubscriberWithArgs> (); callbackSubscribers = new Dictionary<string, CallbackSubscriber> (); frameEvents = new Dictionary<string, List<Dictionary<string, object>>>(); } /// <summary> /// Gets the instance of Mediator. /// </summary> /// <value>The instance.</value> public static Mediator Instance { get { if (instance == null) instance = new Mediator(); return instance; } } /// <summary> /// Subscribe the specified callback to eventName. /// Unsubscribe must be handled manually on the objects destructor using the Mediator.Unsubscribe /// </summary> /// <param name="eventName">Event name.</param> /// <param name="callback">Callback.</param> public static void Subscribe(string eventName, CallbackSubscriberWithSenderAndArgs callback) { Instance.CallbackSubscribe (eventName, callback); } public static void Subscribe(string eventName, CallbackSubscriberWithArgs callback) { Instance.CallbackSubscribe (eventName, callback); } public static void Subscribe(string eventName, CallbackSubscriber callback) { Instance.CallbackSubscribe (eventName, callback); } /// <summary> /// Static subscriber wrapper for shorter syntax. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="subscriber">Subscriber.</param> public static void Subscribe(string eventName, ISubscriber subscriber) { Instance.DirectSubscribe (eventName, subscriber); } /// <summary> /// Unsubscribe the specified callback from eventName. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="callback">Callback.</param> public static void Unsubscribe(string eventName, CallbackSubscriberWithSenderAndArgs callback) { Instance.CallbackUnsubscribe (eventName, callback); } public static void Unsubscribe(string eventName, CallbackSubscriberWithArgs callback) { Instance.CallbackUnsubscribe (eventName, callback); } public static void Unsubscribe(string eventName, CallbackSubscriber callback) { Instance.CallbackUnsubscribe (eventName, callback); } /// <summary> /// Unsubscribe the specified subscriber from eventName. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="subscriber">Subscriber.</param> public static void Unsubscribe(string eventName, ISubscriber subscriber) { Instance.DirectUnsubscribe (eventName, subscriber); } /// <summary> /// Subscribe the specified subscriber to eventName. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="subscriber">Subscriber.</param> public void DirectSubscribe(string eventName, ISubscriber subscriber) { UpdateFrameCount (); if (directSubscribers.ContainsKey (eventName)) directSubscribers [eventName].Add (subscriber); else { List<ISubscriber> list = new List<ISubscriber>(); list.Add (subscriber); directSubscribers.Add (eventName, list); } UpdateSubscriber (eventName, subscriber); } /// <summary> /// Subscribe to a given signal with a callback. The callbacks signature must match the CallbackSubscriber delegates signature. /// If the signal was already published earlier this frame, the callback is instantianted additionally with the arguments in memory. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="callback">Callback.</param> public void CallbackSubscribe(string eventName, CallbackSubscriberWithSenderAndArgs callback) { UpdateFrameCount (); if (callbackSubscribersWithSenderAndArgs.ContainsKey (eventName)) { callbackSubscribersWithSenderAndArgs [eventName] += callback; } else { callbackSubscribersWithSenderAndArgs [eventName] = callback; } if (WasEventPublishedThisFrame (eventName)) { foreach (Dictionary<string, object> item in frameEvents[eventName]) { callback(item["sender"], (Dictionary<string, object>)item["args"]); } } } public void CallbackSubscribe(string eventName, CallbackSubscriberWithArgs callback) { UpdateFrameCount (); if (callbackSubscribersWithArgs.ContainsKey (eventName)) { callbackSubscribersWithArgs [eventName] += callback; } else { callbackSubscribersWithArgs [eventName] = callback; } if (WasEventPublishedThisFrame (eventName)) { foreach (Dictionary<string, object> item in frameEvents[eventName]) { callback((Dictionary<string, object>)item["args"]); } } } public void CallbackSubscribe(string eventName, CallbackSubscriber callback) { UpdateFrameCount (); if (callbackSubscribers.ContainsKey (eventName)) { callbackSubscribers [eventName] += callback; } else { callbackSubscribers [eventName] = callback; } if (WasEventPublishedThisFrame (eventName)) { foreach (Dictionary<string, object> item in frameEvents[eventName]) { callback(); } } } /// <summary> /// Unsubscribes the callback. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="callback">Callback.</param> void CallbackUnsubscribe(string eventName, CallbackSubscriberWithSenderAndArgs callback) { UpdateFrameCount (); if (callbackSubscribersWithSenderAndArgs.ContainsKey (eventName)) { callbackSubscribersWithSenderAndArgs [eventName] -= callback; } } void CallbackUnsubscribe(string eventName, CallbackSubscriberWithArgs callback) { UpdateFrameCount (); if (callbackSubscribersWithArgs.ContainsKey (eventName)) { callbackSubscribersWithArgs [eventName] -= callback; } } void CallbackUnsubscribe(string eventName, CallbackSubscriber callback) { UpdateFrameCount (); if (callbackSubscribers.ContainsKey (eventName)) { callbackSubscribers [eventName] -= callback; } } /// <summary> /// Unsubscribes the subscriber. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="subscriber">Subscriber.</param> void DirectUnsubscribe(string eventName, ISubscriber subscriber) { UpdateFrameCount (); if (directSubscribers.ContainsKey (eventName)) { if (directSubscribers [eventName].Contains (subscriber)) { directSubscribers [eventName].Remove (subscriber); } } } /// <summary> /// Static publisher wrapper for shorter syntax. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public static void Publish(string eventName, object sender, Dictionary<string, object> args = null) { Instance.DirectPublish (eventName, sender, args); Instance.CallbackPublish (eventName, sender, args); Instance.AddFrameEvent (eventName, sender, args); } public static void Publish(string eventName, Dictionary<string, object> args) { Instance.DirectPublish (eventName, null, args); Instance.CallbackPublish (eventName, null, args); Instance.AddFrameEvent (eventName, null, args); } public static void Publish(string eventName) { Instance.DirectPublish (eventName, null, null); Instance.CallbackPublish (eventName, null, null); Instance.AddFrameEvent (eventName, null, null); } /// <summary> /// Publish the specified eventName, sender and args. /// Everys ISubscriber EventDispatcher will be called. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public void DirectPublish(string eventName, object sender, Dictionary<string, object> args = null) { UpdateFrameCount (); List<ISubscriber> invalids = new List<ISubscriber> (); if (directSubscribers.ContainsKey (eventName)) { foreach (ISubscriber subscriber in directSubscribers[eventName]) { if (subscriber == null || subscriber.Equals(null)) { invalids.Add (subscriber); continue; } subscriber.EventDispatcher(eventName, sender, args); } } foreach (ISubscriber sub in invalids) { directSubscribers[eventName].Remove(sub); } } /// <summary> /// Instantiate all subscribed delegates from a given signal. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public void CallbackPublish(string eventName, object sender, Dictionary<string, object> args = null) { UpdateFrameCount (); if (callbackSubscribersWithSenderAndArgs.ContainsKey (eventName)) { if (callbackSubscribersWithSenderAndArgs [eventName] != null) callbackSubscribersWithSenderAndArgs [eventName] (sender, args); } if (callbackSubscribersWithArgs.ContainsKey (eventName)) { if (callbackSubscribersWithArgs [eventName] != null) callbackSubscribersWithArgs [eventName] (args); } if (callbackSubscribers.ContainsKey (eventName)) { if (callbackSubscribers [eventName] != null) callbackSubscribers [eventName] (); } } /// <summary> /// Updates the subscribers with events that may have occured earlier this frame. /// </summary> /// <param name="eventName">Event name.</param> void UpdateSubscriber(string eventName, ISubscriber subscriber) { if (frameEvents.ContainsKey (eventName) && directSubscribers.ContainsKey(eventName)) { foreach (Dictionary<string, object> item in frameEvents[eventName]) { subscriber.EventDispatcher( eventName, item["sender"], (Dictionary<string, object>)item["args"] ); } } } /// <summary> /// Checks if the event was already published this frame. /// </summary> /// <param name="eventName">Event name.</param> bool WasEventPublishedThisFrame(string eventName) { return frameEvents.ContainsKey (eventName); } /// <summary> /// Adds the event available through the current frame for subscribers coming too late. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public void AddFrameEvent(string eventName, object sender, Dictionary<string, object> args = null) { if (!WasEventPublishedThisFrame (eventName)) { frameEvents [eventName] = new List<Dictionary<string, object>>(); } frameEvents[eventName].Add (new Dictionary<string, object> { { "sender", sender }, { "args", args } }); } /// <summary> /// Updates the frame count and clears the frameEvents in case it changed. /// </summary> void UpdateFrameCount() { // We need this here because Time methods access native code which is not available // while testing. It is recommended to only disable it for unit testing or if you want // to have full control over eventing without being frame dependant if (!ignoreFrameCount) { if (Time.frameCount > lastFrame) { lastFrame = Time.frameCount; frameEvents.Clear (); } } } /// <summary> /// Use with caution! /// It is only used by unit-tests in our use-cases! /// </summary> public void ClearFrameEvents() { frameEvents.Clear (); } /// <summary> /// Ignores the frame count. /// Used to disable frameCounting. Use it only if you want to have a frame independant Mediator instance. /// </summary> public bool ignoreFrameCount = false; } }
33.061758
134
0.707307
[ "MIT" ]
hschaeidt/unity-mediator
Assets/Letscode/Signal/Mediator.cs
13,921
C#
namespace CommonComponents { public interface IFinisher { string Beautify(string rhs); } }
15.857143
36
0.648649
[ "Apache-2.0" ]
ModernRonin/Autofac.Extras.Plugins
src/Samples/CommonComponents/IFinisher.cs
113
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.Collections.Immutable; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo { internal static class Extensions { public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type, bool expandDottedNames) { if (name == null) { return; } if (expandDottedNames) { const char separator = '.'; var start = 0; var separatorPos = name.IndexOf(separator, start); while (separatorPos >= 0) { builder.Add(name.Substring(start, separatorPos - start), type); start = separatorPos + 1; separatorPos = name.IndexOf(separator, start); } if (start < name.Length) { builder.Add(name.Substring(start), type); } } else { builder.Add(name, type); } } public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type) { if (string.IsNullOrEmpty(name)) { return; } builder.Add(new NavInfoNode(name, type)); } } }
30.127273
137
0.535305
[ "MIT" ]
06needhamt/roslyn
src/VisualStudio/Core/Def/Implementation/Library/VsNavInfo/Extensions.cs
1,659
C#
using System; using UIKit; namespace Microsoft.Maui { public static class ReturnTypeExtensions { public static UIReturnKeyType ToNative(this ReturnType returnType) { switch (returnType) { case ReturnType.Go: return UIReturnKeyType.Go; case ReturnType.Next: return UIReturnKeyType.Next; case ReturnType.Send: return UIReturnKeyType.Send; case ReturnType.Search: return UIReturnKeyType.Search; case ReturnType.Done: return UIReturnKeyType.Done; case ReturnType.Default: return UIReturnKeyType.Default; default: throw new NotImplementedException($"ReturnType {returnType} not supported"); } } } }
23.310345
81
0.723373
[ "MIT" ]
3DSX/maui
src/Core/src/Platform/iOS/ReturnTypeExtensions.cs
678
C#
using UnityEngine; using UnityEditor; using System.Collections; using UnityEditorInternal; using UnityEditor.Animations; namespace wuxingogo.Editor { public class XAnimatorExtension : XBaseWindow { RuntimeAnimatorController _controller = null; AnimatorType _animatorType = AnimatorType.AnimatorController; GameObject _fbxModel = null; Object[] objects = null; AnimationCurve curve = null; Animator _animator = null; // [MenuItem("Wuxingogo/Animation/XAnimatorExtension ")] static void init() { InitWindow<XAnimatorExtension>(); } public override void OnXGUI() { _animatorType = (AnimatorType)CreateEnumSelectable("AnimatorType", _animatorType); switch (_animatorType) { case AnimatorType.AnimatorController: ShowAnimatorController(); break; case AnimatorType.AnimatorModel: ShowAnimatorModel(); break; case AnimatorType.Animator: ShowAnimatorInfo(); break; } } void ShowAnimatorController() { _controller = (RuntimeAnimatorController)CreateObjectField("animator", _controller, typeof(RuntimeAnimatorController)); if (null != _controller) { EditorGUILayout.BeginHorizontal(); CreateLabel("clip"); CreateLabel("duration"); CreateLabel("isloop"); EditorGUILayout.EndHorizontal(); if (_controller is UnityEditor.Animations.AnimatorController) { UnityEditor.Animations.AnimatorController controller = _controller as UnityEditor.Animations.AnimatorController; #if UNITY_4_6 ShowAnimatorControllerLayer(controller.GetLayer(0)); #endif for (int i = 0; i < controller.layers.Length; i++) { ShowAnimatorControllerLayer(controller.layers[i]); } } else if (_controller is AnimatorOverrideController) { AnimatorOverrideController overrideController = _controller as AnimatorOverrideController; // AnimationClipPair[] clips = (AnimationClipPair[])_controller.GetType().BaseType.GetProperty("clips").GetValue(_controller, null); // ShowAnimatorOverrideControllerClips(overrideController.clips); } } } void ShowAnimatorModel() { _fbxModel = (GameObject)CreateObjectField("model", _fbxModel, typeof(GameObject)); string path = AssetDatabase.GetAssetPath(_fbxModel); ModelImporter modelIm = (ModelImporter)ModelImporter.GetAtPath(path); // AnimationClip newClip = AssetDatabase.LoadAssetAtPath(path, typeof(AnimationClip)) as AnimationClip; EditorGUILayout.BeginHorizontal(); CreateLabel("name"); CreateLabel("start"); CreateLabel("end"); CreateLabel("isLooping"); EditorGUILayout.EndHorizontal(); if (modelIm == null) return; ModelImporterClipAnimation[] animations = modelIm.clipAnimations; for (int pos = 0; pos < animations.Length; pos++) { EditorGUILayout.BeginHorizontal(); animations[pos].name = CreateStringField(animations[pos].name); animations[pos].firstFrame = CreateFloatField(animations[pos].firstFrame); animations[pos].lastFrame = CreateFloatField(animations[pos].lastFrame); animations[pos].loop = CreateCheckBox(animations[pos].loop); // animations[pos]. CreateLabel(animations[pos].loop.ToString()); EditorGUILayout.EndHorizontal(); } if (CreateSpaceButton("Insert")) { ModelImporterClipAnimation[] newAnim = new ModelImporterClipAnimation[animations.Length + 1]; animations.CopyTo(newAnim, 0); animations = newAnim; animations[animations.Length - 1] = animations[0]; } if (CreateSpaceButton("Sub")) { ModelImporterClipAnimation[] newAnim = new ModelImporterClipAnimation[animations.Length - 1]; System.Array.Copy(animations, newAnim, newAnim.Length); animations = newAnim; } if (GUI.changed) { modelIm.clipAnimations = animations; AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } void ShowAnimatorControllerLayer(UnityEditor.Animations.AnimatorControllerLayer layer) { #if UNITY_4_6 StateMachine stateMachine = layer.stateMachine; for (int pos = 0; pos < stateMachine.stateCount; pos++) { Motion motion = stateMachine.GetState(pos).GetMotion(); if (null != motion) { EditorGUILayout.BeginHorizontal(); CreateLabel(stateMachine.GetState(pos).name); CreateLabel(motion.averageDuration.ToString()); CreateLabel(motion.isLooping.ToString()); EditorGUILayout.EndHorizontal(); } } #endif AnimatorStateMachine stateMachine = layer.stateMachine; ChildAnimatorState[] states = layer.stateMachine.states; for (int pos = 0; pos < states.Length; pos++) { var animaState = states[pos].state; Motion motion = states[pos].state.motion; if (motion is UnityEditor.Animations.BlendTree) { var blendTree = (motion as UnityEditor.Animations.BlendTree); var childMotion = blendTree.children; for (int i = 0; i < childMotion.Length; i++) { } } else { } } } void DrawClip(AnimatorState animaState, AnimationClip motion, AnimatorStateMachine stateMachine) { CreateObjectField(animaState); CreateObjectField(motion); if (null != animaState) { EditorGUI.indentLevel = 0; var transitions = animaState.transitions; BeginHorizontal(); DoButton("SelectAll", () => { Selection.objects = transitions; }); DoButton<AnimatorStateTransition[], string>("ExitTime", BatchChangeProperty, transitions, "ExitTime"); DoButton("FixedDuration", () => { }); DoButton("Trans Duration", () => { }); DoButton("Trans Offset", () => { }); EndHorizontal(); EditorGUI.indentLevel = 2; for (int i = 0; i < transitions.Length; i++) { BeginHorizontal(); CreateObjectField(transitions[i]); CreateLabel(transitions[i].GetDisplayName(stateMachine)); EndHorizontal(); } EditorGUI.indentLevel = 0; } if (null != motion) { EditorGUILayout.BeginHorizontal(); CreateLabel(motion.name); CreateLabel(motion.averageDuration.ToString()); CreateLabel(motion.isLooping.ToString()); EditorGUILayout.EndHorizontal(); } } void BatchChangeProperty(AnimatorStateTransition[] transitions, string property) { XTomporaryWindow window = InitWindow<XTomporaryWindow>(); window.OnPaint = () => { }; } void ShowAnimatorInfo() { _animator = CreateObjectField("animator", _animator, typeof(Animator)) as Animator; if (null != _animator) { AnimationClip[] clips = _animator.runtimeAnimatorController.animationClips; for (int i = 0; i < clips.Length; i++) { BeginHorizontal(); CreateLabel(clips[i].name); CreateLabel(clips[i].averageDuration.ToString()); CreateLabel(clips[i].isLooping.ToString()); EndHorizontal(); } } } void ShowAnimatorOverrideControllerClips(AnimationClipPair[] clips) { //for (int pos = 0; pos < clips.Length; pos++) //{ // EditorGUILayout.BeginHorizontal(); // CreateLabel(clips[pos].originalClip.name); // CreateLabel(clips[pos].overrideClip.averageDuration.ToString()); // CreateLabel(clips[pos].overrideClip.isLooping.ToString()); // EditorGUILayout.EndHorizontal(); //} } void OnSelectionChange() { //TODO List // if(Selection.objects.Length > 0) // Logger.Log("obj is " + Selection.objects[0].GetType()); } public static Animation GetAnimation(Animator animator) { // Animation anim = animator.animation; // int count = anim.GetClipCount(); // Assembly ass = typeof(Editor).Assembly; // System.Type refType = ass.GetType("UnityEditor.AnimationEditor"); // PropertyInfo property = refType.GetProperty("target"); // object target = property.GetValue(refType,null); // Animation anim = (Animation)target; return null; } internal enum AnimatorType { AnimatorController, AnimatorModel, Animator } } }
27.391156
136
0.682727
[ "MIT" ]
walklook/WuxingogoExtension
WuxingogoEditor/AnimationUtilies/XAnimatorExtension.cs
8,053
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MethodStepWithNext.cs"> // SPDX-License-Identifier: MIT // Copyright © 2019-2020 Esbjörn Redmo and contributors. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Mocklis.Core { #region Using Directives using System; #endregion /// <summary> /// Class that models a method step that can forward calls on to a next step. It is a common base class for /// implementing new steps. /// Implements the <see cref="IMethodStep{TParam, TResult}" /> interface. /// Implements the <see cref="ICanHaveNextMethodStep{TParam, TResult}" /> interface. /// </summary> /// <typeparam name="TParam">The method parameter type.</typeparam> /// <typeparam name="TResult">The method return type.</typeparam> /// <seealso cref="IMethodStep{TParam, TResult}" /> /// <seealso cref="ICanHaveNextMethodStep{TParam, TResult}" /> public class MethodStepWithNext<TParam, TResult> : IMethodStep<TParam, TResult>, ICanHaveNextMethodStep<TParam, TResult> { /// <summary> /// Gets the current next step. /// </summary> /// <value>The current next step.</value> protected IMethodStep<TParam, TResult>? NextStep { get; private set; } /// <summary> /// Replaces the current 'next' step with a new step. /// </summary> /// <typeparam name="TStep">The actual type of the new step.</typeparam> /// <param name="step">The new step.</param> /// <returns>The new step, so that we can add further steps in a fluent fashion.</returns> TStep ICanHaveNextMethodStep<TParam, TResult>.SetNextStep<TStep>(TStep step) { if (step == null) { throw new ArgumentNullException(nameof(step)); } NextStep = step; return step; } /// <summary> /// Called when the mocked method is called. /// Can be overridden to provide a bespoke behaviour in a step. The default behaviour is to forward calls on to the /// next /// step. /// </summary> /// <param name="mockInfo">Information about the mock through which the method is called.</param> /// <param name="param">The parameters used.</param> /// <returns>The returned result.</returns> public virtual TResult Call(IMockInfo mockInfo, TParam param) { return NextStep.CallWithStrictnessCheckIfNull(mockInfo, param); } } }
42.060606
127
0.556916
[ "MIT" ]
eredmo/mocklis
src/Mocklis.BaseApi/Core/MethodStepWithNext.cs
2,778
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using Toggl.Foundation.Calendar; using Toggl.Foundation.DataSources; using Toggl.Foundation.Exceptions; using Toggl.Foundation.Models.Interfaces; using Toggl.Foundation.Services; using Toggl.Multivac; using Toggl.PrimeRadiant.Settings; namespace Toggl.Foundation.Interactors.Calendar { public sealed class GetCalendarItemsForDateInteractor : IInteractor<IObservable<IEnumerable<CalendarItem>>> { private readonly TimeSpan maxDurationThreshold = TimeSpan.FromHours(24); private readonly ITimeEntriesSource timeEntriesDataSource; private readonly ICalendarService calendarService; private readonly IUserPreferences userPreferences; private readonly DateTime date; public GetCalendarItemsForDateInteractor( ITimeEntriesSource timeEntriesDataSource, ICalendarService calendarService, IUserPreferences userPreferences, DateTime date) { Ensure.Argument.IsNotNull(timeEntriesDataSource, nameof(timeEntriesDataSource)); Ensure.Argument.IsNotNull(calendarService, nameof(calendarService)); Ensure.Argument.IsNotNull(userPreferences, nameof(userPreferences)); Ensure.Argument.IsNotNull(date, nameof(date)); this.timeEntriesDataSource = timeEntriesDataSource; this.calendarService = calendarService; this.userPreferences = userPreferences; this.date = date; } public IObservable<IEnumerable<CalendarItem>> Execute() => Observable.CombineLatest( calendarItemsFromTimeEntries(), calendarItemsFromEvents(), (timeEntries, events) => timeEntries.Concat(events)) .Select(validEvents) .Select(orderByStartTime); private IObservable<IEnumerable<CalendarItem>> calendarItemsFromTimeEntries() => timeEntriesDataSource.GetAll(timeEntry => timeEntry.IsDeleted == false && timeEntry.Start >= date.Date && timeEntry.Start <= date.AddDays(1).Date) .Select(convertTimeEntriesToCalendarItems); private IObservable<IEnumerable<CalendarItem>> calendarItemsFromEvents() => calendarService .GetEventsForDate(date) .Select(enabledCalendarItems) .Catch<IEnumerable<CalendarItem>, NotAuthorizedException>( ex => Observable.Return(new List<CalendarItem>()) ); private IEnumerable<CalendarItem> enabledCalendarItems(IEnumerable<CalendarItem> calendarItems) => calendarItems.Where(userCalendarIsEnabled); private bool userCalendarIsEnabled(CalendarItem calendarItem) => userPreferences.EnabledCalendarIds().Contains(calendarItem.CalendarId); private IEnumerable<CalendarItem> convertTimeEntriesToCalendarItems(IEnumerable<IThreadSafeTimeEntry> timeEntries) => timeEntries.Select(CalendarItem.From); private IEnumerable<CalendarItem> validEvents(IEnumerable<CalendarItem> calendarItems) => calendarItems.Where(eventHasValidDuration); private bool eventHasValidDuration(CalendarItem calendarItem) => calendarItem.Duration == null || calendarItem.Duration < maxDurationThreshold; private IEnumerable<CalendarItem> orderByStartTime(IEnumerable<CalendarItem> calendarItems) => calendarItems.OrderBy(calendarItem => calendarItem.StartTime); } }
44.120482
122
0.69361
[ "BSD-3-Clause" ]
kelimebilgisi/mobileapp
Toggl.Foundation/Interactors/Calendar/GetCalendarItemsForDateInteractor.cs
3,664
C#
using System; using System.Collections.Generic; using System.Windows.Input; namespace IdSharp.Tagging.Harness.Wpf.Commands { /// <summary> /// This class allows delegating the commanding logic to methods passed as parameters, /// and enables a View to bind commands to objects that are not part of the element tree. /// </summary> public class DelegateCommand : ICommand { private readonly Action _executeMethod; private readonly Func<bool> _canExecuteMethod; private bool _isAutomaticRequeryDisabled; private List<WeakReference> _canExecuteChangedHandlers; /// <summary> /// Constructor /// </summary> public DelegateCommand(Action executeMethod) : this(executeMethod, null, false) { } /// <summary> /// Constructor /// </summary> public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod) : this(executeMethod, canExecuteMethod, false) { } /// <summary> /// Constructor /// </summary> public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled) { if (executeMethod == null) { throw new ArgumentNullException("executeMethod"); } _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled; } /// <summary> /// Method to determine if the command can be executed /// </summary> public bool CanExecute() { if (_canExecuteMethod != null) { return _canExecuteMethod(); } return true; } /// <summary> /// Execution of the command /// </summary> public void Execute() { _executeMethod?.Invoke(); } /// <summary> /// Property to enable or disable CommandManager's automatic requery on this command /// </summary> public bool IsAutomaticRequeryDisabled { get { return _isAutomaticRequeryDisabled; } set { if (_isAutomaticRequeryDisabled != value) { if (value) { CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers); } else { CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers); } _isAutomaticRequeryDisabled = value; } } } /// <summary> /// Raises the CanExecuteChaged event /// </summary> public void RaiseCanExecuteChanged() { WpfApplicationHelper.InvokeOnUI(OnCanExecuteChanged); } /// <summary> /// Protected virtual method to raise CanExecuteChanged event /// </summary> protected virtual void OnCanExecuteChanged() { CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers); } /// <summary> /// ICommand.CanExecuteChanged implementation /// </summary> public event EventHandler CanExecuteChanged { add { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested += value; } CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2); } remove { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested -= value; } CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value); } } bool ICommand.CanExecute(object parameter) { return CanExecute(); } void ICommand.Execute(object parameter) { Execute(); } } }
30.402778
114
0.533805
[ "MIT" ]
ivandrofly/IdSharp
Examples/IdSharp.Example.Wpf/Commands/DelegateCommand.cs
4,380
C#
//---------------------- // <auto-generated> // This file was automatically generated. Any changes to it will be lost if and when the file is regenerated. // </auto-generated> //---------------------- #pragma warning disable using System; using SQEX.Luminous.Core.Object; using System.Collections.Generic; using CodeDom = System.CodeDom; namespace Black.Sequence.Event.Menu.Executor { [Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")] public partial class SequenceEventInteractionInfoDisplayExecutor : Black.Sequence.Event.Menu.SequenceEventUiEntityInputBase { new public static ObjectType ObjectType { get; private set; } private static PropertyContainer fieldProperties; new public static void SetupObjectType() { if (ObjectType != null) { return; } var dummy = new SequenceEventInteractionInfoDisplayExecutor(); var properties = dummy.GetFieldProperties(); ObjectType = new ObjectType("Black.Sequence.Event.Menu.Executor.SequenceEventInteractionInfoDisplayExecutor", 0, Black.Sequence.Event.Menu.Executor.SequenceEventInteractionInfoDisplayExecutor.ObjectType, Construct, properties, 0, 1104); } public override ObjectType GetObjectType() { return ObjectType; } protected override PropertyContainer GetFieldProperties() { if (fieldProperties != null) { return fieldProperties; } fieldProperties = new PropertyContainer("Black.Sequence.Event.Menu.Executor.SequenceEventInteractionInfoDisplayExecutor", base.GetFieldProperties(), 556889073, -1260581261); fieldProperties.AddIndirectlyProperty(new Property("refInPorts_", 1035088696, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 24, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("refOutPorts_", 283683627, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 40, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triInPorts_", 291734708, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 96, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triOutPorts_", 3107891487, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 112, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("outPin_", 2732252299, "SQEX.Ebony.Framework.Node.GraphTriggerOutputPin", 176, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.pinName_", 1767361694, "Base.String", 184, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.name_", 2948420441, "Base.String", 200, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.connections_", 78281129, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 216, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.delayType_", 2315115539, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 248, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.delayTime_", 2421045752, "float", 252, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("outPin_.delayMaxTime_", 3973394610, "float", 256, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin0_", 1260278025, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 384, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin0_.pinName_", 378112624, "Base.String", 392, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin0_.name_", 387472539, "Base.String", 408, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin0_.connections_", 977417523, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 424, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin0_.pinValueType_", 934546126, "Base.String", 456, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin1_", 1260425120, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 472, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin1_.pinName_", 2142000239, "Base.String", 480, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin1_.name_", 905090058, "Base.String", 496, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin1_.connections_", 2464003080, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 512, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin1_.pinValueType_", 3289933587, "Base.String", 544, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin2_", 186804599, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 560, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin2_.pinName_", 2460956818, "Base.String", 568, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin2_.name_", 4048616205, "Base.String", 584, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin2_.connections_", 2450805877, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 600, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin2_.pinValueType_", 3805326452, "Base.String", 632, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin3_", 1260719310, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 648, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin3_.pinName_", 1331177705, "Base.String", 656, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin3_.name_", 1358091572, "Base.String", 672, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin3_.connections_", 1823137930, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 688, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin3_.pinValueType_", 2110630761, "Base.String", 720, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin4_", 1259586477, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 736, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin4_.pinName_", 475240524, "Base.String", 744, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin4_.name_", 4286371831, "Base.String", 760, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin4_.connections_", 3976354263, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 776, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin4_.pinValueType_", 74423930, "Base.String", 808, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin5_", 1259733572, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 824, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin5_.pinName_", 3161314315, "Base.String", 832, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin5_.name_", 1510251846, "Base.String", 848, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin5_.connections_", 4070776316, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 864, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin5_.pinValueType_", 2765679519, "Base.String", 896, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin6_", 186216219, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 912, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin6_.pinName_", 930225934, "Base.String", 920, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin6_.name_", 4045414473, "Base.String", 936, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin6_.connections_", 221795001, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 952, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin6_.pinValueType_", 116915520, "Base.String", 984, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin7_", 186363314, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 1000, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin7_.pinName_", 1470745653, "Base.String", 1008, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin7_.name_", 2816610160, "Base.String", 1024, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("pin7_.connections_", 189416126, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 1040, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("pin7_.pinValueType_", 1691388021, "Base.String", 1072, 16, 1, Property.PrimitiveType.String, 0, (char)0)); return fieldProperties; } private static BaseObject Construct() { return new SequenceEventInteractionInfoDisplayExecutor(); } } }
97.078261
248
0.753493
[ "MIT" ]
Gurrimo/Luminaire
Assets/Editor/Generated/Black/Sequence/Event/Menu/Executor/SequenceEventInteractionInfoDisplayExecutor.generated.cs
11,164
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ToDoMvc.Services; namespace ToDoMvc.Controller { public class ToDoController : Controller { private readonly IToDoItemService _toDoItemsService; public ToDoController(IToDoItemService toDoItemsService) { _toDoItemsService = toDoItemsService; } public async Task<IActionResult> Index() { //Get todo Items var todoItems = await _toDoItemsService.GetIncompleteItemsAsync(); //Put into models var viewModel = new ToDoViewModel { Items = todoItems }; //Pass the view to model return View(viewModel); } } }
27.939394
82
0.558568
[ "MIT" ]
HenriqueDPaula/DesenvolvimentoWeb2
source/ToDo/ToDoMvc/Controllers/ToDoController.cs
922
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 support-2013-04-15.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.AWSSupport { /// <summary> /// Configuration for accessing Amazon AWSSupport service /// </summary> public partial class AmazonAWSSupportConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.100.187"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonAWSSupportConfig() { this.AuthenticationServiceName = "support"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "support"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2013-04-15"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.2
105
0.588263
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/AWSSupport/Generated/AmazonAWSSupportConfig.cs
2,096
C#
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.IO; namespace Enhanced.Whip.Client { public class AuthChallenge { public const byte PACKET_IDENTIFIER = 0; public const ushort MESSAGE_SIZE = 8; public const ushort CHALLENGE_SIZE = 7; private AppendableByteArray _challenge = new AppendableByteArray(CHALLENGE_SIZE); public AuthChallenge(Socket conn) { int soFar = 0; byte[] buffer = new byte[MESSAGE_SIZE]; while (soFar < MESSAGE_SIZE) { //read the header and challenge phrase int rcvd = conn.Receive(buffer, (int)MESSAGE_SIZE - soFar, SocketFlags.None); if (rcvd == 0) throw new AuthException("Disconnect during authentication"); if (soFar == 0 && buffer[0] != PACKET_IDENTIFIER) throw new AuthException("Invalid challenge packet header"); //skip the first byte if (soFar == 0) { if (rcvd > 1) _challenge.Append(buffer, 1, rcvd - 1); } else { _challenge.Append(buffer, 0, rcvd); } soFar += rcvd; } } public byte[] Challenge { get { return _challenge.data; } } } }
28.192308
125
0.52251
[ "Apache-2.0" ]
emperorstarfinder/My-Experimental-Whip-Client
client/AuthChallenge.cs
1,468
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Helpers.cs" company=""> // // </copyright> // <summary> // The helpers. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace GaneshNarayanan.Entrevista.Basic { using System; using System.Collections.Generic; using System.IO; using System.Linq; /// <summary>The helpers.</summary> /// <typeparam name="T">Any type of Object</typeparam> public static class Helpers<T> { /// <summary>Initializes static members of the <see cref="Helpers"/> class.</summary> static Helpers() { IntegerArrays = new List<T[]>(); for (int i = 0; i < 10; i++) { IntegerArrays.Add(GenerateArrays(i, i * 101, i * 2563)); } } /// <summary>Gets or sets the integer arrays.</summary> public static List<T[]> IntegerArrays { get; set; } /// <summary>The generate arrays.</summary> /// <param name="count">The count.</param> /// <param name="min">The min.</param> /// <param name="max">The max.</param> /// <returns>The <see cref="T[]"/>.</returns> public static T[] GenerateArrays(int count = 5, int min = 0, int max = int.MaxValue) { Random randNum = new Random(); int[] arrayOfInts = Enumerable.Repeat(default(T), count).Select(i => randNum.Next(min, max)).ToArray(); return arrayOfInts as T[]; } /// <summary>The swap.</summary> /// <param name="a">The a.</param> /// <param name="b">The b.</param> public static void Swap(ref T a, ref T b) { T t = b; b = a; a = t; } /// <summary>The write array.</summary> /// <param name="arrayToWrite">The array to write.</param> /// <exception cref="IOException">An I/O error occurred. </exception> public static void WriteArray(T[] arrayToWrite) { foreach (T i in arrayToWrite) { Console.Write(i + "->"); } Console.WriteLine(Environment.NewLine); } } }
34.558824
120
0.471489
[ "MIT" ]
ganesh-narayanan/Entrevista
Entrevista/Basic/Sorting/Helpers.cs
2,352
C#
using $PROJECT_NAMESPACE$.DataTypes; using FlatRedBall.TileGraphics; using System; using System.Collections.Generic; using System.Linq; using $PROJECT_NAMESPACE$.Performance; using FlatRedBall.Graphics; using System.Reflection; using TMXGlueLib.DataTypes; using System.Collections; using FlatRedBall.Math.Geometry; namespace FlatRedBall.TileEntities { public class InstantiationRestrictions { public AxisAlignedRectangle Bounds = null; public List<string> InclusiveList = null; } public static class TileEntityInstantiator { public class Settings { public bool RemoveTileObjectsAfterEntityCreation = true; } public static Settings CurrentSettings { get; set; } = new Settings(); public static Func<string, PositionedObject> CreationFunction; /// <summary> /// A dictionary that stores all available values for a given type. /// </summary> /// <remarks> /// The structure of this class is a dictionary, where each entry in the dictionary is a list of dictionaries. This mgiht /// seem confusing so let's look at an example. /// This was originally created to cache values from CSVs. Let's say there's a type called PlatformerValues. /// The class PlatformerValues would be the key in the dictionary. /// Of course, platformer values can be defined in multiple entities (if multiple entities are platformers). /// Each CSV in each entity becomes 1 dictionary, but since there can be multiple CSVs, there is a list. Therefore, the struture /// might look like this: /// * PlatformerValues /// * List from Entity 1 /// * OnGround /// * InAir /// * List from Entity 2 /// * OnGround /// * In Air /// // and so on... /// </remarks> static Dictionary<string, List<IDictionary>> allDictionaries = new Dictionary<string, List<IDictionary>>(); /// <summary> /// Creates entities from a single layer for any tile with the EntityToCreate property. /// </summary> /// <param name="mapLayer">The layer to create entities from.</param> /// <param name="layeredTileMap">The map which contains the mapLayer instance.</param> public static void CreateEntitiesFrom(MapDrawableBatch mapLayer, LayeredTileMap layeredTileMap) { var entitiesToRemove = new List<string>(); CreateEntitiesFrom(entitiesToRemove, mapLayer, layeredTileMap.TileProperties, layeredTileMap.WidthPerTile ?? 16); if(CurrentSettings.RemoveTileObjectsAfterEntityCreation) { foreach (var entityToRemove in entitiesToRemove) { string remove = entityToRemove; mapLayer.RemoveTiles(t => t.Any(item => (item.Name == "EntityToCreate" || item.Name == "Type") && item.Value as string == remove), layeredTileMap.TileProperties); } } } public static void CreateEntitiesFrom(LayeredTileMap layeredTileMap, InstantiationRestrictions restrictions = null) { if(layeredTileMap != null) { var entitiesToRemove = new List<string>(); foreach (var layer in layeredTileMap.MapLayers) { CreateEntitiesFrom(entitiesToRemove, layer, layeredTileMap.TileProperties, layeredTileMap.WidthPerTile ?? 16, restrictions); } if(CurrentSettings.RemoveTileObjectsAfterEntityCreation) { foreach (var entityToRemove in entitiesToRemove) { string remove = entityToRemove; layeredTileMap.RemoveTiles(t => t.Any(item => (item.Name == "EntityToCreate" || item.Name == "Type") && item.Value as string == remove), layeredTileMap.TileProperties); } } foreach (var shapeCollection in layeredTileMap.ShapeCollections) { CreateEntitiesFromCircles(layeredTileMap, shapeCollection, restrictions); CreateEntitiesFromRectangles(layeredTileMap, shapeCollection, restrictions); CreateEntitiesFromPolygons(layeredTileMap, shapeCollection, restrictions); } } } private static void CreateEntitiesFromCircles(LayeredTileMap layeredTileMap, ShapeCollection shapeCollection, InstantiationRestrictions restrictions) { var circles = shapeCollection.Circles; for (int i = circles.Count - 1; i > -1; i--) { var circle = circles[i]; if (!string.IsNullOrEmpty(circle.Name) && layeredTileMap.ShapeProperties.ContainsKey(circle.Name)) { var properties = layeredTileMap.ShapeProperties[circle.Name]; var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type"); var entityType = entityAddingProperty.Value as string; var shouldCreate = !string.IsNullOrEmpty(entityType); if (restrictions?.InclusiveList != null) { shouldCreate = restrictions.InclusiveList.Contains(entityType); } if (shouldCreate) { PositionedObject entity = CreateEntity(entityType); if (entity != null) { entity.Name = circle.Name; ApplyPropertiesTo(entity, properties, circle.Position); if (CurrentSettings.RemoveTileObjectsAfterEntityCreation) { shapeCollection.Circles.Remove(circle); } if (entity is Math.Geometry.ICollidable) { var entityCollision = (entity as Math.Geometry.ICollidable).Collision; entityCollision.Circles.Add(circle); circle.AttachTo(entity, false); } } } } } } private static void CreateEntitiesFromRectangles(LayeredTileMap layeredTileMap, ShapeCollection shapeCollection, InstantiationRestrictions restrictions) { var rectangles = shapeCollection.AxisAlignedRectangles; for (int i = rectangles.Count - 1; i > -1; i--) { var rectangle = rectangles[i]; if (!string.IsNullOrEmpty(rectangle.Name) && layeredTileMap.ShapeProperties.ContainsKey(rectangle.Name)) { var properties = layeredTileMap.ShapeProperties[rectangle.Name]; var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type"); var entityType = entityAddingProperty.Value as string; var shouldCreate = !string.IsNullOrEmpty(entityType); if (restrictions?.InclusiveList != null) { shouldCreate = restrictions.InclusiveList.Contains(entityType); } if (shouldCreate) { PositionedObject entity = CreateEntity(entityType); if (entity != null) { entity.Name = rectangle.Name; ApplyPropertiesTo(entity, properties, rectangle.Position); if (CurrentSettings.RemoveTileObjectsAfterEntityCreation) { shapeCollection.AxisAlignedRectangles.Remove(rectangle); } if (entity is Math.Geometry.ICollidable) { var entityCollision = (entity as Math.Geometry.ICollidable).Collision; entityCollision.AxisAlignedRectangles.Add(rectangle); rectangle.AttachTo(entity, false); } } } } } } private static void CreateEntitiesFromPolygons(LayeredTileMap layeredTileMap, Math.Geometry.ShapeCollection shapeCollection, InstantiationRestrictions restrictions) { var polygons = shapeCollection.Polygons; for (int i = polygons.Count - 1; i > -1; i--) { var polygon = polygons[i]; if (!string.IsNullOrEmpty(polygon.Name) && layeredTileMap.ShapeProperties.ContainsKey(polygon.Name)) { var properties = layeredTileMap.ShapeProperties[polygon.Name]; var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type"); var entityType = entityAddingProperty.Value as string; var shouldCreate = !string.IsNullOrEmpty(entityType); if (restrictions?.InclusiveList != null) { shouldCreate = restrictions.InclusiveList.Contains(entityType); } if (shouldCreate) { PositionedObject entity = CreateEntity(entityType); if (entity != null) { entity.Name = polygon.Name; ApplyPropertiesTo(entity, properties, polygon.Position); if (CurrentSettings.RemoveTileObjectsAfterEntityCreation) { shapeCollection.Polygons.Remove(polygon); } if (entity is Math.Geometry.ICollidable) { var entityCollision = (entity as Math.Geometry.ICollidable).Collision; entityCollision.Polygons.Add(polygon); polygon.AttachTo(entity, false); } } } } } } private static PositionedObject CreateEntity(string entityType) { PositionedObject entity = null; IEntityFactory factory = GetFactory(entityType); if (factory != null) { entity = factory.CreateNew(null) as PositionedObject; } else if (CreationFunction != null) { entity = CreationFunction(entityType); } return entity; } private static void CreateEntitiesFrom(List<string> entitiesToRemove, MapDrawableBatch layer, Dictionary<string, List<NamedValue>> propertiesDictionary, float tileSize, InstantiationRestrictions restrictions = null) { var flatRedBallLayer = SpriteManager.Layers.FirstOrDefault(item => item.Batches.Contains(layer)); var dictionary = layer.NamedTileOrderedIndexes; // layer needs its position updated: layer.ForceUpdateDependencies(); foreach (var propertyList in propertiesDictionary.Values) { var property = propertyList.FirstOrDefault(item2 => item2.Name == "EntityToCreate" || item2.Name == "Type"); if (!string.IsNullOrEmpty(property.Name)) { var tileName = propertyList.FirstOrDefault(item => item.Name.ToLowerInvariant() == "name").Value as string; var entityType = property.Value as string; var shouldCreateEntityType = !string.IsNullOrEmpty(entityType) && dictionary.ContainsKey(tileName); if (shouldCreateEntityType && restrictions?.InclusiveList != null) { shouldCreateEntityType = restrictions.InclusiveList.Contains(entityType); } if (shouldCreateEntityType) { IEntityFactory factory = GetFactory(entityType); if (factory == null && CreationFunction == null) { bool isEntity = typesInThisAssembly.Any(item => item.Name.Contains($".Entities.") && item.Name.EndsWith(entityType)); if (isEntity) { string message = $"The factory for entity {entityType} could not be found. To create instances of this entity, " + "set its 'CreatedByOtherEntities' property to true in Glue."; throw new Exception(message); } } else { var createdEntityOfThisType = false; var indexList = dictionary[tileName]; foreach (var tileIndex in indexList) { var shouldCreate = true; var bounds = restrictions?.Bounds; if (bounds != null) { layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out float x, out float y); x += tileSize / 2.0f; y += tileSize / 2.0f; shouldCreate = bounds.IsPointInside(x, y); } if (shouldCreate) { PositionedObject entity = null; if (factory != null) { entity = factory.CreateNew(flatRedBallLayer) as PositionedObject; } else if (CreationFunction != null) { entity = CreationFunction(entityType); // todo - need to support moving to layer } if (entity != null) { ApplyPropertiesTo(entity, layer, tileIndex, propertyList); createdEntityOfThisType = true; } } } if (createdEntityOfThisType) { entitiesToRemove.Add(entityType); } } } } } } private static void ApplyPropertiesTo(PositionedObject entity, MapDrawableBatch layer, int tileIndex, List<NamedValue> propertiesToAssign) { int vertexIndex = tileIndex * 4; var dimension = (layer.Vertices[vertexIndex + 1].Position - layer.Vertices[vertexIndex].Position).Length(); float dimensionHalf = dimension / 2.0f; float left; float bottom; layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out left, out bottom); Microsoft.Xna.Framework.Vector3 position = new Microsoft.Xna.Framework.Vector3(left, bottom, 0); var bottomRight = layer.Vertices[tileIndex * 4 + 1].Position; float xDifference = bottomRight.X - left; float yDifference = bottomRight.Y - bottom; if (yDifference != 0 || xDifference < 0) { float angle = (float)System.Math.Atan2(yDifference, xDifference); entity.RotationZ = angle; } position += entity.RotationMatrix.Right * dimensionHalf; position += entity.RotationMatrix.Up * dimensionHalf; position += layer.Position; ApplyPropertiesTo(entity, propertiesToAssign, position); } private static void ApplyPropertiesTo(PositionedObject entity, List<NamedValue> propertiesToAssign, Microsoft.Xna.Framework.Vector3 position) { if (entity != null) { entity.Position = position; } var entityType = entity.GetType(); var lateBinder = Instructions.Reflection.LateBinder.GetInstance(entityType); foreach (var property in propertiesToAssign) { // If name is EntityToCreate, skip it: string propertyName = property.Name; bool shouldSet = propertyName != "EntityToCreate" && propertyName != "Type"; if (shouldSet) { if (propertyName == "name") { propertyName = "Name"; } var valueToSet = property.Value; var propertyType = property.Type; if (string.IsNullOrEmpty(propertyType)) { propertyType = TryGetPropertyType(entityType, propertyName); } valueToSet = ConvertValueAccordingToType(valueToSet, propertyName, propertyType, entityType); try { switch(propertyName) { case "X": if(valueToSet is float) { entity.X += (float)valueToSet; } else if(valueToSet is int) { entity.X += (int)valueToSet; } break; case "Y": if (valueToSet is float) { entity.Y += (float)valueToSet; } else if (valueToSet is int) { entity.Y += (int)valueToSet; } break; default: lateBinder.SetValue(entity, propertyName, valueToSet); break; } } catch (InvalidCastException e) { string assignedType = valueToSet.GetType().ToString() ?? "unknown type"; assignedType = GetFriendlyNameForType(assignedType); string expectedType = "unknown type"; object outValue; if (lateBinder.TryGetValue(entity, propertyName, out outValue) && outValue != null) { expectedType = outValue.GetType().ToString(); expectedType = GetFriendlyNameForType(expectedType); } // This means that the property exists but is of a different type. string message = $"Attempted to assign the property {propertyName} " + $"to a value of type {assignedType} but expected {expectedType}. " + $"Check the property type in your TMX and make sure it matches the type on the entity."; throw new Exception(message, e); } catch (Exception e) { // Since this code indiscriminately tries to set properties, it may set properties which don't // actually exist. Therefore, we tolerate failures. } } } } private static string TryGetPropertyType(Type entityType, string propertyName) { // todo - cache for perf var property = entityType.GetProperty(propertyName); if (property != null) { return property?.PropertyType.FullName; } else { var field = entityType.GetField(propertyName); return field?.FieldType.FullName; } } public static void RegisterDictionary<T>(Dictionary<string, T> data) { #if DEBUG if(data == null) { throw new ArgumentNullException("The argument data is null - do you need to call LoadStaticContent on the type containing this dictionary?"); } #endif var type = typeof(T).FullName; if (allDictionaries.ContainsKey(type) == false) { allDictionaries.Add(type, new List<IDictionary>()); } if (allDictionaries[type].Contains(data) == false) { allDictionaries[type].Add(data); } } private static string GetFriendlyNameForType(string type) { switch (type) { case "System.String": return "string"; case "System.Single": return "float"; } return type; } private static object ConvertValueAccordingToType(object valueToSet, string valueName, string valueType, Type entityType) { if (valueType == "bool") { bool boolValue = false; if (bool.TryParse((string)valueToSet, out boolValue)) { valueToSet = boolValue; } } else if (valueType == "float") { float floatValue; if (float.TryParse((string)valueToSet, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out floatValue)) { valueToSet = floatValue; } } else if (valueType == "int") { int intValue; if (int.TryParse((string)valueToSet, out intValue)) { valueToSet = intValue; } } else if (valueName == "CurrentState") { // Since it's part of the class, it uses the "+" separator var enumTypeName = entityType.FullName + "+VariableState"; var enumType = typesInThisAssembly.FirstOrDefault(item => item.FullName == enumTypeName); valueToSet = Enum.Parse(enumType, (string)valueToSet); } else if (valueType != null && allDictionaries.ContainsKey(valueType)) { var list = allDictionaries[valueType]; foreach (var dictionary in list) { if (dictionary.Contains(valueToSet)) { valueToSet = dictionary[valueToSet]; break; } } } // todo - could add support for more file types here like textures, etc... else if (valueType == "FlatRedBall.Graphics.Animation.AnimationChainList") { var method = entityType.GetMethod("GetFile"); valueToSet = method.Invoke(null, new object[] { valueToSet }); } // If this has a + in it, then that might mean it's a state. We should try to get the type, and if we find it, stuff // it in allDictionaries to make future calls faster else if (valueType != null && valueType.Contains("+")) { var stateType = typesInThisAssembly.FirstOrDefault(item => item.FullName == valueType); if (stateType != null) { Dictionary<string, object> allValues = new Dictionary<string, object>(); var fields = stateType.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (var field in fields) { allValues[field.Name] = field.GetValue(null); } // The list has all the dictioanries that contain values. But for states there is only one set of values, so // we create a list List<IDictionary> list = new List<IDictionary>(); list.Add(allValues); allDictionaries[valueType] = list; if (allValues.ContainsKey((string)valueToSet)) { valueToSet = allValues[(string)valueToSet]; } } } else if (valueType?.Contains(".") == true) { var type = typeof(TileEntityInstantiator).Assembly.GetType(valueType); if (type != null && type.IsEnum) { valueToSet = Enum.Parse(type, (string)valueToSet); } } return valueToSet; } private static void AssignCustomPropertyTo(PositionedObject entity, NamedValue property) { throw new NotImplementedException(); } static Type[] typesInThisAssembly; public static IEntityFactory GetFactory(string entityType) { if (typesInThisAssembly == null) { #if WINDOWS_8 || UWP var assembly = typeof(TileEntityInstantiator).GetTypeInfo().Assembly; typesInThisAssembly = assembly.DefinedTypes.Select(item=>item.AsType()).ToArray(); #else var assembly = Assembly.GetExecutingAssembly(); typesInThisAssembly = assembly.GetTypes(); #endif } #if WINDOWS_8 || UWP var filteredTypes = typesInThisAssembly.Where(t => t.GetInterfaces().Contains(typeof(IEntityFactory)) && t.GetConstructors().Any(c=>c.GetParameters().Count() == 0)); #else var filteredTypes = typesInThisAssembly.Where(t => t.GetInterfaces().Contains(typeof(IEntityFactory)) && t.GetConstructor(Type.EmptyTypes) != null); #endif var factories = filteredTypes .Select( t => { #if WINDOWS_8 || UWP var propertyInfo = t.GetProperty("Self"); #else var propertyInfo = t.GetProperty("Self"); #endif var value = propertyInfo.GetValue(null, null); return value as IEntityFactory; }).ToList(); var factory = factories.FirstOrDefault(item => { if (string.IsNullOrEmpty(entityType)) { return false; } else { var type = item.GetType(); var methodInfo = type.GetMethod("CreateNew", new[] { typeof(Layer), typeof(float), typeof(float), typeof(float) }); var returntypeString = methodInfo.ReturnType.Name; return entityType == returntypeString || entityType == methodInfo.ReturnType.FullName || entityType.EndsWith("\\" + returntypeString) || entityType.EndsWith("/" + returntypeString); } }); return factory; } } }
41.525253
192
0.493067
[ "MIT" ]
vchelaru/FlatRedBall
FRBDK/Glue/TileGraphicsPlugin/TileGraphicsPlugin/EmbeddedCodeFiles/TileEntityInstantiator.cs
28,779
C#
using Tactics.Models; namespace Tactics.Events { public class ButtonEventData { public Button button; public string buttonType; } }
14.5
34
0.609195
[ "MIT" ]
Joraffe/tactics_mvc
Assets/Scripts/EventSystem/EventDataTypes/ButtonEventData.cs
176
C#
using System.Collections.Generic; using Xunit; namespace TicketOfficeService.Tests; public class TicketOfficeTests { private const string Toto = "toto"; private const string Titi = "titi"; [Fact] public void Must_generate_a_train_reservation_with_one_seat() { var ticketOffice = new TicketOffice(); var reserveRequest = new ReservationRequest(Toto, 1); var actualReservation = ticketOffice.MakeReservation(reserveRequest); Assert.Equal(Toto, actualReservation.TrainId); Assert.Equal(1, actualReservation.Seats[0].SeatNumber); } [Fact] public void Must_generate_a_train_reservation_with_two_seats() { var ticketOffice = new TicketOffice(); var reserveRequest = new ReservationRequest(Titi, 2); var actualReservation = ticketOffice.MakeReservation(reserveRequest); Assert.Equal(Titi, actualReservation.TrainId); Assert.Equal(2, actualReservation.Seats[0].SeatNumber); } }
31.09375
77
0.714573
[ "MIT" ]
MaxMeminArolla/KataTrainReservation
csharp/TicketOfficeService.Tests/TicketOfficeTests.cs
995
C#
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2004 Novell, Inc. // // Authors: // Jordi Mas i Hernandez, jordi@ximian.com // // namespace System.Windows.Forms { public delegate void MeasureItemEventHandler (object sender, MeasureItemEventArgs e); }
41.935484
86
0.760769
[ "Apache-2.0" ]
121468615/mono
mcs/class/Managed.Windows.Forms/System.Windows.Forms/MeasureItemEventHandler.cs
1,300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QQMini.PluginSDK.Core.Model { /// <summary> /// XML格式基本类型 /// </summary> public enum XmlTypes { /// <summary> /// 基本结构 /// </summary> Basic = 0, /// <summary> /// 歌曲结构 /// </summary> Music = 2 } }
17.208333
37
0.525424
[ "Apache-2.0" ]
AmemiyaSigure/QQMini.PluginSDK
src/QQMini.PluginSDK.Core/Model/XmlTypes.cs
443
C#
using Hover.Core.Items; using UnityEngine; namespace Hover.InterfaceModules.Key { /*================================================================================================*/ public struct HoverkeyBuilderKeyInfo { public string ID; public HoverItem.HoverItemType ItemType; public HoverkeyItemLabels.KeyActionType ActionType; public KeyCode DefaultKey; public string DefaultLabel; public bool HasShiftLabel; public string ShiftLabel; public float RelativeSizeX; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverkeyBuilderKeyInfo(KeyCode pDefaultKey, HoverkeyItemLabels.KeyActionType pActionType, string pDefaultLabel) { ID = "Hoverkey-"+pDefaultKey; ItemType = HoverItem.HoverItemType.Selector; ActionType = pActionType; DefaultKey = pDefaultKey; DefaultLabel = pDefaultLabel; HasShiftLabel = false; ShiftLabel = null; RelativeSizeX = 1; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverkeyBuilderKeyInfo Shift(string pShiftLabel) { HasShiftLabel = true; ShiftLabel = pShiftLabel; return this; } /*--------------------------------------------------------------------------------------------*/ public HoverkeyBuilderKeyInfo RelSize(float pRelSizeX) { RelativeSizeX = pRelSizeX; return this; } /*--------------------------------------------------------------------------------------------*/ public HoverkeyBuilderKeyInfo Checkbox() { ItemType = HoverItem.HoverItemType.Checkbox; return this; } /*--------------------------------------------------------------------------------------------*/ public HoverkeyBuilderKeyInfo Sticky() { ItemType = HoverItem.HoverItemType.Sticky; return this; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static HoverkeyBuilderKeyInfo Char(KeyCode pKey, string pLabel) { return new HoverkeyBuilderKeyInfo(pKey, HoverkeyItemLabels.KeyActionType.Character, pLabel); } /*--------------------------------------------------------------------------------------------*/ public static HoverkeyBuilderKeyInfo Ctrl(KeyCode pKey, string pLabel) { return new HoverkeyBuilderKeyInfo(pKey, HoverkeyItemLabels.KeyActionType.Control, pLabel); } /*--------------------------------------------------------------------------------------------*/ public static HoverkeyBuilderKeyInfo Nav(KeyCode pKey, string pLabel) { return new HoverkeyBuilderKeyInfo(pKey, HoverkeyItemLabels.KeyActionType.Navigation, pLabel); } } }
37.0375
101
0.459332
[ "MIT" ]
Agilefreaks/licenta-vr
Assets/Hover/InterfaceModules/Key/Scripts/HoverkeyBuilderKeyInfo.cs
2,965
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Cloudy.Collections; using Cloudy.Computing.Enums; using Cloudy.Computing.Interfaces; using Cloudy.Computing.Reduction; using Cloudy.Computing.Reduction.Delegates; using Cloudy.Computing.Structures; using Cloudy.Computing.Structures.Values; using Cloudy.Computing.Structures.Values.Environment; using Cloudy.Computing.Topologies.Helpers; using Cloudy.Computing.Topologies.Interfaces; using Cloudy.Helpers; namespace Cloudy.Computing { /// <summary> /// Implements a computing thread environment methods. /// </summary> internal class Environment : IInternalEnvironment, IDisposable { private readonly MemoryStorage<MemoryStorageObject> masterRemoteMemoryCache = new MemoryStorage<MemoryStorageObject>(); private int operationId; private byte[] rawRank; protected readonly IEnvironmentTransport Transport; protected readonly BlockingFilteredQueue<EnvironmentOperationValue> Queue = new BlockingFilteredQueue<EnvironmentOperationValue>(); protected readonly Stopwatch Stopwatch = new Stopwatch(); protected Environment(IEnvironmentTransport transport, byte[] rank) { this.Transport = transport; this.rawRank = rank; } /// <summary> /// Gets the serialized current rank. /// </summary> public byte[] RawRank { get { return rawRank; } set { rawRank = value; if (RawRankChanged != null) { RawRankChanged(this, new EventArgs<byte[]>(value)); } } } public event ParameterizedEventHandler<byte[]> RawRankChanged; public void NotifyValueReceived(EnvironmentOperationValue value) { Queue.Enqueue(value); } public void CleanUp() { masterRemoteMemoryCache.CleanUp( value => value.TimeToLive != TimeToLive.Forever); } public void ResetTime() { Stopwatch.Reset(); Stopwatch.Start(); } /// <summary> /// Generates a new operation ID. /// </summary> protected int GetOperationId() { return Interlocked.Increment(ref operationId); } #region Implementation of IDisposable public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Queue.Dispose(); } } #endregion #region Implementation of IEnvironment public void SetRemoteValue<TValue>(byte[] @namespace, string key, TValue value, TimeToLive timeToLive) { SetRemoteValueRequest request = new SetRemoteValueRequest(); request.Namespace = @namespace; request.Key = key; request.Set(new WrappedValue<TValue>(value)); request.TimeToLive = timeToLive; Transport.SendToMaster(request, Tags.SetRemoteValueRequest); } public bool TryGetRemoteValue<TValue>(byte[] @namespace, string key, out TValue value) { lock (masterRemoteMemoryCache) { MemoryStorageObject rawValue; if (masterRemoteMemoryCache.TryGetValue(@namespace, key, out rawValue)) { value = (TValue)rawValue.Value; return true; } lock (Transport.MasterConversationLock) { GetRemoteValueRequest request = new GetRemoteValueRequest(); request.Namespace = @namespace; request.Key = key; Transport.SendToMaster(request, Tags.GetRemoteValueRequest); GetRemoteValueResponse response = Transport.ReceiveFromMaster<GetRemoteValueResponse>( Tags.GetRemoteValueResponse); if (response.Success != false) { value = response.Get<WrappedValue<TValue>>().Value; if (response.TimeToLive != TimeToLive.Flash) { rawValue = new MemoryStorageObject(); rawValue.Value = value; rawValue.TimeToLive = response.TimeToLive; masterRemoteMemoryCache.Add(@namespace, key, rawValue); } return true; } value = default(TValue); return false; } } } #endregion } internal class Environment<TRank> : Environment, IEnvironment<TRank> where TRank : IRank { private TRank rank; public Environment(IEnvironmentTransport transport, byte[] rank) : base(transport, rank) { this.rank = RankConverter<TRank>.Convert(rank); RawRankChanged += OnRawRankChanged; } public TRank Rank { get { return rank; } } private void OnRawRankChanged(object sender, EventArgs<byte[]> e) { rank = RankConverter<TRank>.Convert(e.Value); } #region Send /// <summary> /// Performs a blocking send. /// </summary> public void Send<T>(int tag, T value, TRank recipient) { Send(tag, value, new[] { recipient }); } /// <summary> /// Performs a blocking send. /// </summary> public void Send<T>(int tag, T value, IEnumerable<TRank> recipients) { EnvironmentOperationValue operationValue = new EnvironmentOperationValue(); operationValue.Sender = RawRank; operationValue.OperationId = GetOperationId(); operationValue.OperationType = EnvironmentOperationType.PeerToPeer; operationValue.Set(new WrappedValue<T>(value)); operationValue.Recipients = recipients.Select(RankConverter<TRank>.Convert).ToList(); Transport.Send(operationValue); } #endregion #region Receive /// <summary> /// Blocking receive for a message /// </summary> public void Receive<T>(int tag, out T value, out TRank sender) { EnvironmentOperationValue operationValue = Queue.Dequeue( v => v.UserTag == tag && v.OperationType == EnvironmentOperationType.PeerToPeer); value = operationValue.Get<WrappedValue<T>>().Value; sender = RankConverter<TRank>.Convert(operationValue.Sender); } /// <summary> /// Blocking receive for a message /// </summary> public void Receive<T>(out int tag, out T value, out TRank sender) { EnvironmentOperationValue operationValue = Queue.Dequeue( v => v.OperationType == EnvironmentOperationType.PeerToPeer); value = operationValue.Get<WrappedValue<T>>().Value; sender = RankConverter<TRank>.Convert(operationValue.Sender); tag = operationValue.UserTag; } /// <summary> /// Blocking receive for a message /// </summary> public void Receive<T>(int tag, out T value, TRank sender) { byte[] rawSenderRank = RankConverter<TRank>.Convert(sender); EnvironmentOperationValue operationValue = Queue.Dequeue( v => v.Sender.SameAs(rawSenderRank) && v.UserTag == tag && v.OperationType == EnvironmentOperationType.PeerToPeer); value = operationValue.Get<WrappedValue<T>>().Value; } /// <summary> /// Blocking receive for a message /// </summary> public void Receive<T>(out int tag, out T value, TRank sender) { byte[] rawSenderRank = RankConverter<TRank>.Convert(sender); EnvironmentOperationValue operationValue = Queue.Dequeue( v => v.Sender.SameAs(rawSenderRank) && v.OperationType == EnvironmentOperationType.PeerToPeer); value = operationValue.Get<WrappedValue<T>>().Value; tag = operationValue.UserTag; } #endregion #region Reduction /// <summary> /// Performs the reduction operation. It combines the values provided /// by each thread, using a specified <paramref name="operation"/>, /// and returns the combined value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="operation">The reduce operation.</param> /// <param name="targets">Threads to gather values from.</param> /// <returns>The combined value.</returns> public T Reduce<T>(int tag, ReduceOperation operation, IEnumerable<TRank> targets) { // targetsCount is ignored. int targetsCount; return Reduce<T>(tag, operation, targets, out targetsCount); } /// <summary> /// Performs the reduction operation. It combines the values provided /// by each thread, using a specified <paramref name="operation"/>, /// and returns the combined value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">A value that is provided by the local node.</param> /// <param name="operation">The reduce operation.</param> /// <param name="targets">Threads to gather values from.</param> /// <returns>The combined value.</returns> public T Reduce<T>(int tag, T value, ReduceOperation operation, IEnumerable<TRank> targets) { int targetsCount; T targetsValue = Reduce<T>(tag, operation, targets, out targetsCount); return targetsCount != 0 ? ReduceHelper<T>.Reduce(value, targetsValue, operation) : value; } /// <summary> /// Performs the reduction operation. It combines the values provided /// by each thread, using a specified <paramref name="reductor"/>, /// and returns the combined value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">A value that is provided by the local node.</param> /// <param name="reductor">The custom reductor.</param> /// <param name="targets">Threads to gather values from.</param> /// <returns>The combined value.</returns> public T Reduce<T>(int tag, T value, Reductor reductor, IEnumerable<TRank> targets) { int targetsCount; T targetsValue = Reduce<T>(tag, ReduceOperation.Custom, targets, out targetsCount); return targetsCount != 0 ? ReduceHelper<T>.Reduce(value, targetsValue, reductor) : value; } /// <summary> /// Provides a value for a reduction operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The value to combine.</param> public void Reduce<T>(int tag, T value) { EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.ReduceRequest && v.UserTag == tag); Reduce(value, null, operationValue); } /// <summary> /// Provides a value for a reduction operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The value to combine.</param> /// <param name="reductor">The custom reductor.</param> public void Reduce<T>(int tag, T value, Reductor reductor) { EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.ReduceRequest && v.UserTag == tag); Reduce(value, reductor, operationValue); } /// <summary> /// Provides a value for a reduction operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The value to combine.</param> /// <param name="sender">The rank of a node that should request the reduction operation.</param> public void Reduce<T>(int tag, T value, TRank sender) { byte[] rawSenderRank = RankConverter<TRank>.Convert(sender); EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.UserTag == tag && v.Sender.SameAs(rawSenderRank) && v.OperationType == EnvironmentOperationType.ReduceRequest); Reduce(value, null, operationValue); } /// <summary> /// Provides a value for a reduction operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The value to combine.</param> /// <param name="reductor">The custom reductor.</param> /// <param name="sender">The rank of a node that should request the reduction operation.</param> public void Reduce<T>(int tag, T value, Reductor reductor, TRank sender) { byte[] rawSenderRank = RankConverter<TRank>.Convert(sender); EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.UserTag == tag && v.Sender.SameAs(rawSenderRank) && v.OperationType == EnvironmentOperationType.ReduceRequest); Reduce(value, reductor, operationValue); } /// <summary> /// Performs the reduction operation. It combines the values provided /// by each thread, using a specified <paramref name="operation"/>, /// and returns the combined value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="operation">The reduce operation.</param> /// <param name="targets">Threads to gather values from.</param> /// <param name="targetsCount">A target threads count.</param> /// <returns>The combined value.</returns> private T Reduce<T>(int tag, ReduceOperation operation, IEnumerable<TRank> targets, out int targetsCount) { // Prepare the request. EnvironmentOperationValue requestOperationValue = new EnvironmentOperationValue(); requestOperationValue.Recipients = targets.Select(RankConverter<TRank>.Convert).ToList(); targetsCount = requestOperationValue.Recipients.Count; if (requestOperationValue.Recipients.Count == 0) { return default(T); } requestOperationValue.OperationId = GetOperationId(); requestOperationValue.OperationType = EnvironmentOperationType.ReduceRequest; requestOperationValue.Sender = RawRank; requestOperationValue.UserTag = tag; ReduceRequestValue value = new ReduceRequestValue(); value.Participants = requestOperationValue.Recipients; value.Operation = operation; requestOperationValue.Set(value); // Send the request. Transport.Send(requestOperationValue); // Awaiting for the response. EnvironmentOperationValue previousOperationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.ReduceResponse); return previousOperationValue.Get<WrappedValue<T>>().Value; } /// <summary> /// Handles the reduce request. /// </summary> private void Reduce<T>(T value, Reductor customReductor, EnvironmentOperationValue requestOperationValue) { ReduceRequestValue request = requestOperationValue.Get<ReduceRequestValue>(); // Initialize reduced value... T result = value; // Okay. Now we're to decide whether we should wait for another node... byte[] previousRank = null; IEnumerator<byte[]> participantsEnumerator = request.Participants.GetEnumerator(); while (participantsEnumerator.MoveNext()) { if (participantsEnumerator.Current.SameAs(RawRank)) { break; } previousRank = participantsEnumerator.Current; } if (previousRank != null) { // Wait the previous node. EnvironmentOperationValue previousOperationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.ReduceResponse && v.Sender.SameAs(previousRank)); T previousValue = previousOperationValue.Get<WrappedValue<T>>().Value; result = request.Operation != ReduceOperation.Custom ? ReduceHelper<T>.Reduce(result, previousValue, request.Operation) : ReduceHelper<T>.Reduce(result, previousValue, customReductor); } // Prepare response and send it. EnvironmentOperationValue responseOperationValue = new EnvironmentOperationValue(); responseOperationValue.OperationId = requestOperationValue.OperationId; responseOperationValue.OperationType = EnvironmentOperationType.ReduceResponse; responseOperationValue.Recipients = new[] { participantsEnumerator.MoveNext() ? participantsEnumerator.Current : requestOperationValue.Sender }; responseOperationValue.Sender = RawRank; responseOperationValue.UserTag = requestOperationValue.UserTag; responseOperationValue.Set(new WrappedValue<T>(result)); Transport.Send(responseOperationValue); } /// <summary> /// Performs the reduction operation. It combines the values provided /// by each thread in the specified <paramref name="central"/>, using a specified <paramref name="customReductor"/>, /// and returns the combined value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The value to combine.</param> /// <param name="customReductor">The custom reductor.</param> /// <param name="targets">Threads to gather value from.</param> /// <param name="central">The end node of reduction.</param> /// <returns>The combined value</returns> public T AllReduce<T>(int tag, T value, Reductor customReductor, IEnumerable<TRank> targets, TRank central) { T result; if (Rank.Equals(central)) { result = Reduce<T>(tag, value, customReductor, targets); EnvironmentOperationValue sendValue = new EnvironmentOperationValue(); sendValue.UserTag = tag; sendValue.OperationType = EnvironmentOperationType.AllReduce; sendValue.Recipients = targets.Select(RankConverter<TRank>.Convert).Where(r => !r.Rank.Equals(Rank)).ToList(); sendValue.Sender = RawRank; sendValue.Set(new WrappedValue<T>(result)); Transport.Send(sendValue); } else { Reduce<T>(tag, value, customReductor); EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.AllReduce); result = operationValue.Get<WrappedValue<T>>().Value; } return result; } #endregion #region MapReduce /// <summary> /// Performs the Map-Reduce operation against the nodes. /// </summary> /// <typeparam name="TValue">The type of source values.</typeparam> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">The source value.</param> /// <param name="targets">Target nodes.</param> public TResult MapReduce<TValue, TResult>(int tag, TValue value, IEnumerable<TRank> targets) { // Prepare the request. EnvironmentOperationValue requestOperationValue = new EnvironmentOperationValue(); requestOperationValue.Recipients = targets.Select(RankConverter<TRank>.Convert).ToList(); if (requestOperationValue.Recipients.Count == 0) { return default(TResult); } requestOperationValue.OperationId = GetOperationId(); requestOperationValue.OperationType = EnvironmentOperationType.MapReduceRequest; requestOperationValue.Sender = RawRank; requestOperationValue.UserTag = tag; MapReduceRequestValue<TValue> mapReduceRequest = new MapReduceRequestValue<TValue>(); mapReduceRequest.Participants = requestOperationValue.Recipients; mapReduceRequest.Value = value; requestOperationValue.Set(mapReduceRequest); // Send the request. Transport.Send(requestOperationValue); // Awaiting for the response. EnvironmentOperationValue previousOperationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.MapReduceResponse); return previousOperationValue.Get<WrappedValue<TResult>>().Value; } /// <summary> /// Performs a local part of the Map-Reduce operation. /// </summary> /// <typeparam name="TValue">The type of source values.</typeparam> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="mapOperation">Map operation.</param> /// <param name="reduceOperation">Reduce operation.</param> public void MapReduce<TValue, TResult>(int tag, MapFunction<TValue, TResult> mapOperation, Reductor<TResult> reduceOperation) { EnvironmentOperationValue requestOperationValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.MapReduceRequest && v.UserTag == tag); MapReduceRequestValue<TValue> request = requestOperationValue.Get<MapReduceRequestValue<TValue>>(); TResult result = mapOperation(request.Value); byte[] previousRank = null; IEnumerator<byte[]> participantsEnumerator = request.Participants.GetEnumerator(); while (participantsEnumerator.MoveNext()) { if (participantsEnumerator.Current.SameAs(RawRank)) { break; } previousRank = participantsEnumerator.Current; } if (previousRank != null) { // Wait the previous node. EnvironmentOperationValue previousOperationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.MapReduceResponse && v.Sender.SameAs(previousRank)); TResult previousValue = previousOperationValue.Get<WrappedValue<TResult>>().Value; result = ReduceHelper<TResult>.Reduce(result, previousValue, reduceOperation); } // Prepare response and send it. EnvironmentOperationValue responseOperationValue = new EnvironmentOperationValue(); responseOperationValue.OperationId = requestOperationValue.OperationId; responseOperationValue.OperationType = EnvironmentOperationType.MapReduceResponse; responseOperationValue.Recipients = new[] { participantsEnumerator.MoveNext() ? participantsEnumerator.Current : requestOperationValue.Sender }; responseOperationValue.Sender = RawRank; responseOperationValue.UserTag = requestOperationValue.UserTag; responseOperationValue.Set(new WrappedValue<TResult>(result)); Transport.Send(responseOperationValue); } #endregion #region Gather /// <summary> /// Gathers together values from a group of processes. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="senders">Threads to gather value from.</param> /// <returns>Combined values from senders.</returns> public ICollection<T> Gather<T>(IEnumerable<TRank> senders) { return Gather<T>(UserTags.Default, senders); } /// <summary> /// Gathers together values from a group of processes. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="senders">Threads to gather value from.</param> /// <returns>Combined values from senders.</returns> public ICollection<T> Gather<T>(int tag, IEnumerable<TRank> senders) { // Prepare the request. EnvironmentOperationValue requestOperationValue = new EnvironmentOperationValue(); List<byte[]> convertedSenders = senders.Select(RankConverter<TRank>.Convert).ToList(); // We create a copy because it will be altered by Transport.Send. List<byte[]> convertedRecipients = new List<byte[]>(convertedSenders); requestOperationValue.Recipients = convertedRecipients; if (requestOperationValue.Recipients.Count == 0) { return new List<T>(); } requestOperationValue.OperationId = GetOperationId(); requestOperationValue.OperationType = EnvironmentOperationType.GatherRequest; requestOperationValue.Sender = RawRank; requestOperationValue.UserTag = tag; Transport.Send(requestOperationValue); List<T> gatheredValues = new List<T>(); foreach (byte[] sender in convertedSenders) { // Preventing access to modified closure. byte[] localSender = sender; EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.GatherResponse && v.UserTag == tag && v.Sender.SameAs(localSender)); gatheredValues.Add(operationValue.Get<WrappedValue<T>>().Value); } return gatheredValues; } /// <summary> /// Gathers together values from a group of processes with current. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="value">Current thread value.</param> /// <param name="senders">Threads to gather value from.</param> /// <returns>Combined values from senders and current thread.</returns> public ICollection<T> Gather<T>(T value, IEnumerable<TRank> senders) { return Gather<T>(UserTags.Default, value, senders); } /// <summary> /// Gathers together values from a group of processes with current. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">Current thread value.</param> /// <param name="senders">Threads to gather value from.</param> /// <returns>Combined values from senders and current thread.</returns> public ICollection<T> Gather<T>(int tag, T value, IEnumerable<TRank> senders) { ICollection<T> gatheredValues = Gather<T>(tag, senders); gatheredValues.Add(value); return gatheredValues; } /// <summary> /// Sends a value for the Gather operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="value">Current thread value.</param> public void Gather<T>(T value) { Gather<T>(UserTags.Default, value); } /// <summary> /// Sends a value for the Gather operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="value">Current thread value.</param> public void Gather<T>(int tag, T value) { EnvironmentOperationValue requestValue = Queue.Dequeue(v => v.UserTag == tag && v.OperationType == EnvironmentOperationType.GatherRequest); EnvironmentOperationValue operationValue = new EnvironmentOperationValue(); operationValue.Sender = RawRank; operationValue.OperationId = requestValue.OperationId; operationValue.OperationType = EnvironmentOperationType.GatherResponse; operationValue.Set(new WrappedValue<T>(value)); operationValue.Recipients = new[] { requestValue.Sender }; operationValue.UserTag = tag; Transport.Send(operationValue); } #endregion #region AllGather /// <summary> /// Gathers together values from a group of processes and send them a value. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="value">Current thread value.</param> /// <param name="senders">Threads to send value to and to gather value from.</param> /// <returns>Combined values from senders and current thread.</returns> public ICollection<T> AllGather<T>(T value, IEnumerable<TRank> senders) { // Prepare the request. EnvironmentOperationValue requestOperationValue = new EnvironmentOperationValue(); senders = senders.Where(sender => !sender.Equals(Rank)); List<byte[]> convertedSenders = senders.Select(RankConverter<TRank>.Convert).ToList(); // We create a copy because it will be altered by Transport.Send. List<byte[]> convertedRecipients = new List<byte[]>(convertedSenders); requestOperationValue.Recipients = convertedRecipients; if (requestOperationValue.Recipients.Count == 0) { return new List<T>(); } requestOperationValue.OperationId = GetOperationId(); requestOperationValue.OperationType = EnvironmentOperationType.AllGatherRequest; requestOperationValue.Sender = RawRank; Transport.Send(requestOperationValue); foreach (var sender in senders) { EnvironmentOperationValue requestValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.AllGatherRequest); EnvironmentOperationValue operationValue = new EnvironmentOperationValue(); operationValue.Sender = RawRank; operationValue.OperationId = requestValue.OperationId; operationValue.OperationType = EnvironmentOperationType.AllGatherResponse; operationValue.Set(new WrappedValue<T>(value)); operationValue.Recipients = new[] { requestValue.Sender }; Transport.Send(operationValue); } List<T> gatheredValues = new List<T>(); foreach (byte[] sender in convertedSenders) { // Preventing access to modified closure. byte[] localSender = sender; EnvironmentOperationValue responseOperationValue = Queue.Dequeue(v => v.OperationId == requestOperationValue.OperationId && v.OperationType == EnvironmentOperationType.AllGatherResponse && v.Sender.SameAs(localSender)); gatheredValues.Add(responseOperationValue.Get<WrappedValue<T>>().Value); } gatheredValues.Add(value); return gatheredValues; } #endregion #region Scatter /// <summary> /// Receive value from Scatter operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <returns>Appropriate piece of the data from Scatter operation.</returns> public T Scatter<T>() { return Scatter<T>(UserTags.Default); } /// <summary> /// Receive value from Scatter operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <returns>Appropriate piece of the data from Scatter operation.</returns> public T Scatter<T>(int tag) { EnvironmentOperationValue operationValue = Queue.Dequeue(v => v.OperationType == EnvironmentOperationType.ScatterResponse && v.UserTag == tag); return operationValue.Get<WrappedValue<T>>().Value; } /// <summary> /// Sends values for the Scatter operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="values">Dictionary with ranks and corresponding values for each process in the group.</param> /// <param name="recipients">Threads to scatter values to.</param> public void Scatter<T>(Dictionary<TRank, T> values, IEnumerable<TRank> recipients) { Scatter(UserTags.Default, values, recipients); } /// <summary> /// Sends values for the Scatter operation. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <param name="tag">The user tag.</param> /// <param name="values">Dictionary with ranks and corresponding values for each process in the group.</param> /// <param name="recipients">Threads to scatter values to.</param> public void Scatter<T>(int tag, Dictionary<TRank, T> values, IEnumerable<TRank> recipients) { if (!recipients.Any()) { return; } // Prepare the request. EnvironmentOperationValue responseOperationValue = new EnvironmentOperationValue(); responseOperationValue.OperationId = GetOperationId(); responseOperationValue.OperationType = EnvironmentOperationType.ScatterResponse; responseOperationValue.Sender = RawRank; responseOperationValue.UserTag = tag; foreach (TRank sender in recipients) { responseOperationValue.Recipients = new List<byte[]>() { RankConverter<TRank>.Convert(sender) }; TRank recipientRank = sender; responseOperationValue.Set(new WrappedValue<T>(values[recipientRank])); Transport.Send(responseOperationValue); } } #endregion #region Utilities /// <summary> /// Gets the local time of the thread. /// </summary> /// <returns>Local time of the thread from the start to current time.</returns> public double Time { get { return Stopwatch.Elapsed.TotalSeconds; } } #endregion } }
44.784946
126
0.581299
[ "Apache-2.0" ]
eigenein/cloudy
Cloudy/Computing/Environment.cs
37,487
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TestMachineFrontend1.Helpers; namespace TestMachineFrontend1.ViewModel { public class DisconnectedViewModel : ObservableObject { RemoteControllerViewModel remoteVM; //public DisconnectedViewModel() //{ // remoteVM = MainWindowViewModel.CurrentViewModelRemoteController; // remoteVM.IsPiDisconnected = true; //} } }
25.25
78
0.712871
[ "Apache-2.0" ]
CytheY/amos-ss17-projSivantos
UserAgent/ProductionFrontend/ViewModel/DisconnectedViewModel.cs
507
C#
using System; namespace Epam.Users.Entities { public class Award { public int Id { get; set; } public string Title { get; set; } public byte[] Image { get; set; } public override string ToString() { return $"{Id} {Title} {Convert.ToBase64String(Image)}"; } } }
17.789474
67
0.535503
[ "MIT" ]
NesterovSergey/XT-2018Q4
Epam.Task11-12/Epam.Users.Entities/Award.cs
340
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace DotNetNote.Controllers { public class TreeManagerController : Controller { // GET: /<controller>/ public IActionResult Index() { return View(); } } }
23.05
112
0.683297
[ "MIT" ]
VisualAcademy/Trees
DotNetNote/Controllers/TreeManagerController.cs
463
C#
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace ObjectValidator { /// <summary> /// Implamants validator for any objects using <see cref="ValidationAttribute"/> on object properties /// </summary> public class ValidatorByDataAnnotations : IValidator { /// <summary> /// Performs validation <paramref name="value" /> /// </summary> /// <param name="value">Object to validate</param> /// <returns>Validation results</returns> public IEnumerable<ValidationResult> Validate(object value) { return Validate(value, null); } private IEnumerable<ValidationResult> Validate(object value, ValidationContext context) { if (value == null) return Enumerable.Empty<ValidationResult>(); var valueType = value.GetType(); return ValidateProperties(valueType, value, context).Union(ValidateEnumerable(valueType, value, context)); } private IEnumerable<ValidationResult> ValidateProperties(Type type, object @object, ValidationContext context) { return TypeDescriptor.GetProperties(type) .OfType<PropertyDescriptor>() .Where(p => !p.IsReadOnly) .SelectMany(property => ValidateProperty(property, @object, context)); } private IEnumerable<ValidationResult> ValidateProperty(PropertyDescriptor property, object @object, ValidationContext context) { var propertyContext = context != null ? new ValidationContext(@object, null, null) { DisplayName = string.Join(".", context.DisplayName, GetDisplayName(property)), MemberName = string.Join(".", context.MemberName, property.Name), } : new ValidationContext(@object, null, null) { DisplayName = GetDisplayName(property), MemberName = property.Name, }; var value = property.GetValue(@object); return property.Attributes .OfType<ValidationAttribute>() .Select(attribute => attribute.GetValidationResult(value, propertyContext)) .Where(result => result != ValidationResult.Success) .Union(Validate(value, propertyContext)); } private IEnumerable<ValidationResult> ValidateEnumerable(Type type, object @object, ValidationContext context) { var enumerable = @object as IEnumerable; if (enumerable == null) return Enumerable.Empty<ValidationResult>(); return enumerable.OfType<object>().SelectMany(item => Validate(item, context)); } private string GetDisplayName(PropertyDescriptor property) { var displayAttribute = property.Attributes.OfType<DisplayAttribute>().ToArray().FirstOrDefault(); return displayAttribute != null ? displayAttribute.GetName() : property.DisplayName; } } }
37.378049
132
0.65155
[ "MIT" ]
devamator/ObjectValidator
src/ObjectValidator/ValidatorByDataAnnotations.cs
3,067
C#
namespace Core6.Pipeline { using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Pipeline; using NServiceBus.Transport; #region CustomForkConnector public class CustomForkConnector : ForkConnector<IIncomingPhysicalMessageContext, IAuditContext> { public override async Task Invoke(IIncomingPhysicalMessageContext context, Func<Task> next, Func<IAuditContext, Task> fork) { // Finalize the work in the current stage await next() .ConfigureAwait(false); OutgoingMessage message = null; var auditAddress = "AuditAddress"; // Fork into new pipeline await fork(this.CreateAuditContext(message, auditAddress, context)) .ConfigureAwait(false); } } #endregion }
31.642857
132
0.62754
[ "Apache-2.0" ]
A-Franklin/docs.particular.net
Snippets/Core/Core_6/Pipeline/CustomForkConnector.cs
859
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System; using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute { /// <summary> /// Add an Ssh Public Key object to VM /// </summary> [Cmdlet("Add", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMSshPublicKey"),OutputType(typeof(PSVirtualMachine))] public class NewAzureSshPublicKeyCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Alias("VMProfile")] [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = HelpMessages.VMProfile)] [ValidateNotNullOrEmpty] public PSVirtualMachine VM { get; set; } [Parameter( Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "Certificate Public Key")] [ValidateNotNullOrEmpty] public string KeyData { get; set; } [Parameter( Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "Full Path on VM where SSH Public Key is Stored.")] [ValidateNotNullOrEmpty] public string Path { get; set; } public override void ExecuteCmdlet() { if (this.VM.OSProfile == null) { this.VM.OSProfile = new OSProfile(); } if (this.VM.OSProfile.WindowsConfiguration == null && this.VM.OSProfile.LinuxConfiguration == null) { this.VM.OSProfile.LinuxConfiguration = new LinuxConfiguration(); } else if (this.VM.OSProfile.WindowsConfiguration != null && this.VM.OSProfile.LinuxConfiguration == null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } if (this.VM.OSProfile.LinuxConfiguration.Ssh == null) { this.VM.OSProfile.LinuxConfiguration.Ssh = new SshConfiguration(); } if (this.VM.OSProfile.LinuxConfiguration.Ssh.PublicKeys == null) { this.VM.OSProfile.LinuxConfiguration.Ssh.PublicKeys = new List<SshPublicKey>(); } this.VM.OSProfile.LinuxConfiguration.Ssh.PublicKeys.Add( new SshPublicKey { KeyData = this.KeyData, Path = this.Path, }); WriteObject(this.VM); } } }
39.826087
143
0.591157
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/Compute/Commands.Compute/VirtualMachine/Config/AddAzureVMSshPublicKeyCommand.cs
3,575
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Tarea8.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Tarea8.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.458333
172
0.601661
[ "Apache-2.0" ]
Luissf1/Programas-C-
Tarea8/Tarea8/Properties/Resources.Designer.cs
2,771
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 config-2014-11-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ConfigService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ConfigService.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Compliance Object /// </summary> public class ComplianceUnmarshaller : IUnmarshaller<Compliance, XmlUnmarshallerContext>, IUnmarshaller<Compliance, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> Compliance IUnmarshaller<Compliance, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Compliance Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; Compliance unmarshalledObject = new Compliance(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ComplianceContributorCount", targetDepth)) { var unmarshaller = ComplianceContributorCountUnmarshaller.Instance; unmarshalledObject.ComplianceContributorCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ComplianceType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ComplianceType = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ComplianceUnmarshaller _instance = new ComplianceUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ComplianceUnmarshaller Instance { get { return _instance; } } } }
34.561224
143
0.631532
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ConfigService/Generated/Model/Internal/MarshallTransformations/ComplianceUnmarshaller.cs
3,387
C#
// -------------------------------------------------------------------------------------------------- // <copyright file="CartCustomException.cs" company="InmoIT"> // Copyright (c) InmoIT. All rights reserved. // Developer: Vladimir P. CHibás (vladperchi). // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------- using System.Collections.Generic; using System.Net; using Microsoft.Extensions.Localization; using InmoIT.Shared.Core.Exceptions; namespace InmoIT.Modules.Person.Core.Exceptions { public class CartCustomException : CustomException { public CartCustomException(IStringLocalizer localizer, List<string> errors) : base(localizer["Cart errors have occurred..."], errors, HttpStatusCode.InternalServerError) { } } }
40.782609
105
0.576759
[ "MIT" ]
DevCrafts/InmoIT
src/server/Modules/Person/Modules.Person.Core/Exceptions/CartCustomException.cs
941
C#
// // Copyright 2020 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using Google.Solutions.IapDesktop.Application.ObjectModel; using Moq; using NUnit.Framework; using System; using System.Linq; using System.Threading; using System.Windows.Forms; namespace Google.Solutions.IapDesktop.Application.Test.ObjectModel { [TestFixture] [Apartment(ApartmentState.STA)] public class TestCommandContainerForContextMenu : ApplicationFixtureBase { private Form form; private ContextMenuStrip contextMenu; private CommandContainer<string> commandContainer; [SetUp] public void SetUp() { this.contextMenu = new ContextMenuStrip(); this.form = new Form { ContextMenuStrip = this.contextMenu }; this.contextMenu.Items.Add(new ToolStripSeparator()); this.form.Show(); this.commandContainer = new CommandContainer<string>( this.form, this.contextMenu.Items, ToolStripItemDisplayStyle.ImageAndText, new Mock<IServiceProvider>().Object); } [TearDown] public void TearDown() { this.form.Close(); } //--------------------------------------------------------------------- // Top-level commands. //--------------------------------------------------------------------- [Test] public void WhenQueryStateReturnsUnavailable_ThenMenuItemIsHidden() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Unavailable, ctx => throw new InvalidOperationException())); var menuItem = this.contextMenu.Items .OfType<ToolStripMenuItem>() .First(i => i.Text == "test"); this.commandContainer.Context = "ctx"; this.contextMenu.Show(); Assert.IsFalse(menuItem.Visible); } [Test] public void WhenQueryStateReturnsDisabled_ThenMenuItemIsDisabled() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Disabled, ctx => throw new InvalidOperationException())); var menuItem = this.contextMenu.Items .OfType<ToolStripMenuItem>() .First(i => i.Text == "test"); this.commandContainer.Context = "ctx"; this.contextMenu.Show(); Assert.IsTrue(menuItem.Visible); Assert.IsFalse(menuItem.Enabled); } [Test] public void WhenQueryStateReturnsEnabled_ThenMenuItemIsEnabled() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Enabled, ctx => throw new InvalidOperationException())); var menuItem = this.contextMenu.Items .OfType<ToolStripMenuItem>() .First(i => i.Text == "test"); this.commandContainer.Context = "ctx"; this.contextMenu.Show(); Assert.IsTrue(menuItem.Visible); Assert.IsTrue(menuItem.Enabled); Assert.IsNull(menuItem.ToolTipText); } [Test] public void WhenKeyIsUnknown_ThenExecuteCommandByKeyDoesNothing() { this.commandContainer.ExecuteCommandByKey(Keys.A); } [Test] public void WhenKeyIsMappedAndCommandIsEnabled_ThenExecuteCommandInvokesHandler() { string contextOfCallback = null; this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Enabled, ctx => { contextOfCallback = ctx; }) { ShortcutKeys = Keys.F4 }); this.commandContainer.Context = "foo"; this.commandContainer.ExecuteCommandByKey(Keys.F4); Assert.AreEqual("foo", contextOfCallback); } [Test] public void WhenKeyIsMappedAndCommandIsDisabled_ThenExecuteCommandByKeyDoesNothing() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Disabled, ctx => { Assert.Fail(); }) { ShortcutKeys = Keys.F4 }); this.commandContainer.Context = "foo"; this.commandContainer.ExecuteCommandByKey(Keys.F4); } [Test] public void WhenContainerHasCommands_ThenRefreshCallsQueryState() { int queryCalls = 0; this.commandContainer.AddCommand( new Command<string>( "test", ctx => { Assert.AreEqual("ctx", ctx); queryCalls++; return CommandState.Disabled; }, ctx => throw new InvalidOperationException())); this.commandContainer.Context = "ctx"; this.contextMenu.Show(); Assert.AreEqual(1, queryCalls); this.commandContainer.Refresh(); Assert.AreEqual(2, queryCalls); } //--------------------------------------------------------------------- // Second-level commands. //--------------------------------------------------------------------- [Test] public void WhenSubMenuAdded_ThenContextIsShared() { var parentMenu = this.commandContainer.AddCommand( new Command<string>( "parent", ctx => CommandState.Enabled, ctx => throw new InvalidOperationException())); var subMenu = parentMenu.AddCommand( new Command<string>( "test", ctx => CommandState.Disabled, ctx => throw new InvalidOperationException())); parentMenu.Context = "ctx"; Assert.AreEqual("ctx", parentMenu.Context); Assert.AreEqual("ctx", subMenu.Context); } //--------------------------------------------------------------------- // Default commands. //--------------------------------------------------------------------- [Test] public void WhenContainerDoesNotHaveDefaultCommand_ThenExecuteDefaultCommandDoesNothing() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Enabled, ctx => { Assert.Fail(); }) { }); this.commandContainer.ExecuteDefaultCommand(); } [Test] public void WhenDefaultCommandIsDisabled_ThenExecuteDefaultCommandDoesNothing() { this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Disabled, ctx => { Assert.Fail(); }) { IsDefault = true }); this.commandContainer.ExecuteDefaultCommand(); } [Test] public void WhenDefaultCommandIsEnabled_ThenExecuteDefaultExecutesCommand() { bool commandExecuted = false; this.commandContainer.AddCommand( new Command<string>( "test", ctx => CommandState.Enabled, ctx => { commandExecuted = true; }) { IsDefault = true }); this.commandContainer.ExecuteDefaultCommand(); Assert.IsTrue(commandExecuted); } } }
32.577465
97
0.496541
[ "Apache-2.0" ]
Bhisma19/iap-desktop
sources/Google.Solutions.IapDesktop.Application.Test/ObjectModel/TestCommandContainerForContextMenu.cs
9,254
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 ASC.Web.Studio.UserControls.Management { public partial class TransferPortal { /// <summary> /// PopupTransferStartContainer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ASC.Web.Studio.Controls.Common.Container PopupTransferStartContainer; } }
30.407407
95
0.514007
[ "ECL-2.0", "Apache-2.0", "MIT" ]
ONLYOFFICE/CommunityServer
web/studio/ASC.Web.Studio/UserControls/Management/TransferPortal/TransferPortal.ascx.designer.cs
821
C#
using System; using System.Threading.Tasks; using KdSoft.Services.Protobuf; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; namespace KdSoft.Services.WebApi { public class ProtobufFormatterOptions { public static readonly MediaTypeHeaderValue MediaType = new MediaTypeHeaderValue("application/x-protobuf"); } public class ProtobufOutputFormatter: OutputFormatter { ProtoWriterMap writerMap; public ProtobufOutputFormatter() { SupportedMediaTypes.Add(ProtobufFormatterOptions.MediaType); writerMap = new ProtoWriterMap(); } public ProtoWriterMap WriterMap { get { return writerMap; } } static bool CanWriteTypeCore(Type type) { return true; } protected override bool CanWriteType(Type type) { bool result = CanWriteTypeCore(type); if (result) { var writer = writerMap.GetWriter(type); if (writer == null) result = false; } return result; } public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { var tcs = new TaskCompletionSource<object>(); try { // the type passed to serialization might be more derived than the type publicly registered, // so we also check if we have a parent type serializer that is registered, if no exact match is found var writer = writerMap.GetWriter(context.ObjectType); writer.WriteTo(context.Object, context.HttpContext.Response.Body); tcs.SetResult(null); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; } } public class ProtobufInputFormatter: InputFormatter { ProtoReaderMap readerMap; public ProtobufInputFormatter() { SupportedMediaTypes.Add(ProtobufFormatterOptions.MediaType); readerMap = new ProtoReaderMap(); } public ProtoReaderMap ReaderMap { get { return readerMap; } } static bool CanReadTypeCore(Type type) { return true; } protected override bool CanReadType(Type type) { bool result = CanReadTypeCore(type); if (result) { var reader = readerMap.GetReaderExact(type); if (reader == null) result = false; } return result; } public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { var tcs = new TaskCompletionSource<InputFormatterResult>(); try { // we want to deserialize the exact type that we expecting var reader = readerMap.GetReaderExact(context.ModelType); object result = reader.ReadFrom(context.HttpContext.Request.Body); tcs.SetResult(InputFormatterResult.Success(result)); } catch (Exception ex) { tcs.SetResult(InputFormatterResult.Failure()); //tcs.SetException(ex); } return tcs.Task; } } }
32.284314
118
0.596417
[ "MIT" ]
kwaclaw/KdSoft.Services
Web/KdSoft.Services.WebApi.Utils/ProtobufFormatter.cs
3,295
C#
using System.Runtime.Serialization; namespace Our.Umbraco.CloudPurge.Config { [DataContract] public class CloudPurgeConfig { public CloudPurgeConfig() { CloudFlare = new CloudFlareConfig(false, "", "", ""); } public CloudPurgeConfig(bool enablePublishHooks, ContentFilterConfig contentFilter, CloudFlareConfig cloudFlare) { EnablePublishHooks = enablePublishHooks; ContentFilter = contentFilter; CloudFlare = cloudFlare; } [DataMember] public bool EnablePublishHooks { get; set; } [DataMember] public ContentFilterConfig ContentFilter { get; set; } [DataMember] public CloudFlareConfig CloudFlare { get; set; } } }
21.419355
114
0.739458
[ "MIT" ]
anth12/CloudPurge
Our.Umbraco.CloudPurge/Config/CloudPurgeConfig.cs
666
C#
// *** WARNING: this file was generated by pulumigen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Storage.V1 { /// <summary> /// VolumeAttachmentStatus is the status of a VolumeAttachment request. /// </summary> public class VolumeAttachmentStatusArgs : Pulumi.ResourceArgs { /// <summary> /// The last error encountered during attach operation, if any. This field must only be set by the entity completing the attach operation, i.e. the external-attacher. /// </summary> [Input("attachError")] public Input<Pulumi.Kubernetes.Types.Inputs.Storage.V1.VolumeErrorArgs>? AttachError { get; set; } /// <summary> /// Indicates the volume is successfully attached. This field must only be set by the entity completing the attach operation, i.e. the external-attacher. /// </summary> [Input("attached", required: true)] public Input<bool> Attached { get; set; } = null!; [Input("attachmentMetadata")] private InputMap<string>? _attachmentMetadata; /// <summary> /// Upon successful attach, this field is populated with any information returned by the attach operation that must be passed into subsequent WaitForAttach or Mount calls. This field must only be set by the entity completing the attach operation, i.e. the external-attacher. /// </summary> public InputMap<string> AttachmentMetadata { get => _attachmentMetadata ?? (_attachmentMetadata = new InputMap<string>()); set => _attachmentMetadata = value; } /// <summary> /// The last error encountered during detach operation, if any. This field must only be set by the entity completing the detach operation, i.e. the external-attacher. /// </summary> [Input("detachError")] public Input<Pulumi.Kubernetes.Types.Inputs.Storage.V1.VolumeErrorArgs>? DetachError { get; set; } public VolumeAttachmentStatusArgs() { } } }
42.584906
282
0.671245
[ "Apache-2.0" ]
AaronFriel/pulumi-kubernetes
sdk/dotnet/Storage/V1/Inputs/VolumeAttachmentStatusArgs.cs
2,257
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using Jockusch.Common; using Jockusch.Common.Debugging; using System.Collections; namespace Jockusch.Common { public class AttributeCollectionOwner: IAttributeCollection { public virtual BitArray Underline { get { BitArray r = this._Attributes?.Underline; return r; } set { this.NullCoalescingSetter(a => a.Underline = value, value); } } public virtual void ResetAttributes() { AttributeCollection attributes = this.GetAttributes(false); attributes?.ResetAttributes(); } public void DeepCopyAttributesFrom(IAttributeCollection cloneMe, bool really = true) { if (really && cloneMe!=this) { AttributeCollection attributes = cloneMe?.GetAttributes(false); if (attributes != null) { this.Attributes.DeepCopyAttributesFrom(attributes); } } } public AttributeCollectionOwner() {} public AttributeCollectionOwner(AttributeCollectionOwner otherOwner) : this() { this.DeepCopyAttributesFrom(otherOwner); } public void SetAttributes(AttributeCollection attributes) { if (attributes == null) { this.Attributes = null; } else { this.Attributes.SetAttributes(attributes); } } #region IAttributeCollection public string AccessibilityLabel { get { return this.GetAttributes(false)?.AccessibilityLabel; } set { this.NullCoalescingSetter(a => a.AccessibilityLabel = value, value); } } protected AttributeCollection _Attributes {get;set;} public AttributeCollection Attributes { get { if (_Attributes == null) { _Attributes = new AttributeCollection (); } return _Attributes; } set { _Attributes = value; } } public AttributeCollection GetAttributes(bool createIfNull) { if (createIfNull) { return this.Attributes; } else { return this._Attributes; } } public virtual PointF Location { get { PointF r = PointFAdditions.NaN; if (this._Attributes!=null) { r = this._Attributes.Location; } return r; } set { this.CoalescingSetter(a => a.Location = value, value, p => p.IsNaN()); } } /// <summary> /// See also VerticalAlignment, which is not nullable and returns the default value (center) if this property is null. /// When drawing, one would typically use VerticalAlignment, not VerticalAlignmentQ. /// </summary> public virtual VerticalAlignmentEnum? VerticalAlignmentQ { get { return this.GetAttributes(false)?.VerticalAlignmentQ; } set { this.NullCoalescingSetter(a => a.VerticalAlignmentQ = value, value); } } /// <summary> /// See also GetHorizontalAlignment(), which is not nullable and returns the default value (center) if this property is null. /// When drawing, one would typically use HorizontalAlignment, not HorizontalAlignmentQ. /// </summary> public virtual HorizontalAlignmentEnum? HorizontalAlignmentQ { get { return this.GetAttributes(false)?.HorizontalAlignmentQ; } set { this.NullCoalescingSetter(a => a.HorizontalAlignmentQ = value, value); } } public virtual string GhostedText { get { string r = this.GetAttributes(false)?.GhostedText; return r; } set { this.NullCoalescingSetter(a => a.GhostedText = value, value); } } private void NullCoalescingSetter<T>(Action<AttributeCollection> action, T value) { this.CoalescingSetter(action, value, v => AnyType.EqualsDefault(v)); } private void CoalescingSetter<T>(Action<AttributeCollection> action, T value, Predicate<T> valueIsSpecial) { bool createAttributes = !valueIsSpecial(value); AttributeCollection attributes = this.GetAttributes(createAttributes); if (attributes!=null) { action(attributes); } } public string AttributeDisplayString { get { return this.GetAttributes(false)?.AttributeDisplayString; } set { this.NullCoalescingSetter(a => a.AttributeDisplayString = value, value); } } public float MaxWidth { get { return this.GetAttributes(false)?.MaxWidth ?? float.NaN; } set { this.CoalescingSetter(a => a.MaxWidth = value, value, v => float.IsNaN(v)); } } public void SetHorizontalAlignmentQ(HorizontalAlignmentEnum? value, bool hard = true) { this.NullCoalescingSetter(a => a.SetHorizontalAlignmentQ(value, hard), value); } public void SetVerticalAlignmentQ(VerticalAlignmentEnum? value, bool hard = true) { this.NullCoalescingSetter(a => a.SetVerticalAlignmentQ(value, hard), value); } #endregion } }
30.871166
129
0.648251
[ "Unlicense" ]
verybadcat/Debugging
Jockusch.Common.Debugging/Attributes/AttributeCollectionOwner.cs
5,032
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 19.10.2021. using Microsoft.EntityFrameworkCore.Migrations.Operations; using NUnit.Framework; using xEFCore=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Sql.DECIMAL_5_1{ //////////////////////////////////////////////////////////////////////////////// using T_DATA=System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_ERR020__bad_IsFixedLength public static class TestSet_ERR020__bad_IsFixedLength { private const string c_testTableName ="EFCORE_TTABLE_DUMMY"; private const string c_testColumnName ="MY_COLUMN"; //----------------------------------------------------------------------- private const string c_testColumnTypeName ="DECIMAL(5,1)"; //----------------------------------------------------------------------- [Test] public static void Test_0000() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = c_testColumnTypeName, IsNullable = false, IsFixedLength = false }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_IsFixedLength_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__DECIMAL, false, true); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0000 };//class TestSet_ERR020__bad_IsFixedLength //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Sql.DECIMAL_5_1
30.311828
129
0.607662
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Migrations/Generations/SET001/DataTypes/Sql/DECIMAL_5_1/TestSet_ERR020__bad_IsFixedLength.cs
2,821
C#
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_OzSingleton : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetSingleTon_s(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif var ret=OzSingleton.GetSingleTon<UnityEngine.Component>(); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetLuaSingleton_s(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.String a1; checkType(l,1,out a1); var ret=OzSingleton.GetLuaSingleton(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_IsDestroy(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif pushValue(l,true); pushValue(l,OzSingleton.IsDestroy); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_IsDestroy(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif bool v; checkType(l,2,out v); OzSingleton.IsDestroy=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_SingletonGameObject(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif pushValue(l,true); pushValue(l,OzSingleton.SingletonGameObject); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"OzSingleton"); addMember(l,GetSingleTon_s); addMember(l,GetLuaSingleton_s); addMember(l,"IsDestroy",get_IsDestroy,set_IsDestroy,false); addMember(l,"SingletonGameObject",get_SingletonGameObject,null,false); createTypeMetatable(l,null, typeof(OzSingleton),typeof(UnityEngine.MonoBehaviour)); } }
24.581395
85
0.722091
[ "Apache-2.0" ]
PenpenLi/-game
Assets/Slua/LuaObject/Custom/Lua_OzSingleton.cs
4,230
C#
using UnityEngine; using TMPro; namespace Step11 { public class BounceCounter : MonoBehaviour { [SerializeField] private TextMeshProUGUI counterLabel; private int counter; public int Score => counter; //used in Step 13 private void Awake() { Reset(); } private void UpdateBounceLabel() { counterLabel.text = counter.ToString(); } private void OnTriggerExit2D(Collider2D collider2D) { if(collider2D.gameObject.tag != "Ball") { return; } counter++; UpdateBounceLabel(); } public void Reset() { counter = 0; UpdateBounceLabel(); } } }
19.414634
62
0.503769
[ "MIT" ]
SiriMakesGames/Programmier-Workshop
Assets/Assets by Steps/Step 11 - Count Bounces/BounceCounter.cs
798
C#
using System.Collections.Generic; using System.Linq; namespace GSMailApi.Model.Files.Managment { public class DwtFile : ManagmentFile { public string FieldMonth { get; set; } public double WorkingDay { get; set; } public double WorkingDayPercent => 21 / WorkingDay * 100; public List<BaseModel> TaskBasis { get; set; } public double TaskBasisEfforts { get { if (TaskBasis != null && TaskBasis.Count > 0 && TaskBasis.First() is LineDwtBasis) { return TaskBasis.Sum(lineDwtBasise => (lineDwtBasise as LineDwtBasis).Efforts); } return 0; } } public List<BaseModel> NippoBasis { get; set; } public double NippoBasisEfforts { get { if (NippoBasis != null && NippoBasis.Count > 0 && NippoBasis.First() is LineDwtBasis) { return NippoBasis.Sum(lineDwtBasise => (lineDwtBasise as LineDwtBasis).Efforts); } return 0; } } public List<BaseModel> BtBasis { get; set; } public double BtBasisEfforts { get { if (BtBasis != null && BtBasis.Count > 0 && BtBasis.First() is LineDwtBasis) { return BtBasis.Sum(lineDwtBasise => (lineDwtBasise as LineDwtBasis).Efforts); } return 0; } } public double Reserved => WorkingDay - (BtBasisEfforts + NippoBasisEfforts + TaskBasisEfforts); } public class LineDwtBasis : ManagmentFile { public string TaskName { get; set; } public string Member { get; set; } public double Efforts { get; set; } public string Description { get; set; } } }
27.428571
103
0.525
[ "MIT" ]
ALEX-ANV/GSMail
GSMailApi/Model/Files/Managment/DwtFile.cs
1,922
C#
using System; using System.Collections.Generic; using System.Text; using ServiceStack.OrmLite; using ServiceStack.OrmLite.Sqlite; using System.ComponentModel.DataAnnotations.Schema; using ServiceStack.DataAnnotations; namespace Magicianred.LearnByDoing.MyBlog.DAL.Tests.Unit.Models { [Alias("PostTags")] public class PostTag : Magicianred.LearnByDoing.MyBlog.Domain.Models.PostTag { } }
25.3125
80
0.795062
[ "MIT" ]
peppesicilia/my-blog-sample
Magicianred.LearnByDoing.MyBlog.DAL.Tests.Unit/Models/PostTag.cs
407
C#
namespace CyberCAT.Core.DumpedEnums { public enum ESmartHousePreset { MorningPreset = 0, EveningPreset = 1, NightPreset = 2 } }
13.7
35
0.722628
[ "MIT" ]
Deweh/CyberCAT
CyberCAT.Core/Enums/Dumped Enums/ESmartHousePreset.cs
137
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AreaEffectData : IScriptable { [Ordinal(0)] [RED("action")] public CHandle<ScriptableDeviceAction> Action { get; set; } [Ordinal(1)] [RED("actionRecordID")] public TweakDBID ActionRecordID { get; set; } [Ordinal(2)] [RED("additionaStimSources")] public CArray<NodeRef> AdditionaStimSources { get; set; } [Ordinal(3)] [RED("areaEffectID")] public CName AreaEffectID { get; set; } [Ordinal(4)] [RED("controllerSource")] public NodeRef ControllerSource { get; set; } [Ordinal(5)] [RED("effectInstance")] public CHandle<gameEffectInstance> EffectInstance { get; set; } [Ordinal(6)] [RED("gameEffectOverrideName")] public CName GameEffectOverrideName { get; set; } [Ordinal(7)] [RED("highlightPriority")] public CEnum<EPriority> HighlightPriority { get; set; } [Ordinal(8)] [RED("highlightTargets")] public CBool HighlightTargets { get; set; } [Ordinal(9)] [RED("highlightType")] public CEnum<EFocusForcedHighlightType> HighlightType { get; set; } [Ordinal(10)] [RED("indicatorEffectName")] public CName IndicatorEffectName { get; set; } [Ordinal(11)] [RED("indicatorEffectSize")] public CFloat IndicatorEffectSize { get; set; } [Ordinal(12)] [RED("investigateController")] public CBool InvestigateController { get; set; } [Ordinal(13)] [RED("investigateSpot")] public NodeRef InvestigateSpot { get; set; } [Ordinal(14)] [RED("outlineType")] public CEnum<EFocusOutlineType> OutlineType { get; set; } [Ordinal(15)] [RED("stimLifetime")] public CFloat StimLifetime { get; set; } [Ordinal(16)] [RED("stimRange")] public CFloat StimRange { get; set; } [Ordinal(17)] [RED("stimSource")] public NodeRef StimSource { get; set; } [Ordinal(18)] [RED("stimType")] public CEnum<DeviceStimType> StimType { get; set; } [Ordinal(19)] [RED("useIndicatorEffect")] public CBool UseIndicatorEffect { get; set; } public AreaEffectData(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
61.257143
107
0.701493
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/AreaEffectData.cs
2,110
C#
using System; using System.Collections.Generic; using System.Text; namespace HoneyComb.MessageBroker { public sealed class MessageAttribute : Attribute { public string Exchange { get; } public string RoutingKey { get; } public string Queue { get; } public bool External { get; } public MessageAttribute(string exchange = null, string routingKey = null, string queue = null, bool external = false) { Exchange = exchange; RoutingKey = routingKey; Queue = queue; External = external; } } }
25.75
102
0.600324
[ "MIT" ]
MagdalenaHylinskaSKK/HoneyComb
src/HoneyComb.MessageBroker/MessageAttribute.cs
620
C#
using System; using System.Globalization; namespace cloudscribe.Syndication.Models.Atom { public class AtomIcon { public AtomIcon() { } /// <summary> /// Initializes a new instance of the <see cref="AtomIcon"/> class using the supplied <see cref="Uri"/>. /// <param name="uri">A <see cref="Uri"/> that represents a Internationalized Resource Identifier (IRI) that identifies an image that provides iconic visual identification for this feed.</param> /// </summary> /// <exception cref="ArgumentNullException">The <paramref name="uri"/> is a null reference (Nothing in Visual Basic).</exception> public AtomIcon(Uri uri) { this.Uri = uri; } private Uri commonObjectBaseUri; /// <summary> /// Gets or sets the base URI other than the base URI of the document or external entity. /// </summary> /// <value>A <see cref="Uri"/> that represents a base URI other than the base URI of the document or external entity. The default value is a <b>null</b> reference.</value> /// <remarks> /// <para> /// The value of this property is interpreted as a URI Reference as defined in <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396: Uniform Resource Identifiers</a>, /// after processing according to <a href="http://www.w3.org/TR/xmlbase/#escaping">XML Base, Section 3.1 (URI Reference Encoding and Escaping)</a>.</para> /// </remarks> public Uri BaseUri { get { return commonObjectBaseUri; } set { commonObjectBaseUri = value; } } private CultureInfo commonObjectLanguage; /// <summary> /// Gets or sets the natural or formal language in which the content is written. /// </summary> /// <value>A <see cref="CultureInfo"/> that represents the natural or formal language in which the content is written. The default value is a <b>null</b> reference.</value> /// <remarks> /// <para> /// The value of this property is a language identifier as defined by <a href="http://www.ietf.org/rfc/rfc3066.txt">RFC 3066: Tags for the Identification of Languages</a>, or its successor. /// </para> /// </remarks> public CultureInfo Language { get { return commonObjectLanguage; } set { commonObjectLanguage = value; } } private Uri iconUri; /// <summary> /// Gets or sets an IRI that identifies an image that provides iconic visual identification for this feed. /// </summary> /// <value>A <see cref="Uri"/> that represents a Internationalized Resource Identifier (IRI) that identifies an image that provides iconic visual identification for this feed.</value> /// <remarks> /// <para>See <a href="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987: Internationalized Resource Identifiers</a> for the IRI technical specification.</para> /// <para>See <a href="http://msdn2.microsoft.com/en-us/library/system.uri.aspx">System.Uri</a> for enabling support for IRIs within Microsoft .NET framework applications.</para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="value"/> is a null reference (Nothing in Visual Basic).</exception> public Uri Uri { get { return iconUri; } set { Guard.ArgumentNotNull(value, "value"); iconUri = value; } } } }
40.291667
205
0.575491
[ "Apache-2.0" ]
cloudscribe/cloudscribe.Syndication
src/cloudscribe.Syndication/Models/Atom/AtomIcon.cs
3,870
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> //------------------------------------------------------------------------------ using Bright.Serialization; using System.Collections.Generic; using SimpleJSON; namespace cfg.test { public sealed partial class TbTestSet { private readonly Dictionary<int, test.TestSet> _dataMap; private readonly List<test.TestSet> _dataList; public TbTestSet(JSONNode _json) { _dataMap = new Dictionary<int, test.TestSet>(); _dataList = new List<test.TestSet>(); foreach(JSONNode _row in _json.Children) { var _v = test.TestSet.DeserializeTestSet(_row); _dataList.Add(_v); _dataMap.Add(_v.Id, _v); } PostInit(); } public Dictionary<int, test.TestSet> DataMap => _dataMap; public List<test.TestSet> DataList => _dataList; public test.TestSet GetOrDefault(int key) => _dataMap.TryGetValue(key, out var v) ? v : null; public test.TestSet Get(int key) => _dataMap[key]; public test.TestSet this[int key] => _dataMap[key]; public void Resolve(Dictionary<string, object> _tables) { foreach(var v in _dataList) { v.Resolve(_tables); } PostResolve(); } public void TranslateText(System.Func<string, string, string> translator) { foreach(var v in _dataList) { v.TranslateText(translator); } } partial void PostInit(); partial void PostResolve(); } }
27.169231
97
0.56795
[ "MIT" ]
HFX-93/luban_examples
Projects/Csharp_Unity_json/Assets/Gen/test/TbTestSet.cs
1,766
C#
namespace Application.UnitTests.Items.Commands { using System; using System.Threading; using System.Threading.Tasks; using Application.Items.Commands.DeleteItem; using Common.Exceptions; using Common.Interfaces; using FluentAssertions; using MediatR; using Microsoft.EntityFrameworkCore; using Moq; using Setup; using Xunit; public class DeleteItemCommandHandlerTests : CommandTestBase { private readonly Mock<ICurrentUserService> currentUserServiceMock; private readonly Mock<IMediator> mediatorMock; private readonly DeleteItemCommandHandler handler; public DeleteItemCommandHandlerTests() { this.currentUserServiceMock = new Mock<ICurrentUserService>(); this.currentUserServiceMock .Setup(x => x.UserId) .Returns(DataConstants.SampleUserId); this.mediatorMock = new Mock<IMediator>(); this.handler = new DeleteItemCommandHandler(this.Context, this.currentUserServiceMock.Object, this.mediatorMock.Object); } [Theory] [InlineData("0d0942f7-7ad3-4195-b712-c63d9a2cea30")] [InlineData("8d3cc00e-7f8d-4da8-9a85-088acf728487")] [InlineData("833eb36a-ea38-45e8-ae1c-a52caca13c56")] public async Task Handle_Given_InvalidId_Should_Throw_NotFoundException(string id) { var command = new DeleteItemCommand(Guid.Parse(id)); await Assert.ThrowsAsync<NotFoundException>(() => this.handler.Handle(command, CancellationToken.None)); } [Fact] public async Task Handle_Given_ValidId_Should_Not_ThrowException_And_Should_DeleteItemFromDatabase() { var oldCount = await this.Context.Items.CountAsync(); var command = new DeleteItemCommand(DataConstants.SampleItemId); await this.handler.Handle(command, CancellationToken.None); var newCount = await this.Context.Items.CountAsync(); newCount .Should() .Be(oldCount - 1); } } }
36.655172
121
0.664628
[ "MIT" ]
DigitalSeas-Tech/AuctionSystem
Tests/Application.UnitTests/Items/Commands/DeleteItemCommandHandlerTests.cs
2,128
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AssetStudio { public class Hash128 { public byte[] bytes; public Hash128(BinaryReader reader) { bytes = reader.ReadBytes(16); } } public class StructParameter { public MatrixParameter[] m_MatrixParams; public VectorParameter[] m_VectorParams; public StructParameter(BinaryReader reader) { var m_NameIndex = reader.ReadInt32(); var m_Index = reader.ReadInt32(); var m_ArraySize = reader.ReadInt32(); var m_StructSize = reader.ReadInt32(); int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } } } public class SamplerParameter { public uint sampler; public int bindPoint; public SamplerParameter(BinaryReader reader) { sampler = reader.ReadUInt32(); bindPoint = reader.ReadInt32(); } } public enum TextureDimension { kTexDimUnknown = -1, kTexDimNone = 0, kTexDimAny = 1, kTexDim2D = 2, kTexDim3D = 3, kTexDimCUBE = 4, kTexDim2DArray = 5, kTexDimCubeArray = 6, kTexDimForce32Bit = 2147483647 }; public class SerializedTextureProperty { public string m_DefaultName; public TextureDimension m_TexDim; public SerializedTextureProperty(BinaryReader reader) { m_DefaultName = reader.ReadAlignedString(); m_TexDim = (TextureDimension)reader.ReadInt32(); } } public enum SerializedPropertyType { kColor = 0, kVector = 1, kFloat = 2, kRange = 3, kTexture = 4 }; public class SerializedProperty { public string m_Name; public string m_Description; public string[] m_Attributes; public SerializedPropertyType m_Type; public uint m_Flags; public float[] m_DefValue; public SerializedTextureProperty m_DefTexture; public SerializedProperty(BinaryReader reader) { m_Name = reader.ReadAlignedString(); m_Description = reader.ReadAlignedString(); m_Attributes = reader.ReadStringArray(); m_Type = (SerializedPropertyType)reader.ReadInt32(); m_Flags = reader.ReadUInt32(); m_DefValue = reader.ReadSingleArray(4); m_DefTexture = new SerializedTextureProperty(reader); } } public class SerializedProperties { public SerializedProperty[] m_Props; public SerializedProperties(BinaryReader reader) { int numProps = reader.ReadInt32(); m_Props = new SerializedProperty[numProps]; for (int i = 0; i < numProps; i++) { m_Props[i] = new SerializedProperty(reader); } } } public class SerializedShaderFloatValue { public float val; public string name; public SerializedShaderFloatValue(BinaryReader reader) { val = reader.ReadSingle(); name = reader.ReadAlignedString(); } } public class SerializedShaderRTBlendState { public SerializedShaderFloatValue srcBlend; public SerializedShaderFloatValue destBlend; public SerializedShaderFloatValue srcBlendAlpha; public SerializedShaderFloatValue destBlendAlpha; public SerializedShaderFloatValue blendOp; public SerializedShaderFloatValue blendOpAlpha; public SerializedShaderFloatValue colMask; public SerializedShaderRTBlendState(BinaryReader reader) { srcBlend = new SerializedShaderFloatValue(reader); destBlend = new SerializedShaderFloatValue(reader); srcBlendAlpha = new SerializedShaderFloatValue(reader); destBlendAlpha = new SerializedShaderFloatValue(reader); blendOp = new SerializedShaderFloatValue(reader); blendOpAlpha = new SerializedShaderFloatValue(reader); colMask = new SerializedShaderFloatValue(reader); } } public class SerializedStencilOp { public SerializedShaderFloatValue pass; public SerializedShaderFloatValue fail; public SerializedShaderFloatValue zFail; public SerializedShaderFloatValue comp; public SerializedStencilOp(BinaryReader reader) { pass = new SerializedShaderFloatValue(reader); fail = new SerializedShaderFloatValue(reader); zFail = new SerializedShaderFloatValue(reader); comp = new SerializedShaderFloatValue(reader); } } public class SerializedShaderVectorValue { public SerializedShaderFloatValue x; public SerializedShaderFloatValue y; public SerializedShaderFloatValue z; public SerializedShaderFloatValue w; public string name; public SerializedShaderVectorValue(BinaryReader reader) { x = new SerializedShaderFloatValue(reader); y = new SerializedShaderFloatValue(reader); z = new SerializedShaderFloatValue(reader); w = new SerializedShaderFloatValue(reader); name = reader.ReadAlignedString(); } } public enum FogMode { kFogUnknown = -1, kFogDisabled = 0, kFogLinear = 1, kFogExp = 2, kFogExp2 = 3 }; public class SerializedShaderState { public string m_Name; public SerializedShaderRTBlendState[] rtBlend; public bool rtSeparateBlend; public SerializedShaderFloatValue zClip; public SerializedShaderFloatValue zTest; public SerializedShaderFloatValue zWrite; public SerializedShaderFloatValue culling; public SerializedShaderFloatValue conservative; public SerializedShaderFloatValue offsetFactor; public SerializedShaderFloatValue offsetUnits; public SerializedShaderFloatValue alphaToMask; public SerializedStencilOp stencilOp; public SerializedStencilOp stencilOpFront; public SerializedStencilOp stencilOpBack; public SerializedShaderFloatValue stencilReadMask; public SerializedShaderFloatValue stencilWriteMask; public SerializedShaderFloatValue stencilRef; public SerializedShaderFloatValue fogStart; public SerializedShaderFloatValue fogEnd; public SerializedShaderFloatValue fogDensity; public SerializedShaderVectorValue fogColor; public FogMode fogMode; public int gpuProgramID; public SerializedTagMap m_Tags; public int m_LOD; public bool lighting; public SerializedShaderState(ObjectReader reader) { var version = reader.version; m_Name = reader.ReadAlignedString(); rtBlend = new SerializedShaderRTBlendState[8]; for (int i = 0; i < 8; i++) { rtBlend[i] = new SerializedShaderRTBlendState(reader); } rtSeparateBlend = reader.ReadBoolean(); reader.AlignStream(); if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up { zClip = new SerializedShaderFloatValue(reader); } zTest = new SerializedShaderFloatValue(reader); zWrite = new SerializedShaderFloatValue(reader); culling = new SerializedShaderFloatValue(reader); if (version[0] >= 2020) //2020.1 and up { conservative = new SerializedShaderFloatValue(reader); } offsetFactor = new SerializedShaderFloatValue(reader); offsetUnits = new SerializedShaderFloatValue(reader); alphaToMask = new SerializedShaderFloatValue(reader); stencilOp = new SerializedStencilOp(reader); stencilOpFront = new SerializedStencilOp(reader); stencilOpBack = new SerializedStencilOp(reader); stencilReadMask = new SerializedShaderFloatValue(reader); stencilWriteMask = new SerializedShaderFloatValue(reader); stencilRef = new SerializedShaderFloatValue(reader); fogStart = new SerializedShaderFloatValue(reader); fogEnd = new SerializedShaderFloatValue(reader); fogDensity = new SerializedShaderFloatValue(reader); fogColor = new SerializedShaderVectorValue(reader); fogMode = (FogMode)reader.ReadInt32(); gpuProgramID = reader.ReadInt32(); m_Tags = new SerializedTagMap(reader); m_LOD = reader.ReadInt32(); lighting = reader.ReadBoolean(); reader.AlignStream(); } } public class ShaderBindChannel { public sbyte source; public sbyte target; public ShaderBindChannel(BinaryReader reader) { source = reader.ReadSByte(); target = reader.ReadSByte(); } } public class ParserBindChannels { public ShaderBindChannel[] m_Channels; public uint m_SourceMap; public ParserBindChannels(BinaryReader reader) { int numChannels = reader.ReadInt32(); m_Channels = new ShaderBindChannel[numChannels]; for (int i = 0; i < numChannels; i++) { m_Channels[i] = new ShaderBindChannel(reader); } reader.AlignStream(); m_SourceMap = reader.ReadUInt32(); } } public class VectorParameter { public int m_NameIndex; public int m_Index; public int m_ArraySize; public sbyte m_Type; public sbyte m_Dim; public VectorParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_ArraySize = reader.ReadInt32(); m_Type = reader.ReadSByte(); m_Dim = reader.ReadSByte(); reader.AlignStream(); } } public class MatrixParameter { public int m_NameIndex; public int m_Index; public int m_ArraySize; public sbyte m_Type; public sbyte m_RowCount; public MatrixParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_ArraySize = reader.ReadInt32(); m_Type = reader.ReadSByte(); m_RowCount = reader.ReadSByte(); reader.AlignStream(); } } public class TextureParameter { public int m_NameIndex; public int m_Index; public int m_SamplerIndex; public sbyte m_Dim; public TextureParameter(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_SamplerIndex = reader.ReadInt32(); if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3)) //2017.3 and up { var m_MultiSampled = reader.ReadBoolean(); } m_Dim = reader.ReadSByte(); reader.AlignStream(); } } public class BufferBinding { public int m_NameIndex; public int m_Index; public int m_ArraySize; public BufferBinding(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); if (version[0] >= 2020) //2020.1 and up { m_ArraySize = reader.ReadInt32(); } } } public class ConstantBuffer { public int m_NameIndex; public MatrixParameter[] m_MatrixParams; public VectorParameter[] m_VectorParams; public StructParameter[] m_StructParams; public int m_Size; public bool m_IsPartialCB; public ConstantBuffer(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3)) //2017.3 and up { int numStructParams = reader.ReadInt32(); m_StructParams = new StructParameter[numStructParams]; for (int i = 0; i < numStructParams; i++) { m_StructParams[i] = new StructParameter(reader); } } m_Size = reader.ReadInt32(); if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up { m_IsPartialCB = reader.ReadBoolean(); reader.AlignStream(); } } } public class UAVParameter { public int m_NameIndex; public int m_Index; public int m_OriginalIndex; public UAVParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_OriginalIndex = reader.ReadInt32(); } } public enum ShaderGpuProgramType { kShaderGpuProgramUnknown = 0, kShaderGpuProgramGLLegacy = 1, kShaderGpuProgramGLES31AEP = 2, kShaderGpuProgramGLES31 = 3, kShaderGpuProgramGLES3 = 4, kShaderGpuProgramGLES = 5, kShaderGpuProgramGLCore32 = 6, kShaderGpuProgramGLCore41 = 7, kShaderGpuProgramGLCore43 = 8, kShaderGpuProgramDX9VertexSM20 = 9, kShaderGpuProgramDX9VertexSM30 = 10, kShaderGpuProgramDX9PixelSM20 = 11, kShaderGpuProgramDX9PixelSM30 = 12, kShaderGpuProgramDX10Level9Vertex = 13, kShaderGpuProgramDX10Level9Pixel = 14, kShaderGpuProgramDX11VertexSM40 = 15, kShaderGpuProgramDX11VertexSM50 = 16, kShaderGpuProgramDX11PixelSM40 = 17, kShaderGpuProgramDX11PixelSM50 = 18, kShaderGpuProgramDX11GeometrySM40 = 19, kShaderGpuProgramDX11GeometrySM50 = 20, kShaderGpuProgramDX11HullSM50 = 21, kShaderGpuProgramDX11DomainSM50 = 22, kShaderGpuProgramMetalVS = 23, kShaderGpuProgramMetalFS = 24, kShaderGpuProgramSPIRV = 25, kShaderGpuProgramConsoleVS = 26, kShaderGpuProgramConsoleFS = 27, kShaderGpuProgramConsoleHS = 28, kShaderGpuProgramConsoleDS = 29, kShaderGpuProgramConsoleGS = 30, kShaderGpuProgramRayTracing = 31, }; public class SerializedProgramParameters { public VectorParameter[] m_VectorParams; public MatrixParameter[] m_MatrixParams; public TextureParameter[] m_TextureParams; public BufferBinding[] m_BufferParams; public ConstantBuffer[] m_ConstantBuffers; public BufferBinding[] m_ConstantBufferBindings; public UAVParameter[] m_UAVParams; public SamplerParameter[] m_Samplers; public SerializedProgramParameters(ObjectReader reader) { int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numTextureParams = reader.ReadInt32(); m_TextureParams = new TextureParameter[numTextureParams]; for (int i = 0; i < numTextureParams; i++) { m_TextureParams[i] = new TextureParameter(reader); } int numBufferParams = reader.ReadInt32(); m_BufferParams = new BufferBinding[numBufferParams]; for (int i = 0; i < numBufferParams; i++) { m_BufferParams[i] = new BufferBinding(reader); } int numConstantBuffers = reader.ReadInt32(); m_ConstantBuffers = new ConstantBuffer[numConstantBuffers]; for (int i = 0; i < numConstantBuffers; i++) { m_ConstantBuffers[i] = new ConstantBuffer(reader); } int numConstantBufferBindings = reader.ReadInt32(); m_ConstantBufferBindings = new BufferBinding[numConstantBufferBindings]; for (int i = 0; i < numConstantBufferBindings; i++) { m_ConstantBufferBindings[i] = new BufferBinding(reader); } int numUAVParams = reader.ReadInt32(); m_UAVParams = new UAVParameter[numUAVParams]; for (int i = 0; i < numUAVParams; i++) { m_UAVParams[i] = new UAVParameter(reader); } int numSamplers = reader.ReadInt32(); m_Samplers = new SamplerParameter[numSamplers]; for (int i = 0; i < numSamplers; i++) { m_Samplers[i] = new SamplerParameter(reader); } } } public class SerializedSubProgram { public uint m_BlobIndex; public ParserBindChannels m_Channels; public ushort[] m_KeywordIndices; public sbyte m_ShaderHardwareTier; public ShaderGpuProgramType m_GpuProgramType; public SerializedProgramParameters m_Parameters; public VectorParameter[] m_VectorParams; public MatrixParameter[] m_MatrixParams; public TextureParameter[] m_TextureParams; public BufferBinding[] m_BufferParams; public ConstantBuffer[] m_ConstantBuffers; public BufferBinding[] m_ConstantBufferBindings; public UAVParameter[] m_UAVParams; public SamplerParameter[] m_Samplers; public SerializedSubProgram(ObjectReader reader) { var version = reader.version; m_BlobIndex = reader.ReadUInt32(); m_Channels = new ParserBindChannels(reader); if ((version[0] >= 2019 && version[0] < 2021) || (version[0] == 2021 && version[1] < 2)) //2019 ~2021.1 { var m_GlobalKeywordIndices = reader.ReadUInt16Array(); reader.AlignStream(); var m_LocalKeywordIndices = reader.ReadUInt16Array(); reader.AlignStream(); } else { m_KeywordIndices = reader.ReadUInt16Array(); if (version[0] >= 2017) //2017 and up { reader.AlignStream(); } } m_ShaderHardwareTier = reader.ReadSByte(); m_GpuProgramType = (ShaderGpuProgramType)reader.ReadSByte(); reader.AlignStream(); if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up { m_Parameters = new SerializedProgramParameters(reader); } else { int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numTextureParams = reader.ReadInt32(); m_TextureParams = new TextureParameter[numTextureParams]; for (int i = 0; i < numTextureParams; i++) { m_TextureParams[i] = new TextureParameter(reader); } int numBufferParams = reader.ReadInt32(); m_BufferParams = new BufferBinding[numBufferParams]; for (int i = 0; i < numBufferParams; i++) { m_BufferParams[i] = new BufferBinding(reader); } int numConstantBuffers = reader.ReadInt32(); m_ConstantBuffers = new ConstantBuffer[numConstantBuffers]; for (int i = 0; i < numConstantBuffers; i++) { m_ConstantBuffers[i] = new ConstantBuffer(reader); } int numConstantBufferBindings = reader.ReadInt32(); m_ConstantBufferBindings = new BufferBinding[numConstantBufferBindings]; for (int i = 0; i < numConstantBufferBindings; i++) { m_ConstantBufferBindings[i] = new BufferBinding(reader); } int numUAVParams = reader.ReadInt32(); m_UAVParams = new UAVParameter[numUAVParams]; for (int i = 0; i < numUAVParams; i++) { m_UAVParams[i] = new UAVParameter(reader); } if (version[0] >= 2017) //2017 and up { int numSamplers = reader.ReadInt32(); m_Samplers = new SamplerParameter[numSamplers]; for (int i = 0; i < numSamplers; i++) { m_Samplers[i] = new SamplerParameter(reader); } } } if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up { if (version[0] >= 2021) //2021.1 and up { var m_ShaderRequirements = reader.ReadInt64(); } else { var m_ShaderRequirements = reader.ReadInt32(); } } } } public class SerializedProgram { public SerializedSubProgram[] m_SubPrograms; public SerializedProgramParameters m_CommonParameters; public SerializedProgram(ObjectReader reader) { var version = reader.version; int numSubPrograms = reader.ReadInt32(); m_SubPrograms = new SerializedSubProgram[numSubPrograms]; for (int i = 0; i < numSubPrograms; i++) { m_SubPrograms[i] = new SerializedSubProgram(reader); } if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 4)) //2021.1.4f1 and up { m_CommonParameters = new SerializedProgramParameters(reader); } } } public enum PassType { kPassTypeNormal = 0, kPassTypeUse = 1, kPassTypeGrab = 2 }; public class SerializedPass { public Hash128[] m_EditorDataHash; public byte[] m_Platforms; public ushort[] m_LocalKeywordMask; public ushort[] m_GlobalKeywordMask; public KeyValuePair<string, int>[] m_NameIndices; public PassType m_Type; public SerializedShaderState m_State; public uint m_ProgramMask; public SerializedProgram progVertex; public SerializedProgram progFragment; public SerializedProgram progGeometry; public SerializedProgram progHull; public SerializedProgram progDomain; public SerializedProgram progRayTracing; public bool m_HasInstancingVariant; public string m_UseName; public string m_Name; public string m_TextureName; public SerializedTagMap m_Tags; public ushort[] m_SerializedKeywordStateMask; public SerializedPass(ObjectReader reader) { var version = reader.version; if (version[0] > 2020 || (version[0] == 2020 && version[1] >= 2)) //2020.2 and up { int numEditorDataHash = reader.ReadInt32(); m_EditorDataHash = new Hash128[numEditorDataHash]; for (int i = 0; i < numEditorDataHash; i++) { m_EditorDataHash[i] = new Hash128(reader); } reader.AlignStream(); m_Platforms = reader.ReadUInt8Array(); reader.AlignStream(); if (version[0] < 2021 || (version[0] == 2021 && version[1] < 2)) //2021.1 and down { m_LocalKeywordMask = reader.ReadUInt16Array(); reader.AlignStream(); m_GlobalKeywordMask = reader.ReadUInt16Array(); reader.AlignStream(); } } int numIndices = reader.ReadInt32(); m_NameIndices = new KeyValuePair<string, int>[numIndices]; for (int i = 0; i < numIndices; i++) { m_NameIndices[i] = new KeyValuePair<string, int>(reader.ReadAlignedString(), reader.ReadInt32()); } m_Type = (PassType)reader.ReadInt32(); m_State = new SerializedShaderState(reader); m_ProgramMask = reader.ReadUInt32(); progVertex = new SerializedProgram(reader); progFragment = new SerializedProgram(reader); progGeometry = new SerializedProgram(reader); progHull = new SerializedProgram(reader); progDomain = new SerializedProgram(reader); if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up { progRayTracing = new SerializedProgram(reader); } m_HasInstancingVariant = reader.ReadBoolean(); if (version[0] >= 2018) //2018 and up { var m_HasProceduralInstancingVariant = reader.ReadBoolean(); } reader.AlignStream(); m_UseName = reader.ReadAlignedString(); m_Name = reader.ReadAlignedString(); m_TextureName = reader.ReadAlignedString(); m_Tags = new SerializedTagMap(reader); if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 2)) //2021.2 and up { m_SerializedKeywordStateMask = reader.ReadUInt16Array(); reader.AlignStream(); } } } public class SerializedTagMap { public KeyValuePair<string, string>[] tags; public SerializedTagMap(BinaryReader reader) { int numTags = reader.ReadInt32(); tags = new KeyValuePair<string, string>[numTags]; for (int i = 0; i < numTags; i++) { tags[i] = new KeyValuePair<string, string>(reader.ReadAlignedString(), reader.ReadAlignedString()); } } } public class SerializedSubShader { public SerializedPass[] m_Passes; public SerializedTagMap m_Tags; public int m_LOD; public SerializedSubShader(ObjectReader reader) { int numPasses = reader.ReadInt32(); m_Passes = new SerializedPass[numPasses]; for (int i = 0; i < numPasses; i++) { m_Passes[i] = new SerializedPass(reader); } m_Tags = new SerializedTagMap(reader); m_LOD = reader.ReadInt32(); } } public class SerializedShaderDependency { public string from; public string to; public SerializedShaderDependency(BinaryReader reader) { from = reader.ReadAlignedString(); to = reader.ReadAlignedString(); } } public class SerializedCustomEditorForRenderPipeline { public string customEditorName; public string renderPipelineType; public SerializedCustomEditorForRenderPipeline(BinaryReader reader) { customEditorName = reader.ReadAlignedString(); renderPipelineType = reader.ReadAlignedString(); } } public class SerializedShader { public SerializedProperties m_PropInfo; public SerializedSubShader[] m_SubShaders; public string[] m_KeywordNames; public byte[] m_KeywordFlags; public string m_Name; public string m_CustomEditorName; public string m_FallbackName; public SerializedShaderDependency[] m_Dependencies; public SerializedCustomEditorForRenderPipeline[] m_CustomEditorForRenderPipelines; public bool m_DisableNoSubshadersMessage; public SerializedShader(ObjectReader reader) { var version = reader.version; m_PropInfo = new SerializedProperties(reader); int numSubShaders = reader.ReadInt32(); m_SubShaders = new SerializedSubShader[numSubShaders]; for (int i = 0; i < numSubShaders; i++) { m_SubShaders[i] = new SerializedSubShader(reader); } if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 2)) //2021.2 and up { m_KeywordNames = reader.ReadStringArray(); m_KeywordFlags = reader.ReadUInt8Array(); reader.AlignStream(); } m_Name = reader.ReadAlignedString(); m_CustomEditorName = reader.ReadAlignedString(); m_FallbackName = reader.ReadAlignedString(); int numDependencies = reader.ReadInt32(); m_Dependencies = new SerializedShaderDependency[numDependencies]; for (int i = 0; i < numDependencies; i++) { m_Dependencies[i] = new SerializedShaderDependency(reader); } if (version[0] >= 2021) //2021.1 and up { int m_CustomEditorForRenderPipelinesSize = reader.ReadInt32(); m_CustomEditorForRenderPipelines = new SerializedCustomEditorForRenderPipeline[m_CustomEditorForRenderPipelinesSize]; for (int i = 0; i < m_CustomEditorForRenderPipelinesSize; i++) { m_CustomEditorForRenderPipelines[i] = new SerializedCustomEditorForRenderPipeline(reader); } } m_DisableNoSubshadersMessage = reader.ReadBoolean(); reader.AlignStream(); } } public enum ShaderCompilerPlatform { kShaderCompPlatformNone = -1, kShaderCompPlatformGL = 0, kShaderCompPlatformD3D9 = 1, kShaderCompPlatformXbox360 = 2, kShaderCompPlatformPS3 = 3, kShaderCompPlatformD3D11 = 4, kShaderCompPlatformGLES20 = 5, kShaderCompPlatformNaCl = 6, kShaderCompPlatformFlash = 7, kShaderCompPlatformD3D11_9x = 8, kShaderCompPlatformGLES3Plus = 9, kShaderCompPlatformPSP2 = 10, kShaderCompPlatformPS4 = 11, kShaderCompPlatformXboxOne = 12, kShaderCompPlatformPSM = 13, kShaderCompPlatformMetal = 14, kShaderCompPlatformOpenGLCore = 15, kShaderCompPlatformN3DS = 16, kShaderCompPlatformWiiU = 17, kShaderCompPlatformVulkan = 18, kShaderCompPlatformSwitch = 19, kShaderCompPlatformXboxOneD3D12 = 20, kShaderCompPlatformGameCoreXboxOne = 21, kShaderCompPlatformGameCoreScarlett = 22, kShaderCompPlatformPS5 = 23, kShaderCompPlatformPS5NGGC = 24, }; public class Shader : NamedObject { public byte[] m_Script; //5.3 - 5.4 public uint decompressedSize; public byte[] m_SubProgramBlob; //5.5 and up public SerializedShader m_ParsedForm; public ShaderCompilerPlatform[] platforms; public uint[][] offsets; public uint[][] compressedLengths; public uint[][] decompressedLengths; public byte[] compressedBlob; public Shader(ObjectReader reader) : base(reader) { if (version[0] == 5 && version[1] >= 5 || version[0] > 5) //5.5 and up { m_ParsedForm = new SerializedShader(reader); platforms = reader.ReadUInt32Array().Select(x => (ShaderCompilerPlatform)x).ToArray(); if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up { offsets = reader.ReadUInt32ArrayArray(); compressedLengths = reader.ReadUInt32ArrayArray(); decompressedLengths = reader.ReadUInt32ArrayArray(); } else { offsets = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); compressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); decompressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); } compressedBlob = reader.ReadUInt8Array(); if (BitConverter.ToInt32(compressedBlob, 0) == -1) compressedBlob = reader.ReadUInt8Array(); var m_DependenciesCount = reader.ReadInt32(); for (int i = 0; i < m_DependenciesCount; i++) { new PPtr<Shader>(reader); } if (version[0] >= 2018) { var m_NonModifiableTexturesCount = reader.ReadInt32(); for (int i = 0; i < m_NonModifiableTexturesCount; i++) { var first = reader.ReadAlignedString(); new PPtr<Texture>(reader); } } var m_ShaderIsBaked = reader.ReadBoolean(); reader.AlignStream(); } else { m_Script = reader.ReadUInt8Array(); reader.AlignStream(); var m_PathName = reader.ReadAlignedString(); if (version[0] == 5 && version[1] >= 3) //5.3 - 5.4 { decompressedSize = reader.ReadUInt32(); m_SubProgramBlob = reader.ReadUInt8Array(); } } } } }
35.60274
133
0.571236
[ "MIT" ]
Razmoth/AssetStudio-CAB
AssetStudio/Classes/Shader.cs
36,388
C#
using NuGet.Versioning; using Xunit; using System.Collections.Generic; namespace DotNetOutdated.Test { public class NuGetClientTest { [Theory, MemberData("TestData")] public async void ShouldParseNuGetResponse(string packageName, IEnumerable<SemanticVersion> versions) { var client = new FileSystemNuGetClient(); var package = await client.GetPackageInfo(packageName); Assert.Equal(packageName, package.Name); Assert.Equal(versions, package.Versions); } public static IEnumerable<object[]> TestData { get { return new[] { new object[] { "SharpSapRfc", new List<SemanticVersion> { SemanticVersion.Parse("2.0.10"), SemanticVersion.Parse("2.0.9"), SemanticVersion.Parse("2.0.8"), SemanticVersion.Parse("2.0.5"), SemanticVersion.Parse("2.0.4"), SemanticVersion.Parse("2.0.3"), SemanticVersion.Parse("2.0.2"), SemanticVersion.Parse("2.0.1"), SemanticVersion.Parse("2.0.0") } }, new object[] { "Serilog", new List<SemanticVersion> { SemanticVersion.Parse("2.4.0-dev-00746"), SemanticVersion.Parse("2.4.0-dev-00739"), SemanticVersion.Parse("2.4.0-dev-00736"), SemanticVersion.Parse("2.4.0-dev-00733"), SemanticVersion.Parse("2.4.0-dev-00730"), SemanticVersion.Parse("2.4.0-dev-00728"), SemanticVersion.Parse("2.4.0-dev-00723"), SemanticVersion.Parse("2.3.0"), SemanticVersion.Parse("2.3.0-dev-00719"), SemanticVersion.Parse("2.3.0-dev-00711"), SemanticVersion.Parse("2.3.0-dev-00707"), SemanticVersion.Parse("2.3.0-dev-00705"), SemanticVersion.Parse("2.3.0-dev-00704"), SemanticVersion.Parse("2.2.1"), SemanticVersion.Parse("2.2.1-dev-00697"), SemanticVersion.Parse("2.2.0"), SemanticVersion.Parse("2.2.0-dev-00693"), SemanticVersion.Parse("2.2.0-dev-00690"), SemanticVersion.Parse("2.2.0-dev-00688"), SemanticVersion.Parse("2.1.1-dev-00686"), SemanticVersion.Parse("2.1.1-dev-00680"), SemanticVersion.Parse("2.1.0"), SemanticVersion.Parse("2.1.0-dev-00674"), SemanticVersion.Parse("2.1.0-dev-00670"), SemanticVersion.Parse("2.1.0-dev-00668"), SemanticVersion.Parse("2.1.0-dev-00666"), SemanticVersion.Parse("2.0.1-dev-00665"), SemanticVersion.Parse("2.0.0"), SemanticVersion.Parse("2.0.0-rc-640"), SemanticVersion.Parse("2.0.0-rc-634"), SemanticVersion.Parse("2.0.0-rc-633"), SemanticVersion.Parse("2.0.0-rc-628"), SemanticVersion.Parse("2.0.0-rc-622"), SemanticVersion.Parse("2.0.0-rc-621"), SemanticVersion.Parse("2.0.0-rc-619"), SemanticVersion.Parse("2.0.0-rc-618"), SemanticVersion.Parse("2.0.0-rc-606"), SemanticVersion.Parse("2.0.0-rc-602"), SemanticVersion.Parse("2.0.0-rc-600"), SemanticVersion.Parse("2.0.0-rc-598"), SemanticVersion.Parse("2.0.0-rc-596"), SemanticVersion.Parse("2.0.0-rc-594"), SemanticVersion.Parse("2.0.0-rc-587"), SemanticVersion.Parse("2.0.0-rc-577"), SemanticVersion.Parse("2.0.0-rc-576"), SemanticVersion.Parse("2.0.0-rc-573"), SemanticVersion.Parse("2.0.0-rc-563"), SemanticVersion.Parse("2.0.0-rc-556"), SemanticVersion.Parse("2.0.0-beta-541"), SemanticVersion.Parse("2.0.0-beta-537"), SemanticVersion.Parse("2.0.0-beta-533"), SemanticVersion.Parse("2.0.0-beta-531"), SemanticVersion.Parse("2.0.0-beta-530"), SemanticVersion.Parse("2.0.0-beta-523"), SemanticVersion.Parse("2.0.0-beta-521"), SemanticVersion.Parse("2.0.0-beta-519"), SemanticVersion.Parse("2.0.0-beta-516"), SemanticVersion.Parse("2.0.0-beta-513"), SemanticVersion.Parse("2.0.0-beta-511"), SemanticVersion.Parse("2.0.0-beta-509"), SemanticVersion.Parse("2.0.0-beta-507"), SemanticVersion.Parse("2.0.0-beta-505"), SemanticVersion.Parse("2.0.0-beta-502"), SemanticVersion.Parse("2.0.0-beta-499"), SemanticVersion.Parse("2.0.0-beta-495"), SemanticVersion.Parse("2.0.0-beta-494"), SemanticVersion.Parse("2.0.0-beta-493"), SemanticVersion.Parse("2.0.0-beta-487"), SemanticVersion.Parse("2.0.0-beta-486"), SemanticVersion.Parse("2.0.0-beta-479"), SemanticVersion.Parse("2.0.0-beta-478"), SemanticVersion.Parse("2.0.0-beta-465"), SemanticVersion.Parse("2.0.0-beta-456"), SemanticVersion.Parse("2.0.0-beta-450"), SemanticVersion.Parse("2.0.0-beta-449"), SemanticVersion.Parse("2.0.0-beta-432"), SemanticVersion.Parse("2.0.0-beta-423"), SemanticVersion.Parse("2.0.0-beta-418"), SemanticVersion.Parse("2.0.0-beta-416"), SemanticVersion.Parse("2.0.0-beta-403"), SemanticVersion.Parse("2.0.0-beta-395"), SemanticVersion.Parse("1.5.14"), SemanticVersion.Parse("1.5.13"), SemanticVersion.Parse("1.5.12"), SemanticVersion.Parse("1.5.11"), SemanticVersion.Parse("1.5.10"), SemanticVersion.Parse("1.5.9"), SemanticVersion.Parse("1.5.8"), SemanticVersion.Parse("1.5.7"), SemanticVersion.Parse("1.5.6"), SemanticVersion.Parse("1.5.5"), SemanticVersion.Parse("1.5.1"), SemanticVersion.Parse("1.4.214"), SemanticVersion.Parse("1.4.204"), SemanticVersion.Parse("1.4.196"), SemanticVersion.Parse("1.4.182"), SemanticVersion.Parse("1.4.168"), SemanticVersion.Parse("1.4.155"), SemanticVersion.Parse("1.4.154"), SemanticVersion.Parse("1.4.152"), SemanticVersion.Parse("1.4.139"), SemanticVersion.Parse("1.4.128"), SemanticVersion.Parse("1.4.126"), SemanticVersion.Parse("1.4.118"), SemanticVersion.Parse("1.4.113"), SemanticVersion.Parse("1.4.102"), SemanticVersion.Parse("1.4.99"), SemanticVersion.Parse("1.4.97"), SemanticVersion.Parse("1.4.95"), SemanticVersion.Parse("1.4.76"), SemanticVersion.Parse("1.4.75"), SemanticVersion.Parse("1.4.39"), SemanticVersion.Parse("1.4.34"), SemanticVersion.Parse("1.4.28"), SemanticVersion.Parse("1.4.27"), SemanticVersion.Parse("1.4.23"), SemanticVersion.Parse("1.4.22"), SemanticVersion.Parse("1.4.21"), SemanticVersion.Parse("1.4.18"), SemanticVersion.Parse("1.4.17"), SemanticVersion.Parse("1.4.16"), SemanticVersion.Parse("1.4.15"), SemanticVersion.Parse("1.4.14"), SemanticVersion.Parse("1.4.13"), SemanticVersion.Parse("1.4.12"), SemanticVersion.Parse("1.4.11"), SemanticVersion.Parse("1.4.10"), SemanticVersion.Parse("1.4.9"), SemanticVersion.Parse("1.4.8"), SemanticVersion.Parse("1.4.7"), SemanticVersion.Parse("1.4.6"), SemanticVersion.Parse("1.4.5"), SemanticVersion.Parse("1.4.4"), SemanticVersion.Parse("1.4.3"), SemanticVersion.Parse("1.4.2"), SemanticVersion.Parse("1.4.1"), SemanticVersion.Parse("1.3.43"), SemanticVersion.Parse("1.3.42"), SemanticVersion.Parse("1.3.41"), SemanticVersion.Parse("1.3.40"), SemanticVersion.Parse("1.3.39"), SemanticVersion.Parse("1.3.38"), SemanticVersion.Parse("1.3.37"), SemanticVersion.Parse("1.3.36"), SemanticVersion.Parse("1.3.35"), SemanticVersion.Parse("1.3.34"), SemanticVersion.Parse("1.3.33"), SemanticVersion.Parse("1.3.30"), SemanticVersion.Parse("1.3.29"), SemanticVersion.Parse("1.3.28"), SemanticVersion.Parse("1.3.27"), SemanticVersion.Parse("1.3.26"), SemanticVersion.Parse("1.3.25"), SemanticVersion.Parse("1.3.24"), SemanticVersion.Parse("1.3.23"), SemanticVersion.Parse("1.3.20"), SemanticVersion.Parse("1.3.19"), SemanticVersion.Parse("1.3.18"), SemanticVersion.Parse("1.3.17"), SemanticVersion.Parse("1.3.16"), SemanticVersion.Parse("1.3.15"), SemanticVersion.Parse("1.3.14"), SemanticVersion.Parse("1.3.13"), SemanticVersion.Parse("1.3.12"), SemanticVersion.Parse("1.3.7"), SemanticVersion.Parse("1.3.6"), SemanticVersion.Parse("1.3.5"), SemanticVersion.Parse("1.3.4"), SemanticVersion.Parse("1.3.3"), SemanticVersion.Parse("1.3.1"), SemanticVersion.Parse("1.2.53"), SemanticVersion.Parse("1.2.52"), SemanticVersion.Parse("1.2.51"), SemanticVersion.Parse("1.2.50"), SemanticVersion.Parse("1.2.49"), SemanticVersion.Parse("1.2.48"), SemanticVersion.Parse("1.2.47"), SemanticVersion.Parse("1.2.45"), SemanticVersion.Parse("1.2.44"), SemanticVersion.Parse("1.2.41"), SemanticVersion.Parse("1.2.40"), SemanticVersion.Parse("1.2.39"), SemanticVersion.Parse("1.2.38"), SemanticVersion.Parse("1.2.37"), SemanticVersion.Parse("1.2.29"), SemanticVersion.Parse("1.2.27"), SemanticVersion.Parse("1.2.26"), SemanticVersion.Parse("1.2.25"), SemanticVersion.Parse("1.2.8"), SemanticVersion.Parse("1.2.7"), SemanticVersion.Parse("1.2.6"), SemanticVersion.Parse("1.2.5"), SemanticVersion.Parse("1.2.4"), SemanticVersion.Parse("1.2.3"), SemanticVersion.Parse("1.1.2"), SemanticVersion.Parse("1.1.1"), SemanticVersion.Parse("1.0.3"), SemanticVersion.Parse("1.0.2"), SemanticVersion.Parse("1.0.1"), SemanticVersion.Parse("0.9.5"), SemanticVersion.Parse("0.9.4"), SemanticVersion.Parse("0.9.3"), SemanticVersion.Parse("0.9.2"), SemanticVersion.Parse("0.9.1"), SemanticVersion.Parse("0.8.5"), SemanticVersion.Parse("0.8.4"), SemanticVersion.Parse("0.8.3"), SemanticVersion.Parse("0.8.2"), SemanticVersion.Parse("0.8.1"), SemanticVersion.Parse("0.7.2"), SemanticVersion.Parse("0.6.5"), SemanticVersion.Parse("0.6.4"), SemanticVersion.Parse("0.6.3"), SemanticVersion.Parse("0.6.1"), SemanticVersion.Parse("0.5.5"), SemanticVersion.Parse("0.5.4"), SemanticVersion.Parse("0.5.3"), SemanticVersion.Parse("0.5.2"), SemanticVersion.Parse("0.5.1"), SemanticVersion.Parse("0.4.3"), SemanticVersion.Parse("0.3.2"), SemanticVersion.Parse("0.3.1"), SemanticVersion.Parse("0.2.11"), SemanticVersion.Parse("0.2.10"), SemanticVersion.Parse("0.2.9"), SemanticVersion.Parse("0.2.8"), SemanticVersion.Parse("0.2.4"), SemanticVersion.Parse("0.2.3"), SemanticVersion.Parse("0.2.2"), SemanticVersion.Parse("0.2.1"), SemanticVersion.Parse("0.1.18"), SemanticVersion.Parse("0.1.17"), SemanticVersion.Parse("0.1.16"), SemanticVersion.Parse("0.1.12"), SemanticVersion.Parse("0.1.11"), SemanticVersion.Parse("0.1.10"), SemanticVersion.Parse("0.1.9"), SemanticVersion.Parse("0.1.8"), SemanticVersion.Parse("0.1.7"), SemanticVersion.Parse("0.1.6") } }, new object[] { "NLog", new List<SemanticVersion> { SemanticVersion.Parse("4.4.0-betaV15"), SemanticVersion.Parse("4.4.0-betaV14"), SemanticVersion.Parse("4.4.0-beta13"), SemanticVersion.Parse("4.4.0-beta12"), SemanticVersion.Parse("4.4.0-beta11"), SemanticVersion.Parse("4.4.0-beta10"), SemanticVersion.Parse("4.3.6"), SemanticVersion.Parse("4.3.5"), SemanticVersion.Parse("4.3.4"), SemanticVersion.Parse("4.3.3"), SemanticVersion.Parse("4.3.2"), SemanticVersion.Parse("4.3.1"), SemanticVersion.Parse("4.3.0"), SemanticVersion.Parse("4.2.3"), SemanticVersion.Parse("4.2.2"), SemanticVersion.Parse("4.2.1"), SemanticVersion.Parse("4.2.0"), SemanticVersion.Parse("4.1.2"), SemanticVersion.Parse("4.1.1"), SemanticVersion.Parse("4.1.0"), SemanticVersion.Parse("4.0.1"), SemanticVersion.Parse("4.0.0"), SemanticVersion.Parse("3.2.1"), SemanticVersion.Parse("3.2.0"), SemanticVersion.Parse("3.1.0"), SemanticVersion.Parse("3.0.0"), SemanticVersion.Parse("2.1.0") } } }; } } } }
59.232704
109
0.400616
[ "Apache-2.0" ]
flagbug/dotnet-outdated
test/DotNetOutdated.Test/NuGetClientTest.cs
18,836
C#
using System.Linq; namespace World.Square { public class SquareWorld { private SquareCell[] cells; private readonly IntRange bound; private readonly int edge; private readonly int offset; public SquareWorld(int radius) { this.edge = radius * 2 - 1; var cellCount = this.edge * this.edge; int firstX = 1 - radius; int firstY = 1 - radius; this.bound = IntRange.Inclusive(firstX, -firstX); this.offset = 0 - (firstY * this.edge + firstX); this.cells = Enumerable .Range(0, cellCount) .Select(_ => new SquareCell()) .ToArray(); } private int ToAbsoluteCoord(int x, int y) { return this.edge * y + x + this.offset; } public SquareCell GetCell(int x, int y) { if (!this.bound.Contains(x) || !this.bound.Contains(y)) { return null; } var coord = this.ToAbsoluteCoord(x, y); var l = this.cells.Length; if (coord >= 0 && coord < l) { return this.cells[coord]; } return null; } } }
23.381818
67
0.478227
[ "MIT" ]
Perspektyva/EconomySim
World/Square/SquareWorld.cs
1,288
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class TaskMgrApp : PCApp { public RectTransform list; public UITextButton killButton; public TextMeshProUGUI status; private PCAppInfo current; private IEnumerator ieUpdate; public override void StoreCurrentState(EntityData entityData) { // TODO base.StoreCurrentState(entityData); } public override void RestoreCurrentState(EntityData entityData) { // TODO base.RestoreCurrentState(entityData); } private void Awake() { Init(); } protected override void Effect() { if (!isInfected || !IsActive) return; try { int n = UnityEngine.Random.Range(0, list.childCount); Transform child = list.GetChild(n); PCAppInfo appInfo = child.GetComponent<PCAppInfo>(); if (null != appInfo) { if (UnityEngine.Random.value > 0.75f || appInfo.Id > 25 && appInfo.Id < 55) { appInfo.Click(); GameEvent.GetInstance().Execute(Kill, 1f); } else { appInfo.SetState(UnityEngine.Random.Range(0, 3)); } } } catch (Exception e) { Debug.LogException(e); } GameEvent.GetInstance().Execute(Effect, UnityEngine.Random.Range(5f, 10f)); } protected override void Init() { ClearList(); ClearStatus(); SetCurrent(null); killButton.SetAction(Kill); base.Init(); } public override void SetInfected(bool isInfected) { this.isInfected = isInfected && UnityEngine.Random.value >= 0.5f; if (this.isInfected) { GameEvent.GetInstance().Execute(Effect, UnityEngine.Random.Range(5f, 10f)); } } public override void ResetApp() { computer.OnAppStart -= AddAppInfo; ClearStatus(); } protected override void PreCall() { killButton.SetText(Language.LanguageManager.GetText(Language.LangKey.KillProcess)); computer.OnAppStart += AddAppInfo; UpdateList(); } public void AddAppInfo(PCAppInfo appInfo) { if (null == appInfo) return; appInfo.transform.SetParent(list, false); if (null == appInfo.onKill) { appInfo.Highlight(); appInfo.onKill = SetCurrent; } } private void UpdateList() { if (!IsActive) return; Dictionary<int, PCAppInfo> infos = computer.Infos; if (null != infos && infos.Count > 0) { float sum = 0f; List<PCAppInfo> appList = new List<PCAppInfo>(); int count = 0; foreach (int id in infos.Keys) { PCAppInfo appInfo = infos[id]; if (null != appInfo) { if (null == appInfo.onKill) AddAppInfo(appInfo); appList.Add(appInfo); float value = appInfo.NextValue(); sum += value; count += value > 0f ? 1 : 0; } } float total = sum + UnityEngine.Random.Range(0, 100); foreach (PCAppInfo appInfo in appList) { if (null != appInfo) { float value = (sum > 0f ? appInfo.MemValue / total : 0f) * 100f; appInfo.SetMemValue(value); appInfo.UpdateValues(); } } ShowStatus(sum, total, count, appList.Count); if (sum > 0f) { appList.Sort((PCAppInfo info1, PCAppInfo info2) => { float v1 = null != info1 ? info1.MemValue : 0f; float v2 = null != info2 ? info2.MemValue : 0f; return v1 > v2 ? -1 : 1; }); foreach (PCAppInfo info in appList) info?.transform.SetAsLastSibling(); } } else ClearStatus(); ieUpdate = IEUpdate(); StartCoroutine(ieUpdate); } private void ClearStatus() { status.SetText(""); } private void ShowStatus(float p, float sum, int active, int count) { int value = Mathf.RoundToInt((sum > 0f ? p / sum : 0f) * 100f); string color = value > 80 ? (value > 90 ? "#ff0000" : "#ff8800" ): "#000000"; string sactive = active.ToString(); string svalue = value.ToString(); if (isInfected && UnityEngine.Random.value > .35f) { sactive = StringUtil.ToLeet(sactive); svalue = StringUtil.ToLeet(svalue); } string text = "<color=#000000>Active " + sactive + " / " + count + "</color><br><color=" + color + ">CPU " + svalue + " %</color>"; status.SetText(text); } private void ClearList() { foreach (Transform trans in list) trans.SetParent(null); } private IEnumerator IEUpdate() { yield return new WaitForSecondsRealtime(2f); ieUpdate = null; UpdateList(); } private void SetCurrent(PCAppInfo appInfo = null) { bool b = null != appInfo; killButton.IsEnabled = b; killButton.SetState(b ? 1 : 0); if (current == appInfo) return; if (null != current) current.SetState(0); current = appInfo; } private void Kill() { current?.Kill(); SetCurrent(null); } public override List<string> GetAttributes() { string[] attributes = new string[] { "TaskMgrApp.IsEnabled" }; List<string> list = new List<string>(); foreach (string attribute in attributes) list.Add(attribute); return list; } public override Dictionary<string, Action<bool>> GetDelegates() { Dictionary<string, Action<bool>> dict = new Dictionary<string, Action<bool>>(); dict.Add("TaskMgrApp.IsEnabled", SetEnabled); return dict; } public override List<Formula> GetGoals() { List<Formula> list = new List<Formula>(); list.Add(new Implication(null, WorldDB.Get("TaskMgrApp.IsEnabled"))); return list; } }
25.471264
139
0.51414
[ "MIT" ]
polylith/PlumploriGame
Assets/Scripts/Objects/Computers/Apps/TaskMgrApp.cs
6,650
C#
//----------------------------------------------------------------------- // <copyright> // // Copyright (c) TU Chemnitz, Prof. Technische Thermodynamik // Written by Noah Pflugradt. // 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. // All advertising materials mentioning features or use of this software must display the following acknowledgement: // “This product includes software developed by the TU Chemnitz, Prof. Technische Thermodynamik and its contributors.” // Neither the name of the University nor the names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY '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 UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, S // PECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; L // OSS 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. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using Automation; using Automation.ResultFiles; using CalculationController.DtoFactories; using CalculationEngine.HouseholdElements; using CalculationEngine.OnlineDeviceLogging; using Common; using Common.CalcDto; using Common.Enums; using Common.JSON; using Common.Tests; using FluentAssertions; using Moq; using Xunit; using Xunit.Abstractions; namespace Calculation.Tests { public class CalcAffordanceTests : UnitTestBaseClass { public CalcAffordanceTests([JetBrains.Annotations.NotNull] ITestOutputHelper testOutputHelper):base(testOutputHelper) { } private static void SetupProbabilityTest([JetBrains.Annotations.NotNull] out CalcAffordance aff, [JetBrains.Annotations.NotNull] out CalcLoadType lt, [JetBrains.Annotations.NotNull] out CalcDevice cd, [JetBrains.Annotations.NotNull] out CalcLocation loc, int stepcount, double probability, bool enableFlexibility = false) { Config.IsInUnitTesting = true; DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(stepcount); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate); calcParameters.FlexibilityEnabled = enableFlexibility; var timeStep = new TimeSpan(0, 1, 0); var cp = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub"); cp.AddNewTimepoint(new TimeSpan(0), 100); cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0); cp.ConvertToTimesteps(); loc = new CalcLocation(Utili.GetCurrentMethodAndClass(), Guid.NewGuid().ToStrGuid()); CalcVariableRepository cvr = new CalcVariableRepository(); BitArray isBusy = new BitArray(100, false); var r = new Random(0); var hhkey = new HouseholdKey("HH1"); var nr = new NormalRandom(0, 0.1, r); IMock<IOnlineDeviceActivationProcessor> iodap = new Mock<IOnlineDeviceActivationProcessor>(); using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, normalRandom: nr, rnd: r, odap: iodap.Object); aff = new CalcAffordance("bla", cp, loc, false, new List<CalcDesire>(), 0, 99, PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, new List<CalcAffordanceVariableOp>(), new List<VariableRequirement>(), ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), cvr, new List<CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo, hhkey); lt = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid()); var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1); var devloads = new List<CalcDeviceLoad> { cdl }; CalcDeviceDto cdd = new CalcDeviceDto("device", "devcategoryguid".ToStrGuid(), hhkey, OefcDeviceType.Device, "category", string.Empty, Guid.NewGuid().ToStrGuid(), loc.Guid, loc.Name,FlexibilityType.NoFlexibility, 0); cd = new CalcDevice(devloads, loc, cdd, calcRepo); aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, probability); } private static void CheckForBusyness([JetBrains.Annotations.NotNull] CalcLocation loc, [JetBrains.Annotations.NotNull] CalcAffordance aff, [JetBrains.Annotations.NotNull] CalcDevice cd, [JetBrains.Annotations.NotNull] CalcLoadType lt ) { Logger.Info("------------"); TimeStep ts1 = new TimeStep(0,0,true); var person = new CalcPersonDto("person", null, 30, PermittedGender.Male, null, null, null, -1, null, null); Logger.Info("aff.isbusy 0: " + aff.IsBusy(ts1, loc, person, false)); var prevstate = BusynessType.NotBusy; for (var i = 0; i < 100; i++) { TimeStep ts2 = new TimeStep(i, 0,true); if (aff.IsBusy(ts2, loc, person, false) != prevstate) { prevstate = aff.IsBusy(ts2, loc, person, false); Logger.Info("aff.isbusy:" + i + ": " + prevstate); } } Logger.Info("aff.isbusy 100: " + aff.IsBusyArray[100]); var prevstate1 = false; Logger.Info("aff.isbusyarray 0: " + aff.IsBusyArray[0]); for (var i = 0; i < 100; i++) { if (aff.IsBusyArray[i] != prevstate1) { prevstate1 = aff.IsBusyArray[i]; Logger.Info("aff.isbusyarray: " + i + ": " + prevstate); } } Logger.Info("aff.isbusyarray 100: " + aff.IsBusyArray[100]); prevstate1 = false; TimeStep ts3 = new TimeStep(0, 0,false); Logger.Info("cd.isbusyarray 0: " + cd.GetIsBusyForTesting(ts3, lt)); for (var i = 0; i < 100; i++) { TimeStep ts4 = new TimeStep(i, 0, false); if (cd.GetIsBusyForTesting(ts4, lt) != prevstate1) { prevstate1 = cd.GetIsBusyForTesting(ts4, lt); Logger.Info("cd.isbusyarray: " + i + ": " + prevstate); } } TimeStep ts5 = new TimeStep(100, 0, false); Logger.Info("cd.isbusyarray 100: " + cd.GetIsBusyForTesting(ts5, lt)); } [Fact] [Trait("Category",UnitTestCategories.BasicTest)] public void CalcAffordanceActivateTest0Percent() { Logger.Info("hi"); var calcParameters = CalcParameters.GetNew(); const int stepcount = 150; SetupProbabilityTest(out var aff, out var lt, out var cd, out var loc, stepcount, 0); var trueCount = 0; TimeStep ts1 = new TimeStep(0,0,true); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); var result = aff.IsBusy(ts1, loc, person); result.Should().Be(BusynessType.NotBusy); const int resultcount = stepcount - 20; for (var i = 0; i < resultcount; i++) { for (var j = 0; j < stepcount; j++) { TimeStep ts = new TimeStep(j,calcParameters); cd.SetIsBusyForTesting(ts, false, lt); cd.IsBusyForLoadType[lt][ts.InternalStep] = false; } TimeStep ts2 = new TimeStep(i, calcParameters); aff.IsBusy(ts2, loc, person); //var variableOperator = new VariableOperator(); aff.Activate( ts2, "blub", loc, out var _); if (cd.GetIsBusyForTesting(ts2, lt)) { trueCount++; } } Logger.Info("Truecount: " + trueCount); trueCount.Should().BeApproximately(0,0.1); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceActivateTest100Percent() { const int stepcount = 150; SetupProbabilityTest(out var aff, out var lt, out var cd, out var loc, stepcount, 1); var trueCount = 0; TimeStep ts = new TimeStep(0,0,false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); var result = aff.IsBusy(ts, loc, person); result.Should().Be(BusynessType.NotBusy); const int resultcount = stepcount - 20; for (var i = 0; i < resultcount; i++) { for (var j = 0; j < stepcount; j++) { TimeStep ts2 = new TimeStep(j, 0, false); cd.SetIsBusyForTesting(ts2, false, lt); cd.IsBusyForLoadType[lt][j] = false; } TimeStep ts3 = new TimeStep(i, 0, false); aff.IsBusy(ts3, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts3, "blub", loc, out var _); if (cd.GetIsBusyForTesting(ts3, lt)) { trueCount++; } } Logger.Info("Truecount: " + trueCount); trueCount.Should().BeApproximately(resultcount, 0.1); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceActivateTest25Percent() { const int stepcount = 150; SetupProbabilityTest(out var aff, out var lt, out CalcDevice cd, out var loc, stepcount, 0.25); var trueCount = 0; TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); var result = aff.IsBusy(ts, loc, person); result.Should().Be(BusynessType.NotBusy); const int resultcount = stepcount - 20; for (var i = 0; i < resultcount; i++) { for (var j = 0; j < stepcount; j++) { TimeStep ts2 = new TimeStep(j, 0, false); cd.SetIsBusyForTesting(ts2, false, lt); cd.IsBusyForLoadType[lt][j] = false; } TimeStep ts3 = new TimeStep(i, 0, false); aff.IsBusy(ts3, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts3, "blub", loc, out var _); if (cd.GetIsBusyForTesting(ts3, lt)) { trueCount++; } } Logger.Info("Truecount: " + trueCount); #pragma warning disable VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding. trueCount.Should().BeApproximately(resultcount/4,0.1); #pragma warning restore VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding. } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceActivateTest50Percent() { const int stepcount = 150; SetupProbabilityTest(out var aff, out var lt, out var cd, out var loc, stepcount, 0.5); var trueCount = 0; TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); var result = aff.IsBusy(ts, loc, person); result.Should().Be(BusynessType.NotBusy); const int resultcount = stepcount - 20; for (var i = 0; i < resultcount; i++) { for (var j = 0; j < stepcount; j++) { TimeStep ts2 = new TimeStep(j, 0, false); cd.SetIsBusyForTesting(ts2, false, lt); cd.IsBusyForLoadType[lt][j] = false; } TimeStep ts3 = new TimeStep(i, 0, false); aff.IsBusy(ts3, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts3, "blub", loc, out var _); if (cd.GetIsBusyForTesting(ts3, lt)) { trueCount++; } } Logger.Info("Truecount: " + trueCount); #pragma warning disable VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding. trueCount.Should().BeApproximately(resultcount/2,0.1); #pragma warning restore VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding. } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceActivateTest75Percent() { const int stepcount = 150; SetupProbabilityTest(out var aff, out var lt, out var cd, out var loc, stepcount, 0.75); var trueCount = 0; TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); var result = aff.IsBusy(ts, loc, person); result.Should().Be(BusynessType.NotBusy); const int resultcount = stepcount - 20; for (var i = 0; i < resultcount; i++) { for (var j = 0; j < stepcount; j++) { TimeStep ts2 = new TimeStep(j, 0, false); cd.SetIsBusyForTesting(ts2, false, lt); cd.IsBusyForLoadType[lt][j] = false; } TimeStep ts3 = new TimeStep(i, 0, false); aff.IsBusy(ts3, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts3, "blub", loc, out var _); if (cd.GetIsBusyForTesting(ts3, lt)) { trueCount++; } } Logger.Info("Truecount: " + trueCount); trueCount.Should().BeApproximatelyWithinPercent(resultcount * 0.75, 0.1); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceVariableTestAdd() { var r = new Random(0); var nr = new NormalRandom(0, 0.1, r); const int stepcount = 150; Config.IsInUnitTesting = true; DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(stepcount); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate); var timeStep = new TimeSpan(0, 1, 0); var cp = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub"); cp.AddNewTimepoint(new TimeSpan(0), 100); cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0); cp.ConvertToTimesteps(); //var variableOperator = new VariableOperator(); var variables = new List<CalcAffordanceVariableOp>(); var variableReqs = new List<VariableRequirement>(); var loc = new CalcLocation("loc", Guid.NewGuid().ToStrGuid()); var variableGuid = Guid.NewGuid().ToStrGuid(); CalcVariableRepository variableRepository = new CalcVariableRepository(); HouseholdKey key = new HouseholdKey("hh1"); CalcVariable cv = new CalcVariable("calcvar1", variableGuid, 0, loc.Name, loc.Guid, key); variableRepository.RegisterVariable(cv); variables.Add(new CalcAffordanceVariableOp(cv.Name, 1, loc, VariableAction.Add, VariableExecutionTime.Beginning, cv.Guid)); BitArray isBusy = new BitArray(100, false); var hhkey = new HouseholdKey("HH1"); using CalcRepo calcRepo = new CalcRepo(rnd: r,normalRandom:nr,calcParameters:calcParameters, odap: new Mock<IOnlineDeviceActivationProcessor>().Object); var aff = new CalcAffordance("bla", cp, loc, false, new List<CalcDesire>(), 0, 99, PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, variables, variableReqs, ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), variableRepository, new List<CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low,calcRepo, hhkey); var lt = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid()); var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1); var devloads = new List<CalcDeviceLoad> { cdl }; var categoryGuid = Guid.NewGuid().ToStrGuid(); CalcDeviceDto dto = new CalcDeviceDto("device", categoryGuid,hhkey , OefcDeviceType.Device, "category", string.Empty, Guid.NewGuid().ToStrGuid(), loc.Guid,loc.Name,FlexibilityType.NoFlexibility, 0); var cd = new CalcDevice( devloads, loc, dto,calcRepo ); //loc.Variables.Add("Variable1", 0); aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, 1); TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); aff.IsBusy(ts, loc, person); aff.Activate(ts, "blub", loc, out var _); variableRepository.GetValueByGuid(variableGuid).Should().Be(1); for (var i = 0; i < 15; i++) { TimeStep ts1 = new TimeStep(i, 0, false); cd.SetIsBusyForTesting(ts1, false, lt); } aff.IsBusy(ts, loc, person); aff.Activate(ts, "blub", loc, out var _); variableRepository.GetValueByGuid(variableGuid).Should().Be(2); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceVariableTestSet() { var deviceCategoryGuid = Guid.NewGuid().ToStrGuid(); //var r = new Random(0); //var nr = new NormalRandom(0, 0.1, r); const int stepcount = 150; Config.IsInUnitTesting = true; DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(stepcount); //_calcParameters.InitializeTimeSteps(startdate, enddate, new TimeSpan(0, 1, 0), 3, false); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate); var timeStep = new TimeSpan(0, 1, 0); var cp = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub"); cp.AddNewTimepoint(new TimeSpan(0), 100); cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0); cp.ConvertToTimesteps(); var variables = new List<CalcAffordanceVariableOp>(); var variableReqs = new List<VariableRequirement>(); var loc = new CalcLocation("loc", Guid.NewGuid().ToStrGuid()); CalcVariableRepository calcVariableRepository = new CalcVariableRepository(); var variableGuid = Guid.NewGuid().ToStrGuid(); HouseholdKey key = new HouseholdKey("hh1"); CalcVariable cv = new CalcVariable("varname", variableGuid, 0, loc.Name, loc.Guid, key); calcVariableRepository.RegisterVariable(cv); variables.Add(new CalcAffordanceVariableOp(cv.Name, 1, loc, VariableAction.SetTo, VariableExecutionTime.Beginning, variableGuid)); BitArray isBusy = new BitArray(100, false); Random rnd = new Random(); NormalRandom nr = new NormalRandom(0,1,rnd); using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap: new Mock<IOnlineDeviceActivationProcessor>().Object, normalRandom:nr, rnd:rnd); var aff = new CalcAffordance("bla", cp, loc, false, new List<CalcDesire>(), 0, 99, PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, variables, variableReqs, ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), calcVariableRepository, new List<CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo, key); var lt = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid()); var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1); var devloads = new List<CalcDeviceLoad> { cdl }; CalcDeviceDto cdd = new CalcDeviceDto("device", deviceCategoryGuid,key, OefcDeviceType.Device,"category",string.Empty, Guid.NewGuid().ToStrGuid(),loc.Guid,loc.Name, FlexibilityType.NoFlexibility, 0); var cd = new CalcDevice( devloads, loc, cdd, calcRepo); //loc.Variables.Add("Variable1", 0); aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, 1); TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); aff.IsBusy(ts, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts, "blub", loc, out var _); calcVariableRepository.GetValueByGuid(variableGuid).Should().Be(1); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void CalcAffordanceVariableTestSubtract() { //var r = new Random(0); //var nr = new NormalRandom(0, 0.1, r); const int stepcount = 150; HouseholdKey key = new HouseholdKey("hh1"); Config.IsInUnitTesting = true; DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(stepcount); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate); var timeStep = new TimeSpan(0, 1, 0); var cp = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub"); cp.AddNewTimepoint(new TimeSpan(0), 100); cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0); cp.ConvertToTimesteps(); var variables = new List<CalcAffordanceVariableOp>(); var variableReqs = new List<VariableRequirement>(); var loc = new CalcLocation("loc", Guid.NewGuid().ToStrGuid()); var variableGuid = Guid.NewGuid().ToStrGuid(); variables.Add(new CalcAffordanceVariableOp("Variable1", 1, loc, VariableAction.Subtract, VariableExecutionTime.Beginning, variableGuid)); CalcVariableRepository crv = new CalcVariableRepository(); crv.RegisterVariable(new CalcVariable("Variable1", variableGuid, 0, loc.Name, loc.Guid, key)); BitArray isBusy = new BitArray(calcParameters.InternalTimesteps, false); Random rnd = new Random(); NormalRandom nr = new NormalRandom(0, 1, rnd); using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap: new Mock<IOnlineDeviceActivationProcessor>().Object, rnd:rnd, normalRandom:nr); var aff = new CalcAffordance("bla", cp, loc, false, new List<CalcDesire>(), 0, 99, PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, variables, variableReqs, ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), crv, new List<CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo,key); var lt = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid()); var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1); var devloads = new List<CalcDeviceLoad> { cdl }; var devCatGuid = Guid.NewGuid().ToStrGuid(); CalcDeviceDto cdd = new CalcDeviceDto("device", devCatGuid, key, OefcDeviceType.Device, "category", string.Empty, Guid.NewGuid().ToStrGuid(),loc.Guid,loc.Name, FlexibilityType.NoFlexibility, 0); var cd = new CalcDevice( devloads, loc, cdd, calcRepo); //loc.Variables.Add("Variable1", 0); aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, 1); TimeStep ts = new TimeStep(0, 0, false); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); aff.IsBusy(ts, loc, person); //var variableOperator = new VariableOperator(); aff.Activate(ts, "blub", loc, out var _); crv.GetValueByGuid(variableGuid).Should().Be(-1); for (var i = 0; i < 15; i++) { TimeStep ts1 = new TimeStep(i, 0, false); cd.SetIsBusyForTesting(ts1, false, lt); } aff.IsBusy(ts, loc, person); aff.Activate(ts, "blub", loc, out var _); crv.GetValueByGuid(variableGuid).Should().Be(-2); } [Fact] [Trait(UnitTestCategories.Category,UnitTestCategories.BasicTest)] public void RunDeviceOffsetTest() { //var r = new Random(0); //var nr = new NormalRandom(0, 0.1, r); const int stepcount = 150; var devCategoryGuid = Guid.NewGuid().ToStrGuid(); Config.IsInUnitTesting = true; DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(stepcount); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate); var timeStep = new TimeSpan(0, 1, 0); var cp = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub"); cp.AddNewTimepoint(new TimeSpan(0), 100); cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0); cp.ConvertToTimesteps(); var loc = new CalcLocation(Utili.GetCurrentMethodAndClass(), Guid.NewGuid().ToStrGuid()); CalcVariableRepository crv = new CalcVariableRepository(); BitArray isBusy = new BitArray(calcParameters.InternalTimesteps, false); Random rnd = new Random(); NormalRandom nr = new NormalRandom(0, 1, rnd); HouseholdKey key = new HouseholdKey("HH1"); using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap:new Mock<IOnlineDeviceActivationProcessor>().Object, rnd: rnd, normalRandom: nr); var aff = new CalcAffordance("bla", cp, loc, false, new List<CalcDesire>(), 0, 99, PermittedGender.All, false, 0, new ColorRGB(0, 0, 0), "bla", false, false, new List<CalcAffordanceVariableOp>(), new List<VariableRequirement>(), ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), crv, new List<CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo,key); var lt = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid()); var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1); //var variableOperator = new VariableOperator(); var devloads = new List<CalcDeviceLoad> { cdl }; CalcDeviceDto cdd = new CalcDeviceDto("device", devCategoryGuid, key, OefcDeviceType.Device, "category", string.Empty, Guid.NewGuid().ToStrGuid(), loc.Guid, loc.Name, FlexibilityType.NoFlexibility, 0); var cd = new CalcDevice( devloads, loc, cdd, calcRepo); aff.AddDeviceTuple(cd, cp, lt, 20, timeStep, 10, 1); //bool result = aff.IsBusy(0, nr, r, loc); //(result).Should().BeFalse(); CheckForBusyness(loc, aff, cd, lt); TimeStep ts = new TimeStep(0, 0, false); aff.Activate(ts.AddSteps(10), "blub", loc, out var _); CheckForBusyness( loc, aff, cd, lt); var person = new CalcPersonDto("name", null, 30, PermittedGender.Male, null, null, null, -1, null, null); aff.IsBusy(ts.AddSteps(1), loc, person, false).Should().NotBe(BusynessType.NotBusy); aff.IsBusy(ts.AddSteps(19), loc, person, false).Should().NotBe(BusynessType.NotBusy); aff.IsBusy(ts, loc, person, false).Should().Be(BusynessType.NotBusy); aff.IsBusy(ts.AddSteps(20), loc, person, false).Should().Be(BusynessType.NotBusy); } } }
52.818644
169
0.583352
[ "MIT" ]
kyleniemeyer/LoadProfileGenerator
Calculation.Tests/CalcAffordanceTests.cs
31,169
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails Object /// </summary> public class AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetailsUnmarshaller : IUnmarshaller<AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails, XmlUnmarshallerContext>, IUnmarshaller<AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails IUnmarshaller<AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails unmarshalledObject = new AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetails(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("CloudWatchEncryptionEnabled", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.CloudWatchEncryptionEnabled = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CloudWatchLogGroupName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.CloudWatchLogGroupName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3BucketName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.S3BucketName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3EncryptionEnabled", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.S3EncryptionEnabled = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3KeyPrefix", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.S3KeyPrefix = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetailsUnmarshaller _instance = new AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetailsUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetailsUnmarshaller Instance { get { return _instance; } } } }
43.715517
341
0.670479
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/AwsEcsClusterConfigurationExecuteCommandConfigurationLogConfigurationDetailsUnmarshaller.cs
5,071
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PictureHandler_dll { public abstract class PictureBase : IDisposable { public Image Image { get; set; } public Image HandledImage { get; set; } #region IDisposable Support private bool disposedValue = false; // 要检测冗余调用 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 } Image.Dispose(); HandledImage.Dispose(); // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 disposedValue = true; } } // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。 ~PictureBase() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose(false); } // 添加此代码以正确实现可处置模式。 public void Dispose() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose(true); // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。 GC.SuppressFinalize(this); } #endregion } }
22.298507
69
0.476573
[ "Apache-2.0" ]
hairenaa/PictureCryptFramework
cs_file/PictureBase.cs
1,812
C#
using SimpleDartboard.PAL.Models; namespace SimpleDartboard.PAL.UseCases.DartGameSettings.Save { public interface IDartGameSettingSaveService { void Save(DartGameSetting dartGameSetting, string fileName); } }
26.333333
69
0.751055
[ "MIT" ]
Absolut312/SimpleDartboard
SimpleDartboard/SimpleDartboard.PAL/UseCases/DartGameSettings/Save/IDartGameSettingSaveService.cs
237
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Borg.MVC.BuildingBlocks.Contracts { public interface IComponentPageDescriptorService<TKey> where TKey : IEquatable<TKey> { Task<ComponentPageDescriptor<TKey>> Get(TKey componentId); Task<ComponentPageDescriptor<TKey>> Set(ComponentPageDescriptor<TKey> descriptor); Task Invalidate(TKey componentId); } }
29.933333
90
0.759465
[ "MIT" ]
mitsbits/NoBorg
src/infra/Borg.MVC/BuildingBlocks/Contracts/IComponentPageDescriptorService.cs
451
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Testing; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; namespace Azure.AI.TextAnalytics.Samples { [LiveOnly] public partial class TextAnalyticsSamples { [Test] public void DetectLanguageBatch() { string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT"); string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY"); var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey); #region Snippet:TextAnalyticsSample1DetectLanguagesBatch var inputs = new List<DetectLanguageInput> { new DetectLanguageInput("1", "Hello world") { CountryHint = "us", }, new DetectLanguageInput("2", "Bonjour tout le monde") { CountryHint = "fr", }, new DetectLanguageInput("3", "Hola mundo") { CountryHint = "es", }, new DetectLanguageInput("4", ":) :( :D") { CountryHint = "us", } }; DetectLanguageResultCollection results = client.DetectLanguages(inputs, new TextAnalyticsRequestOptions { IncludeStatistics = true }); #endregion int i = 0; Debug.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{results.ModelVersion}\""); Debug.WriteLine(""); foreach (DetectLanguageResult result in results) { DetectLanguageInput document = inputs[i++]; Debug.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\", Text=\"{document.Text}\"):"); if (result.ErrorMessage != default) { Debug.WriteLine($" Document error: {result.ErrorMessage}."); } else { Debug.WriteLine($" Detected language {result.PrimaryLanguage.Name} with confidence {result.PrimaryLanguage.Score:0.00}."); Debug.WriteLine($" Document statistics:"); Debug.WriteLine($" Character count: {result.Statistics.CharacterCount}"); Debug.WriteLine($" Transaction count: {result.Statistics.TransactionCount}"); Debug.WriteLine(""); } } Debug.WriteLine($"Batch operation statistics:"); Debug.WriteLine($" Document count: {results.Statistics.DocumentCount}"); Debug.WriteLine($" Valid document count: {results.Statistics.ValidDocumentCount}"); Debug.WriteLine($" Invalid document count: {results.Statistics.InvalidDocumentCount}"); Debug.WriteLine($" Transaction count: {results.Statistics.TransactionCount}"); Debug.WriteLine(""); } } }
39.839506
146
0.561512
[ "MIT" ]
abhi1509/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample1_DetectLanguageBatch.cs
3,229
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using ProjectTemplate.Application.Commands.Interfaces; using ProjectTemplate.Domain.Models.Aggregates; using ProjectTemplate.Persistence.Commands; using ProjectTemplate.Persistence.Commands.Interfaces; namespace ProjectTemplate.Persistence { internal class ProjectAggregateUnitOfWork : IProjectAggregateUnitOfWork { private readonly ProjectAggregateCommandContext _dbContext; public ProjectAggregateUnitOfWork( ProjectAggregateCommandContext dbContext, IMutatableRepository<ProjectAggregate> projectAggregates) { ProjectAggregates = projectAggregates; _dbContext = dbContext; } public bool HasActiveTransaction => _dbContext.HasActiveTransaction; public IMutatableRepository<ProjectAggregate> ProjectAggregates { get; } public async Task BeginTransactionAsync() { await _dbContext.BeginTransactionAsync(); } public async Task CommitAsync(CancellationToken cancellationToken = default) { await _dbContext.CommitAsync(); } public async Task RollbackTransactionAsync() { await _dbContext.RollbackTransactionAsync(); } } }
30.311111
84
0.716276
[ "MIT" ]
Edwardchorius/CleanArchitectureTemplate
src/ProjectTemplate.Persistence/ProjectAggregateUnitOfWork.cs
1,366
C#
// This file is part of Dipol-3 Camera Manager. // MIT License // // Copyright(c) 2018-2019 Ilia Kosenkov // // 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 NONINFINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace DIPOL_UF { public class GeometryDescriptor { public Point Center { get; } public List<Tuple<Point, Action<StreamGeometryContext, Point>>> PathDescription { get; } public Size Size { get; } public Size HalfSize { get; } public double Thickness { get; } public Func<int, int, Point, Size, double, bool> IsInsideChecker { get; } public GeometryDescriptor(Point center, Size size, List<Tuple<Point, Action<StreamGeometryContext, Point>>> path, double thickness, Func<int, int, Point, Size, double, bool> isInsideChecker = null) { Center = new Point(center.X, center.Y); Size = new Size(size.Width + thickness, size.Height + thickness); HalfSize = new Size(Size.Width/2, Size.Height/2); PathDescription = path; Thickness = thickness; IsInsideChecker = isInsideChecker; } } }
42.709091
96
0.667092
[ "MIT" ]
Ilia-Kosenkov/DIPOL-UF
src/DIPOL-UF/GeometryDescriptor.cs
2,351
C#
// /* // Copyright 2008-2011 Alex Robson // // 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 Symbiote.Core.DI.Impl { public interface IProvideInstance { object Get(); } }
32.545455
75
0.712291
[ "Apache-2.0" ]
code-attic/Symbiote
src/Symbiote.Core/DI/Impl/IProvideInstance.cs
718
C#
using JobTo.Commom.Data; using JobTo.Commom.Models; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JobTo.Common.Repositories { public class ProviderRepository : IProviderRepository { private readonly JobToDbContext _context; public ProviderRepository(JobToDbContext context) { _context = context; } public async Task<IList<Person>> All() { return await _context.People .Where(p => p.Flag == 'A') .Where(p => p.PersonType.Contains("P")) .ToListAsync(); } public async Task<int> Delete(Person model) { model.Flag = 'D'; _context.People.Update(model); return await _context.SaveChangesAsync(); } public async Task<Person> Get(long grid) { return await _context.People .Where(x => x.Grid == grid) .FirstOrDefaultAsync(); } public async Task<Person> Get(int code) { return await _context.People .Where(x => x.Code == code) .FirstOrDefaultAsync(); } public async Task<int> Insert(Person model) { _context.People.Add(model); return await _context.SaveChangesAsync(); } public async Task<int> Update(Person model) { _context.People.Update(model); return await _context.SaveChangesAsync(); } } }
27.271186
57
0.557489
[ "MIT" ]
sotechdev/jobto-common
Repositories/ProviderRepository.cs
1,611
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EloBuddy; using EloBuddy.SDK.Events; namespace Rookie___Vayne_1v { class Program { static void Main(string[] args) { Loading.OnLoadingComplete += OnLoadingComplete; } private static void OnLoadingComplete(EventArgs args) { if (Player.Instance.ChampionName != "Vayne") return; MenuManager.Initialize(); Chat.OnInput += ChatInputComing; MenuManager.Modes.Gosu.UnSetGod(); new Brain().Initialize(); } private static void ChatInputComing(ChatInputEventArgs args) { if (args.Input == "#IDDQD" && !MenuManager.IDDQD) { args.Input = ""; Chat.Print("Good luck Load Complete."); MenuManager.IDDQD = true; MenuManager.Modes.Gosu.SetGod(); } else if (args.Input == "#IDDQD" && MenuManager.IDDQD) { args.Input = ""; } } } }
27.045455
69
0.526891
[ "Apache-2.0" ]
Dilmas/DLScript
Rookie - Vayne 1v/Rookie - Vayne 1v/Program.cs
1,192
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using CA = MonoDevelop.CodeAnalysis; namespace MonoDevelop.CodeAnalysis.Smokey { internal static class SmokeyParser { private const string RuleErrorMessage = "A rule has failed to run."; public static IEnumerable<IViolation> ParseOutput (StreamReader sr, IEnumerable<CA.IRule> ruleSet) { List<IViolation> found = new List<IViolation> (); // FIXME: instead of checking each defect if its rule is in "set" // we should think on making use of Smokey "ignore" feature // we should only return violations with rules id in this list List<string> ruleIds = new List<string> (); foreach (CA.IRule rule in ruleSet) ruleIds.Add (rule.Id); // if assembly is big, Gendarme outputs progress bar using dots // before actual xml, so we might want to need to move forward while (sr.Peek () != '<') sr.Read (); // go! using (XmlTextReader reader = new XmlTextReader (sr)) { reader.WhitespaceHandling = WhitespaceHandling.None; string file = string.Empty; int line = 0; while (reader.Read ()) { if (reader.NodeType != XmlNodeType.Element) continue; if("Location" == reader.Name) { file = reader.GetAttribute("file"); if(null == file){ file = string.Empty; } if(!int.TryParse(reader.GetAttribute("line"), out line)){ line = 0; } } if (reader.Name != "Violation") continue; // get rule id string ruleId = reader.GetAttribute ("checkID"); // if we don't need to check for this rule, let it go if (!ruleIds.Contains (ruleId)) continue; // parse severity (or try to) CA.Severity severity = ParseSeverity (reader.GetAttribute ("severity")); // parse solution and problem string problem = null; string solution = null; while (reader.Read ()) { if (reader.NodeType != XmlNodeType.Element) continue; if (reader.Name == "Cause") problem = reader.ReadString (); else if (reader.Name == "Fix") solution = reader.ReadString (); else if (problem != null && solution != null) break; } // sometimes Smokey rules throw an exception // we shouldn't return "dead" violations if (IsErrorMessage (problem)) continue; // go! found.Add (new SmokeyViolation (ruleId, problem, solution, severity, file, line)); } } return found; } private static CA.Severity ParseSeverity (string value) { if (value == "Error") return CA.Severity.High; // FIXME: or Critical? else if (value == "Warning") return CA.Severity.Medium; else if (value == "Nitpick") return CA.Severity.Low; else return CA.Severity.Medium; // by default? } private static bool IsErrorMessage (string cause) { return cause == RuleErrorMessage; } } }
28.285714
100
0.634007
[ "MIT" ]
decriptor/MonoDevelop.CodeAnalysis
MonoDevelop.CodeAnalysis.Smokey/SmokeyParser.cs
2,970
C#
#pragma checksum "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "cd422f31ece0fffa4a5cbafdfab92e78baf76816" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_OrganizationManage_Views_User_UserPortrait), @"mvc.1.0.view", @"/Areas/OrganizationManage/Views/User/UserPortrait.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; #nullable restore #line 3 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using Microsoft.AspNetCore.Mvc.ViewFeatures; #line default #line hidden #nullable disable #nullable restore #line 4 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Util; #line default #line hidden #nullable disable #nullable restore #line 5 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Util.Extension; #line default #line hidden #nullable disable #nullable restore #line 6 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Util.Model; #line default #line hidden #nullable disable #nullable restore #line 7 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Enum; #line default #line hidden #nullable disable #nullable restore #line 8 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Enum.OrganizationManage; #line default #line hidden #nullable disable #nullable restore #line 9 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/_ViewImports.cshtml" using YiSha.Web.Code; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cd422f31ece0fffa4a5cbafdfab92e78baf76816", @"/Areas/OrganizationManage/Views/User/UserPortrait.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e45dbd51f3d139278b58e1807e343bf3fa8e8229", @"/Areas/OrganizationManage/_ViewImports.cshtml")] public class Areas_OrganizationManage_Views_User_UserPortrait : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Layout = "~/Views/Shared/_FormWhite.cshtml"; #line default #line hidden #nullable disable WriteLiteral("\r\n"); DefineSection("header", async() => { WriteLiteral("\r\n "); #nullable restore #line 7 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/cropbox/1.0/cropbox.min.css"))); #line default #line hidden #nullable disable WriteLiteral("\r\n "); #nullable restore #line 8 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/cropbox/1.0/cropbox.min.js"))); #line default #line hidden #nullable disable WriteLiteral("\r\n"); } ); WriteLiteral(@" <div class=""container""> <div class=""imageBox""> <div class=""thumbBox""></div> <div class=""spinner"" style=""display: none"">Loading...</div> </div> <div class=""action""> <div class=""new-contentarea tc""> <a href=""javascript:void(0)"" class=""upload-img""> <label for=""avatar"">上传图像</label> </a> <input type=""file"" id=""portrait"" accept=""image/*"" /> </div> <input type=""button"" id=""btnCrop"" class=""Btnsty_peyton"" value=""裁切"" /> <input type=""button"" id=""btnZoomIn"" class=""Btnsty_peyton"" value=""+"" /> <input type=""button"" id=""btnZoomOut"" class=""Btnsty_peyton"" value=""-"" /> <input type=""button"" id=""btnSave"" class=""Btnsty_peyton"" value=""提交"" /> </div> <div class=""cropped""></div> </div> <script type=""text/javascript""> var id = ys.request(""id""); var cropper; var imgFileName; $(function () { var portrait = '"); #nullable restore #line 35 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(ViewBag.OperatorInfo.Portrait); #line default #line hidden #nullable disable WriteLiteral("\';\r\n if (ys.isNullOrEmpty(portrait)) {\r\n portrait = ctx + \'image/portrait.png\';\r\n }\r\n else {\r\n portrait = \'"); #nullable restore #line 40 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(GlobalContext.SystemConfig.ApiSite); #line default #line hidden #nullable disable WriteLiteral(@"' + portrait; } var options = { thumbBox: '.thumbBox', spinner: '.spinner', imgSrc: portrait }; cropper = $('.imageBox').cropbox(options); $('#portrait').on('change', function () { var file = this.files[0]; var reader = new FileReader(); reader.onload = function (e) { options.imgSrc = e.target.result; //根据MIME判断上传的文件是不是图片类型 if ((options.imgSrc).indexOf(""image/"") == -1) { ys.msgError(""文件格式错误,请上传图片类型,如:JPG,JEPG,PNG后缀的文件。""); } else { cropper = $('.imageBox').cropbox(options); } } reader.readAsDataURL(file); imgFileName = file.name; }); $('#btnSave').on('click', function () { saveForm(parent.layer.getFrameIndex(window.name)); }); $('#btnCrop').on('click', function () { "); WriteLiteral(@" if (!checkImageFileName()) { return; } var img = cropper.getDataURL(); $('.cropped').html(''); $('.cropped').append('<img src=""' + img + '"" align=""absmiddle"" style=""width:64px;margin-top:4px;border-radius:64px;box-shadow:0px 0px 12px #7E7E7E;"" ><p>64px*64px</p>'); $('.cropped').append('<img src=""' + img + '"" align=""absmiddle"" style=""width:128px;margin-top:4px;border-radius:128px;box-shadow:0px 0px 12px #7E7E7E;""><p>128px*128px</p>'); $('.cropped').append('<img src=""' + img + '"" align=""absmiddle"" style=""width:180px;margin-top:4px;border-radius:180px;box-shadow:0px 0px 12px #7E7E7E;""><p>180px*180px</p>'); }); $('#btnZoomIn').on('click', function () { cropper.zoomIn(); }); $('#btnZoomOut').on('click', function () { cropper.zoomOut(); }); }); function saveForm(index) { if (!checkImageFileName()) { return; }"); WriteLiteral("\r\n var img = cropper.getBlob();\r\n var formdata = new FormData();\r\n formdata.append(\"fileList\", img, imgFileName);\r\n ys.ajaxUploadFile({\r\n url: \'"); #nullable restore #line 92 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(GlobalContext.SystemConfig.ApiSite); #line default #line hidden #nullable disable WriteLiteral("\' + \'/File/UploadFile?fileModule="); #nullable restore #line 92 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(UploadFileType.Portrait.ParseToInt()); #line default #line hidden #nullable disable WriteLiteral(@"', data: formdata, success: function (obj) { if (obj.Tag == 1) { saveUserPortrait(obj); } else { ys.msgError(obj.Message); } } }) } function saveUserPortrait(data) { var postData = {}; postData.Id = id; postData.Portrait = data.Data; ys.ajax({ url: '"); #nullable restore #line 110 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(Url.Content("~/OrganizationManage/User/ChangeUserJson")); #line default #line hidden #nullable disable WriteLiteral("\',\r\n type: \"post\",\r\n data: postData,\r\n success: function (obj) {\r\n if (obj.Tag == 1) {\r\n ys.msgSuccess(obj.Message);\r\n $(\"#portrait\", parent.document).attr(\"src\", \'"); #nullable restore #line 116 "/Users/lizhao/projects/pomsbs/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/User/UserPortrait.cshtml" Write(GlobalContext.SystemConfig.ApiSite); #line default #line hidden #nullable disable WriteLiteral(@"' + data.Data); ys.closeDialog(); } else { ys.msgError(obj.Message); } } }); } function checkImageFileName() { if (ys.isNullOrEmpty(imgFileName)) { ys.msgError(""请先上传图片""); return false; } else { return true; } } </script>"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment { get; private set; } [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
41.913043
299
0.629582
[ "MIT" ]
lizhaoiot/pomsbs
YiSha.Web/YiSha.Admin.Web/obj/Debug/netcoreapp3.1/Razor/Areas/OrganizationManage/Views/User/UserPortrait.cshtml.g.cs
11,674
C#
namespace IntergalacticTravel.Tests.Mocks { using IntergalacticTravel.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class MockedTeleportStation : TeleportStation { public MockedTeleportStation(IBusinessOwner owner, IEnumerable<IPath> galacticMap, ILocation location) : base(owner, galacticMap, location) { } public IBusinessOwner Owner { get { return base.owner; } } public IEnumerable<IPath> GalacticMap { get { return base.galacticMap; } } public ILocation Location { get { return base.location; } } } }
20.348837
110
0.536
[ "MIT" ]
shopOFF/Telerik-Academy-Courses
Unit-Testing/TelerikUnitTestingg/UnitTestingEvaluation/4-notBad/ExamFileForEvaluation/unit-test-morning-aug-2016/IntergalacticTravel.Tests/Mocks/MockedTeleportStation.cs
877
C#
namespace Stethoscope.Common { /// <summary> /// Available attributes for a log /// </summary> public enum LogAttribute { /// <summary> /// Log timestamp. Will be a DateTime /// </summary> Timestamp, /// <summary> /// Log message. Will be a string /// </summary> Message, /// <summary> /// Source of the log entry. Will be a string /// </summary> LogSource, /// <summary> /// Thread ID (logger system dependent) /// </summary> ThreadID, /// <summary> /// Source file for log /// </summary> SourceFile, /// <summary> /// Source function for log /// </summary> Function, /// <summary> /// Source file line for log /// </summary> SourceLine, /// <summary> /// What level (ex. 0-9, with 9 being most verbose and 0 being most critical) is the log /// </summary> Level, /// <summary> /// What sequence within the original log file, was the log at /// </summary> SequenceNumber, /// <summary> /// Module / library / executable the log came from /// </summary> Module, /// <summary> /// What type of log was produced (ex. error, warning, info) /// </summary> Type, /// <summary> /// What "code group", within a module, produced the log. Ex. Module=VideoGame, Section=Audio /// </summary> Section, /// <summary> /// Identification information for a trace that exists for a short term (Ex. an ID used within a function call) /// </summary> TraceID, /// <summary> /// Identification information for a trace that exists for a long term (Ex. unique IDs for an instance of a class) /// </summary> Context } }
28.970588
122
0.504569
[ "MIT" ]
rcmaniac25/stethoscope
stethoscope/StethoscopeLib/Sources/Common/LogAttributeEnum.cs
1,972
C#
using Abp; namespace Afonsoft.SetBox.Friendships { public static class FriendshipExtensions { public static UserIdentifier ToUserIdentifier(this Friendship friendship) { return new UserIdentifier(friendship.TenantId, friendship.UserId); } public static UserIdentifier ToFriendIdentifier(this Friendship friendship) { return new UserIdentifier(friendship.FriendTenantId, friendship.FriendUserId); } } }
27.166667
90
0.693252
[ "Apache-2.0" ]
afonsoft/SetBox-VideoPlayer
SetBoxWebUI_New/src/Afonsoft.SetBox.Core/Friendships/FriendshipExtensions.cs
491
C#
using Microsoft.Extensions.Options; namespace PM.CloudPlatform.ForkliftManager.Apis.Options { /// <summary> /// Gps点位纠正 /// </summary> public class GpsPointFormatterOption : IOptions<GpsPointFormatterOption> { /// <summary> /// /// </summary> public GpsPointFormatterOption Value => this; /// <summary> /// 速度 /// </summary> public double Speed { get; set; } /// <summary> /// 纠正系数 /// </summary> public double Coefficient { get; set; } /// <summary> /// 检查上个点的时间间隔 /// </summary> public int TimeInterval { get; set; } } /// <summary> /// /// </summary> public static class GpsPointFormatterOptionExtensions { /// <summary> /// km/s -> m/s /// </summary> /// <param name="speed"></param> /// <param name="coefficient"></param> /// <returns></returns> public static double To_m_s(this double speed, double coefficient = 1) { return speed / 3.6d * coefficient; } } }
23.604167
78
0.511033
[ "MIT" ]
DonPangPang/PM.CloudPlatform.ForkliftManager
src/PM.CloudPlatform.ForkliftManager.Apis/Options/GpsPointFormatterOption.cs
1,175
C#
/*<FILE_LICENSE> * Azos (A to Z Application Operating System) Framework * The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. </FILE_LICENSE>*/ using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Text; using Azos.Collections; namespace Azos.Apps.Injection { /// <summary> /// Decorates fields that should be injected with app-rooted services (for example log or data store). /// A call to IApplication.DependencyInjector.InjectInto(instance) performs injection. /// Framework code invokes this method automatically for glue servers and MVC objects. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class InjectAttribute : Attribute { /// <summary> /// When set, provides name of entity to inject, e.g. Module instance name /// </summary> public string Name { get; set; } /// <summary> /// When set, provides the expected type of injected instance, e.g. module type /// </summary> public Type Type { get; set; } public override string ToString() { return "{0}(Type: {1}, Name: {2})".Args(GetType().Name, Type?.Name ?? CoreConsts.NULL_STRING, Name ?? CoreConsts.NULL_STRING); } /// <summary> /// System code not intended to be used by business apps. /// Applies attribute with auto-scoping rules - the system tries to detect /// what is trying to be injected based on the supplied type of the field. /// Return true if assignment was made /// </summary> public bool Apply(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { var tf = fInfo.FieldType; if (Type!=null && !tf.IsAssignableFrom(Type)) throw new DependencyInjectionException(StringConsts.DI_ATTRIBUTE_TYPE_INCOMPATIBILITY_ERROR.Args( Type.DisplayNameWithExpandedGenericArgs(), target.GetType().DisplayNameWithExpandedGenericArgs(), fInfo.ToDescription())); try { return DoApply(target, fInfo, injector); } catch(Exception error) { throw new DependencyInjectionException(StringConsts.DI_ATTRIBUTE_APPLY_ERROR.Args( GetType().Name, target.GetType().DisplayNameWithExpandedGenericArgs(), fInfo.ToDescription(), error.ToMessageWithType()), error); } } protected virtual bool DoApply(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { var tf = fInfo.FieldType; //0. Inject application itself if (tf==typeof(IApplication)) { fInfo.SetValue(target, injector.App); return true; } //1. Inject module if (typeof(IModule).IsAssignableFrom(tf)) return TryInjectModule(target, fInfo, injector); //2. Try app root objects if (TryInjectAppRootObjects(target, fInfo, injector)) return true; return false; } /// <summary> /// Tries to perform module injection by name or type, returning true if assignment was made /// </summary> protected virtual bool TryInjectModule(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { var needType = Type==null ? fInfo.FieldType : Type; IModule module = null; if (Name.IsNotNullOrWhiteSpace()) { module = injector.App.ModuleRoot.ChildModules[Name]; if (module==null) return false; if (!needType.IsAssignableFrom(module.GetType())) return false;//type mismatch } else { module = injector.App.ModuleRoot.ChildModules .OrderedValues .FirstOrDefault( m => needType.IsAssignableFrom(m.GetType()) ); if (module == null) return false; } fInfo.SetValue(target, module); return true; } /// <summary> /// Tries to inject app root object (such as Log, Glue etc.) returning true on a successful assignment. /// The default implementation trips on a first match /// </summary> protected virtual bool TryInjectAppRootObjects(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { var tf = fInfo.FieldType; var needType = Type==null ? tf : Type; foreach(var appRoot in GetApplicationRoots(injector)) { if (needType.IsAssignableFrom(appRoot.GetType()))//trips on first match { if (Name.IsNotNullOrWhiteSpace() && appRoot is INamed named) if (!Name.EqualsIgnoreCase(named.Name)) continue; fInfo.SetValue(target, appRoot); return true; } } return false; } /// <summary> /// Enumerates app injectable roots (root application chassis objects) /// </summary> protected virtual IEnumerable<object> GetApplicationRoots(IApplicationDependencyInjector injector) => injector.GetApplicationRoots(); //the default clones roots from the injector } /// <summary> /// Performs application module injection /// </summary> public class InjectModuleAttribute : InjectAttribute { protected override bool DoApply(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { return TryInjectModule(target, fInfo, injector); } } /// <summary> /// Performs application singleton instance injection based on the type. If Name is specified and /// a singleton instance is INamed, also check for name match /// </summary> public class InjectSingletonAttribute : InjectAttribute { protected override bool DoApply(object target, FieldInfo fInfo, IApplicationDependencyInjector injector) { return TryInjectAppRootObjects(target, fInfo, injector); } protected override IEnumerable<object> GetApplicationRoots(IApplicationDependencyInjector injector) { foreach (var singleton in injector.App.Singletons) yield return singleton; } } //class MyClass //{ // [Inject] private ICardRenderingModule m_CardRedering; // [InjectModule] private IBuzzerModule m_Buzzer; // [Inject] private ILog m_Logger; // [InjectSingleton] private MySingleton m_Singleton; //} }
34.365591
132
0.665832
[ "MIT" ]
saleyn/azos
src/Azos/Apps/Injection/Attributes.cs
6,392
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using Microsoft.AspNet.Identity; using WebProject.Domain; using WebProject.Infrastructure; using Microsoft.AspNet.Identity.EntityFramework; using System.Threading.Tasks; using System.Web.Mvc; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; namespace WebProject.Domain { public class Attendee { public Attendee() { this.Users = new HashSet<User>(); } public Guid Id { get; set; } public virtual ICollection<User> Users { get; set; } public string ExternalUserMailAddresses { get; set; } public string GetAttendeeMailAddresses() { StringBuilder mailAddress = new StringBuilder(); foreach (var user in this.Users) { mailAddress.Append(user.Email + "; "); } mailAddress.Append(this.ExternalUserMailAddresses); return mailAddress.ToString(); } public void SetAttendeeMailAddresses(string mailAddresses,WebProjectDbContext webProjectDbContext) { StringBuilder tempAddresses = new StringBuilder(); if (string.IsNullOrEmpty(mailAddresses)) { throw new InvalidOperationException("E-Mail Address cannot be empty"); } string[] arrayAddresses = mailAddresses.Split(';'); foreach (var address in arrayAddresses) { string tempAddress = address.Trim(' '); User user = webProjectDbContext.Users.Where(u => u.Email == tempAddress).FirstOrDefault(); if (user == null) { tempAddresses.Append(tempAddress + "; "); } else { this.Users.Add(user); } } this.ExternalUserMailAddresses = tempAddresses.ToString(); } } }
29.492754
106
0.583292
[ "MIT" ]
airfoot/WebProject
WebProject/Domain/Attendee.cs
2,037
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("bypshttp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("bypshttp")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("641cbba7-c115-45b8-bbb9-79c54c1fb8c5")] // 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")] [assembly: System.CLSCompliant(true)]
38.526316
85
0.726093
[ "MIT" ]
markusessigde/byps
csharp/bypshttp/Properties/AssemblyInfo.cs
1,467
C#
/********************************************************************* * * Copyright (C) 2002 Andrew Khan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************/ // Port to C# // Chris Laforet // Wachovia, a Wells-Fargo Company // Feb 2010 using CSharpJExcel.Jxl.Biff; namespace CSharpJExcel.Jxl.Write.Biff { /** * Record which stores the maximum iterations option from the Options * dialog box */ class CalcCountRecord : WritableRecordData { /** * The iteration count */ private int calcCount; /** * The binary data to write to the output file */ private byte[] data; /** * Constructor * * @param cnt the count indicator */ public CalcCountRecord(int cnt) : base(Type.CALCCOUNT) { calcCount = cnt; } /** * Gets the data to write out to the file * * @return the binary data */ public override byte[] getData() { byte[] data = new byte[2]; IntegerHelper.getTwoBytes(calcCount, data, 0); return data; } } }
24.109589
76
0.630682
[ "Apache-2.0" ]
Tatetaylor/kbplumbapp
CSharpJExcel/CSharpJExcel/CSharpJExcel/Jxl/Write/Biff/CalcCountRecord.cs
1,760
C#
using UnityEditor; using UIWidgets; namespace UIWidgetsSamples { [CanEditMultipleObjects] [CustomEditor(typeof(ListViewUnderlineSample), true)] public class ListViewUnderlineSampleEditor : ListViewCustomEditor { } }
20.181818
66
0.81982
[ "Apache-2.0" ]
GameDeveloperS001/Unity-EmojiText
TextInlineSpritePro/Assets/UIWidgets/Sample Assets/ListView/Editor/ListViewUnderlineSampleEditor.cs
224
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// KoubeiMallScanpurchaseUserverifyVerifyResponse. /// </summary> public class KoubeiMallScanpurchaseUserverifyVerifyResponse : AopResponse { } }
21
78
0.692308
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiMallScanpurchaseUserverifyVerifyResponse.cs
273
C#
namespace Orange.TestTask.RestQueueService.Infrastructure { public class InfrastructureSettings { public string DbConnectionString { get; set; } public string QueueConnectionString { get; set; } } }
28.375
58
0.709251
[ "MIT" ]
nkiruhin/Orange.TestTask.RestQueueService
src/Orange.TestTask.RestQueueService.Infrastructure/InfrastructureSettings.cs
229
C#
using System; using System.Linq.Expressions; using Xunit; using Should; namespace AutoMapper.UnitTests.Constructors { public class When_renaming_class_constructor_parameter : AutoMapperSpecBase { Destination _destination; public class Source { public InnerSource InnerSource { get; set; } } public class InnerSource { public string Name { get; set; } } public class Destination { public Destination(InnerDestination inner) { InnerDestination = inner; } public InnerDestination InnerDestination { get; } } public class InnerDestination { public string Name { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(c => { c.CreateMap<Source, Destination>().ForCtorParam("inner", o=>o.MapFrom(s=>s.InnerSource)); c.CreateMap<InnerSource, InnerDestination>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { InnerSource = new InnerSource { Name = "Core" } }); } [Fact] public void Should_map_ok() { _destination.InnerDestination.Name.ShouldEqual("Core"); } } public class When_constructor_matches_with_prefix_and_postfix : AutoMapperSpecBase { PersonDto _destination; public class Person { public string PrefixNamePostfix { get; set; } } public class PersonDto { string name; public PersonDto(string name) { this.name = name; } public string Name => name; } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.RecognizePostfixes("postfix"); cfg.RecognizePrefixes("prefix"); cfg.CreateMap<Person, PersonDto>(); }); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { PrefixNamePostfix = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldEqual("John"); } } public class When_constructor_matches_with_destination_prefix_and_postfix : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { string name; public PersonDto(string prefixNamePostfix) { name = prefixNamePostfix; } public string Name => name; } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.RecognizeDestinationPostfixes("postfix"); cfg.RecognizeDestinationPrefixes("prefix"); cfg.CreateMap<Person, PersonDto>(); }); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldEqual("John"); } } public class When_constructor_matches_but_is_overriden_by_ConstructUsing : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { public PersonDto() { } public PersonDto(string name) { Name = name; } public string Name { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => cfg.CreateMap<Person, PersonDto>().ConstructUsing(p=>new PersonDto())); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldEqual("John"); } } public class When_constructor_is_match_with_default_value : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { public PersonDto(string name = null) { Name = name; } public string Name { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => cfg.CreateMap<Person, PersonDto>()); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldEqual("John"); } } public class When_constructor_is_partial_match_with_value_type : AutoMapperSpecBase { GeoCoordinate _destination; public class GeolocationDTO { public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } public struct GeoCoordinate { public GeoCoordinate(double longitude, double latitude, double x) { Longitude = longitude; Latitude = latitude; HorizontalAccuracy = 0; } public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<GeoCoordinate, GeolocationDTO>(); cfg.CreateMap<GeolocationDTO, GeoCoordinate>(); }); protected override void Because_of() { var source = new GeolocationDTO { Latitude = 34d, Longitude = -93d, HorizontalAccuracy = 100 }; _destination = Mapper.Map<GeoCoordinate>(source); } [Fact] public void Should_map_ok() { _destination.Latitude.ShouldEqual(34); _destination.Longitude.ShouldEqual(-93); _destination.HorizontalAccuracy.ShouldEqual(100); } } public class When_constructor_is_partial_match : AutoMapperSpecBase { GeoCoordinate _destination; public class GeolocationDTO { public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } public class GeoCoordinate { public GeoCoordinate() { } public GeoCoordinate(double longitude, double latitude, double x) { Longitude = longitude; Latitude = latitude; } public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } public double Altitude { get; set; } public double VerticalAccuracy { get; set; } public double Speed { get; set; } public double Course { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<GeoCoordinate, GeolocationDTO>(); cfg.CreateMap<GeolocationDTO, GeoCoordinate>() .ForMember(dest => dest.Altitude, opt => opt.Ignore()) .ForMember(dest => dest.VerticalAccuracy, opt => opt.Ignore()) .ForMember(dest => dest.Speed, opt => opt.Ignore()) .ForMember(dest => dest.Course, opt => opt.Ignore()); }); protected override void Because_of() { var source = new GeolocationDTO { Latitude = 34d, Longitude = -93d, HorizontalAccuracy = 100 }; _destination = Mapper.Map<GeoCoordinate>(source); } [Fact] public void Should_map_ok() { _destination.Latitude.ShouldEqual(34); _destination.Longitude.ShouldEqual(-93); _destination.HorizontalAccuracy.ShouldEqual(100); } } public class When_constructor_matches_but_the_destination_is_passed : AutoMapperSpecBase { Destination _destination = new Destination(); public class Source { public int MyTypeId { get; set; } } public class MyType { } public class Destination { private MyType _myType; public Destination() { } public Destination(MyType myType) { _myType = myType; } public MyType MyType { get { return _myType; } set { _myType = value; } } } protected override MapperConfiguration Configuration { get { return new MapperConfiguration(cfg => { cfg.RecognizePostfixes("Id"); cfg.CreateMap<Source, Destination>(); cfg.CreateMap<int, MyType>(); }); } } protected override void Because_of() { Mapper.Map(new Source(), _destination); } [Fact] public void Should_map_ok() { _destination.MyType.ShouldNotBeNull(); } } public class When_mapping_through_constructor_and_destination_has_setter : AutoMapperSpecBase { public class Source { public int MyTypeId { get; set; } } public class MyType { } Destination _destination; public class Destination { private MyType _myType; private Destination() { } public Destination(MyType myType) { _myType = myType; } public MyType MyType { get { return _myType; } private set { throw new Exception("Should not set through setter."); } } } protected override MapperConfiguration Configuration { get { return new MapperConfiguration(cfg => { cfg.RecognizePostfixes("Id"); cfg.CreateMap<Source, Destination>(); cfg.CreateMap<int, MyType>(); }); } } protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.MyType.ShouldNotBeNull(); } } public class When_mapping_an_optional_GUID_constructor : AutoMapperSpecBase { Destination _destination; public class Destination { public Destination(Guid id = default(Guid)) { Id = id; } public Guid Id { get; set; } } public class Source { public Guid Id { get; set; } } protected override MapperConfiguration Configuration { get { return new MapperConfiguration(c=>c.CreateMap<Source, Destination>()); } } protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.Id.ShouldEqual(Guid.Empty); } } public class When_mapping_a_constructor_parameter_from_nested_members : AutoMapperSpecBase { private Destination _destination; public class Source { public NestedSource Nested { get; set; } } public class NestedSource { public int Foo { get; set; } } public class Destination { public int Foo { get; } public Destination(int foo) { Foo = foo; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>().ForCtorParam("foo", opt => opt.MapFrom(s => s.Nested.Foo)); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { Nested = new NestedSource { Foo = 5 } }); } [Fact] public void Should_map_the_constructor_argument() { _destination.Foo.ShouldEqual(5); } } public class When_the_destination_has_a_matching_constructor_with_optional_extra_parameters : AutoMapperSpecBase { private Destination _destination; public class Source { public int Foo { get; set; } } public class Destination { private readonly int _foo; public int Foo { get { return _foo; } } public string Bar { get;} public Destination(int foo, string bar = "bar") { _foo = foo; Bar = bar; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Foo = 5 }); } [Fact] public void Should_map_the_constructor_argument() { _destination.Foo.ShouldEqual(5); _destination.Bar.ShouldEqual("bar"); } } public class When_mapping_to_an_object_with_a_constructor_with_a_matching_argument : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } public int Bar { get; set; } } public class Dest { private readonly int _foo; public int Foo { get { return _foo; } } public int Bar { get; set; } public Dest(int foo) { _foo = foo; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { Expression<Func<object, object>> ctor = (input) => new Dest((int)input); object o = ctor.Compile()(5); _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5, Bar = 10 }); } [Fact] public void Should_map_the_constructor_argument() { _dest.Foo.ShouldEqual(5); } [Fact] public void Should_map_the_existing_properties() { _dest.Bar.ShouldEqual(10); } } public class When_mapping_to_an_object_with_a_private_constructor : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private readonly int _foo; public int Foo { get { return _foo; } } private Dest(int foo) { _foo = foo; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }); } [Fact] public void Should_map_the_constructor_argument() { _dest.Foo.ShouldEqual(5); } } public class When_mapping_to_an_object_using_service_location : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private int _foo; private readonly int _addend; public int Foo { get { return _foo + _addend; } set { _foo = value; } } public Dest(int addend) { _addend = addend; } public Dest() : this(0) { } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.ConstructServicesUsing(t => new Dest(5)); cfg.CreateMap<Source, Dest>() .ConstructUsingServiceLocator(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }); } [Fact] public void Should_map_with_the_custom_constructor() { _dest.Foo.ShouldEqual(10); } } public class When_mapping_to_an_object_using_contextual_service_location : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private int _foo; private readonly int _addend; public int Foo { get { return _foo + _addend; } set { _foo = value; } } public Dest(int addend) { _addend = addend; } public Dest() : this(0) { } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.ConstructServicesUsing(t => new Dest(5)); cfg.CreateMap<Source, Dest>() .ConstructUsingServiceLocator(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }, opt => opt.ConstructServicesUsing(t => new Dest(6))); } [Fact] public void Should_map_with_the_custom_constructor() { _dest.Foo.ShouldEqual(11); } } public class When_mapping_to_an_object_with_multiple_constructors_and_constructor_mapping_is_disabled : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } public int Bar { get; set; } } public class Dest { public int Foo { get; set; } public int Bar { get; set; } public Dest(int foo) { throw new NotImplementedException(); } public Dest() { } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.DisableConstructorMapping(); cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5, Bar = 10 }); } [Fact] public void Should_map_the_existing_properties() { _dest.Foo.ShouldEqual(5); _dest.Bar.ShouldEqual(10); } } public class UsingMappingEngineToResolveConstructorArguments { [Fact] public void Should_resolve_constructor_arguments_using_mapping_engine() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldEqual(sourceBar.FooBar); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationFoo(DestinationBar bar) { _bar = bar; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class MappingMultipleConstructorArguments { [Fact] public void Should_resolve_constructor_arguments_using_mapping_engine() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar, new SourceBar("fooBar2")); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldEqual(sourceBar.FooBar); destinationFoo.Bar2.FooBar.ShouldEqual("fooBar2"); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationBar Bar2 { get; private set; } public DestinationFoo(DestinationBar bar, DestinationBar bar2) { _bar = bar; Bar2 = bar2; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceBar Bar2 { get; private set; } public SourceFoo(SourceBar bar, SourceBar bar2) { Bar = bar; Bar2 = bar2; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_multiple_optional_arguments { [Fact] public void Should_resolve_constructor_when_args_are_optional() { var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceFoo, DestinationFoo>()); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.ShouldBeNull(); destinationFoo.Str.ShouldEqual("hello"); } public class DestinationFoo { private readonly DestinationBar _bar; private string _str; public DestinationBar Bar { get { return _bar; } } public string Str { get { return _str; } } public DestinationFoo(DestinationBar bar=null,string str="hello") { _bar = bar; _str = str; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_single_optional_arguments { [Fact] public void Should_resolve_constructor_when_arg_is_optional() { var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceFoo, DestinationFoo>()); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.ShouldBeNull(); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationFoo(DestinationBar bar = null) { _bar = bar; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_string_optional_arguments { [Fact] public void Should_resolve_constructor_when_string_args_are_optional() { var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceFoo, DestinationFoo>()); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.A.ShouldEqual("a"); destinationFoo.B.ShouldEqual("b"); destinationFoo.C.ShouldEqual(3); } public class DestinationFoo { private string _a; private string _b; private int _c; public string A { get { return _a; } } public string B { get { return _b; } } public int C { get { return _c; } } public DestinationFoo(string a = "a",string b="b", int c = 3) { _a = a; _b = b; _c = c; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_configuring_ctor_param_members : AutoMapperSpecBase { public class Source { public int Value { get; set; } } public class Dest { public Dest(int thing) { Value1 = thing; } public int Value1 { get; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Dest>().ForCtorParam("thing", opt => opt.MapFrom(src => src.Value)); }); [Fact] public void Should_redirect_value() { var dest = Mapper.Map<Source, Dest>(new Source {Value = 5}); dest.Value1.ShouldEqual(5); } } }
26.383527
167
0.492101
[ "MIT" ]
rajabalu/AutoMapper
src/UnitTests/Constructors.cs
31,715
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. /*============================================================ ** ** ** Purpose: A wrapper for establishing a WeakReference to an Object. ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics; using Internal.Runtime.Augments; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class WeakReference : ISerializable { // If you fix bugs here, please fix them in WeakReference<T> at the same time. // Most methods using m_handle should use GC.KeepAlive(this) to avoid potential handle recycling // attacks (i.e. if the WeakReference instance is finalized away underneath you when you're still // handling a cached value of the handle then the handle could be freed and reused). internal volatile IntPtr m_handle; internal bool m_IsLongReference; // Creates a new WeakReference that keeps track of target. // Assumes a Short Weak Reference (ie TrackResurrection is false.) // public WeakReference(Object target) : this(target, false) { } //Creates a new WeakReference that keeps track of target. // public WeakReference(Object target, bool trackResurrection) { m_IsLongReference = trackResurrection; m_handle = GCHandle.ToIntPtr(GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak)); // Set the conditional weak table if the target is a __ComObject. TrySetComTarget(target); } protected WeakReference(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } Object target = info.GetValue("TrackedObject", typeof(Object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) m_IsLongReference = trackResurrection; m_handle = GCHandle.ToIntPtr(GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak)); // Set the conditional weak table if the target is a __ComObject. TrySetComTarget(target); } //Determines whether or not this instance of WeakReference still refers to an object //that has not been collected. // public virtual bool IsAlive { get { IntPtr h = m_handle; // In determining whether it is valid to use this object, we need to at least expose this // without throwing an exception. if (default(IntPtr) == h) return false; bool result = (RuntimeImports.RhHandleGet(h) != null || TryGetComTarget() != null); // We want to ensure that if the target is live, then we will // return it to the user. We need to keep this WeakReference object // live so m_handle doesn't get set to 0 or reused. // Since m_handle is volatile, the following statement will // guarantee the weakref object is live till the following // statement. return (m_handle == default(IntPtr)) ? false : result; } } //Returns a boolean indicating whether or not we're tracking objects until they're collected (true) //or just until they're finalized (false). // public virtual bool TrackResurrection { get { return m_IsLongReference; } } //Gets the Object stored in the handle if it's accessible. // Or sets it. // public virtual Object Target { get { IntPtr h = m_handle; // Should only happen when used illegally, like using a // WeakReference from a finalizer. if (default(IntPtr) == h) return null; Object o = RuntimeImports.RhHandleGet(h); if (o == null) { o = TryGetComTarget(); } // We want to ensure that if the target is live, then we will // return it to the user. We need to keep this WeakReference object // live so m_handle doesn't get set to 0 or reused. // Since m_handle is volatile, the following statement will // guarantee the weakref object is live till the following // statement. return (m_handle == default(IntPtr)) ? null : o; } set { IntPtr h = m_handle; if (h == default(IntPtr)) throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized); #if false // There is a race w/ finalization where m_handle gets set to // NULL and the WeakReference becomes invalid. Here we have to // do the following in order: // // 1. Get the old object value // 2. Get m_handle // 3. HndInterlockedCompareExchange(m_handle, newValue, oldValue); // // If the interlocked-cmp-exchange fails, then either we lost a race // with another updater, or we lost a race w/ the finalizer. In // either case, we can just let the other guy win. Object oldValue = RuntimeImports.RhHandleGet(h); h = m_handle; if (h == default(IntPtr)) throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized); GCHandle.InternalCompareExchange(h, value, oldValue, false /* isPinned */); #else // The above logic seems somewhat paranoid and even wrong. // // 1. It's the GC rather than any finalizer that clears weak handles (indeed there's no guarantee any finalizer is involved // at all). // 2. Retrieving the object from the handle atomically creates a strong reference to it, so // as soon as we get the handle contents above (before it's even assigned into oldValue) // the only race we can be in is with another setter. // 3. We don't really care who wins in a race between two setters: last update wins is just // as good as first update wins. If there was a race with the "finalizer" though, we'd // probably want the setter to win (otherwise we could nullify a set just because it raced // with the old object becoming unreferenced). // // The upshot of all of this is that we can just go ahead and set the handle. I suspect that // with further review I could prove that this class doesn't need to mess around with raw // IntPtrs at all and can simply use GCHandle directly, avoiding all these internal calls. // Check whether the new value is __COMObject. If so, add the new entry to conditional weak table. TrySetComTarget(value); RuntimeImports.RhHandleSet(h, value); #endif // Ensure we don't have any handle recycling attacks in this // method where the finalizer frees the handle. GC.KeepAlive(this); } } /// <summary> /// This method checks whether the target to the weakreference is a native COMObject in which case the native object might still be alive although the RuntimeHandle could be null. /// Hence we check in the conditionalweaktable maintained by the System.private.Interop.dll that maps weakreferenceInstance->nativeComObject to check whether the native COMObject is alive or not. /// and gets\create a new RCW in case it is alive. /// </summary> /// <returns></returns> private Object TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null) { return callbacks.GetCOMWeakReferenceTarget(this); } else { Debug.Fail("WinRTInteropCallback is null"); } #endif // ENABLE_WINRT return null; } /// <summary> /// This method notifies the System.private.Interop.dll to update the conditionalweaktable for weakreferenceInstance->target in case the target is __ComObject. This ensures that we have a means to /// go from the managed weak reference to the actual native object even though the managed counterpart might have been collected. /// </summary> /// <param name="target"></param> private void TrySetComTarget(object target) { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null) { callbacks.SetCOMWeakReferenceTarget(this, target); } else { Debug.Fail("WinRTInteropCallback is null"); } #endif // ENABLE_WINRT } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("TrackedObject", Target, typeof(Object)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", m_IsLongReference); // Do not rename (binary serialization) } // Free all system resources associated with this reference. ~WeakReference() { #pragma warning disable 420 // FYI - ref m_handle causes this. I asked the C# team to add in "ref volatile T" as a parameter type in a future version. IntPtr handle = Interlocked.Exchange(ref m_handle, default(IntPtr)); #pragma warning restore 420 if (handle != default(IntPtr)) ((GCHandle)handle).Free(); } } }
43.843373
205
0.591646
[ "MIT" ]
anydream/corert
src/System.Private.CoreLib/src/System/WeakReference.cs
10,917
C#
using System; using System.IO; using System.Linq; using Abp.Reflection.Extensions; namespace IODD.Web { /// <summary> /// This class is used to find root path of the web project in; /// unit tests (to find views) and entity framework core command line commands (to find conn string). /// </summary> public static class WebContentDirectoryFinder { public static string CalculateContentRootFolder() { var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(IODDCoreModule).GetAssembly().Location); if (coreAssemblyDirectoryPath == null) { throw new Exception("Could not find location of IODD.Core assembly!"); } var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath); while (!DirectoryContains(directoryInfo.FullName, "IODD.sln")) { if (directoryInfo.Parent == null) { throw new Exception("Could not find content root folder!"); } directoryInfo = directoryInfo.Parent; } var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "IODD.Web.Mvc"); if (Directory.Exists(webMvcFolder)) { return webMvcFolder; } var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "IODD.Web.Host"); if (Directory.Exists(webHostFolder)) { return webHostFolder; } throw new Exception("Could not find root folder of the web project!"); } private static bool DirectoryContains(string directory, string fileName) { return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName)); } } }
34.481481
118
0.596133
[ "MIT" ]
forestk20000/IODD-ABP
src/iodd-aspnet-core/src/IODD.Core/Web/WebContentFolderHelper.cs
1,862
C#
namespace NScan.SharedKernel.RuleDtos.ProjectScoped { public static class HasAttributesOnRuleMetadata { public const string HasAttributesOn = "hasAttributesOn"; public static RuleDescription Format(HasAttributesOnRuleComplementDto ruleDto) { var projectAssemblyName = ruleDto.ProjectAssemblyNamePattern.Text(); var classNameInclusionPattern = ruleDto.ClassNameInclusionPattern.Text(); var methodNameInclusionPattern = ruleDto.MethodNameInclusionPattern.Text(); return new RuleDescription($"{projectAssemblyName} {ruleDto.RuleName} {classNameInclusionPattern}:{methodNameInclusionPattern}"); } } }
40.3125
135
0.787597
[ "MIT" ]
grzesiek-galezowski/nscan
src/NScan.SharedKernel/RuleDtos/ProjectScoped/HasAttributesOnRuleMetadata.cs
647
C#