content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using Revenj.DatabasePersistence; using Revenj.DomainPatterns; using Revenj.Extensibility; namespace Revenj { /// <summary> /// Unit of work pattern. /// IDataContext with a transaction. /// Don't forget to Commit() before disposing /// </summary> public interface IUnitOfWork : IDataContext, IDisposable { /// <summary> /// Confirm database transaction. /// After commit, unit of work needs to be disposed /// </summary> void Commit(); /// <summary> /// Rollback database transaction. /// After rollback, unit of work needs to be disposed /// </summary> void Rollback(); } internal class UnitOfWork : IUnitOfWork { private readonly IObjectFactory Scope; private readonly IDatabaseQuery DatabaseQuery; private readonly IDatabaseQueryManager Manager; private readonly IDataContext Context; private bool Finished; public UnitOfWork(IObjectFactory factory) { Scope = factory.CreateInnerFactory(); Manager = factory.Resolve<IDatabaseQueryManager>(); DatabaseQuery = Manager.BeginTransaction(); Scope.RegisterInstance(DatabaseQuery); Context = Scope.Resolve<IDataContext>(); } public void Commit() { if (Finished) throw new InvalidOperationException("Transaction was already closed"); Finished = true; Manager.Commit(DatabaseQuery); } public void Rollback() { if (Finished) throw new InvalidOperationException("Transaction was already closed"); Finished = true; Manager.Rollback(DatabaseQuery); } public void Dispose() { if (!Finished) Rollback(); Scope.Dispose(); } public T Find<T>(string uri) where T : IIdentifiable { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Find<T>(uri); } public T[] Find<T>(IEnumerable<string> uris) where T : IIdentifiable { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Find<T>(uris); } public IQueryable<T> Query<T>() where T : IDataSource { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Query<T>(); } public T[] Search<T>(ISpecification<T> filter, int? limit, int? offset) where T : IDataSource { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Search<T>(filter, limit, offset); } public long Count<T>(ISpecification<T> filter) where T : IDataSource { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Count<T>(filter); } public bool Exists<T>(ISpecification<T> filter) where T : IDataSource { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Exists<T>(filter); } public void Create<T>(IEnumerable<T> aggregates) where T : IAggregateRoot { if (Finished) throw new InvalidOperationException("Transaction was already closed"); Context.Create(aggregates); } public void Update<T>(IEnumerable<KeyValuePair<T, T>> pairs) where T : IAggregateRoot { if (Finished) throw new InvalidOperationException("Transaction was already closed"); Context.Update(pairs); } public void Delete<T>(IEnumerable<T> aggregates) where T : IAggregateRoot { if (Finished) throw new InvalidOperationException("Transaction was already closed"); Context.Delete(aggregates); } public string[] Submit<T>(IEnumerable<T> events) where T : IEvent { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Submit(events); } public T Populate<T>(IReport<T> report) { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Populate(report); } public IObservable<NotifyInfo> Track<T>() where T : IIdentifiable { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.Track<T>(); } public IHistory<T>[] History<T>(IEnumerable<string> uris) where T : IObjectHistory { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.History<T>(uris); } public OlapCubeQueryBuilder<TSource> CubeBuilder<TCube, TSource>() where TCube : IOlapCubeQuery<TSource> where TSource : IDataSource { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.CubeBuilder<TCube, TSource>(); } public TResult[] InvalidItems<TValidation, TResult>(ISpecification<TResult> specification) where TValidation : IValidation<TResult> where TResult : IIdentifiable { if (Finished) throw new InvalidOperationException("Transaction was already closed"); return Context.InvalidItems<TValidation, TResult>(specification); } public void Queue<T>(IEnumerable<T> events) where T : IEvent { Context.Queue(events); } } /// <summary> /// Helper class for IServiceLocator /// </summary> public static class LocatorHelper { /// <summary> /// Create new unit of work from current locator /// </summary> /// <param name="locator">service locator</param> /// <returns>unit of work</returns> public static IUnitOfWork DoWork(this IServiceProvider locator) { return new UnitOfWork(locator.Resolve<IObjectFactory>()); } } }
28.43
96
0.690116
[ "BSD-3-Clause" ]
Kobus-Smit/revenj
csharp/Core/Revenj.Core/UnitOfWork.cs
5,688
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 overlaytests.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute( "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0" )] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ( (Settings) ( global::System.Configuration.ApplicationSettingsBase.Synchronized( new Settings() ) ) ); public static Settings Default { get { return defaultInstance; } } } }
38.962963
153
0.590304
[ "MIT" ]
xuri02/Eternal-Framework
overlaytests/Properties/Settings.Designer.cs
1,054
C#
// Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; namespace EGBench { public partial class CLI { [Command(Name = "publisher", Description = "Generate load against an eventgrid endpoint.")] [Subcommand(typeof(StartPublishCommand))] public class PublisherCLI { public CLI Parent { get; set; } private int OnExecute(CommandLineApplication app, IConsole console) { EGBenchLogger.WriteLine(console, "You must specify a subcommand."); console.WriteLine(); app.ShowHelp(); return 1; } [Command(Name = "start", Description = "Start generating load")] public class StartPublishCommand { public PublisherCLI Parent { get; set; } public CLI Root => this.Parent.Parent; [Option("-u|--topic-url", "REQUIRED. URL to which events should be posted to. Can specify multiple destinations like -u \"http://...\" -u \"http://...\" -u \"http://...\". Make sure number of URLs and number of topic names (-n) match up.", CommandOptionType.MultipleValue)] [Required] public string[] Addresses { get; set; } [Option("-n|--topic-name", "REQUIRED. String that should be used for stamping eventgrid event envelope's Topic field or cloud event envelope's source field. Can specify multiple values. Each value corresponds in order to the topic url.", CommandOptionType.MultipleValue)] [Required] public string[] TopicNames { get; set; } [Option("-s|--topic-schema", "Defaults to CloudEvent10. Possible values: EventGrid / CloudEvent10 / Custom. Specify the -d|--data-payload property for Custom topic schema.", CommandOptionType.SingleValue)] public string TopicSchema { get; set; } = "CloudEvent10"; [Option("-d|--data-payload", "Specify the data payload when -s|--topic-schema=Custom. Either give inline json or a file path.", CommandOptionType.SingleValue)] public string DataPayload { get; set; } [Option("-p|--publishers", "Number of concurrent publishing \"threads\" per topic, defaults to 100. Each publisher sends to all the topic urls/names specified in -u / -n.", CommandOptionType.SingleValue)] public short ConcurrentPublishersCount { get; set; } = 100; [Option("-r|--rps-per-publisher", "Requests per second generated by each publish \"thread\", defaults to 1. Must be between 1 and 1000, inclusive.", CommandOptionType.SingleValue)] public short RequestsPerSecondPerPublisher { get; set; } = 1; [Option("-c|--max-concurrent-requests-per-publisher", "Max requests kept in flight by each publisher before waiting for older requests to end, defaults to 10.", CommandOptionType.SingleValue)] public short MaxConcurrentRequestsPerPublisher { get; set; } = 10; [Option("-e|--events-per-request", "Number of events in each request, defaults to 1.", CommandOptionType.SingleValue)] public ushort EventsPerRequest { get; set; } = 1; [Option("-b|--event-size-in-bytes", "Number of bytes per event, defaults to 1024, doesn't take effect if -s|--topic-schema==Custom. Total request payload size = 2 + (EventsPerRequest * (EventSizeInBytes + 1) - 1)", CommandOptionType.SingleValue)] public uint EventSizeInBytes { get; set; } = 1024; [Option("-t|--runtime-in-minutes", "Time after which the publisher auto-shuts down, defaults to 0 minutes. Set to 0 to run forever.", CommandOptionType.SingleValue)] public ushort RuntimeInMinutes { get; set; } = 0; [Option("-v|--protocol-version", "The protocol version to use, defaults to 1.1.", CommandOptionType.SingleValue)] public string HttpVersion { get; set; } = "1.1"; [Option("|--skip-ssl-validation", "Skip SSL Server Certificate validation, defaults to false.", CommandOptionType.NoValue)] public bool SkipServerCertificateValidation { get; set; } = false; [Option("|--log-errors", "Log Status code, reason, and response content of all non-200 responses. Defaults to false.", CommandOptionType.NoValue)] public bool LogErrors { get; set; } = false; [Option("--total-requests", "Total number of requests to be made at the configured rate. When done, the publisher process will exit. Defaults to 0.", CommandOptionType.SingleValue)] public long TotalRequests { get; set; } = 0; public async Task<int> OnExecuteAsync(CommandLineApplication app, IConsole console) { this.LogOptionValues(console); this.Root.LogOptionValues(console); if (this.ConcurrentPublishersCount < 1) { throw new InvalidOperationException($"-p|--publishers must be greater than 1."); } if (this.RequestsPerSecondPerPublisher < 1 || this.RequestsPerSecondPerPublisher > 1000) { throw new InvalidOperationException($"-r|--rps-per-publisher must be between 1 and 1000 inclusive"); } if (this.Addresses.Length != this.TopicNames.Length || this.Addresses.Length < 1) { throw new InvalidOperationException($"-u|--topic-url and -n|--topic-name must have the same number of values (and have atleast one value)."); } IPayloadCreator[] payloadCreators = this.TopicNames.Select<string, IPayloadCreator>(topicName => this.TopicSchema.ToUpperInvariant() switch { "EVENTGRID" => new EventGridPayloadCreator(topicName, this.EventSizeInBytes, this.EventsPerRequest, console), "CLOUDEVENT10" => new CloudEvent10PayloadCreator(topicName, this.EventSizeInBytes, this.EventsPerRequest, console), "CUSTOM" => new CustomPayloadCreator(this.DataPayload, this.EventsPerRequest, console), _ => throw new NotImplementedException($"Unknown topic schema {this.TopicSchema}. Allowed schemas = EventGrid,CloudEvent10,Custom") }).ToArray(); Metric.InitializePublisher(this.Root); var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); Action<int, Exception> exit = CreateExitHandler(tcs, console, this.RuntimeInMinutes); PublishWorker[] workers = this.Addresses.Zip(payloadCreators).SelectMany( kvp => Enumerable.Range(1, this.ConcurrentPublishersCount) .Select(_ => new PublishWorker(this, kvp.First, kvp.Second, console, exit))) .ToArray(); int timerIntervalMs = (int)(1000 / (double)this.RequestsPerSecondPerPublisher); EGBenchLogger.WriteLine(console, $"{nameof(timerIntervalMs)}={timerIntervalMs} ms | Desired RPS={this.ConcurrentPublishersCount * this.RequestsPerSecondPerPublisher}"); long requestsQueued = 0; long totalRequestsQueued = 0; Timestamp lastLoggedTimestamp = Timestamp.Now; Timestamp beginTimestamp = Timestamp.Now; for (long iteration = 0; !(tcs.Task.IsCanceled | tcs.Task.IsFaulted | tcs.Task.IsCompletedSuccessfully); iteration++) { foreach (PublishWorker worker in workers) { if (worker.TryEnqueue(iteration)) { requestsQueued++; totalRequestsQueued++; } if (this.TotalRequests > 0 && totalRequestsQueued >= this.TotalRequests) { break; } } if (lastLoggedTimestamp.ElapsedSeconds >= this.Parent.Parent.MetricsIntervalSeconds) { lastLoggedTimestamp = Timestamp.Now; EGBenchLogger.WriteLine(console, $"Enqueued RPS in last {this.Parent.Parent.MetricsIntervalSeconds} seconds={requestsQueued / (float)this.Parent.Parent.MetricsIntervalSeconds:0.00f}."); requestsQueued = 0; } if (this.TotalRequests > 0 && totalRequestsQueued >= this.TotalRequests) { await Task.WhenAll(workers.Select(async w => { await Task.Yield(); await w.StopAsync(); }).ToArray()); EGBenchLogger.WriteLine($"Total Requests Made: {totalRequestsQueued}"); tcs.TrySetResult(0); break; } Timestamp expectedTimestampNow = beginTimestamp + TimeSpan.FromMilliseconds(iteration * timerIntervalMs); int lagMs = (int)Math.Ceiling((Timestamp.Now - expectedTimestampNow).TotalMilliseconds); if (lagMs < timerIntervalMs) { await Task.Delay(timerIntervalMs - lagMs); } else { // don't sleep, just continue; } } return await tcs.Task; } private static Action<int, Exception> CreateExitHandler(TaskCompletionSource<int> tcs, IConsole console, int runtimeInMinutes) { if (runtimeInMinutes > 0) { _ = Task.Delay(TimeSpan.FromMinutes(runtimeInMinutes)).ContinueWith( t => { EGBenchLogger.WriteLine(console, $"--runtime-in-minutes ({runtimeInMinutes}) Minutes have passed, stopping the process."); tcs.TrySetResult(0); }, TaskScheduler.Default); } return ExitHandler; void ExitHandler(int returnCode, Exception ex) { EGBenchLogger.WriteLine(console, $"{nameof(CreateExitHandler)} was invoked at stacktrace:\n{new StackTrace(true).ToString()}"); if (ex == null) { tcs.TrySetResult(returnCode); } else { tcs.TrySetException(ex); } } } } } } }
55.49763
289
0.546541
[ "MIT" ]
hiteshmadan/egbench
src/Publisher/CLI.Publisher.cs
11,712
C#
using System; using System.Text; using System.Collections.Generic; namespace JsonOrg { internal class JsonStringer { /** The output data, containing at most one top-level array or object. */ internal StringBuilder output = new StringBuilder(); /** * Lexical scoping elements within this stringer, necessary to insert the * appropriate separator characters (ie. commas and colons) and to detect * nesting errors. */ internal enum Scope { /** * An array with no elements requires no separators or newlines before * it is closed. */ EMPTY_ARRAY, /** * A array with at least one value requires a comma and newline before * the next element. */ NONEMPTY_ARRAY, /** * An object with no keys or values requires no separators or newlines * before it is closed. */ EMPTY_OBJECT, /** * An object whose most recent element is a key. The next element must * be a value. */ DANGLING_KEY, /** * An object with at least one name/value pair requires a comma and * newline before the next element. */ NONEMPTY_OBJECT, /** * A special bracketless array needed by JSONStringer.join() and * JSONObject.quote() only. Not used for JSON encoding. */ NULL, } /** * Unlike the original implementation, this stack isn't limited to 20 * levels of nesting. */ private List<Scope> stack = new List<Scope>(); /** * A string containing a full set of spaces for a single level of * indentation, or null for no pretty printing. */ private string indent; public JsonStringer() { indent = null; } internal JsonStringer(int indentSpaces) { char[] indentChars = new char[indentSpaces]; for (int i = 0 ; i < indentChars.Length ; ++i) { indentChars[i] = ' '; } indent = new String(indentChars); } /** * Begins encoding a new array. Each call to this method must be paired with * a call to {@link #endArray}. * * @return this stringer. */ public JsonStringer Array() { return Open(Scope.EMPTY_ARRAY, "["); } /** * Ends encoding the current array. * * @return this stringer. */ public JsonStringer EndArray() { return Close(Scope.EMPTY_ARRAY, Scope.NONEMPTY_ARRAY, "]"); } /** * Begins encoding a new object. Each call to this method must be paired * with a call to {@link #endObject}. * * @return this stringer. */ public JsonStringer Obj() { return Open(Scope.EMPTY_OBJECT, "{"); } /** * Ends encoding the current object. * * @return this stringer. */ public JsonStringer EndObject() { return Close(Scope.EMPTY_OBJECT, Scope.NONEMPTY_OBJECT, "}"); } /** * Enters a new scope by appending any necessary whitespace and the given * bracket. */ internal JsonStringer Open(Scope empty, String openBracket) { if (stack.Count == 0 && output.Length > 0) { throw new JsonException("Nesting problem: multiple top-level roots"); } BeforeValue(); stack.Add(empty); output.Append(openBracket); return this; } /** * Closes the current scope by appending any necessary whitespace and the * given bracket. */ internal JsonStringer Close(Scope empty, Scope nonempty, String closeBracket) { Scope context = Peek(); if (context != nonempty && context != empty) { throw new JsonException("Nesting problem"); } stack.RemoveAt(stack.Count - 1); if (context == nonempty) { Newline(); } output.Append(closeBracket); return this; } /** * Returns the value on the top of the stack. */ private Scope Peek() { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } return stack[stack.Count - 1]; } /** * Replace the value on the top of the stack with the given value. */ private void ReplaceTop(Scope topOfStack) { stack[stack.Count - 1] = topOfStack; } /** * Encodes {@code value}. * * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, * Integer, Long, Double or null. May not be {@link Double#isNaN() NaNs} * or {@link Double#isInfinite() infinities}. * @return this stringer. */ public JsonStringer Value(Object value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } if (value is JsonArray) { ((JsonArray) value).WriteTo(this); return this; } else if (value is JsonObject) { ((JsonObject) value).WriteTo(this); return this; } BeforeValue(); if (value == null || value == JsonObject.NULL) { output.Append(value); } else if (value is bool) { output.Append(value.ToString().ToLower()); } else if (Json.IsNumber(value)) { output.Append(JsonObject.NumberToString(value)); } else { Str(value.ToString()); } return this; } /** * Encodes {@code value} to this stringer. * * @return this stringer. */ public JsonStringer Value(bool value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(value); return this; } /** * Encodes {@code value} to this stringer. * * @param value a finite value. May not be {@link Double#isNaN() NaNs} or * {@link Double#isInfinite() infinities}. * @return this stringer. */ public JsonStringer Value(double value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(JsonObject.NumberToString(value)); return this; } /** * Encodes {@code value} to this stringer. * * @return this stringer. */ public JsonStringer Value(long value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(value); return this; } private void Str(string value) { output.Append("\""); for (int i = 0, length = value.Length ; i < length; i++) { char c = value[i]; /* * From RFC 4627, "All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." */ switch (c) { case '"': case '\\': case '/': output.Append('\\').Append(c); break; case '\t': output.Append("\\t"); break; case '\b': output.Append("\\b"); break; case '\n': output.Append("\\n"); break; case '\r': output.Append("\\r"); break; case '\f': output.Append("\\f"); break; default: if (c <= 0x1F) { output.Append(string.Format("\\u{0:0000X}", (int) c)); } else { output.Append(c); } break; } } output.Append("\""); } private void Newline() { if (indent == null) { return; } output.Append("\n"); for (int i = 0; i < stack.Count; i++) { output.Append(indent); } } /** * Encodes the key (property name) to this stringer. * * @param name the name of the forthcoming value. May not be null. * @return this stringer. */ public JsonStringer Key(string name) { if (name == null) { throw new JsonException("Names must be non-null"); } BeforeKey(); Str(name); return this; } /** * Inserts any necessary separators and whitespace before a name. Also * adjusts the stack to expect the Key's value. */ private void BeforeKey() { Scope context = Peek(); if (context == Scope.NONEMPTY_OBJECT) { // first in object output.Append(','); } else if (context != Scope.EMPTY_OBJECT) { // not in an object! throw new JsonException("Nesting problem"); } Newline(); ReplaceTop(Scope.DANGLING_KEY); } /** * Inserts any necessary separators and whitespace before a literal value, * inline array, or inline object. Also adjusts the stack to expect either a * closing bracket or another element. */ private void BeforeValue() { if (stack.Count == 0) { return; } Scope context = Peek(); if (context == Scope.EMPTY_ARRAY) { // first in array ReplaceTop(Scope.NONEMPTY_ARRAY); Newline(); } else if (context == Scope.NONEMPTY_ARRAY) { // another in array output.Append(','); Newline(); } else if (context == Scope.DANGLING_KEY) { // value for key output.Append(indent == null ? ":" : ": "); ReplaceTop(Scope.NONEMPTY_OBJECT); } else if (context != Scope.NULL) { throw new JsonException("Nesting problem"); } } /** * Returns the encoded JSON string. * * <p>If invoked with unterminated arrays or unclosed objects, this method's * return value is undefined. * * <p><strong>Warning:</strong> although it contradicts the general contract * of {@link Object#toString}, this method returns null if the stringer * contains no data. */ public override string ToString() { return output.Length == 0 ? null : output.ToString(); } } }
27.498701
83
0.527439
[ "Apache-2.0" ]
KiiPlatform/KiiCloudUnitySDK
JsonOrg/json/JsonStringer.cs
10,587
C#
using System; namespace Ateliex.Modules.Decisoes.Comerciais { public class ServicoDePlanejamentoComercial : IPlanejamentoComercial { public ServicoDePlanejamentoComercial() { } public PlanoComercial CriaPlano(SolicitacaoDeCriacaoDePlanoComercial solicitacao) { throw new NotImplementedException(); } public Custo AdicionaCustoDePlanoComercial(SolicitacaoDeAdicaoDeCustoDePlanoComercial solicitacao) { throw new NotImplementedException(); } public ItemDePlanoComercial AdicionaItemDePlanoComercial(SolicitacaoDeAdicaoDeItemDePlanoComercial solicitacao) { throw new NotImplementedException(); } public void ExcluiCustoDePlanoComercial(string codigo, string descricao) { throw new NotImplementedException(); } public void ExcluiItemDePlanoComercial(string codigo, int id) { throw new NotImplementedException(); } public void ExcluiPlano(string codigo) { throw new NotImplementedException(); } } }
26.860465
119
0.65974
[ "MIT" ]
ateliex/UseCaseDrivenDesign
src/Ateliex.Application.Core/Modules/Decisoes/Comerciais/ServicoDePlanejamentoComercial.cs
1,157
C#
using Ghostly.Core; using Ghostly.Core.Diagnostics; using Ghostly.Core.Pal; namespace Ghostly { public static class SettingsExtensions { public static bool GetShowNotificationToasts(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("ShowNotificationsToasts", defaultValue: true); } public static void SetShowNotificationToasts(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("ShowNotificationsToasts", value); } public static bool GetAggregateNotificationToasts(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("AggregateNotificationToasts", defaultValue: false); } public static void SetAggregateNotificationToasts(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("AggregateNotificationToasts", value); } public static Theme GetAppBackgroundRequestedTheme(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue<Theme>("AppBackgroundRequestedTheme"); } public static void SetAppBackgroundRequestedTheme(this ILocalSettings settings, Theme theme) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue<Theme>("AppBackgroundRequestedTheme", theme); } public static bool GetAllowMeteredConnection(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.AllowMeteredConnection, defaultValue: false); } public static void SetAllowMeteredConnection(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.AllowMeteredConnection, value); } public static bool GetTelemetryEnabled(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.TelemetryEnabled, defaultValue: true); } public static void SetTelemetryEnabled(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.TelemetryEnabled, value); } public static bool GetSynchronizationEnabled(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("SynchronizationEnabled", defaultValue: true); } public static void SetSynchronizationEnabled(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("SynchronizationEnabled", value); } public static int GetSynchronizationInterval(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("SynchronizationInterval", defaultValue: 10); } public static void SetSynchronizationInterval(this ILocalSettings settings, int value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("SynchronizationInterval", value); } public static LogLevel GetLogLevel(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return (LogLevel)settings.GetValue("LogLevel", (int)LogLevel.Information); } public static void SetLogLevel(this ILocalSettings settings, LogLevel value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("LogLevel", (int)value); } public static bool GetShowBadge(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("ShowBadge", defaultValue: true); } public static void SetShowBadge(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("ShowBadge", value); } public static bool GetScrollToLastComment(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.ScrollToLastComment, defaultValue: true); } public static void SetScrollToLastComment(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.ScrollToLastComment, value); } public static bool GetSetSynchronizeUnreadState(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.SynchronizeUnreadState, defaultValue: true); } public static void SetSynchronizeUnreadState(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.SynchronizeUnreadState, value); } public static GhostlyTheme GetTheme(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return (GhostlyTheme)settings.GetValue("Theme", (int)GhostlyTheme.Default); } public static void SetTheme(this ILocalSettings settings, GhostlyTheme theme) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("Theme", (int)theme); } public static bool GetMarkMutedAsRead(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue("MarkMutedAsRead", defaultValue: false); } public static void SetMarkMutedAsRead(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue("MarkMutedAsRead", value); } public static bool GetAutomaticallyMarkNotificationsAsRead(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.AutomaticallyMarkNotificationsAsRead, defaultValue: false); } public static void SetAutomaticallyMarkNotificationsAsRead(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.AutomaticallyMarkNotificationsAsRead, value); } public static bool GetShowAvatars(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.ShowAvatars, defaultValue: true); } public static void SetShowAvatars(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.ShowAvatars, value); } public static bool GetPreferInternetAvatars(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.PreferInternetAvatars, defaultValue: true); } public static void SetPreferInternetAvatars(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.PreferInternetAvatars, value); } public static bool GetSynchronizeAvatars(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue(Constants.Settings.SynchronizeAvatars, defaultValue: true); } public static void SetSynchronizeAvatars(this ILocalSettings settings, bool value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } settings.SetValue(Constants.Settings.SynchronizeAvatars, value); } public static string GetCurrentCulture(this ILocalSettings settings) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } return settings.GetValue<string>(Constants.Settings.CurrentCulture, defaultValue: null); } public static void SetCurrentCulture(this ILocalSettings settings, string value) { if (settings is null) { throw new System.ArgumentNullException(nameof(settings)); } if (value is null) { throw new System.ArgumentNullException(nameof(value)); } settings.SetValue(Constants.Settings.CurrentCulture, value); } } }
31.986667
115
0.590496
[ "MIT" ]
AlexRogalskiy/ghostly
src/Ghostly/Extensions/SettingsExtensions.cs
11,995
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ThirdPartyAPI { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
27.666667
70
0.713855
[ "MIT" ]
CodeMoggy/AADSignInDialogAPI
ThirdPartyAPI/Global.asax.cs
666
C#
using Microsoft.Extensions.DependencyInjection; using StackExchange.Redis.Branch.Repository; using StackExchange.Redis.Branch.UnitTest.Fakes; using System.Reflection; using Xunit; namespace StackExchange.Redis.Branch.UnitTest { public class ServiceCollectionExtensionsTest { [Fact] public void AddRedisBranch_AddBranchesToServiceCollection_ReturnRedisBranch() { //Arrange IServiceCollection services = new ServiceCollection(); services.AddSingleton<IConnectionMultiplexer>(sp => { return FakesFactory.CreateConnectionMultiplexerFake(); }); //Act services.AddRedisBranch(Assembly.GetExecutingAssembly()); //Assert //Connection Multiplexer and StockRepository Assert.Equal(2, services.Count); } [Fact] public void AddRedisBranch_AddBranchesToServiceCollectionAndBuildProvider_GetRedisBranch() { //Arrange IServiceCollection services = new ServiceCollection(); services.AddSingleton<IConnectionMultiplexer>(sp => { return FakesFactory.CreateConnectionMultiplexerFake(); }); //Act services.AddRedisBranch(Assembly.GetExecutingAssembly()); ServiceProvider provider = services.BuildServiceProvider(); IRedisRepository<StockEntity> notNullStockEntity = provider.GetRequiredService<IRedisRepository<StockEntity>>(); //Assert Assert.NotNull(notNullStockEntity); } } }
33.22449
124
0.650491
[ "MIT" ]
dogabariscakmak/StackExchange.Redis.Branch
src/tests/StackExchange.Redis.Branch.UnitTest/ServiceCollectionExtensionsTest.cs
1,630
C#
/* * Consumer Data Standards * * API sets created by the Australian Consumer Data Standards to meet the needs of the Consumer Data Right * * OpenAPI spec version: 1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; namespace ConsumerDataStandards.Models { /// <summary> /// /// </summary> [DataContract] public partial class ResponseBankingAccountList : IEquatable<ResponseBankingAccountList> { /// <summary> /// Gets or Sets Data /// </summary> [Required] [DataMember(Name="data")] public ResponseBankingAccountListData Data { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [Required] [DataMember(Name="links")] public LinksPaginated Links { get; set; } /// <summary> /// Gets or Sets Meta /// </summary> [Required] [DataMember(Name="meta")] public MetaPaginated Meta { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ResponseBankingAccountList {\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" Meta: ").Append(Meta).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((ResponseBankingAccountList)obj); } /// <summary> /// Returns true if ResponseBankingAccountList instances are equal /// </summary> /// <param name="other">Instance of ResponseBankingAccountList to be compared</param> /// <returns>Boolean</returns> public bool Equals(ResponseBankingAccountList other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ( Data == other.Data || Data != null && Data.Equals(other.Data) ) && ( Links == other.Links || Links != null && Links.Equals(other.Links) ) && ( Meta == other.Meta || Meta != null && Meta.Equals(other.Meta) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Data != null) hashCode = hashCode * 59 + Data.GetHashCode(); if (Links != null) hashCode = hashCode * 59 + Links.GetHashCode(); if (Meta != null) hashCode = hashCode * 59 + Meta.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(ResponseBankingAccountList left, ResponseBankingAccountList right) { return Equals(left, right); } public static bool operator !=(ResponseBankingAccountList left, ResponseBankingAccountList right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
31.414474
106
0.53466
[ "MIT" ]
FahaoTang/cds-au-schemas
src/ConsumerDataStandards/Models/ResponseBankingAccountList.cs
4,775
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections.Generic; using System.Text; using Google.GData.Spreadsheets; using ClearCanvas.Desktop.Actions; using ClearCanvas.Common; using ClearCanvas.Desktop; using ClearCanvas.Common.Utilities; using ClearCanvas.Desktop.Tools; using Google.GData.Client; namespace ClearCanvas.Samples.Calendar { [MenuAction("show", "global-menus/Google/Spreadsheet")] [ClickHandler("show", "Show")] [ExtensionOf(typeof(DesktopToolExtensionPoint))] public class SpreadsheetTool : Tool<IDesktopToolContext> { public void Show() { Spreadsheet sheet = Spreadsheet.GetByTitle("DevConf"); Worksheet worksheet = sheet.FirstWorksheet; List<WorksheetRow> rows = worksheet.ListRows(new Dictionary<string, string>()); foreach (WorksheetRow row in rows) { Console.WriteLine(row["Name"] + row["Age"]); row["Age"] += "1"; row.Save(); } } } public class Spreadsheet { const string URL = "http://spreadsheets.google.com/feeds/spreadsheets/private/full"; private SpreadsheetEntry _entry; private SpreadsheetsService _service; public static List<Spreadsheet> ListAll() { SpreadsheetsService service = new SpreadsheetsService("ClearCanvas-Workstation-1.0"); service.setUserCredentials("jresnick", "bl00b0lt"); SpreadsheetQuery query = new SpreadsheetQuery(); SpreadsheetFeed feed = service.Query(query); return CollectionUtils.Map<SpreadsheetEntry, Spreadsheet, List<Spreadsheet>>( feed.Entries, delegate(SpreadsheetEntry entry) { return new Spreadsheet(service, entry); }); } public static Spreadsheet GetByTitle(string title) { SpreadsheetsService service = new SpreadsheetsService("ClearCanvas-Workstation-1.0"); service.setUserCredentials("jresnick", "bl00b0lt"); SpreadsheetQuery query = new SpreadsheetQuery(); query.Title = title; SpreadsheetFeed feed = service.Query(query); return feed.Entries.Count > 0 ? new Spreadsheet(service, (SpreadsheetEntry)feed.Entries[0]) : null; } internal Spreadsheet(SpreadsheetsService service, SpreadsheetEntry entry) { _entry = entry; _service = service; } public string Title { get { return _entry.Title.Text; } } public Worksheet FirstWorksheet { get { List<Worksheet> worksheets = ListWorksheets(); return worksheets.Count > 0 ? worksheets[0] : null; } } public List<Worksheet> ListWorksheets() { AtomLink link = _entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null); WorksheetQuery query = new WorksheetQuery(link.HRef.ToString()); WorksheetFeed feed = _service.Query(query); return CollectionUtils.Map<WorksheetEntry, Worksheet, List<Worksheet>>( feed.Entries, delegate(WorksheetEntry entry) { return new Worksheet(_service, entry); }); } } public class Worksheet { private WorksheetEntry _entry; private SpreadsheetsService _service; internal Worksheet(SpreadsheetsService service, WorksheetEntry entry) { _entry = entry; _service = service; } public string Title { get { return _entry.Title.Text; } } public List<WorksheetRow> ListRows(Dictionary<string, string> parameters) { AtomLink listFeedLink = _entry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); ListQuery query = new ListQuery(listFeedLink.HRef.ToString()); string sq = CollectionUtils.Reduce<string, string>(parameters.Keys, "", delegate(string key, string memo) { return (string.IsNullOrEmpty(memo) ? "" : " and ") + string.Format("{0}={1}", key, parameters[key]); }); query.SpreadsheetQuery = sq; ListFeed feed = _service.Query(query); return CollectionUtils.Map<ListEntry, WorksheetRow, List<WorksheetRow>>( feed.Entries, delegate(ListEntry entry) { return new WorksheetRow(feed, entry); }); } } public class WorksheetRow { private bool _unsaved; private ListEntry _entry; private ListFeed _feed; internal WorksheetRow(ListFeed feed, ListEntry entry) { _entry = entry; _feed = feed; } internal WorksheetRow(ListFeed feed) { // TODO need to pre-init listEntry columns _feed = feed; _entry = new ListEntry(); _unsaved = true; } public void Save() { if (_unsaved) { _entry = _feed.Insert(_entry) as ListEntry; _unsaved = false; } else { _entry = _entry.Update() as ListEntry; } } public string this[string key] { get { ListEntry.Custom entry = CollectionUtils.SelectFirst<ListEntry.Custom>(_entry.Elements, delegate(ListEntry.Custom e) { return e.LocalName.Equals(key, StringComparison.CurrentCultureIgnoreCase); }); return entry == null ? null : entry.Value; } set { ListEntry.Custom entry = CollectionUtils.SelectFirst<ListEntry.Custom>(_entry.Elements, delegate(ListEntry.Custom e) { return e.LocalName.Equals(key, StringComparison.CurrentCultureIgnoreCase); }); if (entry == null) { entry = new ListEntry.Custom(); _entry.Elements.Add(entry); } entry.Value = value; } } } }
32.565217
130
0.561341
[ "Apache-2.0" ]
SNBnani/Xian
Samples/Google/Calendar/Spreadsheet.cs
6,741
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3d12umddi.h(2805,9) namespace DirectN { public enum D3D12DDI_3DPIPELINELEVEL { D3D12DDI_3DPIPELINELEVEL_1_0_CORE = 2, D3D12DDI_3DPIPELINELEVEL_11_0 = 10, D3D12DDI_3DPIPELINELEVEL_11_1 = 11, D3D12DDI_3DPIPELINELEVEL_12_0 = 12, D3D12DDI_3DPIPELINELEVEL_12_1 = 13, } }
29.692308
87
0.702073
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/D3D12DDI_3DPIPELINELEVEL.cs
388
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; using Azure.ResourceManager.Resources.Models; namespace Azure.ResourceManager.Network { /// <summary> A Class representing a P2SVpnGateway along with the instance operations that can be performed on it. </summary> public partial class P2SVpnGateway : ArmResource { private readonly ClientDiagnostics _clientDiagnostics; private readonly P2SVpnGatewaysRestOperations _p2sVpnGatewaysRestClient; private readonly P2SVpnGatewayData _data; /// <summary> Initializes a new instance of the <see cref="P2SVpnGateway"/> class for mocking. </summary> protected P2SVpnGateway() { } /// <summary> Initializes a new instance of the <see cref = "P2SVpnGateway"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="resource"> The resource that is the target of operations. </param> internal P2SVpnGateway(ArmResource options, P2SVpnGatewayData resource) : base(options, resource.Id) { HasData = true; _data = resource; _clientDiagnostics = new ClientDiagnostics(ClientOptions); _p2sVpnGatewaysRestClient = new P2SVpnGatewaysRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); } /// <summary> Initializes a new instance of the <see cref="P2SVpnGateway"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal P2SVpnGateway(ArmResource options, ResourceIdentifier id) : base(options, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _p2sVpnGatewaysRestClient = new P2SVpnGatewaysRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); } /// <summary> Initializes a new instance of the <see cref="P2SVpnGateway"/> class. </summary> /// <param name="clientOptions"> The client options to build client context. </param> /// <param name="credential"> The credential to build client context. </param> /// <param name="uri"> The uri to build client context. </param> /// <param name="pipeline"> The pipeline to build client context. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal P2SVpnGateway(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _p2sVpnGatewaysRestClient = new P2SVpnGatewaysRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.Network/p2svpnGateways"; /// <summary> Gets the valid resource type for the operations. </summary> protected override ResourceType ValidResourceType => ResourceType; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual P2SVpnGatewayData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } /// <summary> Retrieves the details of a virtual wan p2s vpn gateway. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<Response<P2SVpnGateway>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Get"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new P2SVpnGateway(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Retrieves the details of a virtual wan p2s vpn gateway. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<P2SVpnGateway> Get(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Get"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new P2SVpnGateway(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public async virtual Task<IEnumerable<Location>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default) { return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false); } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public virtual IEnumerable<Location> GetAvailableLocations(CancellationToken cancellationToken = default) { return ListAvailableLocations(ResourceType, cancellationToken); } /// <summary> Deletes a virtual wan p2s vpn gateway. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<P2SVpnGatewayDeleteOperation> DeleteAsync(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Delete"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayDeleteOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes a virtual wan p2s vpn gateway. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual P2SVpnGatewayDeleteOperation Delete(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Delete"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); var operation = new P2SVpnGatewayDeleteOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates virtual wan p2s vpn gateway tags. </summary> /// <param name="p2SVpnGatewayParameters"> Parameters supplied to update a virtual wan p2s vpn gateway tags. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="p2SVpnGatewayParameters"/> is null. </exception> public async virtual Task<P2SVpnGatewayUpdateTagsOperation> UpdateAsync(TagsObject p2SVpnGatewayParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (p2SVpnGatewayParameters == null) { throw new ArgumentNullException(nameof(p2SVpnGatewayParameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Update"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.UpdateTagsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, p2SVpnGatewayParameters, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayUpdateTagsOperation(this, _clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateUpdateTagsRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, p2SVpnGatewayParameters).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates virtual wan p2s vpn gateway tags. </summary> /// <param name="p2SVpnGatewayParameters"> Parameters supplied to update a virtual wan p2s vpn gateway tags. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="p2SVpnGatewayParameters"/> is null. </exception> public virtual P2SVpnGatewayUpdateTagsOperation Update(TagsObject p2SVpnGatewayParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (p2SVpnGatewayParameters == null) { throw new ArgumentNullException(nameof(p2SVpnGatewayParameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Update"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.UpdateTags(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, p2SVpnGatewayParameters, cancellationToken); var operation = new P2SVpnGatewayUpdateTagsOperation(this, _clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateUpdateTagsRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, p2SVpnGatewayParameters).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the primary of the p2s vpn gateway in the specified resource group. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<P2SVpnGatewayResetOperation> ResetAsync(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Reset"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.ResetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayResetOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateResetRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the primary of the p2s vpn gateway in the specified resource group. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual P2SVpnGatewayResetOperation Reset(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.Reset"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.Reset(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); var operation = new P2SVpnGatewayResetOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateResetRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. </summary> /// <param name="parameters"> Parameters supplied to the generate P2SVpnGateway VPN client package operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception> public async virtual Task<P2SVpnGatewayGenerateVpnProfileOperation> GenerateVpnProfileAsync(P2SVpnProfileParameters parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GenerateVpnProfile"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GenerateVpnProfileAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayGenerateVpnProfileOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGenerateVpnProfileRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. </summary> /// <param name="parameters"> Parameters supplied to the generate P2SVpnGateway VPN client package operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception> public virtual P2SVpnGatewayGenerateVpnProfileOperation GenerateVpnProfile(P2SVpnProfileParameters parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GenerateVpnProfile"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.GenerateVpnProfile(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters, cancellationToken); var operation = new P2SVpnGatewayGenerateVpnProfileOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGenerateVpnProfileRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<P2SVpnGatewayGetP2SVpnConnectionHealthOperation> GetP2SVpnConnectionHealthAsync(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GetP2SVpnConnectionHealth"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GetP2SVpnConnectionHealthAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayGetP2SVpnConnectionHealthOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGetP2SVpnConnectionHealthRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual P2SVpnGatewayGetP2SVpnConnectionHealthOperation GetP2SVpnConnectionHealth(bool waitForCompletion = true, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GetP2SVpnConnectionHealth"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.GetP2SVpnConnectionHealth(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); var operation = new P2SVpnGatewayGetP2SVpnConnectionHealthOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGetP2SVpnConnectionHealthRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the sas url to get the connection health detail of P2S clients of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="request"> Request parameters supplied to get p2s vpn connections detailed health. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="request"/> is null. </exception> public async virtual Task<P2SVpnGatewayGetP2SVpnConnectionHealthDetailedOperation> GetP2SVpnConnectionHealthDetailedAsync(P2SVpnConnectionHealthRequest request, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GetP2SVpnConnectionHealthDetailed"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GetP2SVpnConnectionHealthDetailedAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayGetP2SVpnConnectionHealthDetailedOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGetP2SVpnConnectionHealthDetailedRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the sas url to get the connection health detail of P2S clients of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="request"> Request parameters supplied to get p2s vpn connections detailed health. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="request"/> is null. </exception> public virtual P2SVpnGatewayGetP2SVpnConnectionHealthDetailedOperation GetP2SVpnConnectionHealthDetailed(P2SVpnConnectionHealthRequest request, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.GetP2SVpnConnectionHealthDetailed"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.GetP2SVpnConnectionHealthDetailed(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request, cancellationToken); var operation = new P2SVpnGatewayGetP2SVpnConnectionHealthDetailedOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateGetP2SVpnConnectionHealthDetailedRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="request"> The parameters are supplied to disconnect p2s vpn connections. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="request"/> is null. </exception> public async virtual Task<P2SVpnGatewayDisconnectP2SVpnConnectionsOperation> DisconnectP2SVpnConnectionsAsync(P2SVpnConnectionRequest request, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.DisconnectP2SVpnConnections"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.DisconnectP2SVpnConnectionsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayDisconnectP2SVpnConnectionsOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateDisconnectP2SVpnConnectionsRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request).Request, response); if (waitForCompletion) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource group. </summary> /// <param name="request"> The parameters are supplied to disconnect p2s vpn connections. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="request"/> is null. </exception> public virtual P2SVpnGatewayDisconnectP2SVpnConnectionsOperation DisconnectP2SVpnConnections(P2SVpnConnectionRequest request, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGateway.DisconnectP2SVpnConnections"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.DisconnectP2SVpnConnections(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request, cancellationToken); var operation = new P2SVpnGatewayDisconnectP2SVpnConnectionsOperation(_clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateDisconnectP2SVpnConnectionsRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, request).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } } }
58.374016
273
0.662845
[ "MIT" ]
LeiWang3/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/P2SVpnGateway.cs
29,654
C#
using Newtonsoft.Json; namespace JustSaying.Messaging.Interrogation; /// <summary> /// This type represents the result of interrogating a bus component. /// </summary> [JsonConverter(typeof(InterrogationResultJsonConverter))] public sealed class InterrogationResult { public InterrogationResult(object data) { Data = data; } /// <summary> /// Serialize this to JSON and log it on startup to gain some valuable insights into what's /// going on inside JustSaying. /// </summary> /// <remarks>This property is intentionally untyped, because it is unstructured and subject to change. /// It should only be used for diagnostic purposes.</remarks> public object Data { get; } internal static InterrogationResult Empty { get; } = new InterrogationResult(new {}); }
32.56
106
0.712531
[ "Apache-2.0" ]
justeat/JustSaying
src/JustSaying/Messaging/Interrogation/InterrogationResult.cs
814
C#
namespace PoESkillTree.Engine.Computation.Core.Events { /// <summary> /// Provides two views onto objects of type <typeparamref name="T"/>: <see cref="DefaultView"/> will always raise /// events. <see cref="BufferingView"/> will raise events subject through <see cref="IEventBuffer"/>, i.e. they may /// be buffered and raised delayed. /// <para> /// The reason for this interface: The calculation graph itself has to propagate change events as they /// arise so it can invalidate its node values. But the interfaces surfaced by <see cref="ICalculator"/> should /// only send events at the end of <see cref="ICalculator.Update"/>, i.e. they have to be suspended while the /// update is in progress. To enable that, <see cref="DefaultView"/> is the instance used in the calculation /// itself and <see cref="BufferingView"/> is the instance surfaced by <see cref="ICalculator"/>. /// </para> /// </summary> /// <typeparam name="T">Type of the views</typeparam> public interface IBufferingEventViewProvider<out T> : ICountsSubsribers { /// <summary> /// Events raised by <see cref="DefaultView"/> are not buffered. /// <see cref="DefaultView"/> raises events as soon as they occur. /// </summary> T DefaultView { get; } /// <summary> /// Events raised by <see cref="BufferingView"/> are buffered by <see cref="IEventBuffer"/> and may be delayed. /// </summary> T BufferingView { get; } } }
52.586207
119
0.651148
[ "MIT" ]
BlazesRus/PoESkillTreeBlazesRusBranch.Engine
PoESkillTree.Engine.Computation.Core/Events/IBufferingEventViewProvider.cs
1,527
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System.IO; using System.Linq; namespace MappingEdu.Core.DataAccess.Migrations { using System; using System.Data.Entity.Migrations; public partial class ExportAndPerformanceProcedures : DbMigration { private readonly string _alterGetReviewQueuePage = DataAccessHelper.GetStoredProcedurePath("GetReviewQueuePage", "Alter1.sql"); private readonly string _createGetReviewQueuePage = DataAccessHelper.GetStoredProcedurePath("GetReviewQueuePage", "Create.sql"); private readonly string _dropGetReviewQueuePage = DataAccessHelper.GetStoredProcedurePath("GetReviewQueuePage", "Drop.sql"); private readonly string _alterSystemItemSearch = DataAccessHelper.GetStoredProcedurePath("SystemItemSearch", "Alter1.sql"); private readonly string _createSystemItemSearch = DataAccessHelper.GetStoredProcedurePath("SystemItemSearch", "Create.sql"); private readonly string _dropSystemItemSearch = DataAccessHelper.GetStoredProcedurePath("SystemItemSearch", "Drop.sql"); public override void Up() { Sql(File.ReadAllText(_alterGetReviewQueuePage)); Sql(File.ReadAllText(_alterSystemItemSearch)); } public override void Down() { Sql(File.ReadAllText(_dropGetReviewQueuePage)); Sql(File.ReadAllText(_createGetReviewQueuePage)); Sql(File.ReadAllText(_dropSystemItemSearch)); Sql(File.ReadAllText(_createSystemItemSearch)); } } }
43.317073
136
0.737613
[ "Apache-2.0" ]
Ed-Fi-Exchange-OSS/MappingEDU
src/MappingEdu.Core.DataAccess/Migrations/201604160022445_ExportAndPerformanceProcedures.cs
1,776
C#
namespace BankSystem.Models.Enums { public enum BankAccountType { Checking = 1, Savings = 2, Retirement = 3, Credit = 4 } }
15.363636
34
0.532544
[ "MIT" ]
HristianPavlov/MoneyWorld
BankSystem/BankSystem.Models/Enums/BankAccountType.cs
171
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.AppRunner; using Amazon.AppRunner.Model; namespace Amazon.PowerShell.Cmdlets.AAR { /// <summary> /// List tags that are associated with for an AWS App Runner resource. The response contains /// a list of tag key-value pairs. /// </summary> [Cmdlet("Get", "AARResourceTag")] [OutputType("Amazon.AppRunner.Model.Tag")] [AWSCmdlet("Calls the AWS App Runner ListTagsForResource API operation.", Operation = new[] {"ListTagsForResource"}, SelectReturnType = typeof(Amazon.AppRunner.Model.ListTagsForResourceResponse))] [AWSCmdletOutput("Amazon.AppRunner.Model.Tag or Amazon.AppRunner.Model.ListTagsForResourceResponse", "This cmdlet returns a collection of Amazon.AppRunner.Model.Tag objects.", "The service call response (type Amazon.AppRunner.Model.ListTagsForResourceResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetAARResourceTagCmdlet : AmazonAppRunnerClientCmdlet, IExecutor { #region Parameter ResourceArn /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of the resource that a tag list is requested for.</para><para>It must be the ARN of an App Runner resource.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ResourceArn { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Tags'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AppRunner.Model.ListTagsForResourceResponse). /// Specifying the name of a property of type Amazon.AppRunner.Model.ListTagsForResourceResponse 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; } = "Tags"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the ResourceArn parameter. /// The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion 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.AppRunner.Model.ListTagsForResourceResponse, GetAARResourceTagCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.ResourceArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ResourceArn = this.ResourceArn; #if MODULAR if (this.ResourceArn == null && ParameterWasBound(nameof(this.ResourceArn))) { WriteWarning("You are passing $null as a value for parameter ResourceArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.AppRunner.Model.ListTagsForResourceRequest(); if (cmdletContext.ResourceArn != null) { request.ResourceArn = cmdletContext.ResourceArn; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.AppRunner.Model.ListTagsForResourceResponse CallAWSServiceOperation(IAmazonAppRunner client, Amazon.AppRunner.Model.ListTagsForResourceRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS App Runner", "ListTagsForResource"); try { #if DESKTOP return client.ListTagsForResource(request); #elif CORECLR return client.ListTagsForResourceAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ResourceArn { get; set; } public System.Func<Amazon.AppRunner.Model.ListTagsForResourceResponse, GetAARResourceTagCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Tags; } } }
45.378109
282
0.614297
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/AppRunner/Basic/Get-AARResourceTag-Cmdlet.cs
9,121
C#
using System; namespace Hotfix.Runtime { [AttributeUsage( AttributeTargets.Class)] public class GfProcedureAttribute:Attribute { public readonly ProcedureType ProceType; public GfProcedureAttribute() { ProceType = ProcedureType.Normal; } public GfProcedureAttribute(ProcedureType procedureType) { ProceType = procedureType; } } }
22.526316
64
0.635514
[ "MIT" ]
wuzhangwuzhang/ILGameFramework
Hotfix/Runtime/Procedure/GFProcedureAttribute.cs
430
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 dataexchange-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DataExchange.Model { /// <summary> /// This is the response object from the CreateDataSet operation. /// </summary> public partial class CreateDataSetResponse : AmazonWebServiceResponse { private string _arn; private AssetType _assetType; private DateTime? _createdAt; private string _description; private string _id; private string _name; private Origin _origin; private OriginDetails _originDetails; private string _sourceId; private Dictionary<string, string> _tags = new Dictionary<string, string>(); private DateTime? _updatedAt; /// <summary> /// Gets and sets the property Arn. /// <para> /// The ARN for the data set. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property AssetType. /// <para> /// The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. /// </para> /// </summary> public AssetType AssetType { get { return this._assetType; } set { this._assetType = value; } } // Check to see if AssetType property is set internal bool IsSetAssetType() { return this._assetType != null; } /// <summary> /// Gets and sets the property CreatedAt. /// <para> /// The date and time that the data set was created, in ISO 8601 format. /// </para> /// </summary> public DateTime CreatedAt { get { return this._createdAt.GetValueOrDefault(); } set { this._createdAt = value; } } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this._createdAt.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description for the data set. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Id. /// <para> /// The unique identifier for the data set. /// </para> /// </summary> public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the data set. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Origin. /// <para> /// A property that defines the data set as OWNED by the account (for providers) or ENTITLED /// to the account (for subscribers). /// </para> /// </summary> public Origin Origin { get { return this._origin; } set { this._origin = value; } } // Check to see if Origin property is set internal bool IsSetOrigin() { return this._origin != null; } /// <summary> /// Gets and sets the property OriginDetails. /// <para> /// If the origin of this data set is ENTITLED, includes the details for the product on /// AWS Marketplace. /// </para> /// </summary> public OriginDetails OriginDetails { get { return this._originDetails; } set { this._originDetails = value; } } // Check to see if OriginDetails property is set internal bool IsSetOriginDetails() { return this._originDetails != null; } /// <summary> /// Gets and sets the property SourceId. /// <para> /// The data set ID of the owned data set corresponding to the entitled data set being /// viewed. This parameter is returned when a data set owner is viewing the entitled copy /// of its owned data set. /// </para> /// </summary> public string SourceId { get { return this._sourceId; } set { this._sourceId = value; } } // Check to see if SourceId property is set internal bool IsSetSourceId() { return this._sourceId != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tags for the data set. /// </para> /// </summary> public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property UpdatedAt. /// <para> /// The date and time that the data set was last updated, in ISO 8601 format. /// </para> /// </summary> public DateTime UpdatedAt { get { return this._updatedAt.GetValueOrDefault(); } set { this._updatedAt = value; } } // Check to see if UpdatedAt property is set internal bool IsSetUpdatedAt() { return this._updatedAt.HasValue; } } }
29
110
0.538948
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/DataExchange/Generated/Model/CreateDataSetResponse.cs
7,279
C#
using System; namespace _9.MakingDecisions.Listing { public class MainListing1X55 { // Using an else statement public MainListing1X55() { Boolean b = false; if(b) { Console.WriteLine("True"); Console.ReadLine(); } else { Console.WriteLine("False"); Console.ReadLine(); } } } }
18.192308
43
0.427061
[ "MIT" ]
IsraelNicacio/70-483
Weblank.EXAM-REF-70-483/CAP 1.3 - IMPLEMENT PROGRAM FLOW/1.3.02.MakingDecisions/Listing/MainListing1X55.cs
475
C#
using RabbitMQ.Client; using System; using System.Linq; using System.Threading.Tasks; using static CookedRabbit.Core.Demo.DemoHelper; using static CookedRabbit.Core.Library.Utilities.RandomData; namespace CookedRabbit.Core.Demo { public static class BatchSendExamples { #region Cross Thread Channels #1 - Concurrent Dictionary (No SemaphoreSlim) Re-use Channel public static async Task RunCrossThreadChannelsOneAsync() { var connectionFactory = await CreateChannelFactoryAsync(); var connection = await CreateConnection(connectionFactory, "SemaphoreRealPayloadConcurrentTestConnection"); cleanupTask7 = CleanupDictionariesWithConcurrentDictionaryAndSingleChannelAsync(new TimeSpan(0, 0, 20)); var send = SendMessagesForeverWithConcurrentDictionaryAndSingleChannelAsync(connection); var receive = ReceiveMessagesForeverWithConcurrentDictionaryAndSingleChannelAsync(connection); await Task.WhenAll(new Task[] { send, receive }); } public static async Task CleanupDictionariesWithConcurrentDictionaryAndSingleChannelAsync(TimeSpan timeSpan) { while (true) { await Task.Delay(timeSpan); var count = 0; var listOfItemsToRemove = models7.Where(x => x.Key.IsClosed).ToArray(); foreach (var key in listOfItemsToRemove) { models7.Remove(key.Key); count++; } await Console.Out.WriteLineAsync($"Dead channels removed: {count}"); } } public static async Task SendMessagesForeverWithConcurrentDictionaryAndSingleChannelAsync(IConnection connection) { int counter = 0; var channel = await CreateChannel(connection); models7.Add(channel, counter); // re-simulate memoryleak by switching just this to models3. while (true) { var sendMessages1 = SendMessageAsync(channel, counter++); var sendMessages2 = SendMessageAsync(channel, counter++); var sendMessages3 = SendMessageAsync(channel, counter++); var sendMessages4 = SendMessageAsync(channel, counter++); var sendMessages5 = SendMessageAsync(channel, counter++); await Task.WhenAll(new Task[] { sendMessages1, sendMessages2, sendMessages3, sendMessages4, sendMessages5 }); } //channel.Dispose(); } public static async Task ReceiveMessagesForeverWithConcurrentDictionaryAndSingleChannelAsync(IConnection connection) { int counter = 0; var channel = await CreateChannel(connection); models7.Add(channel, counter); // re-simulate memoryleak by switching just this to models3. while (true) { var receiveMessages1 = ReceiveMessageAsync(channel); var receiveMessages2 = ReceiveMessageAsync(channel); var receiveMessages3 = ReceiveMessageAsync(channel); var receiveMessages4 = ReceiveMessageAsync(channel); var receiveMessages5 = ReceiveMessageAsync(channel); var receiveMessages6 = ReceiveMessageAsync(channel); var receiveMessages7 = ReceiveMessageAsync(channel); var receiveMessages8 = ReceiveMessageAsync(channel); await Task.WhenAll(new Task[] { receiveMessages1, receiveMessages2, receiveMessages3, receiveMessages4, receiveMessages5, receiveMessages6, receiveMessages7, receiveMessages8 }); } //channel.Dispose(); } #endregion #region Non-Cross Thread Channels #1 - Re-use Channel public static async Task RunNonCrossThreadChannelsAsync() { var connectionFactory = await CreateChannelFactoryAsync(); var connection = await CreateConnection(connectionFactory, "NonCrossThreadChannels"); var send = SendMessagesForeverAsync(connection); var receive = ReceiveMessagesForeverAsync(connection); await Task.WhenAll(new Task[] { send, receive }); } public static async Task SendMessagesForeverAsync(IConnection connection) { var channel = await CreateChannel(connection); while (true) { var payloads = await CreatePayloadsAsync(100); var sendMessages1 = SendMessagesAsync(payloads, channel); await Task.WhenAll(new Task[] { sendMessages1 }); await Task.Delay(100); } } public static async Task ReceiveMessagesForeverAsync(IConnection connection) { var channel = await CreateChannel(connection); while (true) { var messageCount = channel.MessageCount(queueName); await Console.Out.WriteLineAsync($"Message count threshold reached: {messageCount}"); if (messageCount > 10) { var receiveMessages1 = ReceiveMessageAsync(channel); var receiveMessages2 = ReceiveMessageAsync(channel); var receiveMessages3 = ReceiveMessageAsync(channel); var receiveMessages4 = ReceiveMessageAsync(channel); var receiveMessages5 = ReceiveMessageAsync(channel); var receiveMessages6 = ReceiveMessageAsync(channel); var receiveMessages7 = ReceiveMessageAsync(channel); var receiveMessages8 = ReceiveMessageAsync(channel); await Task.WhenAll(new Task[] { receiveMessages1, receiveMessages2, receiveMessages3, receiveMessages4, receiveMessages5, receiveMessages6, receiveMessages7, receiveMessages8 }); } await Task.Delay(10); } } #endregion } }
43.503597
198
0.629238
[ "MIT" ]
area55git/CookedRabbit
NetCore/CookedRabbit.Core.Demo/Examples/02_BatchSendExamples.cs
6,049
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Roslynator.CSharp.Refactorings.MakeMemberReadOnly { internal class MarkFieldAsReadOnlyRefactoring : MakeMemberReadOnlyRefactoring { private MarkFieldAsReadOnlyRefactoring() { } public static MarkFieldAsReadOnlyRefactoring Instance { get; } = new MarkFieldAsReadOnlyRefactoring(); public override HashSet<ISymbol> GetAnalyzableSymbols(SymbolAnalysisContext context, INamedTypeSymbol containingType) { HashSet<ISymbol> analyzableFields = null; foreach (ISymbol member in containingType.GetMembers()) { if (member.IsField()) { var fieldSymbol = (IFieldSymbol)member; if (!fieldSymbol.IsConst && fieldSymbol.IsPrivate() && !fieldSymbol.IsReadOnly && !fieldSymbol.IsVolatile && !fieldSymbol.IsImplicitlyDeclared && (fieldSymbol.Type.IsReferenceType || fieldSymbol.Type.IsPredefinedValueType() || fieldSymbol.Type.IsEnum())) { (analyzableFields ?? (analyzableFields = new HashSet<ISymbol>())).Add(fieldSymbol); } } } return analyzableFields; } protected override bool ValidateSymbol(ISymbol symbol) { return symbol?.IsField() == true; } public override void ReportFixableSymbols(SymbolAnalysisContext context, INamedTypeSymbol containingType, HashSet<ISymbol> symbols) { foreach (IGrouping<VariableDeclarationSyntax, SyntaxNode> grouping in symbols .Select(f => f.GetSyntax(context.CancellationToken)) .GroupBy(f => (VariableDeclarationSyntax)f.Parent)) { int count = grouping.Count(); VariableDeclarationSyntax declaration = grouping.Key; int variablesCount = declaration.Variables.Count; if (variablesCount == 1 || variablesCount == count) { context.ReportDiagnostic( DiagnosticDescriptors.MarkFieldAsReadOnly, declaration.Parent); } } } } }
37.767123
160
0.580704
[ "Apache-2.0" ]
vitsatishjs/Roslynator
source/Analyzers/Refactorings/MakeMemberReadOnly/MarkFieldAsReadOnlyRefactoring.cs
2,759
C#
#if NET5_0 using Shouldly; using Xunit; namespace Bunit.Rendering.Internal { public partial class HtmlizerTests : TestContext { [Theory(DisplayName = "IsBlazorAttribute correctly identifies Blazor attributes")] [InlineData("b-twl12ishk1=\"\"")] [InlineData("blazor:onclick=\"1\"")] [InlineData("blazor:__internal_stopPropagation_onclick=\"\"")] [InlineData("blazor:__internal_preventDefault_onclick=\"\"")] public void TestNET5_001(string blazorAttribute) { Htmlizer.IsBlazorAttribute(blazorAttribute).ShouldBeTrue(); } } } #endif
26.380952
84
0.752708
[ "MIT" ]
HamedMoghadasi/bUn
tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs
554
C#
/* EnumViewModel.cs * part of Daniel's XL Toolbox NG * * Copyright 2014-2018 Daniel Kraus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bovender.Mvvm.ViewModels { /// <summary> /// View model for enum members. This class is used internally by the /// <see cref="EnumProvider"/>. For specific purposes, the a new class /// based on EnumProvider should be created. The EnumViewModel class /// is sealed and cannot be inherited from. /// </summary> public sealed class EnumViewModel<T> : ViewModelBase where T : struct, IConvertible { #region Public properties public T Value { get; private set; } public string Description { get { return _description; } set { _description = value; OnPropertyChanged("Description"); } } public string ToolTip { get { return _toolTip; } set { _toolTip = value; OnPropertyChanged("ToolTip"); } } public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; OnPropertyChanged("IsEnabled"); } } #endregion #region Constructors internal EnumViewModel(T value) : base() { Value = value; _isEnabled = true; } internal EnumViewModel(T value, string description) : this(value) { _description = description; } internal EnumViewModel(T value, string description, string toolTip) : this(value, description) { _toolTip = toolTip; } internal EnumViewModel(T value, string description, string toolTip, bool isEnabled) : this(value, description, toolTip) { _isEnabled = isEnabled; } internal EnumViewModel(T value, string description, bool isEnabled) : this(value, description) { _isEnabled = isEnabled; } #endregion #region Overrides public override string DisplayString { get { if (String.IsNullOrEmpty(Description)) { return Value.ToString(); } else { return Description; } } } public override string ToString() { return DisplayString; } #endregion #region Implementation of ViewModelBase public override object RevealModelObject() { return Value; } #endregion #region Private fields private string _description; private string _toolTip; private bool _isEnabled; #endregion } }
25.237179
76
0.505461
[ "Apache-2.0", "BSD-3-Clause" ]
bovender/bovender
Bovender/Mvvm/ViewModels/EnumViewModel.cs
3,939
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// TradeItemResult Data Structure. /// </summary> [Serializable] public class TradeItemResult : AopObject { /// <summary> /// 支付宝订单号。对账使用,不脱敏 /// </summary> [XmlElement("alipay_order_no")] public string AlipayOrderNo { get; set; } /// <summary> /// 交易创建时间 /// </summary> [XmlElement("gmt_create")] public string GmtCreate { get; set; } /// <summary> /// 交易支付时间 /// </summary> [XmlElement("gmt_pay")] public string GmtPay { get; set; } /// <summary> /// 交易退款时间 /// </summary> [XmlElement("gmt_refund")] public string GmtRefund { get; set; } /// <summary> /// 商品备注信息 /// </summary> [XmlElement("goods_memo")] public string GoodsMemo { get; set; } /// <summary> /// 商品名称 /// </summary> [XmlElement("goods_title")] public string GoodsTitle { get; set; } /// <summary> /// 商户订单号,创建支付宝交易时传入的信息。对账使用,不脱敏 /// </summary> [XmlElement("merchant_order_no")] public string MerchantOrderNo { get; set; } /// <summary> /// 商家优惠金额 /// </summary> [XmlElement("net_mdiscount")] public string NetMdiscount { get; set; } /// <summary> /// 对方账户 /// </summary> [XmlElement("other_account")] public string OtherAccount { get; set; } /// <summary> /// 订单退款金额 /// </summary> [XmlElement("refund_amount")] public string RefundAmount { get; set; } /// <summary> /// 服务费金额 /// </summary> [XmlElement("service_fee")] public string ServiceFee { get; set; } /// <summary> /// 门店名称 /// </summary> [XmlElement("store_name")] public string StoreName { get; set; } /// <summary> /// 门店编号 /// </summary> [XmlElement("store_no")] public string StoreNo { get; set; } /// <summary> /// 订单金额 /// </summary> [XmlElement("total_amount")] public string TotalAmount { get; set; } /// <summary> /// 订单状态(待付款,成功,关闭,待发货,待确认收货,已预付,进行中) /// </summary> [XmlElement("trade_status")] public string TradeStatus { get; set; } /// <summary> /// 业务类型,帮助商户作为对账参考 /// </summary> [XmlElement("trade_type")] public string TradeType { get; set; } } }
24.422018
51
0.489857
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Domain/TradeItemResult.cs
2,950
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.452) // Version 5.452.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Draws a small image from a group cluster button. /// </summary> internal class ViewDrawRibbonGroupClusterButtonImage : ViewDrawRibbonGroupImageBase { #region Static Fields private static Size _smallSize;// = new Size(16, 16); #endregion #region Instance Fields private readonly KryptonRibbonGroupClusterButton _ribbonButton; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupClusterButtonImage class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonButton">Reference to ribbon group button definition.</param> public ViewDrawRibbonGroupClusterButtonImage(KryptonRibbon ribbon, KryptonRibbonGroupClusterButton ribbonButton) : base(ribbon) { Debug.Assert(ribbonButton != null); //Seb dpi aware _smallSize = new Size((int)(16 * FactorDpiX), (int)(16 * FactorDpiY)); _ribbonButton = ribbonButton; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawRibbonGroupClusterButtonImage:" + Id; } #endregion #region Protected /// <summary> /// Gets the size to draw the image. /// </summary> protected override Size DrawSize { get { return _smallSize; } } /// <summary> /// Gets the image to be drawn. /// </summary> protected override Image DrawImage { get => _ribbonButton.KryptonCommand != null ? _ribbonButton.KryptonCommand.ImageSmall : _ribbonButton.ImageSmall; } #endregion } }
36.7125
157
0.593803
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.452
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonGroupClusterButtonImage.cs
2,940
C#
/******************************************************************************* * Copyright (c) 2015 Bo Kang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ using System.Linq.Expressions; namespace AlgebraGeometry { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting; using System.Text; using CSharpLogic; using NUnit.Framework; [TestFixture] public partial class TestGoal { [Test] public void Test_Unify_1() { //a = 1, a*b = -1; //true positive var a = new Var("a"); var b = new Var("b"); var eqGoal = new EqGoal(a, 1); var lhsTerm = new Term(Expression.Multiply, new List<object>() {a, b}); var equation = new Equation(lhsTerm, -1); var eqNode = new EquationNode(equation); object obj; bool result = RelationLogic.ConstraintCheck(eqNode, eqGoal, null, out obj); Assert.True(result); Assert.NotNull(obj); } [Test] public void Test_Unify_2() { // a=2, b=a var a = new Var("a"); var b = new Var("b"); var eqGoal = new EqGoal(a, 2); var equation = new Equation(b, a); var eqNode = new EquationNode(equation); object obj; bool result = RelationLogic.ConstraintCheck(eqNode, eqGoal, null, out obj); Assert.True(result); Assert.NotNull(obj); } [Test] public void Test_Unify_3() { // a=2, b=a var a = new Var("a"); var b = new Var("b"); var eqGoal = new EqGoal(a, 2); var goalNode = new GoalNode(eqGoal); var equation = new Equation(b, a); object obj; bool result = RelationLogic.ConstraintCheck(goalNode, equation, null, out obj); Assert.True(result); Assert.NotNull(obj); } [Test] public void Test_Unify_4() { // c=2, b=a var c = new Var("c"); var b = new Var("b"); var eqGoal = new EqGoal(c, 2); var goalNode = new GoalNode(eqGoal); var a = new Var("a"); var equation = new Equation(b, a); object obj; bool result = RelationLogic.ConstraintCheck(goalNode, equation, null, out obj); Assert.False(result); } } }
30.336538
91
0.518225
[ "Apache-2.0" ]
buptkang/Relation.Logic
Test/1.Relation/3.Test.Goal.cs
3,157
C#
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace MosaicoSolutions.CSharpProperties { public interface IProperties : IEnumerable<KeyValuePair<string, string>> { string this[string key] { get; set; } bool ContainsKey(string key); void Add(string key, string value); void Add(KeyValuePair<string, string> valuePair); IDictionary<string, string> ToDictionary(); IEnumerable<string> Keys { get; } IEnumerable<string> Values { get; } string Get(string key); void Save(string path); void Save(TextWriter writer); void Save(Stream stream); Task SaveAsync(string path); Task SaveAsync(TextWriter writer); Task SaveAsync(Stream stream); void SaveAsXml(string path); void SaveAsXml(TextWriter writer); void SaveAsXml(Stream stream); Task SaveAsXmlAsync(string path); Task SaveAsXmlAsync(TextWriter writer); Task SaveAsXmlAsync(Stream stream); void SaveAsJson(string path); void SaveAsJson(TextWriter writer); void SaveAsJson(Stream stream); Task SaveAsJsonAsync(string path); Task SaveAsJsonAsync(TextWriter writer); Task SaveAsJsonAsync(Stream stream); void SaveAsCsv(string path); void SaveAsCsv(TextWriter writer); void SaveAsCsv(Stream stream); Task SaveAsCsvAsync(string path); Task SaveAsCsvAsync(TextWriter writer); Task SaveAsCsvAsync(Stream stream); } }
22.164384
76
0.642769
[ "MIT" ]
MosaicoSolutions/CSharpProperties
MosaicoSolutions.CSharpProperties/IProperties.cs
1,620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NLECloudSDK { /// <summary> /// 用户登录结果DTO /// </summary> public class AccountLoginResultDTO { /// <summary> /// 用户ID /// </summary> public virtual int UserID { get; set; } /// <summary> /// 用户名 /// </summary> public virtual string UserName { get; set; } /// <summary> /// EMAIL /// </summary> public virtual string Email { get; set; } /// <summary> /// 手机号 /// </summary> public virtual string Telphone { get; set; } /// <summary> /// 性别 /// </summary> public virtual bool Gender { get; set; } /// <summary> /// 学校/企业ID /// </summary> public virtual int CollegeID { get; set; } /// <summary> /// 学校/企业 /// </summary> public virtual string CollegeName { get; set; } /// <summary> /// 角色名称 /// </summary> public virtual string RoleName { get; set; } /// <summary> /// 角色ID /// </summary> public virtual int RoleID { get; set; } /// <summary> /// 调用API令牌 /// </summary> public String AccessToken { get; set; } } }
20.80597
55
0.474892
[ "MIT" ]
AuntYang/Pandora-Box
NLECloudSDK/Model/AccountLoginResultDTO.cs
1,464
C#
using System.Net.WebSockets; using Microsoft.AspNetCore.Http; namespace RegularWebsockets.Events { public class OpenEvent { public WebSocket Socket { get; set; } public HttpRequest Request { get; set; } } }
19.75
48
0.679325
[ "MIT" ]
killbom/regular-websockets
regular-websockets/Events/OpenEvent.cs
239
C#
// © 2016 Sitecore Corporation A/S. All rights reserved. Sitecore® is a registered trademark of Sitecore Corporation A/S. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Braintree; using Braintree.Exceptions; using Microsoft.Extensions.Logging; using Sitecore.Commerce.Core; using Sitecore.Commerce.Plugin.ManagedLists; using Sitecore.Commerce.Plugin.Orders; using Sitecore.Commerce.Plugin.Payments; using Sitecore.Framework.Conditions; using Sitecore.Framework.Pipelines; namespace Plugin.Sample.Payments.Braintree { /// <summary> /// Defines a void canceled order federated paymentBlock. /// </summary> /// <seealso> /// <cref> /// Sitecore.Framework.Pipelines.PipelineBlock{Sitecore.Commerce.Plugin.Payments.Order, /// Sitecore.Commerce.Plugin.Payments.Order, Sitecore.Commerce.Core.CommercePipelineExecutionContext} /// </cref> /// </seealso> [PipelineDisplayName(PaymentsBraintreeConstants.VoidCancelOrderFederatedPaymentBlock)] public class VoidCancelOrderFederatedPaymentBlock : PipelineBlock<Order, Order, CommercePipelineExecutionContext> { private readonly IPersistEntityPipeline _persistPipeline; /// <summary> /// Initializes a new instance of the <see cref="VoidCancelOrderFederatedPaymentBlock"/> class. /// </summary> /// <param name="persistEntityPipeline">The persist entity pipeline.</param> public VoidCancelOrderFederatedPaymentBlock(IPersistEntityPipeline persistEntityPipeline) { _persistPipeline = persistEntityPipeline; } /// <summary> /// Runs the specified argument. /// </summary> /// <param name="arg">The argument.</param> /// <param name="context">The context.</param> /// <returns>An order with Federated payment info</returns> public override async Task<Order> Run(Order arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull("The arg can not be null"); var order = arg; if (!order.HasComponent<OnHoldOrderComponent>() && !order.Status.Equals(context.GetPolicy<KnownOrderStatusPolicy>().Pending, StringComparison.OrdinalIgnoreCase) && !order.Status.Equals(context.GetPolicy<KnownOrderStatusPolicy>().Problem, StringComparison.OrdinalIgnoreCase)) { var expectedStatuses = $"{context.GetPolicy<KnownOrderStatusPolicy>().Pending}, {context.GetPolicy<KnownOrderStatusPolicy>().Problem}, {context.GetPolicy<KnownOrderStatusPolicy>().OnHold}"; var invalidOrderStateMessage = $"{Name}: Expected order in '{expectedStatuses}' statuses but order was in '{order.Status}' status"; context.Abort( await context.CommerceContext.AddMessage( context.GetPolicy<KnownResultCodes>().ValidationError, "InvalidOrderState", new object[] { expectedStatuses, order.Status }, invalidOrderStateMessage).ConfigureAwait(false), context); return arg; } if (!order.HasComponent<FederatedPaymentComponent>()) { return arg; } var braintreeClientPolicy = context.GetPolicy<BraintreeClientPolicy>(); if (!(await braintreeClientPolicy.IsValid(context.CommerceContext).ConfigureAwait(false))) { return arg; } try { var gateway = new BraintreeGateway(braintreeClientPolicy?.Environment, braintreeClientPolicy?.MerchantId, braintreeClientPolicy?.PublicKey, braintreeClientPolicy?.PrivateKey); var existingPayment = order.GetComponent<FederatedPaymentComponent>(); if (existingPayment == null) { return arg; } Result<Transaction> result = gateway.Transaction.Void(existingPayment.TransactionId); if (result.IsSuccess()) { context.Logger.LogInformation($"{Name} - Void Payment succeeded:{existingPayment.Id}"); existingPayment.TransactionStatus = result.Target.Status.ToString(); await GenerateSalesActivity(order, existingPayment, context).ConfigureAwait(false); } else { var errorMessages = result.Errors.DeepAll().Aggregate(string.Empty, (current, error) => current + ("Error: " + (int) error.Code + " - " + error.Message + "\n")); context.Abort( await context.CommerceContext.AddMessage( context.GetPolicy<KnownResultCodes>().Error, "PaymentVoidFailed", new object[] { existingPayment.TransactionId }, $"{Name}. Payment void failed for transaction {existingPayment.TransactionId}: {errorMessages}").ConfigureAwait(false), context); return arg; } } catch (BraintreeException ex) { await context.CommerceContext.AddMessage( context.GetPolicy<KnownResultCodes>().Error, "PaymentVoidFailed", new object[] { order.Id, ex }, $"{Name}. Payment refund failed.").ConfigureAwait(false); return arg; } return arg; } /// <summary> /// Generates the sales activity. /// </summary> /// <param name="order">The order.</param> /// <param name="payment">The payment.</param> /// <param name="context">The context.</param> /// <returns>A <see cref="Task"/></returns> protected virtual async Task GenerateSalesActivity(Order order, PaymentComponent payment, CommercePipelineExecutionContext context) { var salesActivity = new SalesActivity { Id = CommerceEntity.IdPrefix<SalesActivity>() + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture), ActivityAmount = new Money(payment.Amount.CurrencyCode, 0), Customer = new EntityReference { EntityTarget = order.EntityComponents.OfType<ContactComponent>().FirstOrDefault()?.CustomerId }, Order = new EntityReference { EntityTarget = order.Id, EntityTargetUniqueId = order.UniqueId }, Name = "Void the Federated payment", PaymentStatus = context.GetPolicy<KnownSalesActivityStatusesPolicy>().Void }; salesActivity.SetComponent(new ListMembershipsComponent { Memberships = new List<string> { CommerceEntity.ListName<SalesActivity>(), string.Format(CultureInfo.InvariantCulture, context.GetPolicy<KnownOrderListsPolicy>().OrderSalesActivities, order.FriendlyId) } }); salesActivity.SetComponent(payment); var salesActivities = order.SalesActivity.ToList(); salesActivities.Add(new EntityReference { EntityTarget = salesActivity.Id, EntityTargetUniqueId = salesActivity.UniqueId }); order.SalesActivity = salesActivities; await _persistPipeline.Run(new PersistEntityArgument(salesActivity), context).ConfigureAwait(false); } } }
43.545455
205
0.581235
[ "Apache-2.0" ]
ajsuth/CatalogSynchronizer
9.3/Sitecore.Commerce.Engine.SDK.5.0.76/src/Plugin.Sample.Payments.Braintree/Pipelines/Blocks/VoidCancelOrderFederatedPaymentBlock.cs
8,147
C#
using System; using System.Collections.Generic; namespace Performance.EFCore { public partial class ErrorLog { public int ErrorLogID { get; set; } public DateTime ErrorTime { get; set; } public string UserName { get; set; } public int ErrorNumber { get; set; } public int? ErrorSeverity { get; set; } public int? ErrorState { get; set; } public string ErrorProcedure { get; set; } public int? ErrorLine { get; set; } public string ErrorMessage { get; set; } } }
28.842105
50
0.614964
[ "MIT" ]
tkopacz/2016SQLDay
02EFCore/CompletedSourceCode/Performance/EFCore/ErrorLog.cs
550
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 Certify.Locales { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CoreSR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CoreSR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Certify.Locales.CoreSR", typeof(CoreSR).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)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Certificate Request was aborted by PS script. /// </summary> public static string CertificateRequestWasAbortedByPSScript { get { return ResourceManager.GetString("CertificateRequestWasAbortedByPSScript", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Performing Automated Certificate Binding. /// </summary> public static string CertifyManager_AutoBinding { get { return ResourceManager.GetString("CertifyManager_AutoBinding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Automated configuration checks failed. Authorizations will not be able to complete. ///Check you have http bindings for your site and ensure you can browse to http://{0}/.well-known/acme-challenge/configcheck before proceeding.. /// </summary> public static string CertifyManager_AutomateConfigurationCheckFailed_HTTP { get { return ResourceManager.GetString("CertifyManager_AutomateConfigurationCheckFailed_HTTP", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Automated configuration checks failed. Authorizations will not be able to complete. ///Check you have https SNI bindings for your site ///(ex: &apos;0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF0123456789ABCDEF.acme.invalid&apos;) before proceeding.. /// </summary> public static string CertifyManager_AutomateConfigurationCheckFailed_SNI { get { return ResourceManager.GetString("CertifyManager_AutomateConfigurationCheckFailed_SNI", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Certificate created ready for manual binding: {0}. /// </summary> public static string CertifyManager_CertificateCreatedForBinding { get { return ResourceManager.GetString("CertifyManager_CertificateCreatedForBinding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Certificate installed and SSL bindings updated for {0}. /// </summary> public static string CertifyManager_CertificateInstalledAndBindingUpdated { get { return ResourceManager.GetString("CertifyManager_CertificateInstalledAndBindingUpdated", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An error occurred installing the certificate. Certificate file may not be valid: {0}. /// </summary> public static string CertifyManager_CertificateInstallFailed { get { return ResourceManager.GetString("CertifyManager_CertificateInstallFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Completed Certificate Request.. /// </summary> public static string CertifyManager_CompleteRequest { get { return ResourceManager.GetString("CertifyManager_CompleteRequest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Completed certificate request and automated bindings update (IIS). /// </summary> public static string CertifyManager_CompleteRequestAndUpdateBinding { get { return ResourceManager.GetString("CertifyManager_CompleteRequestAndUpdateBinding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Domain validation completed: {0}. /// </summary> public static string CertifyManager_DomainValidationCompleted { get { return ResourceManager.GetString("CertifyManager_DomainValidationCompleted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Domain validation failed: {0} ///{1}. /// </summary> public static string CertifyManager_DomainValidationFailed { get { return ResourceManager.GetString("CertifyManager_DomainValidationFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Domain already has current authorization, skipping verification: {0}. /// </summary> public static string CertifyManager_DomainValidationSkipVerifed { get { return ResourceManager.GetString("CertifyManager_DomainValidationSkipVerifed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed prerequisite configuration checks ({0}). /// </summary> public static string CertifyManager_FailedPrerequisiteCheck { get { return ResourceManager.GetString("CertifyManager_FailedPrerequisiteCheck", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Let&apos;s Encrypt service did not issue a valid certificate in the time allowed. {0}. /// </summary> public static string CertifyManager_LetsEncryptServiceTimeout { get { return ResourceManager.GetString("CertifyManager_LetsEncryptServiceTimeout", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Performing Challenge Response via IIS: {0} . /// </summary> public static string CertifyManager_PerformingChallengeResponseViaIISX0 { get { return ResourceManager.GetString("CertifyManager_PerformingChallengeResponseViaIISX0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Performing Config Tests. /// </summary> public static string CertifyManager_PerformingConfigTests { get { return ResourceManager.GetString("CertifyManager_PerformingConfigTests", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Registering Domain Identifiers. /// </summary> public static string CertifyManager_RegisterDomainIdentity { get { return ResourceManager.GetString("CertifyManager_RegisterDomainIdentity", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Registering and Validating {0} . /// </summary> public static string CertifyManager_RegisteringAndValidatingX0 { get { return ResourceManager.GetString("CertifyManager_RegisteringAndValidatingX0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Previous renewals failed: {0}. Renewal will be attempted within 48hrs.. /// </summary> public static string CertifyManager_RenewalOnHold { get { return ResourceManager.GetString("CertifyManager_RenewalOnHold", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Requesting Validation from Let&apos;s Encrypt: {0}. /// </summary> public static string CertifyManager_ReqestValidationFromLetsEncrypt { get { return ResourceManager.GetString("CertifyManager_ReqestValidationFromLetsEncrypt", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Requesting Certificate via Lets Encrypt. /// </summary> public static string CertifyManager_RequestCertificate { get { return ResourceManager.GetString("CertifyManager_RequestCertificate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0}: Request failed - {1} {2}. /// </summary> public static string CertifyManager_RequestFailed { get { return ResourceManager.GetString("CertifyManager_RequestFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Site stopped (or not present), renewal skipped as domain validation cannot be performed. . /// </summary> public static string CertifyManager_SiteStopped { get { return ResourceManager.GetString("CertifyManager_SiteStopped", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Skipping Renewal, existing certificate still OK. . /// </summary> public static string CertifyManager_SkipRenewalOk { get { return ResourceManager.GetString("CertifyManager_SkipRenewalOk", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Validation of the required challenges did not complete successfully. {0}. /// </summary> public static string CertifyManager_ValidationForChallengeNotSuccess { get { return ResourceManager.GetString("CertifyManager_ValidationForChallengeNotSuccess", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Finish. /// </summary> public static string Finish { get { return ResourceManager.GetString("Finish", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Local IIS, SSL Certificate via Let&apos;s Encrypt. /// </summary> public static string ManagedCertificateType_LocalIIS { get { return ResourceManager.GetString("ManagedCertificateType_LocalIIS", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Manual SSL Certificate via Let&apos;s Encrypt. /// </summary> public static string ManagedCertificateType_Manual { get { return ResourceManager.GetString("ManagedCertificateType_Manual", resourceCulture); } } } }
42.878125
164
0.606734
[ "MIT" ]
AJH16/certify
src/Certify.Locales/CoreSR.Designer.cs
13,723
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Amqp.Framing { using System; using System.Globalization; using System.Text; using Microsoft.Azure.Amqp.Encoding; public sealed class Frame : IDisposable { public const int HeaderSize = 8; const byte DefaultDataOffset = 2; public Frame() : this(FrameType.Amqp) { } public Frame(FrameType type) { this.Type = type; this.DataOffset = Frame.DefaultDataOffset; } public int Size { get; private set; } public byte DataOffset { get; private set; } public FrameType Type { get; private set; } public ushort Channel { get; set; } public Performative Command { get; set; } public ArraySegment<byte> Payload { get; set; } public ByteBuffer RawByteBuffer { get; private set; } public static ByteBuffer EncodeCommand(FrameType type, ushort channel, Performative command, int payloadSize) { int frameSize = HeaderSize; if (command != null) { frameSize += AmqpCodec.GetSerializableEncodeSize(command); } frameSize += payloadSize; ByteBuffer buffer = new ByteBuffer(frameSize, false, false); AmqpBitConverter.WriteUInt(buffer, (uint)frameSize); AmqpBitConverter.WriteUByte(buffer, DefaultDataOffset); AmqpBitConverter.WriteUByte(buffer, (byte)type); AmqpBitConverter.WriteUShort(buffer, channel); if (command != null) { AmqpCodec.EncodeSerializable(command, buffer); } return buffer; } public void Decode(ByteBuffer buffer) { // the frame now owns disposing the buffer this.RawByteBuffer = buffer; int offset = buffer.Offset; int length = buffer.Length; this.DecodeHeader(buffer); this.DecodeCommand(buffer); this.DecodePayload(buffer); buffer.AdjustPosition(offset, length); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "FRM({0:X4}|{1}|{2}|{3:X2}", this.Size, this.DataOffset, (byte)this.Type, this.Channel); if (this.Command != null) { sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", this.Command); } if (this.Payload.Count > 0) { sb.AppendFormat(CultureInfo.InvariantCulture, ",{0}", this.Payload.Count); } sb.Append(')'); return sb.ToString(); } void DecodeHeader(ByteBuffer buffer) { this.Size = (int)AmqpBitConverter.ReadUInt(buffer); this.DataOffset = AmqpBitConverter.ReadUByte(buffer); this.Type = (FrameType)AmqpBitConverter.ReadUByte(buffer); this.Channel = AmqpBitConverter.ReadUShort(buffer); // skip extended header buffer.Complete(this.DataOffset * 4 - Frame.HeaderSize); } void DecodeCommand(ByteBuffer buffer) { if (buffer.Length > 0) { this.Command = (Performative)AmqpCodec.DecodeAmqpDescribed(buffer); } } void DecodePayload(ByteBuffer buffer) { if (buffer.Length > 0) { this.Payload = new ArraySegment<byte>(buffer.Buffer, buffer.Offset, buffer.Length); } } public void Dispose() { if (this.RawByteBuffer != null) { this.RawByteBuffer.Dispose(); } } } }
26.61875
146
0.525241
[ "MIT" ]
CIPop/azure-amqp
Microsoft.Azure.Amqp/Amqp/Framing/Frame.cs
4,261
C#
namespace SignalFx.Tracing.DuckTyping.Tests.Properties.TypeChaining.ProxiesDefinitions { public class ObscureDuckTypeVirtualClass { public virtual IDummyFieldObject PublicStaticGetSelfType { get; } public virtual IDummyFieldObject InternalStaticGetSelfType { get; } public virtual IDummyFieldObject ProtectedStaticGetSelfType { get; } public virtual IDummyFieldObject PrivateStaticGetSelfType { get; } // * public virtual IDummyFieldObject PublicStaticGetSetSelfType { get; set; } public virtual IDummyFieldObject InternalStaticGetSetSelfType { get; set; } public virtual IDummyFieldObject ProtectedStaticGetSetSelfType { get; set; } public virtual IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } // * public virtual IDummyFieldObject PublicGetSelfType { get; } public virtual IDummyFieldObject InternalGetSelfType { get; } public virtual IDummyFieldObject ProtectedGetSelfType { get; } public virtual IDummyFieldObject PrivateGetSelfType { get; } // * public virtual IDummyFieldObject PublicGetSetSelfType { get; set; } public virtual IDummyFieldObject InternalGetSetSelfType { get; set; } public virtual IDummyFieldObject ProtectedGetSetSelfType { get; set; } public virtual IDummyFieldObject PrivateGetSetSelfType { get; set; } } }
32.477273
86
0.725682
[ "Apache-2.0" ]
AJJLVizio/signalfx-dotnet-tracing
test/Datadog.Trace.DuckTyping.Tests/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs
1,429
C#
using NUnit.Framework; namespace JetBrains.ReSharper.Koans.Editing { // 显示参数信息 // // 显示方法及其重载中的参数类型和名称 // // Ctrl+K, P (VS) // Ctrl+P (IntelliJ) // 按ESC取消 // // 行为配置 ReSharper → Options → Environment → IntelliSense → Parameter Info public class ParameterInfo { public void Foo() { // 1. 显示参数信息 // 将光标放到下面方法的参数中 // 执行 Show Parameter Info SayHello("Steve"); // 2. 高亮当前参数 // 将光标放到下面方法的参数中 // 执行 Show Parameter Info // 移动光标, 当前参数显示为粗体 Add(1, 2, 3, 4); // 3. 显示重载 // 将光标放到下面方法的参数中 // 执行 Show Parameter Info // 按上下键, 切换不同的重载函数 Assert.AreEqual(12, 12); // 4. 重载成员的紧凑视图 // ReSharper → Options → Environment → IntelliSense → Parameter Info // 取消 "Display all signatures at once" (一次性显示所有签名) // 将光标放到下面方法的参数中 // 执行 Show Parameter Info // 按上下键, 切换不同的重载函数 Assert.AreEqual(12, 12); } #region Implementation details public string SayHello(string name) { return "Hello " + name; } public int Add(int a, int b, int c, int d) { return a + b + c + d; } #endregion } }
23.881356
83
0.469127
[ "Apache-2.0" ]
yusjoel/resharper-rider-samples-cn
02-Editing/03-ParameterInfo.cs
1,755
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xpf.FileSystem { class Network { } }
12.25
33
0.707483
[ "MIT" ]
dotnetprofessional/xpf
xpf.FileSystem/Network.cs
149
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 s3control-2018-08-20.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.S3Control.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using System.Xml; namespace Amazon.S3Control.Model.Internal.MarshallTransformations { /// <summary> /// CreateJob Request Marshaller /// </summary> public class CreateJobRequestMarshaller : IMarshaller<IRequest, CreateJobRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateJobRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateJobRequest publicRequest) { var request = new DefaultRequest(publicRequest, "Amazon.S3Control"); request.HttpMethod = "POST"; if (publicRequest.IsSetAccountId()) { request.Headers["x-amz-account-id"] = publicRequest.AccountId; } request.ResourcePath = "/v20180820/jobs"; var stringWriter = new XMLEncodedStringWriter(CultureInfo.InvariantCulture); using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true, NewLineHandling = NewLineHandling.Entitize })) { xmlWriter.WriteStartElement("CreateJobRequest", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.IsSetClientRequestToken()) xmlWriter.WriteElementString("ClientRequestToken", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ClientRequestToken)); else xmlWriter.WriteElementString("ClientRequestToken", "http://awss3control.amazonaws.com/doc/2018-08-20/", Guid.NewGuid().ToString()); if(publicRequest.IsSetConfirmationRequired()) xmlWriter.WriteElementString("ConfirmationRequired", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.ConfirmationRequired)); if(publicRequest.IsSetDescription()) xmlWriter.WriteElementString("Description", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Description)); if (publicRequest.Manifest != null) { xmlWriter.WriteStartElement("Manifest", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.Manifest.Location != null) { xmlWriter.WriteStartElement("Location", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Manifest.Location.IsSetETag()) xmlWriter.WriteElementString("ETag", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Manifest.Location.ETag)); if(publicRequest.Manifest.Location.IsSetObjectArn()) xmlWriter.WriteElementString("ObjectArn", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Manifest.Location.ObjectArn)); if(publicRequest.Manifest.Location.IsSetObjectVersionId()) xmlWriter.WriteElementString("ObjectVersionId", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Manifest.Location.ObjectVersionId)); xmlWriter.WriteEndElement(); } if (publicRequest.Manifest.Spec != null) { xmlWriter.WriteStartElement("Spec", "http://awss3control.amazonaws.com/doc/2018-08-20/"); var publicRequestManifestSpecFields = publicRequest.Manifest.Spec.Fields; if (publicRequestManifestSpecFields != null && publicRequestManifestSpecFields.Count > 0) { xmlWriter.WriteStartElement("Fields", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestManifestSpecFieldsValue in publicRequestManifestSpecFields) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteValue(publicRequestManifestSpecFieldsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.Manifest.Spec.IsSetFormat()) xmlWriter.WriteElementString("Format", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Manifest.Spec.Format)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.ManifestGenerator != null) { xmlWriter.WriteStartElement("ManifestGenerator", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.ManifestGenerator.S3JobManifestGenerator != null) { xmlWriter.WriteStartElement("S3JobManifestGenerator", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.IsSetEnableManifestOutput()) xmlWriter.WriteElementString("EnableManifestOutput", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.ManifestGenerator.S3JobManifestGenerator.EnableManifestOutput)); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.IsSetExpectedBucketOwner()) xmlWriter.WriteElementString("ExpectedBucketOwner", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ExpectedBucketOwner)); if (publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter != null) { xmlWriter.WriteStartElement("Filter", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.IsSetCreatedAfter()) xmlWriter.WriteElementString("CreatedAfter", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.CreatedAfter)); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.IsSetCreatedBefore()) xmlWriter.WriteElementString("CreatedBefore", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.CreatedBefore)); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.IsSetEligibleForReplication()) xmlWriter.WriteElementString("EligibleForReplication", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.EligibleForReplication)); var publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatuses = publicRequest.ManifestGenerator.S3JobManifestGenerator.Filter.ObjectReplicationStatuses; if (publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatuses != null && publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatuses.Count > 0) { xmlWriter.WriteStartElement("ObjectReplicationStatuses", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatusesValue in publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatuses) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteValue(publicRequestManifestGeneratorS3JobManifestGeneratorFilterObjectReplicationStatusesValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation != null) { xmlWriter.WriteStartElement("ManifestOutputLocation", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.IsSetBucket()) xmlWriter.WriteElementString("Bucket", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.Bucket)); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.IsSetExpectedManifestBucketOwner()) xmlWriter.WriteElementString("ExpectedManifestBucketOwner", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ExpectedManifestBucketOwner)); if (publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestEncryption != null) { xmlWriter.WriteStartElement("ManifestEncryption", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestEncryption.SSEKMS != null) { xmlWriter.WriteStartElement("SSE-KMS", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestEncryption.SSEKMS.IsSetKeyId()) xmlWriter.WriteElementString("KeyId", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestEncryption.SSEKMS.KeyId)); xmlWriter.WriteEndElement(); } if (publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestEncryption.SSES3 != null) { xmlWriter.WriteStartElement("SSE-S3", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.IsSetManifestFormat()) xmlWriter.WriteElementString("ManifestFormat", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestFormat)); if(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.IsSetManifestPrefix()) xmlWriter.WriteElementString("ManifestPrefix", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.ManifestOutputLocation.ManifestPrefix)); xmlWriter.WriteEndElement(); } if(publicRequest.ManifestGenerator.S3JobManifestGenerator.IsSetSourceBucket()) xmlWriter.WriteElementString("SourceBucket", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.ManifestGenerator.S3JobManifestGenerator.SourceBucket)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.Operation != null) { xmlWriter.WriteStartElement("Operation", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.Operation.LambdaInvoke != null) { xmlWriter.WriteStartElement("LambdaInvoke", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.LambdaInvoke.IsSetFunctionArn()) xmlWriter.WriteElementString("FunctionArn", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.LambdaInvoke.FunctionArn)); xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3DeleteObjectTagging != null) { xmlWriter.WriteStartElement("S3DeleteObjectTagging", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3InitiateRestoreObject != null) { xmlWriter.WriteStartElement("S3InitiateRestoreObject", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3InitiateRestoreObject.IsSetExpirationInDays()) xmlWriter.WriteElementString("ExpirationInDays", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromInt(publicRequest.Operation.S3InitiateRestoreObject.ExpirationInDays)); if(publicRequest.Operation.S3InitiateRestoreObject.IsSetGlacierJobTier()) xmlWriter.WriteElementString("GlacierJobTier", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3InitiateRestoreObject.GlacierJobTier)); xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectAcl != null) { xmlWriter.WriteStartElement("S3PutObjectAcl", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy != null) { xmlWriter.WriteStartElement("AccessControlPolicy", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList != null) { xmlWriter.WriteStartElement("AccessControlList", "http://awss3control.amazonaws.com/doc/2018-08-20/"); var publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrants = publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Grants; if (publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrants != null && publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrants.Count > 0) { xmlWriter.WriteStartElement("Grants", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue in publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrants) { if (publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue != null) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee != null) { xmlWriter.WriteStartElement("Grantee", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.IsSetDisplayName()) xmlWriter.WriteElementString("DisplayName", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.DisplayName)); if(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.IsSetIdentifier()) xmlWriter.WriteElementString("Identifier", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.Identifier)); if(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.IsSetTypeIdentifier()) xmlWriter.WriteElementString("TypeIdentifier", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Grantee.TypeIdentifier)); xmlWriter.WriteEndElement(); } if(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.IsSetPermission()) xmlWriter.WriteElementString("Permission", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectAclAccessControlPolicyAccessControlListGrantsValue.Permission)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Owner != null) { xmlWriter.WriteStartElement("Owner", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Owner.IsSetDisplayName()) xmlWriter.WriteElementString("DisplayName", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Owner.DisplayName)); if(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Owner.IsSetID()) xmlWriter.WriteElementString("ID", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.AccessControlList.Owner.ID)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.IsSetCannedAccessControlList()) xmlWriter.WriteElementString("CannedAccessControlList", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectAcl.AccessControlPolicy.CannedAccessControlList)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectCopy != null) { xmlWriter.WriteStartElement("S3PutObjectCopy", "http://awss3control.amazonaws.com/doc/2018-08-20/"); var publicRequestOperationS3PutObjectCopyAccessControlGrants = publicRequest.Operation.S3PutObjectCopy.AccessControlGrants; if (publicRequestOperationS3PutObjectCopyAccessControlGrants != null && publicRequestOperationS3PutObjectCopyAccessControlGrants.Count > 0) { xmlWriter.WriteStartElement("AccessControlGrants", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestOperationS3PutObjectCopyAccessControlGrantsValue in publicRequestOperationS3PutObjectCopyAccessControlGrants) { if (publicRequestOperationS3PutObjectCopyAccessControlGrantsValue != null) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee != null) { xmlWriter.WriteStartElement("Grantee", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.IsSetDisplayName()) xmlWriter.WriteElementString("DisplayName", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.DisplayName)); if(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.IsSetIdentifier()) xmlWriter.WriteElementString("Identifier", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.Identifier)); if(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.IsSetTypeIdentifier()) xmlWriter.WriteElementString("TypeIdentifier", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Grantee.TypeIdentifier)); xmlWriter.WriteEndElement(); } if(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.IsSetPermission()) xmlWriter.WriteElementString("Permission", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyAccessControlGrantsValue.Permission)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.Operation.S3PutObjectCopy.IsSetBucketKeyEnabled()) xmlWriter.WriteElementString("BucketKeyEnabled", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.Operation.S3PutObjectCopy.BucketKeyEnabled)); if(publicRequest.Operation.S3PutObjectCopy.IsSetCannedAccessControlList()) xmlWriter.WriteElementString("CannedAccessControlList", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.CannedAccessControlList)); if(publicRequest.Operation.S3PutObjectCopy.IsSetMetadataDirective()) xmlWriter.WriteElementString("MetadataDirective", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.MetadataDirective)); if(publicRequest.Operation.S3PutObjectCopy.IsSetModifiedSinceConstraint()) xmlWriter.WriteElementString("ModifiedSinceConstraint", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.Operation.S3PutObjectCopy.ModifiedSinceConstraint)); if (publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata != null) { xmlWriter.WriteStartElement("NewObjectMetadata", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetCacheControl()) xmlWriter.WriteElementString("CacheControl", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.CacheControl)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentDisposition()) xmlWriter.WriteElementString("ContentDisposition", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentDisposition)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentEncoding()) xmlWriter.WriteElementString("ContentEncoding", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentEncoding)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentLanguage()) xmlWriter.WriteElementString("ContentLanguage", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentLanguage)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentLength()) xmlWriter.WriteElementString("ContentLength", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromLong(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentLength)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentMD5()) xmlWriter.WriteElementString("ContentMD5", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentMD5)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetContentType()) xmlWriter.WriteElementString("ContentType", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.ContentType)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetHttpExpiresDate()) xmlWriter.WriteElementString("HttpExpiresDate", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.HttpExpiresDate)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetRequesterCharged()) xmlWriter.WriteElementString("RequesterCharged", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.RequesterCharged)); if(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.IsSetSSEAlgorithm()) xmlWriter.WriteElementString("SSEAlgorithm", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.SSEAlgorithm)); xmlWriter.WriteStartElement("UserMetadata", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var kvp in publicRequest.Operation.S3PutObjectCopy.NewObjectMetadata.UserMetadata) { xmlWriter.WriteStartElement("entry", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteElementString("key", "http://awss3control.amazonaws.com/doc/2018-08-20/", kvp.Key); xmlWriter.WriteElementString("value", "http://awss3control.amazonaws.com/doc/2018-08-20/", kvp.Value); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } var publicRequestOperationS3PutObjectCopyNewObjectTagging = publicRequest.Operation.S3PutObjectCopy.NewObjectTagging; if (publicRequestOperationS3PutObjectCopyNewObjectTagging != null && publicRequestOperationS3PutObjectCopyNewObjectTagging.Count > 0) { xmlWriter.WriteStartElement("NewObjectTagging", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestOperationS3PutObjectCopyNewObjectTaggingValue in publicRequestOperationS3PutObjectCopyNewObjectTagging) { if (publicRequestOperationS3PutObjectCopyNewObjectTaggingValue != null) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequestOperationS3PutObjectCopyNewObjectTaggingValue.IsSetKey()) xmlWriter.WriteElementString("Key", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyNewObjectTaggingValue.Key)); if(publicRequestOperationS3PutObjectCopyNewObjectTaggingValue.IsSetValue()) xmlWriter.WriteElementString("Value", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectCopyNewObjectTaggingValue.Value)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.Operation.S3PutObjectCopy.IsSetObjectLockLegalHoldStatus()) xmlWriter.WriteElementString("ObjectLockLegalHoldStatus", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.ObjectLockLegalHoldStatus)); if(publicRequest.Operation.S3PutObjectCopy.IsSetObjectLockMode()) xmlWriter.WriteElementString("ObjectLockMode", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.ObjectLockMode)); if(publicRequest.Operation.S3PutObjectCopy.IsSetObjectLockRetainUntilDate()) xmlWriter.WriteElementString("ObjectLockRetainUntilDate", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.Operation.S3PutObjectCopy.ObjectLockRetainUntilDate)); if(publicRequest.Operation.S3PutObjectCopy.IsSetRedirectLocation()) xmlWriter.WriteElementString("RedirectLocation", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.RedirectLocation)); if(publicRequest.Operation.S3PutObjectCopy.IsSetRequesterPays()) xmlWriter.WriteElementString("RequesterPays", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.Operation.S3PutObjectCopy.RequesterPays)); if(publicRequest.Operation.S3PutObjectCopy.IsSetSSEAwsKmsKeyId()) xmlWriter.WriteElementString("SSEAwsKmsKeyId", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.SSEAwsKmsKeyId)); if(publicRequest.Operation.S3PutObjectCopy.IsSetStorageClass()) xmlWriter.WriteElementString("StorageClass", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.StorageClass)); if(publicRequest.Operation.S3PutObjectCopy.IsSetTargetKeyPrefix()) xmlWriter.WriteElementString("TargetKeyPrefix", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.TargetKeyPrefix)); if(publicRequest.Operation.S3PutObjectCopy.IsSetTargetResource()) xmlWriter.WriteElementString("TargetResource", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectCopy.TargetResource)); if(publicRequest.Operation.S3PutObjectCopy.IsSetUnModifiedSinceConstraint()) xmlWriter.WriteElementString("UnModifiedSinceConstraint", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.Operation.S3PutObjectCopy.UnModifiedSinceConstraint)); xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectLegalHold != null) { xmlWriter.WriteStartElement("S3PutObjectLegalHold", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if (publicRequest.Operation.S3PutObjectLegalHold.LegalHold != null) { xmlWriter.WriteStartElement("LegalHold", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3PutObjectLegalHold.LegalHold.IsSetStatus()) xmlWriter.WriteElementString("Status", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectLegalHold.LegalHold.Status)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectRetention != null) { xmlWriter.WriteStartElement("S3PutObjectRetention", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3PutObjectRetention.IsSetBypassGovernanceRetention()) xmlWriter.WriteElementString("BypassGovernanceRetention", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.Operation.S3PutObjectRetention.BypassGovernanceRetention)); if (publicRequest.Operation.S3PutObjectRetention.Retention != null) { xmlWriter.WriteStartElement("Retention", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Operation.S3PutObjectRetention.Retention.IsSetMode()) xmlWriter.WriteElementString("Mode", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Operation.S3PutObjectRetention.Retention.Mode)); if(publicRequest.Operation.S3PutObjectRetention.Retention.IsSetRetainUntilDate()) xmlWriter.WriteElementString("RetainUntilDate", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromDateTimeToISO8601(publicRequest.Operation.S3PutObjectRetention.Retention.RetainUntilDate)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3PutObjectTagging != null) { xmlWriter.WriteStartElement("S3PutObjectTagging", "http://awss3control.amazonaws.com/doc/2018-08-20/"); var publicRequestOperationS3PutObjectTaggingTagSet = publicRequest.Operation.S3PutObjectTagging.TagSet; if (publicRequestOperationS3PutObjectTaggingTagSet != null && publicRequestOperationS3PutObjectTaggingTagSet.Count > 0) { xmlWriter.WriteStartElement("TagSet", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestOperationS3PutObjectTaggingTagSetValue in publicRequestOperationS3PutObjectTaggingTagSet) { if (publicRequestOperationS3PutObjectTaggingTagSetValue != null) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequestOperationS3PutObjectTaggingTagSetValue.IsSetKey()) xmlWriter.WriteElementString("Key", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectTaggingTagSetValue.Key)); if(publicRequestOperationS3PutObjectTaggingTagSetValue.IsSetValue()) xmlWriter.WriteElementString("Value", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestOperationS3PutObjectTaggingTagSetValue.Value)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.Operation.S3ReplicateObject != null) { xmlWriter.WriteStartElement("S3ReplicateObject", "http://awss3control.amazonaws.com/doc/2018-08-20/"); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.IsSetPriority()) xmlWriter.WriteElementString("Priority", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromInt(publicRequest.Priority)); if (publicRequest.Report != null) { xmlWriter.WriteStartElement("Report", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequest.Report.IsSetBucket()) xmlWriter.WriteElementString("Bucket", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Report.Bucket)); if(publicRequest.Report.IsSetEnabled()) xmlWriter.WriteElementString("Enabled", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromBool(publicRequest.Report.Enabled)); if(publicRequest.Report.IsSetFormat()) xmlWriter.WriteElementString("Format", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Report.Format)); if(publicRequest.Report.IsSetPrefix()) xmlWriter.WriteElementString("Prefix", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Report.Prefix)); if(publicRequest.Report.IsSetReportScope()) xmlWriter.WriteElementString("ReportScope", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.Report.ReportScope)); xmlWriter.WriteEndElement(); } if(publicRequest.IsSetRoleArn()) xmlWriter.WriteElementString("RoleArn", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequest.RoleArn)); var publicRequestTags = publicRequest.Tags; if (publicRequestTags != null && publicRequestTags.Count > 0) { xmlWriter.WriteStartElement("Tags", "http://awss3control.amazonaws.com/doc/2018-08-20/"); foreach (var publicRequestTagsValue in publicRequestTags) { if (publicRequestTagsValue != null) { xmlWriter.WriteStartElement("member", "http://awss3control.amazonaws.com/doc/2018-08-20/"); if(publicRequestTagsValue.IsSetKey()) xmlWriter.WriteElementString("Key", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestTagsValue.Key)); if(publicRequestTagsValue.IsSetValue()) xmlWriter.WriteElementString("Value", "http://awss3control.amazonaws.com/doc/2018-08-20/", StringUtils.FromString(publicRequestTagsValue.Value)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } try { string content = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(content); request.Headers["Content-Type"] = "application/xml"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-08-20"; } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } var hostPrefixLabels = new { AccountId = StringUtils.FromString(publicRequest.AccountId), }; if (!HostPrefixUtils.IsValidLabelValue(hostPrefixLabels.AccountId)) throw new AmazonS3ControlException("AccountId can only contain alphanumeric characters and dashes and must be between 1 and 63 characters long."); request.HostPrefix = $"{hostPrefixLabels.AccountId}."; return request; } private static CreateJobRequestMarshaller _instance = new CreateJobRequestMarshaller(); internal static CreateJobRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateJobRequestMarshaller Instance { get { return _instance; } } } }
80.129241
297
0.578145
[ "Apache-2.0" ]
andyhopp/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/Internal/MarshallTransformations/CreateJobRequestMarshaller.cs
49,600
C#
using System; using System.Collections.Generic; namespace TensorShader.Operators.Connection1D { /// <summary>ストライドプーリング</summary> internal class StridePooling : Operator { /// <summary>チャネル数</summary> public int Channels { private set; get; } /// <summary>ストライド</summary> public int Stride { private set; get; } /// <summary>バッチサイズ</summary> public int Batch { private set; get; } /// <summary>コンストラクタ</summary> public StridePooling(int inwidth, int channels, int stride, int batch = 1) { if (stride < 2) { throw new ArgumentException(nameof(stride)); } this.arguments = new List<(ArgumentType type, Shape shape)>{ (ArgumentType.In, Shape.Map1D(channels, inwidth, batch)), (ArgumentType.Out, Shape.Map1D(channels, inwidth / stride, batch)), }; this.Channels = channels; this.Stride = stride; this.Batch = batch; } /// <summary>操作を実行</summary> public override void Execute(params Tensor[] tensors) { CheckArgumentShapes(tensors); Tensor inmap = tensors[0], outmap = tensors[1]; TensorShaderCudaBackend.Pool.StridePool1D((uint)Channels, (uint)inmap.Width, (uint)Batch, (uint)Stride, inmap.Buffer, outmap.Buffer); } /// <summary>操作を実行</summary> public void Execute(Tensor inmap, Tensor outmap) { Execute(new Tensor[] { inmap, outmap }); } } }
33.234043
145
0.585147
[ "MIT" ]
tk-yoshimura/TensorShader
TensorShader/Operators/Connection1D/Pool/StridePooling.cs
1,648
C#
using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; using Updater.Models; namespace Updater.Classes { public class Api { public static async Task<VersionModel> GetModpackVersion() { return await Request<VersionModel>(Config.MODPACK_URL + Config.MODPACK_INFO); } private static async Task<T> Request<T>(string url) { var response = await GetRequest(url); if (response != null) { var result = JsonConvert.DeserializeObject<T>(response); if (result != null) { return result; } } return default(T); } private static async Task<string> GetRequest(string url) { #if DEBUG System.Diagnostics.Debug.WriteLine(url); #endif try { using (var c = new HttpClient()) { //c.Timeout = new TimeSpan(5000); var response = await c.GetStringAsync(url); return response; } } catch (Exception e) { // Log and continue #if DEBUG System.Diagnostics.Debug.WriteLine(e.ToString()); #endif } return null; } } }
23.783333
89
0.483532
[ "MIT" ]
Nekroido/modpackupdater
Updater/Classes/Api.cs
1,429
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace Smartpos.Api.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
37.433526
175
0.569642
[ "MIT" ]
AbabeiAndrei/SmartPos
SmartPos.Api/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
6,476
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle { // https://github.com/dotnet/roslyn/issues/36330 tracks uncommenting the below attributes. //[ExportConfigurationFixProvider(PredefinedCodeFixProviderNames.ConfigureCodeStyleOption, LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] //[ExtensionOrder(Before = PredefinedCodeFixProviderNames.ConfigureSeverity)] internal sealed partial class ConfigureCodeStyleOptionCodeFixProvider : IConfigurationFixProvider { private static readonly ImmutableArray<bool> s_boolValues = ImmutableArray.Create(true, false); public bool IsFixableDiagnostic(Diagnostic diagnostic) { // We only offer fix for configurable code style diagnostics which have one of more editorconfig based storage locations. // Also skip suppressed diagnostics defensively, though the code fix engine should ideally never call us for suppressed diagnostics. if (diagnostic.IsSuppressed || SuppressionHelpers.IsNotConfigurableDiagnostic(diagnostic) || diagnostic.Location.SourceTree == null) { return false; } var language = diagnostic.Location.SourceTree.Options.Language; return IDEDiagnosticIdToOptionMappingHelper.TryGetMappedOptions(diagnostic.Id, language, out var options) && !options.IsEmpty && options.All(o => o.StorageLocations.Any(l => l is IEditorConfigStorageLocation2)); } public FixAllProvider GetFixAllProvider() => null; public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken)); public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken)); private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var result = ArrayBuilder<CodeFix>.GetInstance(); foreach (var diagnostic in diagnostics) { // First get all the relevant code style options for the diagnostic. var codeStyleOptions = ConfigurationUpdater.GetCodeStyleOptionsForDiagnostic(diagnostic, project); if (codeStyleOptions.IsEmpty) { continue; } // For each code style option, create a top level code action with nested code actions for every valid option value. // For example, if the option value is CodeStyleOption<bool>, we will have two nested actions, one for 'true' setting and one // for 'false' setting. If the option value is CodeStyleOption<SomeEnum>, we will have a nested action for each enum field. var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); var optionSet = project.Solution.Workspace.Options; var hasMultipleOptions = codeStyleOptions.Length > 1; foreach (var (optionKey, codeStyleOption, editorConfigLocation) in codeStyleOptions.OrderBy(t => t.optionKey.Option.Name)) { var topLevelAction = GetCodeActionForCodeStyleOption(optionKey, codeStyleOption, editorConfigLocation, diagnostic, optionSet, hasMultipleOptions); if (topLevelAction != null) { nestedActions.Add(topLevelAction); } } if (nestedActions.Count != 0) { // Wrap actions by another level if the diagnostic ID has multiple associated code style options to reduce clutter. var resultCodeAction = nestedActions.Count > 1 ? new TopLevelConfigureCodeStyleOptionCodeAction(diagnostic, nestedActions.ToImmutable()) : nestedActions.Single(); result.Add(new CodeFix(project, resultCodeAction, diagnostic)); } nestedActions.Free(); } return result.ToImmutableAndFree(); // Local functions TopLevelConfigureCodeStyleOptionCodeAction GetCodeActionForCodeStyleOption( OptionKey optionKey, ICodeStyleOption codeStyleOption, IEditorConfigStorageLocation2 editorConfigLocation, Diagnostic diagnostic, OptionSet optionSet, bool hasMultiplOptions) { // Add a code action for every valid value of the given code style option. // We only support light-bulb configuration of code style options with boolean or enum values. var nestedActions = ArrayBuilder<CodeAction>.GetInstance(); var severity = codeStyleOption.Notification.ToEditorConfigString(); string optionName = null; if (codeStyleOption.Value is bool) { foreach (var boolValue in s_boolValues) { AddCodeActionWithOptionValue(codeStyleOption, boolValue); } } else if (codeStyleOption.Value?.GetType() is Type t && t.IsEnum) { foreach (var enumValue in Enum.GetValues(t)) { AddCodeActionWithOptionValue(codeStyleOption, enumValue); } } if (nestedActions.Count > 0) { // If this is not a unique code style option for the diagnostic, use the optionName as the code action title. // In that case, we will already have a containing top level action for the diagnostic. // Otherwise, use the diagnostic information in the title. return hasMultiplOptions ? new TopLevelConfigureCodeStyleOptionCodeAction(optionName, nestedActions.ToImmutableAndFree()) : new TopLevelConfigureCodeStyleOptionCodeAction(diagnostic, nestedActions.ToImmutableAndFree()); } nestedActions.Free(); return null; // Local functions void AddCodeActionWithOptionValue(ICodeStyleOption codeStyleOption, object newValue) { // Create a new code style option value with the newValue var configuredCodeStyleOption = codeStyleOption.WithValue(newValue); // Try to get the parsed editorconfig string representation of the new code style option value if (ConfigurationUpdater.TryGetEditorConfigStringParts(configuredCodeStyleOption, editorConfigLocation, optionSet, out var parts)) { // We expect all code style values for same code style option to have the same editorconfig option name. Debug.Assert(optionName == null || optionName == parts.optionName); optionName ??= parts.optionName; // Add code action to configure the optionValue. nestedActions.Add( new SolutionChangeAction( parts.optionValue, solution => ConfigurationUpdater.ConfigureCodeStyleOptionAsync(parts.optionName, parts.optionValue, parts.optionSeverity, diagnostic, project, cancellationToken))); } } } } } }
53.213415
196
0.635957
[ "Apache-2.0" ]
geelscraig/roslyn
src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs
8,729
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.Networking.Transport.EditorTests")] [assembly: InternalsVisibleTo("Unity.Networking.Transport.RuntimeTests")] [assembly: InternalsVisibleTo("Unity.Networking.Transport.PlayTests.Performance")] // We are making certain things visible for certain projects that require // access to Network Protocols thus not requiring the API be visible [assembly: InternalsVisibleTo("Unity.InternalAPINetworkingBridge.001")]
53.888889
82
0.830928
[ "Apache-2.0" ]
Paccifficul/nervm
FPS Escape R7/Library/PackageCache/com.unity.transport@1.0.0/Runtime/AssemblyInfo.cs
485
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; namespace System.ComponentModel.Composition { /// <summary> /// The exception that is thrown when the underlying exported value or metadata of an /// <see cref="Lazy{T}"/> or <see cref="Lazy{T, TMetadataView}"/> object cannot be /// cast to <c>T</c> or <c>TMetadataView</c>, respectively. /// </summary> [Serializable] public class CompositionContractMismatchException : Exception { /// <summary> /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class. /// </summary> public CompositionContractMismatchException() : this((string?)null, (Exception?)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class /// with the specified error message. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> public CompositionContractMismatchException(string? message) : this(message, (Exception?)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class /// with the specified error message and exception that is the cause of the /// exception. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> /// <param name="innerException"> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>. /// </param> public CompositionContractMismatchException(string? message, Exception? innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class /// with the specified serialization data. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds the serialized object data about the /// <see cref="CompositionContractMismatchException"/>. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains contextual information about the /// source or destination. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="info"/> is <see langword="null"/>. /// </exception> /// <exception cref="SerializationException"> /// <paramref name="info"/> is missing a required value. /// </exception> /// <exception cref="InvalidCastException"> /// <paramref name="info"/> contains a value that cannot be cast to the correct type. /// </exception> protected CompositionContractMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
45.658824
107
0.599845
[ "MIT" ]
2m0nd/runtime
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs
3,881
C#
using StardewModdingAPI; using StardewModdingAPI.Utilities; namespace CJBCheatsMenu.Framework.Models { /// <summary>The mod configuration model.</summary> internal class ModConfig { /********* ** Accessors *********/ /// <summary>The default values.</summary> public static ModConfig Defaults { get; } = new(); /**** ** Keyboard buttons ****/ /// <summary>The button which opens the menu.</summary> public KeybindList OpenMenuKey { get; set; } = new(SButton.P); /// <summary>The button which freezes the game clock.</summary> public KeybindList FreezeTimeKey { get; set; } = new(); /// <summary>The button held to grow trees around the player.</summary> public KeybindList GrowTreeKey { get; set; } = new(SButton.NumPad1); /// <summary>The button held to grow crops around the player.</summary> public KeybindList GrowCropsKey { get; set; } = new(SButton.NumPad2); /// <summary>The number of tiles in each direction around the player to cover when pressing <see cref="GrowCropsKey"/> or <see cref="GrowTreeKey"/>.</summary> public int GrowRadius { get; set; } = 1; /**** ** Menu settings ****/ /// <summary>The tab shown by default when you open the menu.</summary> public MenuTab DefaultTab { get; set; } = MenuTab.PlayerAndTools; /**** ** Player cheats ****/ /// <summary>The player speed buff to add.</summary> public int MoveSpeed { get; set; } /// <summary>The player's health never decreases.</summary> public bool InfiniteHealth { get; set; } /// <summary>The player's stamina never decreases.</summary> public bool InfiniteStamina { get; set; } /// <summary>Tool and weapon cooldowns are instant.</summary> public bool InstantCooldowns { get; set; } /// <summary>The player's daily luck is always at the maximum value.</summary> public bool MaxDailyLuck { get; set; } /// <summary>The player's attacks kill any monster in one hit.</summary> public bool OneHitKill { get; set; } /// <summary>The player's tools break things instantly.</summary> public bool OneHitBreak { get; set; } /// <summary>The player's watering can never runs dry.</summary> public bool InfiniteWateringCan { get; set; } /// <summary>The player can harvest any crop with the scythe.</summary> public bool HarvestScythe { get; set; } /**** ** Fishing cheats ****/ /// <summary>After casting the fishing line, the fishing minigame appears immediately.</summary> public bool InstantBite { get; set; } /// <summary>When the fishing minigame appears, the fish is caught immediately.</summary> public bool InstantCatch { get; set; } /// <summary>When casting the fishing line, it always reaches the maximum distance.</summary> public bool ThrowBobberMax { get; set; } /// <summary>Fishing tackles never break.</summary> public bool DurableTackles { get; set; } /// <summary>Every fishing minigame has a treasure.</summary> public bool AlwaysTreasure { get; set; } /**** ** Time cheats ****/ /// <summary>The game clock never changes.</summary> public bool FreezeTime { get; set; } /// <summary>The game clock doesn't change when you're inside a building.</summary> public bool FreezeTimeInside { get; set; } /// <summary>The game clock doesn't change when you're inside the mines, Skull Cavern, or farm cave.</summary> public bool FreezeTimeCaves { get; set; } /// <summary>Bee houses finish instantly.</summary> public bool FastBeeHouse { get; set; } /// <summary>Bone mills finish instantly.</summary> public bool FastBoneMill { get; set; } /// <summary>Casks finish instantly.</summary> public bool FastCask { get; set; } /// <summary>Charcoal kilns finish instantly.</summary> public bool FastCharcoalKiln { get; set; } /// <summary>Cheese presses finish instantly.</summary> public bool FastCheesePress { get; set; } /// <summary>Coffee makers finish instantly.</summary> public bool FastCoffeeMaker { get; set; } /// <summary>Crab pots finish instantly.</summary> public bool FastCrabPot { get; set; } /// <summary>Crystalariums finish instantly.</summary> public bool FastCrystalarium { get; set; } /// <summary>Deconstructors finish instantly.</summary> public bool FastDeconstructor { get; set; } /// <summary>Fruit trees bear fruit instantly.</summary> public bool FastFruitTree { get; set; } /// <summary>Furnaces finish instantly.</summary> public bool FastFurnace { get; set; } /// <summary>Geode crushers finish instantly.</summary> public bool FastGeodeCrusher { get; set; } /// <summary>Egg incubators finish overnight.</summary> public bool FastIncubator { get; set; } /// <summary>Kegs finish instantly.</summary> public bool FastKeg { get; set; } /// <summary>Lightning rods finish instantly.</summary> public bool FastLightningRod { get; set; } /// <summary>Looms finish instantly.</summary> public bool FastLoom { get; set; } /// <summary>Mayonnaise machines finish instantly.</summary> public bool FastMayonnaiseMachine { get; set; } /// <summary>Mushroom boxs finish instantly.</summary> public bool FastMushroomBox { get; set; } /// <summary>Oil makers finish instantly.</summary> public bool FastOilMaker { get; set; } /// <summary>Ostrich incubators finish overnight.</summary> public bool FastOstrichIncubator { get; set; } /// <summary>Preserves jars finish instantly.</summary> public bool FastPreservesJar { get; set; } /// <summary>Recycling machines finish instantly.</summary> public bool FastRecyclingMachine { get; set; } /// <summary>Seed makers finish instantly.</summary> public bool FastSeedMaker { get; set; } /// <summary>Slime egg press finish instantly.</summary> public bool FastSlimeEggPress { get; set; } /// <summary>Slime incubators finish instantly.</summary> public bool FastSlimeIncubator { get; set; } /// <summary>Soda machines finish instantly.</summary> public bool FastSodaMachine { get; set; } /// <summary>Solar panels finish instantly.</summary> public bool FastSolarPanel { get; set; } /// <summary>Statues of endless fortune finish instantly.</summary> public bool FastStatueOfEndlessFortune { get; set; } /// <summary>Statues of perfection finish instantly.</summary> public bool FastStatueOfPerfection { get; set; } /// <summary>Statues of true perfection finish instantly.</summary> public bool FastStatueOfTruePerfection { get; set; } /// <summary>Tappers finish instantly.</summary> public bool FastTapper { get; set; } /// <summary>Wood Chippers finish instantly.</summary> public bool FastWoodChipper { get; set; } /// <summary>Worm bins finish instantly.</summary> public bool FastWormBin { get; set; } /**** ** Other cheats ****/ /// <summary>The player can always give gifts to villagers, regardless of the daily and weekly limits.</summary> public bool AlwaysGiveGift { get; set; } /// <summary>A villager's friendship value no longer slowly decays if it isn't maxed out.</summary> public bool NoFriendshipDecay { get; set; } /// <summary>Fences never break.</summary> public bool DurableFences { get; set; } /// <summary>Building new structures on the farm completes instantly.</summary> public bool InstantBuild { get; set; } /// <summary>Feed troughs in your barns and coops are refilled automatically.</summary> public bool AutoFeed { get; set; } /// <summary>Farm animals are pet automatically.</summary> public bool AutoPetAnimals { get; set; } /// <summary>Crops are watered automatically.</summary> public bool AutoWater { get; set; } /// <summary>Hay silos are always full.</summary> public bool InfiniteHay { get; set; } } }
38.362832
166
0.621569
[ "MIT" ]
Blackcobra126/SDV-Mods
CJBCheatsMenu/Framework/Models/ModConfig.cs
8,670
C#
using Mono.CecilX; using Mono.CecilX.Cil; namespace Mirror.Weaver { public static class SyncObjectProcessor { /// <summary> /// Generates the serialization and deserialization methods for a specified generic argument /// </summary> /// <param name="td">The type of the class that needs serialization methods</param> /// <param name="genericArgument">Which generic argument to serialize, 0 is the first one</param> /// <param name="serializeMethod">The name of the serialize method</param> /// <param name="deserializeMethod">The name of the deserialize method</param> public static void GenerateSerialization(TypeDefinition td, int genericArgument, string serializeMethod, string deserializeMethod) { // find item type GenericInstanceType gt = (GenericInstanceType)td.BaseType; if (gt.GenericArguments.Count <= genericArgument) { Weaver.Error($"{td} should have {genericArgument} generic arguments"); return; } TypeReference itemType = Weaver.CurrentAssembly.MainModule.ImportReference(gt.GenericArguments[genericArgument]); Weaver.DLog(td, "SyncObjectProcessor Start item:" + itemType.FullName); MethodReference writeItemFunc = GenerateSerialization(serializeMethod, td, itemType); if (Weaver.WeavingFailed) { return; } MethodReference readItemFunc = GenerateDeserialization(deserializeMethod, td, itemType); if (readItemFunc == null || writeItemFunc == null) return; Weaver.DLog(td, "SyncObjectProcessor Done"); } // serialization of individual element static MethodReference GenerateSerialization(string methodName, TypeDefinition td, TypeReference itemType) { Weaver.DLog(td, " GenerateSerialization"); MethodDefinition existing = td.GetMethod(methodName); if (existing != null) return existing; MethodDefinition serializeFunc = new MethodDefinition(methodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.HideBySig, Weaver.voidType); serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); serializeFunc.Parameters.Add(new ParameterDefinition("item", ParameterAttributes.None, itemType)); ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); if (itemType.IsGenericInstance) { Weaver.Error($"{td} cannot have generic elements {itemType}"); return null; } MethodReference writeFunc = Writers.GetWriteFunc(itemType); if (writeFunc != null) { serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); } else { Weaver.Error($"{td} cannot have item of type {itemType}. Use a type supported by mirror instead"); return null; } serWorker.Append(serWorker.Create(OpCodes.Ret)); td.Methods.Add(serializeFunc); return serializeFunc; } static MethodReference GenerateDeserialization(string methodName, TypeDefinition td, TypeReference itemType) { Weaver.DLog(td, " GenerateDeserialization"); MethodDefinition existing = td.GetMethod(methodName); if (existing != null) return existing; MethodDefinition deserializeFunction = new MethodDefinition(methodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.HideBySig, itemType); deserializeFunction.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); ILProcessor serWorker = deserializeFunction.Body.GetILProcessor(); MethodReference readerFunc = Readers.GetReadFunc(itemType); if (readerFunc != null) { serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc)); serWorker.Append(serWorker.Create(OpCodes.Ret)); } else { Weaver.Error($"{td} cannot have item of type {itemType}. Use a type supported by mirror instead"); return null; } td.Methods.Add(deserializeFunction); return deserializeFunction; } } }
43.201681
185
0.618362
[ "MIT" ]
Arahain/FlyCasual
Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs
5,141
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _08Assenze_15 { class Assenze { #region attributi private DateTime day = new DateTime(); private ushort classe = 1; private char sezione = 'A'; private ushort assenti = 0; #endregion #region costruttori public Assenze(DateTime day, ushort classe, char sezione) { this.day = day; this.classe = classe; this.sezione = sezione; } #endregion #region Get&Set public char GetSezione() { return sezione; } public void SetSezione(char sezione) { this.sezione = sezione; } public void SetDay(DateTime day) { this.day = day; } public int GetDay() { return day.Day; } public void SetClasse(ushort classe) { this.classe = classe; } public ushort GetClasse() { return classe; } public ushort GetAssenti() { return assenti; } public void SetAssenti(int assenti) { this.assenti = (ushort)assenti; } #endregion } }
20.242857
67
0.47283
[ "Unlicense" ]
VenomBigBozz/Esercizi
Scuola/Esercizi C#/Informatica/08Assenze_15/08Assenze_15/08Assenze_15_Sezioni/08Assenze_15/08Assenze_15/Assenze.cs
1,419
C#
using System; using System.Collections.Generic; using UnityEngine; [AddComponentMenu("NGUI/Interaction/Button")] public class UIButton : UIButtonColor { public override Boolean isEnabled { get { if (!base.enabled) { return false; } Collider component = base.gameObject.GetComponent<Collider>(); if (component && component.enabled) { return true; } Collider2D component2 = base.GetComponent<Collider2D>(); return component2 && component2.enabled; } set { if (this.isEnabled != value) { Collider component = base.gameObject.GetComponent<Collider>(); if (component != (UnityEngine.Object)null) { component.enabled = value; UIButton[] components = base.GetComponents<UIButton>(); UIButton[] array = components; for (Int32 i = 0; i < (Int32)array.Length; i++) { UIButton uibutton = array[i]; uibutton.SetState((UIButtonColor.State)((!value) ? UIButtonColor.State.Disabled : UIButtonColor.State.Normal), false); } } else { Collider2D component2 = base.GetComponent<Collider2D>(); if (component2 != (UnityEngine.Object)null) { component2.enabled = value; UIButton[] components2 = base.GetComponents<UIButton>(); UIButton[] array2 = components2; for (Int32 j = 0; j < (Int32)array2.Length; j++) { UIButton uibutton2 = array2[j]; uibutton2.SetState((UIButtonColor.State)((!value) ? UIButtonColor.State.Disabled : UIButtonColor.State.Normal), false); } } else { base.enabled = value; } } } } } public String normalSprite { get { if (!this.mInitDone) { this.OnInit(); } return this.mNormalSprite; } set { if (!this.mInitDone) { this.OnInit(); } if (this.mSprite != (UnityEngine.Object)null && !String.IsNullOrEmpty(this.mNormalSprite) && this.mNormalSprite == this.mSprite.spriteName) { this.mNormalSprite = value; this.SetSprite(value); NGUITools.SetDirty(this.mSprite); } else { this.mNormalSprite = value; if (this.mState == UIButtonColor.State.Normal) { this.SetSprite(value); } } } } public Sprite normalSprite2D { get { if (!this.mInitDone) { this.OnInit(); } return this.mNormalSprite2D; } set { if (!this.mInitDone) { this.OnInit(); } if (this.mSprite2D != (UnityEngine.Object)null && this.mNormalSprite2D == this.mSprite2D.sprite2D) { this.mNormalSprite2D = value; this.SetSprite(value); NGUITools.SetDirty(this.mSprite); } else { this.mNormalSprite2D = value; if (this.mState == UIButtonColor.State.Normal) { this.SetSprite(value); } } } } protected override void OnInit() { base.OnInit(); this.mSprite = (this.mWidget as UISprite); this.mSprite2D = (this.mWidget as UI2DSprite); if (this.mSprite != (UnityEngine.Object)null) { this.mNormalSprite = this.mSprite.spriteName; } if (this.mSprite2D != (UnityEngine.Object)null) { this.mNormalSprite2D = this.mSprite2D.sprite2D; } } protected override void OnEnable() { if (this.isEnabled) { if (this.mInitDone) { this.OnHover(UICamera.hoveredObject == base.gameObject); } } else { this.SetState(UIButtonColor.State.Disabled, true); } } protected override void OnDragOver() { if (this.isEnabled && (this.dragHighlight || UICamera.currentTouch.pressed == base.gameObject)) { base.OnDragOver(); } } protected override void OnDragOut() { if (this.isEnabled && (this.dragHighlight || UICamera.currentTouch.pressed == base.gameObject)) { base.OnDragOut(); } } protected virtual void OnClick() { if (UIButton.current == (UnityEngine.Object)null && this.isEnabled) { UIButton.current = this; EventDelegate.Execute(this.onClick); UIButton.current = (UIButton)null; } } public override void SetState(UIButtonColor.State state, Boolean immediate) { base.SetState(state, immediate); if (this.mSprite != (UnityEngine.Object)null) { switch (state) { case UIButtonColor.State.Normal: this.SetSprite(this.mNormalSprite); break; case UIButtonColor.State.Hover: this.SetSprite((!String.IsNullOrEmpty(this.hoverSprite)) ? this.hoverSprite : this.mNormalSprite); break; case UIButtonColor.State.Pressed: this.SetSprite(this.pressedSprite); break; case UIButtonColor.State.Disabled: this.SetSprite(this.disabledSprite); break; } } else if (this.mSprite2D != (UnityEngine.Object)null) { switch (state) { case UIButtonColor.State.Normal: this.SetSprite(this.mNormalSprite2D); break; case UIButtonColor.State.Hover: this.SetSprite((!(this.hoverSprite2D == (UnityEngine.Object)null)) ? this.hoverSprite2D : this.mNormalSprite2D); break; case UIButtonColor.State.Pressed: this.SetSprite(this.pressedSprite2D); break; case UIButtonColor.State.Disabled: this.SetSprite(this.disabledSprite2D); break; } } } protected void SetSprite(String sp) { if (this.mSprite != (UnityEngine.Object)null && !String.IsNullOrEmpty(sp) && this.mSprite.spriteName != sp) { this.mSprite.spriteName = sp; if (this.pixelSnap) { this.mSprite.MakePixelPerfect(); } } } protected void SetSprite(Sprite sp) { if (sp != (UnityEngine.Object)null && this.mSprite2D != (UnityEngine.Object)null && this.mSprite2D.sprite2D != sp) { this.mSprite2D.sprite2D = sp; if (this.pixelSnap) { this.mSprite2D.MakePixelPerfect(); } } } public static UIButton current; public Boolean dragHighlight; public String hoverSprite; public String pressedSprite; public String disabledSprite; public Sprite hoverSprite2D; public Sprite pressedSprite2D; public Sprite disabledSprite2D; public Boolean pixelSnap; public List<EventDelegate> onClick = new List<EventDelegate>(); [NonSerialized] private UISprite mSprite; [NonSerialized] private UI2DSprite mSprite2D; [NonSerialized] private String mNormalSprite; [NonSerialized] private Sprite mNormalSprite2D; }
21.812057
142
0.668021
[ "MIT" ]
Albeoris/Memoria
Assembly-CSharp/Global/UI/UIButton/UIButton.cs
6,153
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class SiteMember_profilepic1 : System.Web.UI.Page { SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\data.mdf;Integrated Security=True;User Instance=True"); SqlCommand cmd = new SqlCommand(); SqlDataReader reader; protected void Page_Load(object sender, EventArgs e) { FileUpload1.Focus(); } protected void upload_btn_Click(object sender, EventArgs e) { string filepath = ""; if (FileUpload1.HasFile) { filepath = "~/ProfilePic/" + Session["username"].ToString() + FileUpload1.FileName; FileUpload1.SaveAs(Server.MapPath(filepath)); cn.Open(); cmd.Connection = cn; cmd.CommandText = "select count(*) from profile_picture where username=@username"; cmd.Parameters.AddWithValue("@username", Session["username"].ToString()); int count = Convert.ToInt32(cmd.ExecuteScalar()); cmd.Parameters.Clear(); if (count == 0) { cmd.CommandText = "insert into profile_picture values(@photo,@username)"; } else { cmd.CommandText = "update profile_picture set photo=@photo where username=@username"; } cmd.Parameters.AddWithValue("@photo", filepath); cmd.Parameters.AddWithValue("@username", Session["username"].ToString()); cmd.ExecuteNonQuery(); cn.Close(); cmd.Parameters.Clear(); Image1.ImageUrl = filepath; } } protected void savechanges_btn_Click(object sender, EventArgs e) { Response.Redirect("information.aspx"); } }
30.777778
156
0.612171
[ "MIT" ]
JoyNas/get2gether-Social-networking-website
get2gether/SiteMember/profilepic1.aspx.cs
1,941
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ChristmasPreparation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ChristmasPreparation")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7bdee6ba-6606-43e7-bfed-ecac7a2d44d5")] // 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.027778
84
0.747261
[ "MIT" ]
pirocorp/Programming-Basics
ProgrammingBasicsExamPreparation/ChristmasPreparation/Properties/AssemblyInfo.cs
1,372
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.Runtime.InteropServices; #if IS_DESKTOP using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; #endif namespace NuGet.Packaging.Signing { internal static class NativeUtility { internal static void SafeFree(IntPtr ptr) { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } internal static void ThrowIfFailed(bool result) { if (!result) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } #if IS_DESKTOP internal static SignedCms NativeSign(CmsSigner cmsSigner, byte[] data, CngKey privateKey) { using (var hb = new HeapBlockRetainer()) { var certificateBlobs = new BLOB[cmsSigner.Certificates.Count]; for (var i = 0; i < cmsSigner.Certificates.Count; ++i) { var cert = cmsSigner.Certificates[i]; var context = Marshal.PtrToStructure<CERT_CONTEXT>(cert.Handle); certificateBlobs[i] = new BLOB() { cbData = context.cbCertEncoded, pbData = context.pbCertEncoded }; } byte[] encodedData; var signerInfo = CreateSignerInfo(cmsSigner, privateKey, hb); var signedInfo = new CMSG_SIGNED_ENCODE_INFO(); signedInfo.cbSize = Marshal.SizeOf(signedInfo); signedInfo.cSigners = 1; using (var signerInfoHandle = new SafeLocalAllocHandle(Marshal.AllocHGlobal(Marshal.SizeOf(signerInfo)))) { Marshal.StructureToPtr(signerInfo, signerInfoHandle.DangerousGetHandle(), fDeleteOld: false); signedInfo.rgSigners = signerInfoHandle.DangerousGetHandle(); signedInfo.cCertEncoded = certificateBlobs.Length; using (var certificatesHandle = new SafeLocalAllocHandle(Marshal.AllocHGlobal(Marshal.SizeOf(certificateBlobs[0]) * certificateBlobs.Length))) { for (var i = 0; i < certificateBlobs.Length; ++i) { Marshal.StructureToPtr(certificateBlobs[i], new IntPtr(certificatesHandle.DangerousGetHandle().ToInt64() + Marshal.SizeOf(certificateBlobs[i]) * i), fDeleteOld: false); } signedInfo.rgCertEncoded = certificatesHandle.DangerousGetHandle(); var hMsg = NativeMethods.CryptMsgOpenToEncode( CMSG_ENCODING.Any, dwFlags: 0, dwMsgType: NativeMethods.CMSG_SIGNED, pvMsgEncodeInfo: ref signedInfo, pszInnerContentObjID: null, pStreamInfo: IntPtr.Zero); ThrowIfFailed(!hMsg.IsInvalid); ThrowIfFailed(NativeMethods.CryptMsgUpdate( hMsg, data, (uint)data.Length, fFinal: true)); uint valueLength = 0; ThrowIfFailed(NativeMethods.CryptMsgGetParam( hMsg, CMSG_GETPARAM_TYPE.CMSG_CONTENT_PARAM, dwIndex: 0, pvData: null, pcbData: ref valueLength)); encodedData = new byte[(int)valueLength]; ThrowIfFailed(NativeMethods.CryptMsgGetParam( hMsg, CMSG_GETPARAM_TYPE.CMSG_CONTENT_PARAM, dwIndex: 0, pvData: encodedData, pcbData: ref valueLength)); } } var cms = new SignedCms(); cms.Decode(encodedData); return cms; } } internal unsafe static CMSG_SIGNER_ENCODE_INFO CreateSignerInfo( CmsSigner cmsSigner, CngKey privateKey, HeapBlockRetainer hb) { var signerInfo = new CMSG_SIGNER_ENCODE_INFO(); signerInfo.cbSize = (uint)Marshal.SizeOf(signerInfo); signerInfo.pCertInfo = Marshal.PtrToStructure<CERT_CONTEXT>(cmsSigner.Certificate.Handle).pCertInfo; signerInfo.hCryptProvOrhNCryptKey = privateKey.Handle.DangerousGetHandle(); signerInfo.HashAlgorithm.pszObjId = cmsSigner.DigestAlgorithm.Value; if (cmsSigner.SignerIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) { var certContextHandle = IntPtr.Zero; try { certContextHandle = NativeMethods.CertDuplicateCertificateContext(cmsSigner.Certificate.Handle); uint cbData = 0; var pbData = IntPtr.Zero; ThrowIfFailed(NativeMethods.CertGetCertificateContextProperty( certContextHandle, NativeMethods.CERT_KEY_IDENTIFIER_PROP_ID, pbData, ref cbData)); if (cbData > 0) { pbData = hb.Alloc((int)cbData); ThrowIfFailed(NativeMethods.CertGetCertificateContextProperty( certContextHandle, NativeMethods.CERT_KEY_IDENTIFIER_PROP_ID, pbData, ref cbData)); signerInfo.SignerId.dwIdChoice = NativeMethods.CERT_ID_KEY_IDENTIFIER; signerInfo.SignerId.KeyId.cbData = cbData; signerInfo.SignerId.KeyId.pbData = pbData; } } finally { if (certContextHandle != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(certContextHandle); } } } if (cmsSigner.SignedAttributes.Count != 0) { signerInfo.cAuthAttr = cmsSigner.SignedAttributes.Count; checked { var attributeSize = Marshal.SizeOf<CRYPT_ATTRIBUTE>(); var blobSize = Marshal.SizeOf<CRYPT_INTEGER_BLOB>(); var attributesArray = (CRYPT_ATTRIBUTE*)hb.Alloc(attributeSize * cmsSigner.SignedAttributes.Count); var currentAttribute = attributesArray; foreach (var attribute in cmsSigner.SignedAttributes) { currentAttribute->pszObjId = hb.AllocAsciiString(attribute.Oid.Value); currentAttribute->cValue = (uint)attribute.Values.Count; currentAttribute->rgValue = hb.Alloc(blobSize); foreach (var value in attribute.Values) { var attrData = value.RawData; if (attrData.Length > 0) { var blob = (CRYPT_INTEGER_BLOB*)currentAttribute->rgValue; blob->cbData = (uint)attrData.Length; blob->pbData = hb.Alloc(value.RawData.Length); Marshal.Copy(attrData, 0, blob->pbData, attrData.Length); } } currentAttribute++; } signerInfo.rgAuthAttr = new IntPtr(attributesArray); } } return signerInfo; } #endif } }
39.349282
196
0.508025
[ "Apache-2.0" ]
BdDsl/NuGet.Client
src/NuGet.Core/NuGet.Packaging/Signing/Native/NativeUtility.cs
8,224
C#
/* * Copyright (c) 2015 Blake McBride (blake@mcbridemail.com) * All rights reserved. * * 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Text; // Author: Blake McBride namespace CSUtils { public static class StringUtils { /// <summary> /// APL-like Take for strings. /// </summary> /// <param name="s">the string</param> /// <param name="n">number of characters to take (negative means take from back)</param> public static string Take(string s, int n) { int len = s.Length; if (len == n) return s; if (n >= 0) { if (n < len) return s.Substring(0, n); StringBuilder sb = new StringBuilder(s); for (n -= len; n-- > 0;) sb.Append(' '); return sb.ToString(); } else { n = -n; if (n < len) return Drop(s, len - n); StringBuilder sb = new StringBuilder(); for (n -= len; n-- > 0;) sb.Append(' '); sb.Append(s); return sb.ToString(); } } /// <summary> /// APL-like Drop for strings. /// </summary> /// <param name="s">the string</param> /// <param name="n">number of characters to drop (negative means from back)</param> public static string Drop(string s, int n) { if (n == 0) return s; int len = s.Length; if (n >= len || -n >= len) return ""; if (n > 0) return s.Substring(n); return s.Substring(0, len + n); } } }
32.910112
90
0.679071
[ "BSD-2-Clause" ]
blakemcbride/CSUtils
StringUtils.cs
2,931
C#
using AutoMapper; using Gymate.Application.Mapping; using Gymate.Domain.BOs.ExerciseBOs; using Microsoft.AspNetCore.Mvc.Rendering; using System.Collections.Generic; namespace Gymate.Application.ViewModels.ExerciseVm { public class NewExerciseVm : IMapFrom<CreateExerciseBO> { public int Id { get; set; } public string Name { get; set; } public int ExerciseTypeId { get; set; } public List<SelectListItem> SelectListExerciseTypes { get; set; } public void Mapping(Profile profile) { profile.CreateMap<CreateExerciseBO, NewExerciseVm>(); } } }
28.409091
73
0.6896
[ "MIT" ]
kvervandil/GymateWebApi
GymateApi.Api/ViewModels/ExerciseVm/NewExerciseVm.cs
627
C#
using UnityEngine; namespace EditorExtensions { /// <summary> /// Class that represents data of highlighted object in hierarchy /// </summary> public class HierarchyHighlighter : MonoBehaviour { [SerializeField] private bool isDisplayed = true; [Space(10)] [SerializeField] [Range(0, 15)] private int fontSize = 10; [SerializeField] private FontStyle fontStyle = FontStyle.Normal; [SerializeField] private Color fontColor = Color.black; [Space] [SerializeField] private Color backgroundColor = Color.white; public bool IsDisplayed => isDisplayed; public int FontSize => fontSize; public FontStyle FontStyle => fontStyle; public Color FontColor => fontColor; public Color BackgroundColor => backgroundColor; private void OnValidate() { fontColor.a = 255; backgroundColor.a = 255; } } }
31.833333
72
0.637696
[ "MIT" ]
Vo1z/pilgrim-concept
Assets/Editor/EditorExtensions/HierarchyHighlighter.cs
955
C#
// Copyright (c) 2022 .NET Foundation and Contributors. All rights reserved. // 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 full license information. using System; using System.Windows; namespace ReactiveUI.Tests.Wpf { public class WpfActiveContentApp : Application { #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. /// <summary> /// Gets the mock window factory. /// </summary> /// <value> /// The mock window factory. /// </value> public Func<MockWindow> MockWindowFactory { get; } = () => new(); /// <summary> /// Gets the tc mock window factory. /// </summary> /// <value> /// The tc mock window factory. /// </value> public Func<TCMockWindow> TCMockWindowFactory { get; } = () => new(); /// <summary> /// Gets the WPF test window factory. /// </summary> /// <value> /// The WPF test window factory. /// </value> public Func<WpfTestWindow> WpfTestWindowFactory { get; } = () => new(); #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. } }
34.571429
140
0.621212
[ "MIT" ]
Awsmolak/ReactiveUI
src/ReactiveUI.Tests/Platforms/wpf/Mocks/WpfActiveContentApp.cs
1,454
C#
namespace Octokit.Webhooks.AspNetCore; using System; using System.Globalization; using System.IO; using System.Net.Mime; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; /// <summary> /// A class containing extension methods for <see cref="IEndpointRouteBuilder"/> /// for adding an HTTP endpoint for processing GitHub webhook payloads. /// </summary> public static partial class GitHubWebhookExtensions { public static void MapGitHubWebhooks(this IEndpointRouteBuilder endpoints, string path = "/api/github/webhooks", string secret = null!) => endpoints.MapPost(path, async context => { var logger = context.RequestServices.GetRequiredService<ILogger<WebhookEventProcessor>>(); // Verify content type if (!VerifyContentType(context, MediaTypeNames.Application.Json)) { Log.IncorrectContentType(logger); return; } // Get body var body = await GetBodyAsync(context).ConfigureAwait(false); // Verify signature if (!await VerifySignatureAsync(context, secret, body).ConfigureAwait(false)) { Log.SignatureValidationFailed(logger); return; } // Process body try { var service = context.RequestServices.GetRequiredService<WebhookEventProcessor>(); await service.ProcessWebhookAsync(context.Request.Headers, body) .ConfigureAwait(false); context.Response.StatusCode = 200; } catch (Exception ex) { Log.ProcessingFailed(logger, ex); context.Response.StatusCode = 500; } }); private static bool VerifyContentType(HttpContext context, string expectedContentType) { if (context.Request.ContentType is null) { return false; } var contentType = new ContentType(context.Request.ContentType); if (contentType.MediaType != expectedContentType) { context.Response.StatusCode = 400; return false; } return true; } private static async Task<string> GetBodyAsync(HttpContext context) { using var reader = new StreamReader(context.Request.Body); return await reader.ReadToEndAsync().ConfigureAwait(false); } private static async Task<bool> VerifySignatureAsync(HttpContext context, string secret, string body) { _ = context.Request.Headers.TryGetValue("X-Hub-Signature-256", out var signatureSha256); var isSigned = signatureSha256.Count > 0; var isSignatureExpected = !string.IsNullOrEmpty(secret); if (!isSigned && !isSignatureExpected) { // Nothing to do. return true; } if (!isSigned && isSignatureExpected) { context.Response.StatusCode = 400; return false; } if (isSigned && !isSignatureExpected) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Payload includes a secret, so the webhook receiver must configure a secret.") .ConfigureAwait(false); return false; } var keyBytes = Encoding.UTF8.GetBytes(secret); var bodyBytes = Encoding.UTF8.GetBytes(body); var hash = HMACSHA256.HashData(keyBytes, bodyBytes); var hashHex = Convert.ToHexString(hash); var expectedHeader = $"sha256={hashHex.ToLower(CultureInfo.InvariantCulture)}"; if (signatureSha256.ToString() != expectedHeader) { context.Response.StatusCode = 400; return false; } return true; } /// <summary> /// Log messages for the class. /// </summary> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] internal static partial class Log { [LoggerMessage( EventId = 1, Level = LogLevel.Error, Message = "GitHub event does not have the correct content type.")] public static partial void IncorrectContentType(ILogger logger); [LoggerMessage( EventId = 2, Level = LogLevel.Error, Message = "GitHub event failed signature validation.")] public static partial void SignatureValidationFailed(ILogger logger); [LoggerMessage( EventId = 3, Level = LogLevel.Error, Message = "Exception processing GitHub event.")] public static partial void ProcessingFailed(ILogger logger, Exception exception); } }
33.201342
142
0.621993
[ "MIT" ]
JamieMagee/webhooks.net
src/Octokit.Webhooks.AspNetCore/GitHubWebhookExtensions.cs
4,949
C#
namespace mana.fs.elf { public enum ElfSectionType : uint { Null = 0, ProgBits = 1, SymTab = 2, StrTab = 3, Rela = 4, Hash = 5, Dynamic = 6, Note = 7, NoBits = 8, Rel = 9, ShLib = 10, DynSym = 11, LoProc = 0x70000000, HiProc = 0x7fffffff, LoUser = 0x80000000, HiUser = 0xffffffff } }
18.434783
37
0.441038
[ "MIT" ]
Djelnar/mana_lang
backend/Ishtar/fs/elf/ElfSectionType.cs
424
C#
 namespace OpenQA.Selenium.Appium { public class AppiumElementFactory : CachedElementFactory<AppiumElement> { public AppiumElementFactory(WebDriver parentDriver) : base(parentDriver) { } protected override AppiumElement CreateCachedElement(WebDriver parentDriver, string elementId) { return new AppiumElement(parentDriver, elementId); } } }
27.6
102
0.68599
[ "Apache-2.0" ]
TroyWalshProf/appium-dotnet-driver
src/Appium.Net/Appium/AppiumElementFactory.cs
416
C#
using Microsoft.AspNetCore.Http; using System.Diagnostics; using System.Threading.Tasks; namespace Agile.BaseLib.Extensions { public class ResponseTimeMiddleware { // Name of the Response Header, Custom Headers starts with "X-" private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms"; // Handle to the next Middleware in the pipeline private readonly RequestDelegate _next; public ResponseTimeMiddleware(RequestDelegate next) { _next = next; } public Task InvokeAsync(HttpContext context) { // Start the Timer using Stopwatch var watch = new Stopwatch(); watch.Start(); context.Response.OnStarting(() => { // Stop the timer information and calculate the time watch.Stop(); var responseTimeForCompleteRequest = watch.ElapsedMilliseconds; // Add the Response time information in the Response headers. context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString(); return Task.CompletedTask; }); // Call the next delegate/middleware in the pipeline return this._next(context); } } }
38.2
116
0.621541
[ "MIT" ]
Rohmeng/Agile.BaseLib
Extensions/MiddlewareExtensions.cs
1,339
C#
using System; using EventStore.Core.Data; namespace EventStore.Core { public class VNodeStatusChangeArgs : EventArgs { public readonly VNodeState NewVNodeState; public VNodeStatusChangeArgs(VNodeState newVNodeState) { NewVNodeState = newVNodeState; } } }
20.8
62
0.676282
[ "Apache-2.0", "CC0-1.0" ]
BertschiAG/EventStore
src/EventStore.Core/VNodeStatusChangeArgs.cs
312
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using WinForm.UI.Animations; using WinForm.UI.Events; namespace WinForm.UI.Controls { /*** * =========================================================== * 创建人:yuanj * 创建时间:2018/01/11 16:20:19 * 说明: * ========================================================== * */ [ComVisibleAttribute(true)] [ToolboxItem(true), DefaultProperty("BorderStyle"), DefaultEvent("ItemClick")] public class FListView : Control { /// <summary> /// 所有行的矩形 /// </summary> private List<ViewHolder> Rows; private VScroll chatVScroll; //滚动条 private HScroll listHScroll; ///// <summary> ///// 鼠标位置 ///// </summary> private Point m_ptMousePos; [Browsable(false)] public ViewHolder MouseHolder { get; set; } /// <summary> /// 当前选中向 /// </summary> [Browsable(false)] public ViewHolder SelectHolder { get; set; } /// <summary> /// 是否有鼠标反馈效果 /// </summary> public bool IsMouseFeedBack = true; public FListView() { this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.Selectable, true); //强制分配样式重新应用到控件上 UpdateStyles(); this.Size = new Size(150, 250); borderStyle = BorderStyle.FixedSingle; chatVScroll = new VScroll(this); listHScroll = new HScroll(this); chatVScroll.OnScrollEvent += ChatVScroll_OnScrollEvent; listHScroll.OnScrollEvent += ChatVScroll_OnScrollEvent; Rows = new List<ViewHolder>(); } private void ChatVScroll_OnScrollEvent(object sender, ScrollEventArgs e) { OnScroll(e); } public int VirtualHeight, VirtualWidth = 0; #region 属性 private BorderStyle borderStyle; /// <summary> /// 指示控件的边框样式 /// </summary> [DefaultValue(typeof(BorderStyle), "1")] [Description("获取或设置控件的边框")] public BorderStyle BorderStyle { get { return borderStyle; } set { if (value == borderStyle) return; borderStyle = value; this.Invalidate(); } } [Bindable(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override string Text { get { return base.Text; } set { base.Text = value; } } private int itemDivider = 0; [Category("Skin")] [Description("获取或设置当前控件Item向的间隔")] [DefaultValue(typeof(int), "0")] public int ItemDivider { get { return itemDivider; } set { if (itemDivider == value) return; itemDivider = value; this.Invalidate(); } } #region 滚动条 /// <summary> /// 获取或者设置滚动条背景色 /// </summary> [DefaultValue(typeof(Color), "214, 219, 233"), Category("Scroll")] [Description("滚动条的背景颜色")] public Color ScrollBackColor { get { return chatVScroll.BackColor; } set { chatVScroll.BackColor = value; listHScroll.BackColor = value; } } /// <summary> /// 获取或者设置滚动条鼠标以上颜色 /// </summary> [DefaultValue(typeof(Color), "104, 104, 104"), Category("Scroll")] [Description("滚动条鼠标移上默认情况下的颜色")] public Color ScrollMouseMoveColor { get { return chatVScroll.MouseMoveColor; } set { chatVScroll.MouseMoveColor = value; listHScroll.MouseMoveColor = value; } } /// <summary> /// 获取或者设置横向滚动条高 /// </summary> [DefaultValue(typeof(int), "10"), Category("Scroll")] [Description("获取或者设置横向滚动条高")] public int HScrollHeight { get { return listHScroll.Height; } set { listHScroll.Height = value; } } /// <summary> /// 获取或者设置纵向滚动条宽 /// </summary> [DefaultValue(typeof(int), "10"), Category("Scroll")] [Description("获取或者设置纵向滚动条宽")] public int VScrollWidth { get { return chatVScroll.Width; } set { chatVScroll.Width = value; } } ///// <summary> ///// 获取或者设置滚动条滑块默认颜色 ///// </summary> //[DefaultValue(typeof(Color), "Gray"), Category("ControlColor")] //[Description("滚动条滑块默认情况下的颜色")] //public Color ScrollSliderDefaultColor //{ // get { return chatVScroll.SliderDefaultColor; } // set { chatVScroll.SliderDefaultColor = value; } //} #endregion /// <summary> /// 鼠标是否在当前控件中 /// </summary> private bool MouseVisible = false; private bool scrollBottom = false; #endregion private Adapter adapter; [Bindable(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public Adapter Adapter { get { return adapter; } set { if (value == null) return; adapter = value; adapter.Owner = this; adapter.OnNotifyDataSetChanged += Adapter_OnNotifyDataSetChanged; } } private void Adapter_OnNotifyDataSetChanged() { if (!scrollBottom || VirtualHeight == 0) return; //VirtualHeight = 0; ////计算滚动条高 //if (adapter == null || adapter.GetCount() == 0) //{ // return; //} //for (int i = 0; i < adapter.GetCount(); i++) //{ // VirtualHeight += adapter.GetRowHeight(i); // VirtualHeight += itemDivider; //} chatVScroll.VirtualHeight = VirtualHeight; int max = VirtualHeight - this.Height; chatVScroll.Value = max; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); VirtualHeight = 0; VirtualWidth = 0; Graphics g = e.Graphics; //绘制边框 if (borderStyle == BorderStyle.FixedSingle) { Pen pen = new Pen(Color.FromArgb(100, 100, 100)); Point[] point = new Point[4]; point[0] = new Point(0, 0); point[1] = new Point(Width - 1, 0); point[2] = new Point(Width - 1, Height - 1); point[3] = new Point(0, Height - 1); g.DrawPolygon(pen, point);// } g.TranslateTransform(-listHScroll.Value, 0); //根据滚动条的值设置坐标偏移 g.TranslateTransform(0, -chatVScroll.Value); //根据滚动条的值设置坐标偏移 DrawColumn(g); g.ResetTransform(); //重置坐标系 if (!scrollBottom) chatVScroll.VirtualHeight = VirtualHeight + 5; //绘制完成计算虚拟高度决定是否绘制滚动条 if (MouseVisible && chatVScroll.Visible) //是否绘制滚动条 chatVScroll.ReDrawScroll(g); listHScroll.VirtualWidth = VirtualWidth; if (MouseVisible && listHScroll.Visible) listHScroll.ReDrawScroll(g); } #region 绘制行列 /// <summary> /// 绘制行 /// </summary> /// <param name="g"></param> private void DrawColumn(Graphics g) { if (adapter == null || adapter.GetCount() == 0) { VirtualWidth = 0; return; } int y = 0; for (int i = 0; i < adapter.GetCount(); i++) { ViewHolder holder = null; if (Rows.Count > i) { holder = Rows[i]; holder.position = i; holder.bounds.X = 1; holder.bounds.Y = y; holder.bounds.Width = this.Width - 2; holder.bounds.Height = adapter.GetRowHeight(i); } else { Rectangle rect = new Rectangle(1, y, this.Width - 2, adapter.GetRowHeight(i)); holder = new ViewHolder(rect); holder.position = i; Rows.Add(holder); } holder.isMouseClick = false; holder.isMouseMove = false; holder.MouseLocation = Point.Empty; if (SelectHolder == holder) { holder.isMouseClick = true; holder.MouseLocation = SelectHolder.MouseLocation; } else if (MouseHolder == holder) holder.isMouseMove = true; adapter.GetView(i, holder, g); y += holder.bounds.Height + itemDivider; VirtualWidth = holder.bounds.Width; } VirtualHeight = y; if (listHScroll.Visible) VirtualHeight += listHScroll.Height; } #endregion protected override void OnMouseMove(MouseEventArgs e) { m_ptMousePos = e.Location; m_ptMousePos.Y += chatVScroll.Value; if (IsMouseFeedBack) { //判断鼠标是否在行中 foreach (ViewHolder item in Rows) { if (item.bounds.Contains(m_ptMousePos)) { if (item == MouseHolder) break; MouseHolder = item; this.Invalidate(); break; } } } base.OnMouseMove(e); } //鼠标进入 protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); MouseVisible = true; } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); MouseHolder = null; MouseVisible = false; this.Invalidate(); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button == MouseButtons.Left) { if (chatVScroll.IsMouseDown|| chatVScroll.IsMouseOnSlider) return; foreach (ViewHolder item in Rows) { if (item.bounds.Contains(m_ptMousePos)) { SelectHolder = item; SelectHolder.MouseLocation = e.Location; if (item != SelectHolder) { this.Invalidate(); } OnItemClick(new ItemClickEventArgs(item)); break; } } } } protected override void OnMouseDown(MouseEventArgs e) { this.Focus(); base.OnMouseDown(e); } /// <summary> /// 滚动到底部 /// </summary> public void ScrollBottom(int time = 50) { new Task(()=> { Thread.Sleep(time); scrollBottom = true; Adapter_OnNotifyDataSetChanged(); }).Start(); } public delegate void ScrollHandler(object sender, ScrollEventArgs e); /// <summary> /// 滚动时 /// </summary> public event ScrollHandler Scroll; public virtual void OnScroll(ScrollEventArgs e) { Scroll?.Invoke(this, e); } public delegate void ItemClickHandler(object sender, ItemClickEventArgs e); public event ItemClickHandler ItemClick; public virtual void OnItemClick(ItemClickEventArgs e) { ItemClick?.Invoke(this, e); } } }
30.553444
144
0.482236
[ "MIT" ]
Lamica/WinForm.UI
WinForm.UI/WinForm.UI/Controls/FListView.cs
13,507
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; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Windows.Forms.Design; namespace System.ComponentModel.Design { /// <summary> /// Provides a set of methods for analyzing and identifying inherited components. /// </summary> public class InheritanceService : IInheritanceService, IDisposable { private static readonly TraceSwitch s_inheritanceServiceSwitch = new TraceSwitch("InheritanceService", "InheritanceService : Debug inheritance scan."); private Hashtable _inheritedComponents; // While we're adding an inherited component, we must be wary of components that the inherited component adds as a result of being sited. These are treated as inherited as well. To track these, we keep track of the component we're currently adding as well as it's inheritance attribute. During the add, we sync IComponentAdding events and push in the component private IComponent _addingComponent; private InheritanceAttribute _addingAttribute; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.Design.InheritanceService'/> class. /// </summary> public InheritanceService() { _inheritedComponents = new Hashtable(); } /// <summary> /// Disposes of the resources (other than memory) used by the <see cref='System.ComponentModel.Design.InheritanceService'/>. /// </summary> public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing && _inheritedComponents != null) { _inheritedComponents.Clear(); _inheritedComponents = null; } } /// <summary> /// Adds inherited components to the <see cref='System.ComponentModel.Design.InheritanceService'/>. /// </summary> public void AddInheritedComponents(IComponent component, IContainer container) { AddInheritedComponents(component.GetType(), component, container); } /// <summary> /// Adds inherited components to the <see cref='System.ComponentModel.Design.InheritanceService'/>. /// </summary> protected virtual void AddInheritedComponents(Type type, IComponent component, IContainer container) { // We get out now if this component type is not assignable from IComponent. We only walk down to the component level. if (type is null || !typeof(IComponent).IsAssignableFrom(type)) { return; } Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Searching for inherited components on '" + type.FullName + "'."); Debug.Indent(); ISite site = component.Site; IComponentChangeService cs = null; INameCreationService ncs = null; if (site != null) { ncs = (INameCreationService)site.GetService(typeof(INameCreationService)); cs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (cs != null) { cs.ComponentAdding += new ComponentEventHandler(OnComponentAdding); } } try { while (type != typeof(object)) { Type reflect = TypeDescriptor.GetReflectionType(type); FieldInfo[] fields = reflect.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic); Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found " + fields.Length.ToString(CultureInfo.InvariantCulture) + " fields."); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; string name = field.Name; // Get out now if this field is not assignable from IComponent. Type reflectionType = GetReflectionTypeFromTypeHelper(field.FieldType); if (!GetReflectionTypeFromTypeHelper(typeof(IComponent)).IsAssignableFrom(reflectionType)) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Not IComponent"); continue; } // Now check the attributes of the field and get out if it isn't something that can be inherited. Debug.Assert(!field.IsStatic, "Instance binding shouldn't have found this field"); // If the value of the field is null, then don't mess with it. If it wasn't assigned when our base class was created then we can't really use it. object value = field.GetValue(component); if (value is null) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Contains NULL"); continue; } // We've been fine up to this point looking at the field. Now, however, we must check to see if this field has an AccessedThroughPropertyAttribute on it. If it does, then we must look for the property and use its name and visibility for the remainder of the scan. Should any of this bail we just use the field. MemberInfo member = field; object[] fieldAttrs = field.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false); if (fieldAttrs != null && fieldAttrs.Length > 0) { Debug.Assert(fieldAttrs.Length == 1, "Non-inheritable attribute has more than one copy"); Debug.Assert(fieldAttrs[0] is AccessedThroughPropertyAttribute, "Reflection bug: GetCustomAttributes(type) didn't discriminate by type"); AccessedThroughPropertyAttribute propAttr = (AccessedThroughPropertyAttribute)fieldAttrs[0]; PropertyInfo fieldProp = reflect.GetProperty(propAttr.PropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Debug.Assert(fieldProp != null, "Field declared with AccessedThroughPropertyAttribute has no associated property"); Debug.Assert(fieldProp.PropertyType == field.FieldType, "Field declared with AccessedThroughPropertyAttribute is associated with a property with a different return type."); if (fieldProp != null && fieldProp.PropertyType == field.FieldType) { // If the property cannot be read, it is useless to us. if (!fieldProp.CanRead) { continue; } // We never access the set for the property, so we can concentrate on just the get method. member = fieldProp.GetGetMethod(true); Debug.Assert(member != null, "GetGetMethod for property didn't return a method, but CanRead is true"); name = propAttr.PropertyName; } } // Add a user hook to add or remove members. The default hook here ignores all inherited private members. bool ignoreMember = IgnoreInheritedMember(member, component); // We now have an inherited member. Gather some information about it and then add it to our list. We must always add to our list, but we may not want to add it to the container. That is up to the IngoreInheritedMember method. We add here because there are components in the world that, when sited, add their children to the container too. That's fine, but we want to make sure we account for them in the inheritance service too. Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found inherited member '" + name + "'"); Debug.Indent(); Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Type: " + field.FieldType.FullName); InheritanceAttribute attr; Debug.Assert(value is IComponent, "Value of inherited field is not IComponent. How did this value get into the datatype?"); bool privateInherited = false; if (ignoreMember) { // If we are ignoring this member, then always mark it as private. The designer doesn't want it; we only do this in case some other component adds this guy to the container. privateInherited = true; } else { if (member is FieldInfo fi) { privateInherited = fi.IsPrivate | fi.IsAssembly; } else if (member is MethodInfo mi) { privateInherited = mi.IsPrivate | mi.IsAssembly; } } if (privateInherited) { attr = InheritanceAttribute.InheritedReadOnly; Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Private"); } else { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Public"); attr = InheritanceAttribute.Inherited; } bool notPresent = (_inheritedComponents[value] is null); _inheritedComponents[value] = attr; if (!ignoreMember && notPresent) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Adding " + name + " to container."); try { _addingComponent = (IComponent)value; _addingAttribute = attr; // Lets make sure this is a valid name if (ncs is null || ncs.IsValidName(name)) { try { container.Add((IComponent)value, name); } catch { // We do not always control the base components, and there could be a lot of rogue base components. If there are exceptions when adding them, lets just ignore and continue. } } } finally { _addingComponent = null; _addingAttribute = null; } } Debug.Unindent(); } type = type.BaseType; } } finally { if (cs != null) { cs.ComponentAdding -= new ComponentEventHandler(OnComponentAdding); } Debug.Unindent(); } } /// <summary> /// Indicates the inherited members to ignore. /// </summary> protected virtual bool IgnoreInheritedMember(MemberInfo member, IComponent component) { // Our default implementation ignores all private or assembly members. if (member is FieldInfo field) { return field.IsPrivate || field.IsAssembly; } else if (member is MethodInfo method) { return method.IsPrivate || method.IsAssembly; } Debug.Fail("Unknown member type passed to IgnoreInheritedMember"); return true; } /// <summary> /// Gets the inheritance attribute of the specified component. /// </summary> public InheritanceAttribute GetInheritanceAttribute(IComponent component) { InheritanceAttribute attr = (InheritanceAttribute)_inheritedComponents[component]; if (attr is null) { attr = InheritanceAttribute.Default; } return attr; } private void OnComponentAdding(object sender, ComponentEventArgs ce) { if (_addingComponent != null && _addingComponent != ce.Component) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Adding component... " + ce.Component.ToString()); _inheritedComponents[ce.Component] = InheritanceAttribute.InheritedReadOnly; // If this component is being added to a nested container of addingComponent, it should get the same inheritance level. if (sender is INestedContainer nested && nested.Owner == _addingComponent) { _inheritedComponents[ce.Component] = _addingAttribute; } } } private static Type GetReflectionTypeFromTypeHelper(Type type) { if (type != null) { TypeDescriptionProvider targetProvider = GetTargetFrameworkProviderForType(type); if (targetProvider != null) { if (targetProvider.IsSupportedType(type)) { return targetProvider.GetReflectionType(type); } } } return type; } private static TypeDescriptionProvider GetTargetFrameworkProviderForType(Type type) { IDesignerSerializationManager manager = DocumentDesigner.manager; if (manager != null) { if (manager.GetService(typeof(TypeDescriptionProviderService)) is TypeDescriptionProviderService service) { return service.GetProvider(type); } } return null; } } }
50.042208
456
0.539804
[ "MIT" ]
Amy-Li03/winforms
src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritanceService.cs
15,415
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; namespace Org.BouncyCastle.Crypto.Tls { public interface TlsHandshakeHash : IDigest { void Init(TlsContext context); TlsHandshakeHash NotifyPrfDetermined(); void TrackHashAlgorithm(byte hashAlgorithm); void SealHashAlgorithms(); TlsHandshakeHash StopTracking(); IDigest ForkPrfHash(); byte[] GetFinalHash(byte hashAlgorithm); } } #endif
18.814815
69
0.673228
[ "MIT" ]
Manolomon/space-checkers
client/Assets/Libs/Best HTTP (Pro)/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/tls/TlsHandshakeHash.cs
508
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using Mono.Options; using Octokit; using Splat; using Squirrel; namespace SyncGitHubReleases { class Program : IEnableLogger { static OptionSet opts; public static int Main(string[] args) { var pg = new Program(); try { return pg.main(args).Result; } catch (Exception ex) { // NB: Normally this is a terrible idea but we want to make // sure Setup.exe above us gets the nonzero error code Console.Error.WriteLine(ex); return -1; } } async Task<int> main(string[] args) { using (var logger = new SetupLogLogger(false) { Level = Splat.LogLevel.Info }) { Splat.Locator.CurrentMutable.Register(() => logger, typeof(Splat.ILogger)); var releaseDir = default(string); var repoUrl = default(string); var token = default(string); opts = new OptionSet() { "Usage: SyncGitHubReleases.exe command [OPTS]", "Builds a Releases directory from releases on GitHub", "", "Options:", { "h|?|help", "Display Help and exit", _ => {} }, { "r=|releaseDir=", "Path to a release directory to download to", v => releaseDir = v}, { "u=|repoUrl=", "The URL to the repository root page", v => repoUrl = v}, { "t=|token=", "The OAuth token to use as login credentials", v => token = v}, }; opts.Parse(args); if (token == null || repoUrl == null || repoUrl.StartsWith("http", true, CultureInfo.InvariantCulture) == false) { ShowHelp(); return -1; } var releaseDirectoryInfo = new DirectoryInfo(releaseDir ?? Path.Combine(".", "Releases")); if (!releaseDirectoryInfo.Exists) releaseDirectoryInfo.Create(); var repoUri = new Uri(repoUrl); var userAgent = new ProductHeaderValue("SyncGitHubReleases", Assembly.GetExecutingAssembly().GetName().Version.ToString()); var client = new GitHubClient(userAgent, repoUri) { Credentials = new Credentials(token) }; var nwo = nwoFromRepoUrl(repoUrl); var releases = await client.Release.GetAll(nwo.Item1, nwo.Item2); await releases.ForEachAsync(async release => { // NB: Why do I have to double-fetch the release assets? It's already in GetAll var assets = await client.Release.GetAssets(nwo.Item1, nwo.Item2, release.Id); await assets .Where(x => x.Name.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase)) .Where(x => { var fi = new FileInfo(Path.Combine(releaseDirectoryInfo.FullName, x.Name)); return !(fi.Exists && fi.Length == x.Size); }) .ForEachAsync(async x => { var target = new FileInfo(Path.Combine(releaseDirectoryInfo.FullName, x.Name)); if (target.Exists) target.Delete(); var hc = new HttpClient(); var rq = new HttpRequestMessage(HttpMethod.Get, x.Url); rq.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream")); rq.Headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(userAgent.Name, userAgent.Version)); rq.Headers.Add("Authorization", "Bearer " + token); var resp = await hc.SendAsync(rq); resp.EnsureSuccessStatusCode(); using (var from = await resp.Content.ReadAsStreamAsync()) using (var to = File.OpenWrite(target.FullName)) { await from.CopyToAsync(to); } }); }); var entries = releaseDirectoryInfo.GetFiles("*.nupkg") .AsParallel() .Select(x => ReleaseEntry.GenerateFromFile(x.FullName)); ReleaseEntry.WriteReleaseFile(entries, Path.Combine(releaseDirectoryInfo.FullName, "RELEASES")); } return 0; } public void ShowHelp() { opts.WriteOptionDescriptions(Console.Out); } Tuple<string, string> nwoFromRepoUrl(string repoUrl) { var uri = new Uri(repoUrl); var segments = uri.AbsolutePath.Split('/'); if (segments.Count() != 3) { throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo"); } return Tuple.Create(segments[1], segments[2]); } } class SetupLogLogger : Splat.ILogger, IDisposable { StreamWriter inner; readonly object gate = 42; public Splat.LogLevel Level { get; set; } public SetupLogLogger(bool saveInTemp) { var dir = saveInTemp ? Path.GetTempPath() : Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); var file = Path.Combine(dir, "SquirrelSetup.log"); if (File.Exists(file)) File.Delete(file); inner = new StreamWriter(file, false, Encoding.UTF8); } public void Write(string message, Splat.LogLevel logLevel) { if (logLevel < Level) { return; } lock (gate) inner.WriteLine(message); } public void Dispose() { lock(gate) inner.Dispose(); } } }
38.2
140
0.524353
[ "MIT" ]
PapaMufflon/Squirrel.Windows
src/SyncGitHubReleases/Program.cs
6,305
C#
using Volo.Abp.Threading; namespace Prometyum.Sample { public static class SampleGlobalFeatureConfigurator { private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); public static void Configure() { OneTimeRunner.Run(() => { /* You can configure (enable/disable) global features of the used modules here. * * YOU CAN SAFELY DELETE THIS CLASS AND REMOVE ITS USAGES IF YOU DON'T NEED TO IT! * * Please refer to the documentation to lear more about the Global Features System: * https://docs.abp.io/en/commercial/latest/Global-Features */ }); } } }
31.875
99
0.56732
[ "MIT" ]
ozturkmuslum/Prometyum.Abp.AspNetCore.Mvc.UI.Bootstrap
src/Prometyum.Sample.Domain.Shared/SampleGlobalFeatureConfigurator.cs
767
C#
using System.Windows.Input; using Waf.NewsReader.Applications.Views; using Waf.NewsReader.Domain; namespace Waf.NewsReader.Applications.ViewModels { public class FeedItemViewModel : ViewModel<IFeedItemView> { private FeedItem feedItem; public FeedItemViewModel(IFeedItemView view) : base(view) { } public ICommand LaunchBrowserCommand { get; set; } public FeedItem FeedItem { get => feedItem; set => SetProperty(ref feedItem, value); } } }
22.708333
65
0.642202
[ "MIT" ]
GerHobbelt/waf
src/NewsReader/NewsReader.Applications/ViewModels/FeedItemViewModel.cs
547
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901 { using Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.PowerShell; /// <summary>Key-value pairs for configuring an add-on.</summary> [System.ComponentModel.TypeConverter(typeof(ManagedClusterAddonProfileConfigTypeConverter))] public partial class ManagedClusterAddonProfileConfig { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ManagedClusterAddonProfileConfig" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAddonProfileConfig" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAddonProfileConfig DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ManagedClusterAddonProfileConfig(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ManagedClusterAddonProfileConfig" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAddonProfileConfig" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAddonProfileConfig DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ManagedClusterAddonProfileConfig(content); } /// <summary> /// Creates a new instance of <see cref="ManagedClusterAddonProfileConfig" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAddonProfileConfig FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ManagedClusterAddonProfileConfig" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ManagedClusterAddonProfileConfig(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize // this type is a dictionary; copy elements from source to here. CopyFrom(content); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ManagedClusterAddonProfileConfig" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ManagedClusterAddonProfileConfig(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize // this type is a dictionary; copy elements from source to here. CopyFrom(content); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Key-value pairs for configuring an add-on. [System.ComponentModel.TypeConverter(typeof(ManagedClusterAddonProfileConfigTypeConverter))] public partial interface IManagedClusterAddonProfileConfig { } }
58.3
237
0.678388
[ "MIT" ]
Agazoth/azure-powershell
src/Aks/Aks.Autorest/generated/api/Models/Api20200901/ManagedClusterAddonProfileConfig.PowerShell.cs
8,023
C#
using UnityEngine; namespace Terra.CoherentNoise.Generation.Combination { /// <summary> /// This generator returns maximum value of its two source generators /// </summary> public class Max:Generator { private readonly Generator m_A; private readonly Generator m_B; ///<summary> /// Create new generator ///</summary> ///<param name="a">First generator</param> ///<param name="b">Second generator</param> public Max(Generator a, Generator b) { m_A = a; m_B = b; } #region Implementation of Noise /// <summary> /// Returns settings value at given point. /// </summary> /// <param name="x">X coordinate</param> /// <param name="y">Y coordinate</param> /// <param name="z">Z coordinate</param> /// <returns>Noise value</returns> public override float GetValue(float x, float y, float z) { return Mathf.Max(m_A.GetValue(x, y, z), m_B.GetValue(x, y, z)); } #endregion } }
23.275
70
0.655209
[ "MIT" ]
DavidArppe/GameOff2020
Assets/Misc/Terra/Library/CoherentNoise/Generation/Combination/Max.cs
931
C#
using TES4Lib.Base; using Utility; namespace TES4Lib.Subrecords.DOOR { /// <summary> /// Door flags /// </summary> public class FNAM : Subrecord { /// <summary> /// Flags /// 0x01 = Oblivion gate /// 0x02 = Automatic door /// 0x04 = Hidden /// 0x08 = Minimal use /// </summary> public byte Flags { get; set; } public FNAM(byte[] rawData) : base(rawData) { var reader = new ByteReader(); Flags = reader.ReadBytes<byte>(base.Data); } } }
21.296296
54
0.50087
[ "MIT" ]
NullCascade/TES3Tool
TES4Lib/Subrecords/DOOR/FNAM.cs
577
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using ICSharpCode.SharpDevelop.Dom; namespace ICSharpCode.PythonBinding { public class PythonNamespaceResolver : IPythonResolver { PythonResolverContext resolverContext; ExpressionResult expressionResult; public ResolveResult Resolve(PythonResolverContext resolverContext) { return Resolve(resolverContext, resolverContext.ExpressionResult); } public ResolveResult Resolve(PythonResolverContext resolverContext, ExpressionResult expressionResult) { this.resolverContext = resolverContext; this.expressionResult = expressionResult; if (resolverContext.HasImport(expressionResult.Expression)) { return ResolveFullNamespace(); } return ResolvePartialNamespaceMatch(); } ResolveResult ResolveFullNamespace() { string actualNamespace = resolverContext.UnaliasImportedModuleName(expressionResult.Expression); return ResolveIfNamespaceExistsInProjectReferences(actualNamespace); } ResolveResult ResolvePartialNamespaceMatch() { string fullNamespace = expressionResult.Expression; if (resolverContext.IsStartOfDottedModuleNameImported(fullNamespace)) { return ResolveIfPartialNamespaceExistsInProjectReferences(fullNamespace); } else if (resolverContext.HasDottedImportNameThatStartsWith(fullNamespace)) { return CreateNamespaceResolveResult(fullNamespace); } return null; } ResolveResult ResolveIfNamespaceExistsInProjectReferences(string namespaceName) { if (resolverContext.NamespaceExistsInProjectReferences(namespaceName)) { return CreateNamespaceResolveResult(namespaceName); } return null; } ResolveResult ResolveIfPartialNamespaceExistsInProjectReferences(string namespaceName) { string actualNamespace = resolverContext.UnaliasStartOfDottedImportedModuleName(namespaceName); if (resolverContext.PartialNamespaceExistsInProjectReferences(actualNamespace)) { return CreateNamespaceResolveResult(actualNamespace); } return null; } ResolveResult CreateNamespaceResolveResult(string namespaceName) { return new NamespaceResolveResult(null, null, namespaceName); } } }
38.541176
104
0.793956
[ "MIT" ]
galich/SharpDevelop
src/AddIns/BackendBindings/Python/PythonBinding/Project/Src/PythonNamespaceResolver.cs
3,278
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core) // Version 5.500.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Windows.Forms; using System.Drawing; namespace Krypton.Toolkit { /// <summary> /// Details for an cancellable event that provides a position, offset and control value. /// </summary> public class DragStartEventCancelArgs : PointEventCancelArgs { #region Instance Fields #endregion #region Identity /// <summary> /// Initialize a new instance of the DragStartEventCancelArgs class. /// </summary> /// <param name="point">Point associated with event.</param> /// <param name="offset">Offset associated with event.</param> /// <param name="c">Control that is generating the drag start.</param> public DragStartEventCancelArgs(Point point, Point offset, Control c) : base(point) { Offset = offset; Control = c; } #endregion #region Point /// <summary> /// Gets and sets the offset. /// </summary> public Point Offset { get; set; } #endregion #region Point /// <summary> /// Gets the control starting the drag. /// </summary> public Control Control { get; } #endregion } }
34.862069
170
0.583086
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-NET-Core
Source/Truncated Namespaces/Source/Krypton Components/Krypton.Toolkit/EventArgs/PointOffsetEventCancelArgs.cs
2,025
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201 { using Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="StaticSiteUserProvidedFunctionAppsCollection" /// /> /// </summary> public partial class StaticSiteUserProvidedFunctionAppsCollectionTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="StaticSiteUserProvidedFunctionAppsCollection" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="StaticSiteUserProvidedFunctionAppsCollection" /> type, /// otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="StaticSiteUserProvidedFunctionAppsCollection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="StaticSiteUserProvidedFunctionAppsCollection" /// />.</param> /// <returns> /// an instance of <see cref="StaticSiteUserProvidedFunctionAppsCollection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSiteUserProvidedFunctionAppsCollection ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSiteUserProvidedFunctionAppsCollection).IsAssignableFrom(type)) { return sourceValue; } try { return StaticSiteUserProvidedFunctionAppsCollection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return StaticSiteUserProvidedFunctionAppsCollection.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return StaticSiteUserProvidedFunctionAppsCollection.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
53.153333
247
0.604164
[ "MIT" ]
Agazoth/azure-powershell
src/Websites/Websites.Autorest/generated/api/Models/Api20201201/StaticSiteUserProvidedFunctionAppsCollection.TypeConverter.cs
7,824
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Hodgkins { public class ChunkSpawner : MonoBehaviour { public Chunk prefab; private List<Chunk> chunks = new List<Chunk>(); void Start() { for (int i = 0; i < 5; i++) { Vector3 pos = Vector3.zero; if (chunks.Count > 0) { Chunk lastChunk = chunks[chunks.Count - 1]; pos = lastChunk.connectionPoint.position; } //float y = Random.Range(-2, 2f); //pos.y += y; Chunk newChunk = Instantiate(prefab, pos, Quaternion.identity); chunks.Add(newChunk); } } void Update() { } } }
22.45
80
0.44098
[ "MIT" ]
Baggy336/255-2021-SlipstreamJumper
Assets/Hodgkins/Scripts/ChunkSpawner.cs
898
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using ARMClient.Authentication.AADAuthentication; using ARMClient.Authentication.Utilities; namespace RDFEClient { class Program { static void Main(string[] args) { if (args.Length == 0) { PrintUsage(); return; } var methodName = args[0]; try { var method = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.NonPublic) .FirstOrDefault(m => string.Equals(methodName, m.Name, StringComparison.OrdinalIgnoreCase)); if (method == null) { PrintUsage(); return; } method.Invoke(null, args.Skip(1).ToArray()); } catch (TargetParameterCountException) { PrintUsage(methodName); } catch (Exception ex) { Console.WriteLine(ex.GetBaseException()); } } static void PrintUsage(string methodName = null) { Console.WriteLine("Usage:"); foreach (var cmd in new[] { " RDFEClient.exe Login", " RDFEClient.exe ListCache", " RDFEClient.exe GetDeployment subscriptionId serviceName", " RDFEClient.exe DeleteDeployment subscriptionId serviceName", " RDFEClient.exe GetConfiguration subscriptionId serviceName", " RDFEClient.exe UpdateConfiguration subscriptionId serviceName content", " RDFEClient.exe ListExtensions subscriptionId serviceName", " RDFEClient.exe GetExtension subscriptionId serviceName extensionId", " RDFEClient.exe AddExtension subscriptionId serviceName content", " RDFEClient.exe DeleteExtension subscriptionId serviceName extensionId", " RDFEClient.exe AddServiceTunnelingExtension subscriptionId serviceName", " RDFEClient.exe EnableServiceTunnelingExtension subscriptionId serviceName", " RDFEClient.exe DisableServiceTunnelingExtension subscriptionId serviceName", " RDFEClient.exe AddServiceTunnelingExtensionConfiguration subscriptionId serviceName", " RDFEClient.exe ListReservedIps subscriptionId", " RDFEClient.exe GetReservedIp subscriptionId reservedIpName", " RDFEClient.exe AddReservedIp subscriptionId reservedIpName location", " RDFEClient.exe DeleteReservedIp subscriptionId reservedIpName", " RDFEClient.exe GetOperation subscriptionId requestId", }) { if (string.IsNullOrEmpty(methodName) || cmd.IndexOf(" " + methodName + " ", StringComparison.OrdinalIgnoreCase) > 0) { Console.WriteLine(cmd); } } } static void Login() { Utils.SetTraceListener(new ConsoleTraceListener()); var persistentAuthHelper = new PersistentAuthHelper(); persistentAuthHelper.AcquireTokens().Wait(); } static void ListCache() { Utils.SetTraceListener(new ConsoleTraceListener()); var persistentAuthHelper = new PersistentAuthHelper(); foreach (var line in persistentAuthHelper.DumpTokenCache()) { Console.WriteLine(line); } } static void GetDeployment(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } static void DeleteDeployment(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "delete").Result) { } } static void GetConfiguration(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { if (!response.IsSuccessStatusCode) { return; } var deploymentElem = XDocument.Parse(response.Content.ReadAsStringAsync().Result).Root; var deploymentNs = deploymentElem.Name.Namespace; var mgr = new XmlNamespaceManager(new NameTable()); mgr.AddNamespace("x", deploymentNs.NamespaceName); var configurationElem = deploymentElem.XPathSelectElement("/x:Deployment/x:Configuration", mgr); var serviceConfigurationElem = XDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(configurationElem.Value))).Root; Console.WriteLine(); Console.WriteLine("---------- ServiceConfiguration.cscfg -----------------------"); Console.WriteLine(); RDFEClient.PrintColoredXml(serviceConfigurationElem.ToString()); } } static void UpdateConfiguration(string subscriptionId, string serviceName, string content) { var payload = content; if (File.Exists(content)) { payload = File.ReadAllText(content); } if (payload.StartsWith("<ServiceConfiguration ")) { payload = string.Format(@" <ChangeConfiguration xmlns='http://schemas.microsoft.com/windowsazure'> <Configuration>{0}</Configuration> <TreatWarningsAsError>false</TreatWarningsAsError> </ChangeConfiguration> ", Convert.ToBase64String(Encoding.UTF8.GetBytes(XDocument.Parse(payload).ToString(SaveOptions.DisableFormatting)))); } var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production/?comp=config", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "post", new StringContent(payload, Encoding.UTF8, "text/xml")).Result) { } } static string GetAuthorizationHeader(string subscriptionId) { Utils.SetTraceListener(new ConsoleTraceListener()); var accessToken = Utils.GetDefaultToken(); if (!String.IsNullOrEmpty(accessToken)) { return String.Format("Bearer {0}", accessToken); } var persistentAuthHelper = new PersistentAuthHelper(); var cacheInfo = persistentAuthHelper.GetToken(subscriptionId, "https://management.core.windows.net/").Result; return cacheInfo.CreateAuthorizationHeader(); } static void ListExtensions(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/extensions", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } static void GetExtension(string subscriptionId, string serviceName, string extensionId) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/extensions/{2}", subscriptionId, serviceName, extensionId)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } static void AddExtension(string subscriptionId, string serviceName, string content) { var payload = content; if (File.Exists(content)) { payload = File.ReadAllText(content); } var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/extensions", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "post", new StringContent(payload, Encoding.UTF8, "text/xml")).Result) { } } static void AddServiceTunnelingExtension(string subscriptionId, string serviceName) { var payload = @" <Extension xmlns='http://schemas.microsoft.com/windowsazure'> <ProviderNameSpace>Microsoft.Azure.Networking.SDN</ProviderNameSpace> <Type>Aquarius</Type> <Id>FrontEndRole-Aquarius-Production-Ext-1</Id> <Thumbprint></Thumbprint> <ThumbprintAlgorithm></ThumbprintAlgorithm> <PublicConfiguration>eyJQbHVnaW5zVG9FbmFibGUiOlsiU2VydmljZVR1bm5lbEV4dGVuc2lvbiJdfQ==</PublicConfiguration> <PrivateConfiguration>e30=</PrivateConfiguration> <Version>4.2</Version> </Extension>"; var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/extensions", subscriptionId, serviceName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "post", new StringContent(payload, Encoding.UTF8, "text/xml")).Result) { } } static void EnableServiceTunnelingExtension(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); string base64Configuration; string roleName; using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { if (!response.IsSuccessStatusCode) { return; } var deploymentElem = XDocument.Parse(response.Content.ReadAsStringAsync().Result).Root; var deploymentNs = deploymentElem.Name.Namespace; var mgr = new XmlNamespaceManager(new NameTable()); mgr.AddNamespace("x", deploymentNs.NamespaceName); var configurationElem = deploymentElem.XPathSelectElement("/x:Deployment/x:Configuration", mgr); base64Configuration = configurationElem.Value; var serviceConfigurationElem = XDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(base64Configuration))).Root; var serviceConfigurationNs = serviceConfigurationElem.Name.Namespace; var serviceConfigurationMgr = new XmlNamespaceManager(new NameTable()); serviceConfigurationMgr.AddNamespace("x", serviceConfigurationNs.NamespaceName); roleName = null != serviceConfigurationElem.XPathSelectElement("/x:ServiceConfiguration/x:Role[@name='MultiRole']", serviceConfigurationMgr) ? "MultiRole" : "FrontEndRole"; } var payload = string.Format(@" <ChangeConfiguration xmlns='http://schemas.microsoft.com/windowsazure'> <Configuration>{0}</Configuration> <TreatWarningsAsError>false</TreatWarningsAsError> <Mode>Auto</Mode> <ExtensionConfiguration> <NamedRoles> <Role> <RoleName>{1}</RoleName> <Extensions> <Extension> <Id>FrontEndRole-Aquarius-Production-Ext-1</Id> </Extension> </Extensions> </Role> </NamedRoles> </ExtensionConfiguration> </ChangeConfiguration>", base64Configuration, roleName); UpdateConfiguration(subscriptionId, serviceName, payload); } static void DisableServiceTunnelingExtension(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); string base64Configuration; string roleName; using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { if (!response.IsSuccessStatusCode) { return; } var deploymentElem = XDocument.Parse(response.Content.ReadAsStringAsync().Result).Root; var deploymentNs = deploymentElem.Name.Namespace; var mgr = new XmlNamespaceManager(new NameTable()); mgr.AddNamespace("x", deploymentNs.NamespaceName); var configurationElem = deploymentElem.XPathSelectElement("/x:Deployment/x:Configuration", mgr); base64Configuration = configurationElem.Value; var serviceConfigurationElem = XDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(base64Configuration))).Root; var serviceConfigurationNs = serviceConfigurationElem.Name.Namespace; var serviceConfigurationMgr = new XmlNamespaceManager(new NameTable()); serviceConfigurationMgr.AddNamespace("x", serviceConfigurationNs.NamespaceName); roleName = null != serviceConfigurationElem.XPathSelectElement("/x:ServiceConfiguration/x:Role[@name='MultiRole']", serviceConfigurationMgr) ? "MultiRole" : "FrontEndRole"; } var payload = string.Format(@" <ChangeConfiguration xmlns='http://schemas.microsoft.com/windowsazure'> <Configuration>{0}</Configuration> <TreatWarningsAsError>false</TreatWarningsAsError> <Mode>Auto</Mode> <ExtensionConfiguration> <NamedRoles> <Role> <RoleName>{1}</RoleName> <Extensions> <Extension> <Id>FrontEndRole-Aquarius-Production-Ext-1</Id> <State>Disable</State> </Extension> </Extensions> </Role> </NamedRoles> </ExtensionConfiguration> </ChangeConfiguration>", base64Configuration, roleName); UpdateConfiguration(subscriptionId, serviceName, payload); } static void DeleteExtension(string subscriptionId, string serviceName, string extensionId) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/extensions/{2}", subscriptionId, serviceName, extensionId)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "delete").Result) { } } static void AddServiceTunnelingExtensionConfiguration(string subscriptionId, string serviceName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/Production", subscriptionId, serviceName)); XElement serviceConfigurationElem; using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { if (!response.IsSuccessStatusCode) { return; } var deploymentElem = XDocument.Parse(response.Content.ReadAsStringAsync().Result).Root; var deploymentNs = deploymentElem.Name.Namespace; var mgr = new XmlNamespaceManager(new NameTable()); mgr.AddNamespace("x", deploymentNs.NamespaceName); var configurationElem = deploymentElem.XPathSelectElement("/x:Deployment/x:Configuration", mgr); serviceConfigurationElem = XDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(configurationElem.Value))).Root; } var serviceConfigurationNs = serviceConfigurationElem.Name.Namespace; var networkConfiguration = serviceConfigurationElem.Elements().FirstOrDefault(n => n.Name == serviceConfigurationNs.GetName("NetworkConfiguration")); var guestAgentSettings = serviceConfigurationElem.Elements().FirstOrDefault(n => n.Name == serviceConfigurationNs.GetName("GuestAgentSettings")); XElement serviceTunnelingConfigurations = null; if (networkConfiguration == null) { networkConfiguration = new XElement(serviceConfigurationNs.GetName("NetworkConfiguration")); guestAgentSettings.AddBeforeSelf(networkConfiguration); } else { serviceTunnelingConfigurations = networkConfiguration.Elements().FirstOrDefault(n => n.Name == serviceConfigurationNs.GetName("ServiceTunnelingConfigurations")); } // only add if not exists if (serviceTunnelingConfigurations == null) { var mgr = new XmlNamespaceManager(new NameTable()); mgr.AddNamespace("x", serviceConfigurationNs.NamespaceName); var roleName = null != serviceConfigurationElem.XPathSelectElement("/x:ServiceConfiguration/x:Role[@name='MultiRole']", mgr) ? "MultiRole" : "FrontEndRole"; serviceTunnelingConfigurations = new XElement(serviceConfigurationNs.GetName("ServiceTunnelingConfigurations")); foreach (var endpoint in serviceConfigurationElem.XPathSelectElements("/x:ServiceConfiguration/x:NetworkConfiguration/x:AddressAssignments/x:VirtualIPs/x:VirtualIP/x:Endpoints/x:Endpoint[@role='"+ roleName + "' and contains(@name,'FrontEndPort')]", mgr)) { var endpointName = endpoint.Attributes().First(a => a.Name.LocalName == "name").Value; serviceTunnelingConfigurations.Add(new XElement(serviceConfigurationNs.GetName("ServiceTunnelingConfiguration"), new XAttribute("name", "ServiceTunneling-" + endpointName), new XAttribute("role", roleName), new XAttribute("endpoint", endpointName) )); } if (!serviceTunnelingConfigurations.Elements().Any()) { return; } networkConfiguration.Add(serviceTunnelingConfigurations); UpdateConfiguration(subscriptionId, serviceName, serviceConfigurationElem.ToString()); } } static void ListReservedIps(string subscriptionId) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/networking/reservedips", subscriptionId)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } static void GetReservedIp(string subscriptionId, string reservedIpName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/networking/reservedips/{1}", subscriptionId, reservedIpName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } static void AddReservedIp(string subscriptionId, string reservedIpName, string location) { // NOTE: another valid tag is /AppServiceManagement var payload = string.Format(@" <ReservedIP xmlns='http://schemas.microsoft.com/windowsazure'> <Name>{0}</Name> <Label>AppServiceReservedIp</Label> <DeploymentName></DeploymentName> <Location>{1}</Location> <IPTags> <IPTag> <IPTagType>FirstPartyUsage</IPTagType> <Value>/AppService</Value> </IPTag> </IPTags> </ReservedIP>", reservedIpName, location); var authHeader = GetAuthorizationHeader(subscriptionId); var content = new StringContent(payload, Encoding.UTF8, "text/xml"); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/networking/reservedips", subscriptionId)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "post", content).Result) { } } static void DeleteReservedIp(string subscriptionId, string reservedIpName) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/services/networking/reservedips/{1}", subscriptionId, reservedIpName)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "delete").Result) { } } static void GetOperation(string subscriptionId, string requestId) { var authHeader = GetAuthorizationHeader(subscriptionId); var uri = new Uri(string.Format("https://management.core.windows.net/{0}/operations/{1}", subscriptionId, requestId)); using (var response = RDFEClient.HttpInvoke(uri, authHeader, "get").Result) { } } } }
46.639583
270
0.631438
[ "Apache-2.0" ]
velasco0606/ARMClient
RDFEClient.Console/Program.cs
22,389
C#
using System; using System.Reflection; namespace Modern.WindowKit.Platform { public interface IRuntimePlatform { IDisposable StartSystemTimer(TimeSpan interval, Action tick); RuntimePlatformInfo GetRuntimeInfo(); IUnmanagedBlob AllocBlob(int size); } public interface IUnmanagedBlob : IDisposable { IntPtr Address { get; } int Size { get; } bool IsDisposed { get; } } public struct RuntimePlatformInfo { public OperatingSystemType OperatingSystem { get; set; } public bool IsDesktop { get; set; } public bool IsMobile { get; set; } public bool IsCoreClr { get; set; } public bool IsMono { get; set; } public bool IsDotNetFramework { get; set; } public bool IsUnix { get; set; } } public enum OperatingSystemType { Unknown, WinNT, Linux, OSX, Android, iOS } }
23.166667
69
0.597122
[ "MIT" ]
modern-forms/Modern.WindowKit
src/Modern.WindowKit/IRuntimePlatform.cs
975
C#
namespace MegaBuild { #region Using Directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using Menees; using Menees.Windows.Forms; #endregion internal partial class MSBuildStepCtrl : StepEditorControl { #region Private Data Members private static readonly string[] BaseSolutionTargets = { string.Empty, "Rebuild", "Clean" }; private MSBuildStep step; #endregion #region Constructors public MSBuildStepCtrl() { this.InitializeComponent(); // https://www.codementor.io/cerkit/giving-an-enum-a-string-value-using-the-description-attribute-6b4fwdle0 Type type = typeof(MSBuildToolsVersion); string[] names = Enum.GetNames(type); foreach (string name in names) { string value = name; DescriptionAttribute description = type.GetMember(name) .Select(m => (DescriptionAttribute)m.GetCustomAttribute(typeof(DescriptionAttribute))) .FirstOrDefault(); if (description != null) { value = description.Description; } this.cbToolsVersion.Items.Add(value); } } #endregion #region Public Properties public override string DisplayName => "MSBuild"; public MSBuildStep Step { set { if (this.step != value) { this.step = value; this.edtProject.Text = this.step.ProjectFile; this.edtWorkingDirectory.Text = this.step.WorkingDirectory; this.txtTargets.Lines = this.step.Targets; this.txtProperties.Lines = (from p in this.step.Properties orderby p.Key select p.Key + "=" + p.Value).ToArray(); this.cbVerbosity.SelectedIndex = (int)this.step.Verbosity; this.cbToolsVersion.SelectedIndex = (int)this.step.ToolsVersion; this.edtOtherOptions.Text = this.step.CommandLineOptions; this.chk32Bit.Checked = this.step.Use32BitProcess; } } } #endregion #region Private Properties private string ExpandedProjectFileName { get { string result = Manager.ExpandVariables(this.edtProject.Text.Trim()); return result; } } #endregion #region Public Methods public override bool OnOk() { bool result = false; string projectFile = this.edtProject.Text.Trim(); if (string.IsNullOrEmpty(projectFile)) { WindowsUtility.ShowError(this, "You must enter a project file name."); } else { List<string> targets = new(); foreach (string line in this.txtTargets.Lines) { string target = line.Trim(); if (!string.IsNullOrEmpty(target)) { targets.Add(target); } } result = true; Dictionary<string, string> properties = new(); foreach (string line in this.txtProperties.Lines) { string[] parts = line.Trim().Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { properties[parts[0].Trim()] = parts[1].Trim(); } else if (parts.Length != 0) { WindowsUtility.ShowError(this, "Unable to parse the following as a Name=Value pair: " + line); result = false; break; } } if (result) { this.step.ProjectFile = projectFile; this.step.WorkingDirectory = this.edtWorkingDirectory.Text.Trim(); this.step.Targets = targets.ToArray(); this.step.Properties = properties; this.step.Verbosity = (MSBuildVerbosity)this.cbVerbosity.SelectedIndex; this.step.ToolsVersion = (MSBuildToolsVersion)this.cbToolsVersion.SelectedIndex; this.step.CommandLineOptions = this.edtOtherOptions.Text; this.step.Use32BitProcess = this.chk32Bit.Checked; } } return result; } #endregion #region Private Methods private static string FindSolutionTargets(string fileName) { // According to the MSBuild Command Line Reference (http://msdn.microsoft.com/en-us/library/ms164311.aspx) // the projects referenced by a solution file can be listed as targets if they are colon-suffixed with one of VS's // base targets (e.g., Rebuild, Clean): msbuild MegaBuild.sln /t:MegaBuildSDK /t:Menees:Clean var projectLines = from line in File.ReadAllLines(fileName) where line.StartsWith("Project(\"") select line; string result = null; if (projectLines.FirstOrDefault() != null) { StringBuilder sb = new("Solution Targets:"); sb.AppendLine(); foreach (string line in projectLines) { int equalPos = line.IndexOf('='); if (equalPos >= 0) { int openQuote = line.IndexOf('"', equalPos); if (openQuote >= 0) { int closeQuote = line.IndexOf('"', openQuote + 1); if (closeQuote >= 0) { string projectName = line.Substring(openQuote + 1, closeQuote - openQuote - 1); if (!string.IsNullOrEmpty(projectName)) { foreach (string baseTarget in BaseSolutionTargets) { sb.AppendLine().Append(projectName); if (!string.IsNullOrEmpty(baseTarget)) { sb.Append(':').Append(baseTarget); } } sb.AppendLine(); } } } } } result = sb.ToString(); } return result; } private static bool IsSolutionFile(string fileName) { string extension = Path.GetExtension(fileName); bool result = string.Equals(extension, ".sln", StringComparison.CurrentCultureIgnoreCase); return result; } private void SelectProject_Click(object sender, EventArgs e) { this.OpenDlg.FileName = Manager.ExpandVariables(this.edtProject.Text); if (this.OpenDlg.ShowDialog(this) == DialogResult.OK) { this.edtProject.Text = Manager.CollapseVariables(this.OpenDlg.FileName); } } private void SelectWorkingDirectory_Click(object sender, EventArgs e) { string initialFolder = Manager.ExpandVariables(this.edtWorkingDirectory.Text); string selectedFolder = WindowsUtility.SelectFolder(this, "Select Working Directory", initialFolder); if (!string.IsNullOrEmpty(selectedFolder)) { this.edtWorkingDirectory.Text = Manager.CollapseVariables(selectedFolder); } } private void ShowProperties_Click(object sender, EventArgs e) { string message = null; string fileName = this.ExpandedProjectFileName; if (!File.Exists(fileName)) { message = "The project file was not found."; } else if (!IsSolutionFile(fileName)) { XElement doc = XElement.Load(fileName); XNamespace ns = doc.Name.Namespace; var groups = doc.Elements(XName.Get("PropertyGroup", ns.NamespaceName)); if (groups.FirstOrDefault() != null) { StringBuilder sb = new(); foreach (var g in groups) { sb.Append("Property Group: "); string condition = (string)g.Attribute("Condition"); if (!string.IsNullOrEmpty(condition)) { sb.Append(condition); } sb.AppendLine(); var properties = from prop in g.Elements() orderby prop.Name.LocalName select prop; foreach (XElement p in properties) { sb.AppendLine().Append(p.Name.LocalName).Append('=').Append(p.Value); } sb.AppendLine().AppendLine(); } message = sb.ToString(); } } if (string.IsNullOrEmpty(message)) { message = "No properties were found in the project file."; } MessageBox.Show(this, message, nameof(Properties), MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ShowTargets_Click(object sender, EventArgs e) { string message = null; string fileName = this.ExpandedProjectFileName; if (!File.Exists(fileName)) { message = "The project file was not found."; } else if (IsSolutionFile(fileName)) { message = FindSolutionTargets(fileName); } else { XElement doc = XElement.Load(fileName); XNamespace ns = doc.Name.Namespace; var targets = from t in doc.Elements(XName.Get("Target", ns.NamespaceName)) where !string.IsNullOrEmpty((string)t.Attribute("Name")) select t; StringBuilder sb = new(); if (targets.FirstOrDefault() != null) { sb.AppendLine("Project Target(s):"); foreach (XElement t in targets) { sb.AppendLine((string)t.Attribute("Name")); } } else if (doc.Elements(XName.Get("Import", ns.NamespaceName)).FirstOrDefault() != null) { sb.AppendLine("The project file only contains imported targets."); } string defaultTargets = (string)doc.Attribute("DefaultTargets"); if (!string.IsNullOrEmpty(defaultTargets)) { if (sb.Length > 0) { sb.AppendLine(); } sb.AppendLine("Default Target(s):"); foreach (string target in defaultTargets.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { sb.AppendLine(target); } } message = sb.ToString(); } if (string.IsNullOrEmpty(message)) { message = "No targets were found in the project file."; } MessageBox.Show(this, message, "Targets", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion } }
26.469741
117
0.659445
[ "MIT" ]
menees/MegaBuild
src/MegaBuildSdk/Controls/MSBuildStepCtrl.cs
9,187
C#
using System; namespace LeetCode.Leets { class FindKthLargestSln:ISolution { public int FindKthLargest(int[] nums, int k) { throw new NotImplementedException(); } public void Execute() { throw new NotImplementedException(); } } }
18.647059
52
0.55836
[ "MIT" ]
YouenZeng/LeetCode
LeetCode/Leets/FindKthLargest.cs
319
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("14.IntegerToHexAndBinary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("14.IntegerToHexAndBinary")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dadafad4-dc9d-4126-8592-4c3b21186f05")] // 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.27027
84
0.750706
[ "MIT" ]
TsvetanNikolov123/CSharp---Programming-Fundamentals
10 Data Types And Variables - Exercises/14.IntegerToHexAndBinary/Properties/AssemblyInfo.cs
1,419
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Klaus Potzesny // // Copyright (c) 2005-2017 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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. #endregion namespace PdfSharp.Drawing.BarCodes { /// <summary> /// Specifies whether and how the text is displayed at the code area. /// </summary> public enum AnchorType { /// <summary> /// The anchor is located top left. /// </summary> TopLeft, /// <summary> /// The anchor is located top center. /// </summary> TopCenter, /// <summary> /// The anchor is located top right. /// </summary> TopRight, /// <summary> /// The anchor is located middle left. /// </summary> MiddleLeft, /// <summary> /// The anchor is located middle center. /// </summary> MiddleCenter, /// <summary> /// The anchor is located middle right. /// </summary> MiddleRight, /// <summary> /// The anchor is located bottom left. /// </summary> BottomLeft, /// <summary> /// The anchor is located bottom center. /// </summary> BottomCenter, /// <summary> /// The anchor is located bottom right. /// </summary> BottomRight, } }
30.493976
77
0.627815
[ "MIT" ]
AVPolyakov/PDFsharp
src/PdfSharp/Drawing.BarCodes/enums/AnchorType.cs
2,531
C#
using Microsoft.Extensions.Options; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; using Together.Location.Domain.Entities; namespace Together.Location.Infrastructure { public class LocationDbContext { private readonly IMongoDatabase _database = null; public LocationDbContext(IOptions<LocationDbSettings> settings) { var client = new MongoClient(settings.Value.ConnectionString); if (client != null) _database = client.GetDatabase(settings.Value.Database); } public IMongoCollection<Locations> Locations => _database.GetCollection<Locations>("Locations"); } }
28.48
74
0.696629
[ "MIT" ]
zengande/together
src/microservices/Location/Location.Infrastructure/LocationDbContext.cs
714
C#
namespace VRTK.Examples { using UnityEngine; public class ModelVillage_TeleportLocation : VRTK_DestinationMarker { public Transform destination; private bool lastUsePressedState = false; private void OnTriggerStay(Collider collider) { VRTK_ControllerEvents controller = (collider.GetComponent<VRTK_ControllerEvents>() ? collider.GetComponent<VRTK_ControllerEvents>() : collider.GetComponentInParent<VRTK_ControllerEvents>()); if (controller != null) { if (lastUsePressedState == true && !controller.triggerPressed) { float distance = Vector3.Distance(transform.position, destination.position); VRTK_ControllerReference controllerReference = VRTK_ControllerReference.GetControllerReference(controller.gameObject); OnDestinationMarkerSet(SetDestinationMarkerEvent(distance, destination, new RaycastHit(), destination.position, controllerReference)); } lastUsePressedState = controller.triggerPressed; } } } }
46.44
203
0.654608
[ "MIT" ]
AmrMKayid/Wheelchair-Waiter
Assets/VRTK/Examples/ExampleResources/Scripts/ModelVillage_TeleportLocation.cs
1,163
C#
using System; using System.Collections.Generic; using System.Text; namespace SqlDao { /// <summary> /// 空类 /// </summary> public class TableScema { } }
12.714286
33
0.601124
[ "MIT" ]
crazywolfcode/SqlDaoDemo
SqlDaoLibrary/src/schema/TableScema.cs
184
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Steeltoe.Messaging.Support.Test; public class TaskSchedulerSubscribableChannelTest { internal readonly TaskSchedulerSubscribableChannel _channel; internal readonly object _payload; internal readonly IMessage _message; internal IMessageHandler _handler; public TaskSchedulerSubscribableChannelTest() { _channel = new TaskSchedulerSubscribableChannel(); _payload = new object(); _message = MessageBuilder.WithPayload(_payload).Build(); } [Fact] public void MessageMustNotBeNull() { var ex = Assert.Throws<ArgumentNullException>(() => _channel.Send(null)); Assert.Contains("message", ex.Message); } [Fact] public void SendNoInterceptors() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; _channel.Subscribe(_handler); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message)); } [Fact] public void SendWithoutScheduler() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; var interceptor = new BeforeHandleInterceptor(); _channel.AddInterceptor(interceptor); _channel.Subscribe(_handler); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message)); Assert.Equal(1, interceptor.Counter); Assert.True(interceptor.WasAfterHandledInvoked); } [Fact] public void SendWithScheduler() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; var interceptor = new BeforeHandleInterceptor(); var scheduler = new TestScheduler(); var testChannel = new TaskSchedulerSubscribableChannel(scheduler); testChannel.AddInterceptor(interceptor); testChannel.Subscribe(_handler); testChannel.Send(_message); Assert.True(scheduler.WasTaskScheduled); mock.Verify(h => h.HandleMessage(_message)); Assert.Equal(1, interceptor.Counter); Assert.True(interceptor.WasAfterHandledInvoked); } [Fact] public void SubscribeTwice() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; Assert.True(_channel.Subscribe(_handler)); Assert.False(_channel.Subscribe(_handler)); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message), Times.Once); } [Fact] public void UnsubscribeTwice() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; _channel.Subscribe(_handler); Assert.True(_channel.Unsubscribe(_handler)); Assert.False(_channel.Unsubscribe(_handler)); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message), Times.Never); } [Fact] public void FailurePropagates() { var ex = new Exception("My exception"); var mock = new Mock<IMessageHandler>(); mock.Setup(h => h.HandleMessage(_message)).Throws(ex); _handler = mock.Object; var mock2 = new Mock<IMessageHandler>(); var secondHandler = mock2.Object; _channel.Subscribe(_handler); _channel.Subscribe(secondHandler); var exceptionThrown = false; try { _channel.Send(_message); } catch (MessageDeliveryException actualException) { exceptionThrown = true; Assert.Equal(ex, actualException.InnerException); Assert.Contains("My exception", actualException.InnerException.Message); } Assert.True(exceptionThrown); mock2.Verify(h => h.HandleMessage(_message), Times.Never); } [Fact] public void ConcurrentModification() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; var unsubscribeHandler = new UnsubscribeHandler(this); _channel.Subscribe(unsubscribeHandler); _channel.Subscribe(_handler); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message), Times.Once); } [Fact] public void InterceptorWithModifiedMessage() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; var mock2 = new Mock<IMessage>(); var expected = mock2.Object; var interceptor = new BeforeHandleInterceptor { MessageToReturn = expected }; _channel.AddInterceptor(interceptor); _channel.Subscribe(_handler); _channel.Send(_message); mock.Verify(h => h.HandleMessage(expected), Times.Once); Assert.Equal(1, interceptor.Counter); Assert.True(interceptor.WasAfterHandledInvoked); } [Fact] public void InterceptorWithNull() { var mock = new Mock<IMessageHandler>(); _handler = mock.Object; var interceptor1 = new BeforeHandleInterceptor(); var interceptor2 = new NullReturningBeforeHandleInterceptor(); _channel.AddInterceptor(interceptor1); _channel.AddInterceptor(interceptor2); _channel.Subscribe(_handler); _channel.Send(_message); mock.Verify(h => h.HandleMessage(_message), Times.Never); Assert.Equal(1, interceptor1.Counter); Assert.Equal(1, interceptor2.Counter); Assert.True(interceptor1.WasAfterHandledInvoked); } [Fact] public void InterceptorWithException() { var expected = new Exception("Fake exception"); var mock = new Mock<IMessageHandler>(); mock.Setup(h => h.HandleMessage(_message)).Throws(expected); _handler = mock.Object; var interceptor = new BeforeHandleInterceptor(); _channel.AddInterceptor(interceptor); _channel.Subscribe(_handler); var exceptionThrown = false; try { _channel.Send(_message); } catch (MessageDeliveryException actual) { exceptionThrown = true; Assert.Same(expected, actual.InnerException); } Assert.True(exceptionThrown); mock.Verify(h => h.HandleMessage(_message), Times.Once); Assert.Equal(1, interceptor.Counter); Assert.True(interceptor.WasAfterHandledInvoked); } internal class UnsubscribeHandler : IMessageHandler { private readonly TaskSchedulerSubscribableChannelTest _test; private readonly TaskSchedulerSubscribableChannelWriterTest _test2; public UnsubscribeHandler(TaskSchedulerSubscribableChannelTest test) { _test = test; } public UnsubscribeHandler(TaskSchedulerSubscribableChannelWriterTest test) { _test2 = test; } public string ServiceName { get; set; } = nameof(UnsubscribeHandler); public void HandleMessage(IMessage message) { _test?._channel.Unsubscribe(_test._handler); _test2?._channel.Unsubscribe(_test2._handler); } } internal class TestScheduler : TaskScheduler { public bool WasTaskScheduled; protected override IEnumerable<Task> GetScheduledTasks() { throw new NotImplementedException(); } protected override void QueueTask(Task task) { WasTaskScheduled = true; TryExecuteTask(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { WasTaskScheduled = true; TryExecuteTask(task); return true; } } internal class AbstractTestInterceptor : AbstractTaskSchedulerChannelInterceptor { private volatile int counter; private volatile bool afterHandledInvoked; public int Counter { get { return counter; } } public bool WasAfterHandledInvoked { get { return afterHandledInvoked; } } public override IMessage BeforeHandled(IMessage message, IMessageChannel channel, IMessageHandler handler) { Assert.NotNull(message); Interlocked.Increment(ref counter); return message; } public override void AfterMessageHandled(IMessage message, IMessageChannel channel, IMessageHandler handler, Exception ex) { afterHandledInvoked = true; } } internal class BeforeHandleInterceptor : AbstractTestInterceptor { public IMessage MessageToReturn { get; set; } public Exception ExceptionToRaise { get; set; } public override IMessage BeforeHandled(IMessage message, IMessageChannel channel, IMessageHandler handler) { base.BeforeHandled(message, channel, handler); if (ExceptionToRaise != null) { throw ExceptionToRaise; } return MessageToReturn ?? message; } } internal class NullReturningBeforeHandleInterceptor : AbstractTestInterceptor { public override IMessage BeforeHandled(IMessage message, IMessageChannel channel, IMessageHandler handler) { base.BeforeHandled(message, channel, handler); return null; } } }
31.029032
130
0.640607
[ "Apache-2.0" ]
SteeltoeOSS/steeltoe
src/Messaging/test/MessagingBase.Test/Support/TaskSchedulerSubscribableChannelTest.cs
9,619
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Dcs.V2.Model { /// <summary> /// Response Object /// </summary> public class ListBackupFileLinksResponse : SdkResponse { /// <summary> /// OBS桶内文件路径。 /// </summary> [JsonProperty("file_path", NullValueHandling = NullValueHandling.Ignore)] public string FilePath { get; set; } /// <summary> /// OBS桶名。 /// </summary> [JsonProperty("bucket_name", NullValueHandling = NullValueHandling.Ignore)] public string BucketName { get; set; } /// <summary> /// 备份文件下链接集合,链接数最大为64个。 /// </summary> [JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)] public List<LinksItem> Links { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ListBackupFileLinksResponse {\n"); sb.Append(" filePath: ").Append(FilePath).Append("\n"); sb.Append(" bucketName: ").Append(BucketName).Append("\n"); sb.Append(" links: ").Append(Links).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ListBackupFileLinksResponse); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ListBackupFileLinksResponse input) { if (input == null) return false; return ( this.FilePath == input.FilePath || (this.FilePath != null && this.FilePath.Equals(input.FilePath)) ) && ( this.BucketName == input.BucketName || (this.BucketName != null && this.BucketName.Equals(input.BucketName)) ) && ( this.Links == input.Links || this.Links != null && input.Links != null && this.Links.SequenceEqual(input.Links) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.FilePath != null) hashCode = hashCode * 59 + this.FilePath.GetHashCode(); if (this.BucketName != null) hashCode = hashCode * 59 + this.BucketName.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); return hashCode; } } } }
31.019048
83
0.501689
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Dcs/V2/Model/ListBackupFileLinksResponse.cs
3,313
C#
namespace XaMaps.Models { public class Route { public DirectionsSummary Summary { get; set; } public Leg[] Legs { get; set; } public Section[] Sections { get; set; } public Guidance Guidance { get; set; } } }
25.3
54
0.581028
[ "MIT" ]
AlexPshul/XaMaps
XaMaps/XaMaps/Models/Route.cs
255
C#
// // PInvokeAttributes.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.Cecil { [Flags] public enum PInvokeAttributes : ushort { NoMangle = 0x0001, // PInvoke is to use the member name as specified // Character set CharSetMask = 0x0006, CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, SupportsLastError = 0x0040, // Information about target function. Not relevant for fields // Calling convetion CallConvMask = 0x0700, CallConvWinapi = 0x0100, CallConvCdecl = 0x0200, CallConvStdCall = 0x0300, CallConvThiscall = 0x0400, CallConvFastcall = 0x0500, BestFitMask = 0x0030, BestFitEnabled = 0x0010, BestFitDisabled = 0x0020, ThrowOnUnmappableCharMask = 0x3000, ThrowOnUnmappableCharEnabled = 0x1000, ThrowOnUnmappableCharDisabled = 0x2000, } }
32.904762
92
0.718283
[ "MIT" ]
2823896/cshotfix
CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Core/MonoCecil/Mono.Cecil.20/MonoCecil/Mono.Cecil/PInvokeAttributes.cs
2,073
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Dnx.Runtime.Internal; using NuGet; using Xunit; namespace Microsoft.Dnx.Runtime.Tests { public class ProjectReferenceDependencyResolverFacts { [Theory] [InlineData("net20", "mscorlib,System")] [InlineData("net35", "mscorlib,System,System.Core")] [InlineData("net40", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("net45", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("net451", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("net452", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("net46", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("dnx451", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("dnx452", "mscorlib,System,System.Core,Microsoft.CSharp")] [InlineData("dnx46", "mscorlib,System,System.Core,Microsoft.CSharp")] public void GetDescriptionAddsCoreReferences(string shortFrameworkName, string expectedNames) { string projectJson = @"{ ""frameworks"": { """ + shortFrameworkName + @""": {} } }"; using (var strm = new MemoryStream(Encoding.UTF8.GetBytes(projectJson))) { var project = new ProjectReader().ReadProject(strm, "TheTestProject", @"C:\TestProject", diagnostics: null); var provider = new ProjectDependencyProvider(); var expected = expectedNames.Split(',').Select(s => "fx/" + s).ToArray(); var actual = provider.GetDescription(VersionUtility.ParseFrameworkName(shortFrameworkName), project, null) .Dependencies .Select(d => d.LibraryRange.Name).ToArray(); Assert.Equal(expected, actual); } } } }
47.243902
124
0.636035
[ "Apache-2.0" ]
aspnet/DNX
test/Microsoft.Dnx.Runtime.Tests/DependencyManagement/ProjectReferenceDependencyResolverFacts.cs
1,939
C#
//Copyright 2014 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ArcGIS.Desktop.Internal.Mapping; using ArcGIS.Desktop.Mapping; namespace Geocode { /// <summary> /// Interaction logic for GeocodeTextWindow.xaml /// </summary> public partial class GeocodeTextWindow : Window { public GeocodeTextWindow() { InitializeComponent(); // fill in a default address this.SearchText.Text = "1401 SW Naito Parkway, Portland, Oregon, 97201"; } private async void Button_Click(object sender, RoutedEventArgs e) { // get the current module to access helper method GeocodeModule module = GeocodeModule.Current; // remove any existing graphics MapView mapView = MapView.Active; GeocodeUtils.RemoveFromMapOverlay(mapView); try { // initiate the search CandidateResponse results = GeocodeUtils.SearchFor(this.SearchText.Text, 1); if (results.OrderedResults.Count > 0) { // add a point graphic overlay GeocodeUtils.UpdateMapOverlay(results.OrderedResults[0].ToMapPoint(), mapView); // zoom to the location await GeocodeUtils.ZoomToLocation(results.OrderedResults[0].Extent); // add the search results to the dialog window this.LastSearch.Text = string.Format("Last Match: {0}", results.OrderedResults[0].CandidateDetails); } else { ArcGIS.Desktop.Internal.Framework.DialogManager.ShowMessageBox( string.Format("No results returned for {0}", this.SearchText.Text), "GeocodeExample"); } } catch (Exception ex) { string errorName = "Search Error"; System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}", errorName, ex.ToString())); ArcGIS.Desktop.Internal.Framework.DialogManager.ShowMessageBox(errorName, this.SearchText.Text); } } } }
38.703704
120
0.628389
[ "Apache-2.0" ]
hnasr/arcgis-pro-sdk-community-samples
Geoprocessing/Geocode/GeocodeTextWindow.xaml.cs
3,137
C#
//----------------------------------------------------------------------- // <copyright file="BaseDataReaderWriter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace instance.id.OdinSerializer { using System; /// <summary> /// Implements functionality that is shared by both data readers and data writers. /// </summary> public abstract class BaseDataReaderWriter { // Once, there was a stack here. But stacks are slow, so now there's no longer // a stack here and we just do it ourselves. private NodeInfo[] nodes = new NodeInfo[32]; private int nodesLength = 0; /// <summary> /// Gets or sets the context's or writer's serialization binder. /// </summary> /// <value> /// The reader's or writer's serialization binder. /// </value> [Obsolete("Use the Binder member on the writer's SerializationContext/DeserializationContext instead.", error: false)] public TwoWaySerializationBinder Binder { get { if (this is IDataWriter) { return (this as IDataWriter).Context.Binder; } else if (this is IDataReader) { return (this as IDataReader).Context.Binder; } return TwoWaySerializationBinder.Default; } set { if (this is IDataWriter) { (this as IDataWriter).Context.Binder = value; } else if (this is IDataReader) { (this as IDataReader).Context.Binder = value; } } } /// <summary> /// Gets a value indicating whether the reader or writer is in an array node. /// </summary> /// <value> /// <c>true</c> if the reader or writer is in an array node; otherwise, <c>false</c>. /// </value> public bool IsInArrayNode { get { return this.nodesLength == 0 ? false : this.nodes[this.nodesLength - 1].IsArray; } } /// <summary> /// Gets the current node depth. In other words, the current count of the node stack. /// </summary> /// <value> /// The current node depth. /// </value> protected int NodeDepth { get { return this.nodesLength; } } /// <summary> /// Gets the current node, or <see cref="NodeInfo.Empty"/> if there is no current node. /// </summary> /// <value> /// The current node. /// </value> protected NodeInfo CurrentNode { get { return this.nodesLength == 0 ? NodeInfo.Empty : this.nodes[this.nodesLength - 1]; } } /// <summary> /// Pushes a node onto the node stack. /// </summary> /// <param name="node">The node to push.</param> protected void PushNode(NodeInfo node) { if (this.nodesLength == this.nodes.Length) { this.ExpandNodes(); } this.nodes[this.nodesLength] = node; this.nodesLength++; } /// <summary> /// Pushes a node with the given name, id and type onto the node stack. /// </summary> /// <param name="name">The name of the node.</param> /// <param name="id">The id of the node.</param> /// <param name="type">The type of the node.</param> protected void PushNode(string name, int id, Type type) { if (this.nodesLength == this.nodes.Length) { this.ExpandNodes(); } this.nodes[this.nodesLength] = new NodeInfo(name, id, type, false); this.nodesLength++; } /// <summary> /// Pushes an array node onto the node stack. This uses values from the current node to provide extra info about the array node. /// </summary> protected void PushArray() { if (this.nodesLength == this.nodes.Length) { this.ExpandNodes(); } if (this.nodesLength == 0 || this.nodes[this.nodesLength - 1].IsArray) { this.nodes[this.nodesLength] = new NodeInfo(null, -1, null, true); } else { var current = this.nodes[this.nodesLength - 1]; this.nodes[this.nodesLength] = new NodeInfo(current.Name, current.Id, current.Type, true); } this.nodesLength++; } private void ExpandNodes() { var newArr = new NodeInfo[this.nodes.Length * 2]; var oldNodes = this.nodes; for (int i = 0; i < oldNodes.Length; i++) { newArr[i] = oldNodes[i]; } this.nodes = newArr; } /// <summary> /// Pops the current node off of the node stack. /// </summary> /// <param name="name">The name of the node to pop.</param> /// <exception cref="System.InvalidOperationException"> /// There are no nodes to pop. /// or /// Tried to pop node with given name, but the current node's name was different. /// </exception> protected void PopNode(string name) { if (this.nodesLength == 0) { throw new InvalidOperationException("There are no nodes to pop."); } // @Speedup - this safety isn't worth the performance hit, and never happens with properly written writers //var current = this.CurrentNode; //if (current.Name != name) //{ // throw new InvalidOperationException("Tried to pop node with name " + name + " but current node's name is " + current.Name); //} this.nodesLength--; } /// <summary> /// Pops the current node if the current node is an array node. /// </summary> protected void PopArray() { if (this.nodesLength == 0) { throw new InvalidOperationException("There are no nodes to pop."); } if (this.nodes[this.nodesLength - 1].IsArray == false) { throw new InvalidOperationException("Was not in array when exiting array."); } this.nodesLength--; } protected void ClearNodes() { this.nodesLength = 0; } } }
34.438679
141
0.521572
[ "MIT" ]
instance-id/SO-Persistent-Reference
Assets/instance.id/SOReference/Utils/OdinSerializer/Core/DataReaderWriters/BaseDataReaderWriter.cs
7,301
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; namespace InteractiveStories.IdentityProvider.Models.ManageViewModels { public class ExternalLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationScheme> OtherLogins { get; set; } public bool ShowRemoveButton { get; set; } public string StatusMessage { get; set; } } }
25.857143
69
0.742173
[ "MIT" ]
Bit-Coin/InteractiveStories
InteractiveStories.IdentityProvider/Models/ManageViewModels/ExternalLoginsViewModel.cs
545
C#
using System; using System.Collections.Generic; using System.Diagnostics; using Verse; using Verse.AI; using RimWorld; namespace TorannMagic.Enchantment { public class JobDriver_RemoveEnchantingGem : JobDriver { private int useDuration = -1; public override void ExposeData() { base.ExposeData(); Scribe_Values.Look<int>(ref this.useDuration, "useDuration", 0, false); } public override void Notify_Starting() { base.Notify_Starting(); } public override bool TryMakePreToilReservations(bool errorOnFailed) { return this.pawn.Reserve(this.job.targetA, this.job, 1, -1, null); } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch); //probably remove, drop should be immediate at location Toil drop = new Toil(); drop.initAction = delegate { Pawn actor = drop.actor; CompEnchant comp = actor.TryGetComp<CompEnchant>(); comp.enchantingContainer.TryDropAll(actor.Position, actor.Map, ThingPlaceMode.Near); }; drop.defaultCompleteMode = ToilCompleteMode.Instant; yield return drop; } } }
29.978261
136
0.613488
[ "BSD-3-Clause" ]
CaptainMuscles/TMagic
Source/TMagic/TMagic/Enchantment/JobDriver_RemoveEnchantingGem.cs
1,381
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project3 { class Program { static Random r = new Random(); static void Main(string[] args) { // 1.a String[] duraklar = { "İnciraltı, 28, 2, 10", "Sahilevleri, 8, 1, 11", "Doğal Yaşam Parkı, 17, 1, 6", "Bostanlı İskele, 7, 0, 5", "Buz Pisti , 11, 0, 9", "Hasanağa Parkı, 7, 0, 5", "Alsancak İskele, 8, 5, 3", "Fuar Montrö, 8, 7, 1", "Karataş, 7, 0, 8"}; List<Durak> durakNesneler = new List<Durak>(); foreach (string durak in duraklar) //duraklar arrayinden bilgileri çekip istenen random müşteri bilgileri tutuldu. { string[] splitNesne = durak.Split(","); List<Müsteri> müşteriler = new List<Müsteri>(20); int randomMusteriSay = r.Next(1, 10); if (randomMusteriSay > (Int32.Parse(splitNesne[2]) + Int32.Parse(splitNesne[3]))) { randomMusteriSay = Int32.Parse(splitNesne[2]) + Int32.Parse(splitNesne[3]); } for (int j = 0; j < randomMusteriSay; j++) { int müsID = r.Next(1, 21); int s = r.Next(1, 25); int d = r.Next(1, 61); Zaman zmn = new Zaman(s, d); // Zaman sınıfından obje yaratıldı Müsteri m = new Müsteri(müsID, zmn); müşteriler.Add(m); } durakNesneler.Add(new Durak(splitNesne[0], Int32.Parse(splitNesne[1]), Int32.Parse(splitNesne[2]), Int32.Parse(splitNesne[3]), müşteriler)); // Veriler listeye gönderildi } DurakAğacı bt = new DurakAğacı(); foreach (Durak x in durakNesneler) //Oluşturduğumuz Generic ile tüm nesneleri burdan ağaca attık { bt.insert(x); } bt.updateTree(bt.getRoot()); // 1.b Console.WriteLine("Ağacın Derinliği: " + bt.getMaxDepth(bt.getRoot())); Console.WriteLine(); Console.WriteLine("Ağaçtaki Tüm Bilgiler; "); Console.WriteLine(); bt.preOrder(bt.getRoot()); // 1.c Console.WriteLine("Kiralama bilgilerini görmek istediğiniz Müşteri ID: "); int mID = Convert.ToInt32(Console.ReadLine()); bt.getMüşteriInfo(mID, bt.getRoot()); // 1.d Console.WriteLine("Normal bisiklet kiralama;"); Console.WriteLine("Müşteri ID: "); int id = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Durak adı: "); string da = Console.ReadLine(); bt.normalKiralama(da, id, bt.getRoot()); // 2.a Hashtable hash = new Hashtable(); foreach (string s in duraklar) // Duraklar listesinden gerekli bilgiler çekilip key- value olarak hash'e aktarıldı { string[] keysNvalues = s.Split(","); int[] durakBilgileri = { Convert.ToInt32(keysNvalues[1]), Convert.ToInt32(keysNvalues[2]), Convert.ToInt32(keysNvalues[3]) }; hash.Add(keysNvalues[0], durakBilgileri); } // 2.b foreach (string str in duraklar) // Boş park sayısı 5ten büyük olan parklar için güncelleme yapıldı { string[] keysNvalues = str.Split(","); if (Convert.ToInt32(keysNvalues[1]) > 5) { int a = Convert.ToInt32(keysNvalues[3]); a += 5; keysNvalues[3] = Convert.ToString(a); int[] durakBilgileri = { Convert.ToInt32(keysNvalues[1]), Convert.ToInt32(keysNvalues[2]), Convert.ToInt32(keysNvalues[3]) }; hash[keysNvalues[0]] = durakBilgileri; } } } class Durak // Yapılandırıcı sınıf { string durakAdi; int bos_park_say; int tandem_say; int normal_say; List<Müsteri> müsteriList = new List<Müsteri>(); public Durak(string durak, int bos_park, int tandem, int normal, List<Müsteri> m) { this.durakAdi = durak; this.bos_park_say = bos_park; this.tandem_say = tandem; this.normal_say = normal; this.müsteriList = m; } public string getDurakAdi() { return durakAdi; } public int getBosPark() { return bos_park_say; } public void setBosPark(int bPark) { this.bos_park_say = bPark; } // Güncelleme için public int getTandem() { return tandem_say; } public void setTandem(int tndm) { this.tandem_say = tndm; } public int getNormal() { return normal_say; } public void setNormal(int nrml) { this.normal_say = nrml; } public int getListSize() { return müsteriList.Count; } public List<Müsteri> getList() { return this.müsteriList; } } class TreeNode { public Durak data; public TreeNode leftChild; public TreeNode rightChild; public void displayNode() { Console.Write("Durak Adı: " + data.getDurakAdi() + "\n" + "Boş Park Yeri: " + data.getBosPark() + "\n" + "Tandem Bisiklet Sayısı: " + data.getTandem() + "\n" + "Normal Bisiklet Sayısı: " + data.getNormal() + "\n" + "Kiralama İşlemi Yapan Müşteri Sayısı: " + data.getListSize() + "\n"); Console.WriteLine(); Console.WriteLine("Müşteri Bilgileri; "); Console.WriteLine(); foreach (Müsteri m in data.getList()) { Console.Write("Müşteri ID: " + m.getMüşteriID() + "\n" + m.getZaman().toString()); } Console.WriteLine(); } } class DurakAğacı { private TreeNode root; private int size; public DurakAğacı() { root = null; } public TreeNode getRoot() { return root; } // Agacın preOrder Dolasılması public void preOrder(TreeNode localRoot) { if (localRoot != null) { localRoot.displayNode(); preOrder(localRoot.leftChild); preOrder(localRoot.rightChild); } } // Agacın inOrder Dolasılması public void inOrder(TreeNode localRoot) { if (localRoot != null) { inOrder(localRoot.leftChild); localRoot.displayNode(); inOrder(localRoot.rightChild); } } // Agacın postOrder Dolasılması public void postOrder(TreeNode localRoot) { if (localRoot != null) { postOrder(localRoot.leftChild); postOrder(localRoot.rightChild); localRoot.displayNode(); } } // Agaca bir dügüm eklemeyi saglayan metot public void insert(Durak newdata) { TreeNode newNode = new TreeNode(); newNode.data = newdata; if (root == null) root = newNode; else { TreeNode current = root; TreeNode parent; while (true) { parent = current; if (string.Compare(newdata.getDurakAdi(), current.data.getDurakAdi()) < 0) { current = current.leftChild; if (current == null) { parent.leftChild = newNode; return; } } else { current = current.rightChild; if (current == null) { parent.rightChild = newNode; return; } } } // end while } // end else not root size++; } // end insert() public void updateTree(TreeNode localRoot) // Eklenen müşteri bilgileri ve kiralanan bisiklet sayılarından dolayı ağaç güncellemede kullanıldı { if (localRoot != null) { for (int i = 0; i < localRoot.data.getListSize(); i++) { localRoot.data.setBosPark(localRoot.data.getBosPark() + 1); if (localRoot.data.getNormal() != 0) { localRoot.data.setNormal(localRoot.data.getNormal() - 1); } else { localRoot.data.setTandem(localRoot.data.getTandem() - 1); } } updateTree(localRoot.leftChild); updateTree(localRoot.rightChild); } } public int getMaxDepth(TreeNode localRoot) // Ağaç derinliği bulmak için { if (localRoot == null) return 0; else { int leftDepth = getMaxDepth(localRoot.leftChild); int rightDepth = getMaxDepth(localRoot.rightChild); if (leftDepth > rightDepth) return (leftDepth + 1); else return (rightDepth + 1); } } public int getSize() { return size; } public void getMüşteriInfo(int ID, TreeNode localRoot) // ID'si verilen müşterinin kiralama bilgileri için kullanılan metot { if (localRoot != null) { foreach (Müsteri m in localRoot.data.getList()) { if (m.getMüşteriID() == ID) { Console.WriteLine("Bisiklet kiralanan durak adı: " + localRoot.data.getDurakAdi()); Console.WriteLine("Bisikletin kiralandığı saat: " + m.getZaman().toString()); } } getMüşteriInfo(ID, localRoot.leftChild); getMüşteriInfo(ID, localRoot.rightChild); } } public void normalKiralama(string ad, int ID, TreeNode localRoot) // Normal bisiklet kiralamak isteyenler için kullanılan metot { if (localRoot != null) { if (ad == localRoot.data.getDurakAdi()) { int st = r.Next(25); int dk = r.Next(61); Zaman zaman = new Zaman(st, dk); Müsteri mu = new Müsteri(ID, zaman); localRoot.data.getList().Add(mu); localRoot.data.setBosPark(localRoot.data.getBosPark() + 1); localRoot.data.setNormal(localRoot.data.getNormal() - 1); return; } normalKiralama(ad, ID, localRoot.leftChild); normalKiralama(ad, ID, localRoot.rightChild); } } } class Müsteri { int MüşteriID; Zaman zaman; public Müsteri(int mID, Zaman z) { this.MüşteriID = mID; this.zaman = z; } public int getMüşteriID() { return MüşteriID; } public Zaman getZaman() { return zaman; } } class Zaman { int saat; int dakika; public Zaman(int sa, int dk) { this.saat = sa; this.dakika = dk; } public int getSaat() { return saat; } public int getDakika() { return dakika; } public string toString() // Displayde rahatça kullanabilmek için { return "Kiralama saati: " + this.saat + ":" + this.dakika + "\n"; } } } }
34.311856
156
0.449185
[ "MIT" ]
eberkeaydin/ds-project-3
source-code.cs
13,479
C#
// ------------------------------------------------------------ // Copyright (c) Dover Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using global::Iot.Common; namespace TargetSolution { public static class Names { public const string EventLatestDictionaryName = "store://events/latest/dictionary"; public const string EventHistoryDictionaryName = "store://events/history/dictionary"; public const long DataOffloadBatchIntervalInSeconds = 600; // this application is not doing any data offload - this timer is only a placehoder; public const int DataOffloadBatchSize = 100; public const int DataDrainIteration = 5; } }
36.423077
153
0.63886
[ "MIT" ]
doverpublic/dds-launchpad-iiot-cloud
src/TargetSolutionCommon/Config/Names.cs
949
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 chime-2018-05-01.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.Chime.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Chime.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteMediaCapturePipeline operation /// </summary> public class DeleteMediaCapturePipelineResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteMediaCapturePipelineResponse response = new DeleteMediaCapturePipelineResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailureException")) { return ServiceFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottledClientException")) { return ThrottledClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedClientException")) { return UnauthorizedClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonChimeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteMediaCapturePipelineResponseUnmarshaller _instance = new DeleteMediaCapturePipelineResponseUnmarshaller(); internal static DeleteMediaCapturePipelineResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteMediaCapturePipelineResponseUnmarshaller Instance { get { return _instance; } } } }
41.926829
188
0.65445
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/DeleteMediaCapturePipelineResponseUnmarshaller.cs
5,157
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fap.Core.Annex.Utility.Events { /// <summary> /// 文件上传委托 /// </summary> /// <param name="fileInfo"></param> /// <param name="args"></param> public delegate void FileUploadEventHandler(FapFileInfo fileInfo, FileUploadEventArgs args); public class FileUploadEventArgs : EventArgs { public long Total { get; set; } public long Uploaded { get; set; } public string FileFullName { get; set; } public string FileName { get; set; } public string FileDirectory { get; set; } } }
17.959184
96
0.502273
[ "Apache-2.0" ]
48355746/FapCore3.0
src/Fap.Core/Annex/Utility/Events/FileUploadEventArgs.cs
894
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 Microsoft.AspNetCore.Mvc.RazorPages; namespace Identity.DefaultUI.WebSite.Pages { public class ContactModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Your contact page."; } } }
25.055556
111
0.658537
[ "Apache-2.0" ]
06b/AspNetCore
src/Identity/testassets/Identity.DefaultUI.WebSite/Pages/Contact.cshtml.cs
453
C#
using System.Collections.Generic; namespace GetShredded.Models { public class DiaryRating { public DiaryRating() { this.GetShreddedRatings = new HashSet<GetShreddedRating>(); } public int Id { get; set; } public double Rating { get; set; } public string GetShreddedUserId { get; set; } public GetShreddedUser GetShreddedUser { get; set; } public ICollection<GetShreddedRating> GetShreddedRatings { get; set; } } }
23.090909
78
0.627953
[ "MIT" ]
krasimirLyubomirov/GetShredded
src/GetShredded.Models/DiaryRating.cs
510
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 directconnect-2012-10-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectConnect.Model { /// <summary> /// Container for the parameters to the DescribeLocations operation. /// Lists the AWS Direct Connect locations in the current AWS Region. These are the locations /// that can be selected when calling <a>CreateConnection</a> or <a>CreateInterconnect</a>. /// </summary> public partial class DescribeLocationsRequest : AmazonDirectConnectRequest { } }
33.717949
111
0.736882
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DirectConnect/Generated/Model/DescribeLocationsRequest.cs
1,315
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request to get the list of Application Server Registration system parameters. /// The response is either SystemASRParametersGetResponse14sp7 or ErrorResponse. /// /// Replaced by: SystemASRParametersGetRequest23 in AS data mode. /// <see cref="SystemASRParametersGetResponse14sp7"/> /// <see cref="ErrorResponse"/> /// <see cref="SystemASRParametersGetRequest23"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""de4d76f01f337fe4694212ec9f771753:6902""}]")] public class SystemASRParametersGetRequest14sp7 : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.SystemASRParametersGetResponse14sp7> { } }
37.481481
167
0.744071
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemASRParametersGetRequest14sp7.cs
1,012
C#
// Created via this command line: "C:\CRM Tools\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /url:"https://xrmvituralunittest.api.crm.dynamics.com/XRMServices/2011/Organization.svc" /namespace:"DLaB.Xrm.Entities" /out:"C:\Temp\Entities\OptionSets\OptionSets.cs" /codecustomization:"DLaB.CrmSvcUtilExtensions.OptionSet.CreateOptionSetEnums,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.OptionSet.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /username:"kenm@XrmVituralUnitTest.onmicrosoft.com" /password:"**********"
750
750
0.844
[ "MIT" ]
Bhawk90/DLaB.Xrm.XrmToolBoxTools
DLaB.Xrm.Entities/OptionSets/OptionSets.cs
750
C#