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
sequence | 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 Newtonsoft.Json;
namespace greenergy.chatbot_fulfillment.Models
{
public class DialogFlowResponseDTO
{
public string fulfillmentText { get; set; }
public List<FulfillmentMessage> fulfillmentMessages { get; set; }
public string source { get; set; }
public Payload payload { get; set; }
public List<OutputContext> outputContexts { get; set; }
public OutputContext followupEventInput { get; set; }
}
public class DialogFlowRequestDTO
{
public string responseId { get; set; }
public string session { get; set; }
public QueryResult queryResult { get; set; }
public OriginalDetectIntentRequest originalDetectIntentRequest { get; set; }
}
public class QueryResult
{
public string queryText { get; set; }
public string action { get; set; }
public Parameters parameters { get; set; }
public bool allRequiredParamsPresent { get; set; }
public string fulfillmentText { get; set; }
public List<FulfillmentMessage> fulfillmentMessages { get; set; }
public List<OutputContext> outputContexts { get; set; }
public Intent intent { get; set; }
public float intentDetectionConfidence { get; set; }
public DiagnosticInfo diagnosticInfo { get; set; }
public string languageCode { get; set; }
}
public class OriginalDetectIntentRequest
{
}
public class Button
{
public string text { get; set; }
public string postback { get; set; }
}
public class Card
{
public string title { get; set; }
public string subtitle { get; set; }
public string imageUri { get; set; }
public List<Button> buttons { get; set; }
}
public class FulfillmentMessage
{
}
public class CardFulfillmentMessage : FulfillmentMessage
{
public Card card { get; set; }
}
public class TextFulfillmentMessage : FulfillmentMessage
{
public Text text { get; set; }
}
public class Text
{
public List<string> text { get; set; }
}
public class SimpleResponse
{
public string textToSpeech { get; set; }
}
public class Item
{
public SimpleResponse simpleResponse { get; set; }
}
public class RichResponse
{
public List<Item> items { get; set; }
}
public class Google
{
public bool expectUserResponse { get; set; }
public RichResponse richResponse { get; set; }
}
public class Facebook
{
public string text { get; set; }
}
public class Slack
{
public string text { get; set; }
}
public class Payload
{
public Google google { get; set; }
public Facebook facebook { get; set; }
public Slack slack { get; set; }
}
public class Parameters
{
// public string test1 { get; set; }
// public string test2 { get; set; }
public string readableduration { get; set; }
public DateTime date { get; set; }
public DateTime time { get; set; }
public double kilometers { get; set; }
public Duration duration { get; set; }
public DateTimeOffset prognosisend { get; set; }
public double savingspercentage { get; set; }
public double initialemissions { get; set; }
public double optimalemissions { get; set; }
public double lastEmissions { get; set; }
public string optimalconsumptionstart { get; set; }
public string finishnolaterthan { get; set; }
public string devicetype { get; set; }
public double waitinghours { get; set; }
}
public class Duration
{
public float amount { get; set; }
public string unit { get; set; }
public int toMinutes()
{
if (unit.Equals("min"))
return (int)amount;
else if (unit.Equals("h"))
return (int)amount * 60;
else if (unit.Equals("day"))
return (int)amount * 60 * 24;
return -1;
}
public int toHours()
{
if (unit.Equals("min"))
return (int) Math.Round(amount/60);
else if (unit.Equals("h"))
return (int)amount;
else if (unit.Equals("day"))
return (int) Math.Round(amount*24);
return -1;
}
public string toReadableString()
{
if (unit.Equals("min"))
return $"{amount} minutes";
else if (unit.Equals("h"))
if (amount == 1) return "hour";
else return $"{amount} hours";
else if (unit.Equals("day"))
return $"{amount} days";
return $"{amount} {unit}";
}
}
public class OutputContext
{
public string name { get; set; }
public int lifespanCount { get; set; }
public Parameters parameters { get; set; }
}
public class Intent
{
public string name { get; set; }
public string displayName { get; set; }
}
public class DiagnosticInfo
{
}
} | 27.727749 | 84 | 0.568731 | [
"MIT"
] | sorbra/greenergy | emissions-chatbot/emissions-chatbot.fulfillment/Models/DialogFlowModels.cs | 5,296 | C# |
#region License, Terms and Conditions
//
// Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
// Written by Atif Aziz ([email protected])
// Copyright (c) 2005 Atif Aziz. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace Jayrock.Json.Conversion.Converters
{
#region Importer
using System;
using Jayrock.Json.Conversion;
#endregion
public class ImportAwareImporter : ImporterBase
{
public ImportAwareImporter(Type type) :
base(type) {}
protected override object ImportFromBoolean(ImportContext context, JsonReader reader)
{
return ReflectImport(context, reader);
}
protected override object ImportFromNumber(ImportContext context, JsonReader reader)
{
return ReflectImport(context, reader);
}
protected override object ImportFromString(ImportContext context, JsonReader reader)
{
return ReflectImport(context, reader);
}
protected override object ImportFromArray(ImportContext context, JsonReader reader)
{
return ReflectImport(context, reader);
}
protected override object ImportFromObject(ImportContext context, JsonReader reader)
{
return ReflectImport(context, reader);
}
private object ReflectImport(ImportContext context, JsonReader reader)
{
if (context == null)
throw new ArgumentNullException("context");
if (reader == null)
throw new ArgumentNullException("reader");
IJsonImportable o = CreateObject();
o.Import(context, reader);
return o;
}
protected virtual IJsonImportable CreateObject()
{
return (IJsonImportable) Activator.CreateInstance(OutputType);
}
}
} | 32.7125 | 93 | 0.668705 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Jayrock/Json/Json/Conversion/Converters/ImportAwareImporter.cs | 2,617 | C# |
// Copyright © William Sugarman.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Auth;
namespace Keda.Scaler.DurableTask.AzureStorage.Cloud;
internal interface ITokenCredentialFactory
{
ValueTask<TokenCredential> CreateAsync(string resource, Uri authorityHost, CancellationToken cancellationToken = default);
}
| 27.4 | 126 | 0.817518 | [
"MIT"
] | wsugarman/durabletask-azurestorage-external-scaler | src/Keda.Scaler.DurableTask.AzureStorage/Cloud/ITokenCredentialFactory.cs | 414 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Integration.AspNet.Core.Handlers
{
public abstract class BotMessageHandlerBase
{
public static readonly JsonSerializer BotMessageSerializer = JsonSerializer.Create(new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() }
});
private BotFrameworkAdapter _botFrameworkAdapter;
public BotMessageHandlerBase(BotFrameworkAdapter botFrameworkAdapter)
{
_botFrameworkAdapter = botFrameworkAdapter;
}
public async Task HandleAsync(HttpContext httpContext)
{
var request = httpContext.Request;
var response = httpContext.Response;
if (request.Method != HttpMethods.Post)
{
response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
return;
}
if (request.ContentLength == 0)
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
return;
}
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeaderValue)
||
mediaTypeHeaderValue.MediaType != "application/json")
{
response.StatusCode = (int)HttpStatusCode.NotAcceptable;
return;
}
try
{
var invokeResponse = await ProcessMessageRequestAsync(
request,
_botFrameworkAdapter,
context =>
{
var bot = httpContext.RequestServices.GetRequiredService<IBot>();
return bot.OnTurn(context);
});
if (invokeResponse == null)
{
response.StatusCode = (int)HttpStatusCode.OK;
}
else
{
response.ContentType = "application/json";
response.StatusCode = invokeResponse.Status;
using (var writer = new StreamWriter(response.Body))
{
using (var jsonWriter = new JsonTextWriter(writer))
{
BotMessageSerializer.Serialize(jsonWriter, invokeResponse.Body);
}
}
}
}
catch (UnauthorizedAccessException)
{
response.StatusCode = (int)HttpStatusCode.Forbidden;
}
}
protected abstract Task<InvokeResponse> ProcessMessageRequestAsync(HttpRequest request, BotFrameworkAdapter botFrameworkAdapter, Func<ITurnContext, Task> botCallbackHandler);
}
} | 34.740385 | 182 | 0.584002 | [
"MIT"
] | JiayueHu/botbuilder-dotnet | libraries/integration/Microsoft.Bot.Builder.Integration.AspNet.Core/BotMessageHandlerBase.cs | 3,615 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using QlikView_CLI.QMSAPI;
namespace QlikView_CLI.PWSH
{
[Cmdlet(VerbsCommon.Get, "QVServerObjectMetaDataForUser")]
public class GetQVServerObjectMetaDataForUser : PSClient
{
[Parameter]
public Guid[] qvsID;
[Parameter]
public string User;
private System.Collections.Generic.List<QlikView_CLI.QMSAPI.ServerObjectMetaData> Serverobjectmetadata = new System.Collections.Generic.List<QlikView_CLI.QMSAPI.ServerObjectMetaData>();
protected override void BeginProcessing()
{
base.BeginProcessing();
if (qvsID == null)
{
qvsID = Connection.QlikViewWebServer.Select(x => x.ID).ToArray();
}
}
protected override void ProcessRecord()
{
try
{
foreach (Guid obj in qvsID)
{
Serverobjectmetadata = Connection.client.GetServerObjectMetaDataForUser(obj, User);
}
}
catch (System.Exception e)
{
var errorRecord = new ErrorRecord(e, e.Source, ErrorCategory.NotSpecified, Connection.client);
WriteError(errorRecord);
}
}
protected override void EndProcessing()
{
base.EndProcessing();
WriteObject(Serverobjectmetadata);
}
}
}
| 26.982143 | 193 | 0.590338 | [
"MIT"
] | QlikProfessionalServices/QlikView-CLI | PWSH/Generated/Get/ServerObjectMetaDataForUser.cs | 1,513 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
namespace Discount.API.Extensions
{
public static class HostExtensions
{
public static IHost MigrateDatabase<TContext>(this IHost host, int? retry = 0)
{
int retryForAvailability = retry.Value;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var configuration = services.GetRequiredService<IConfiguration>();
var logger = services.GetRequiredService<ILogger<TContext>>();
try
{
logger.LogInformation("Migrating postresql database.");
using var connection = new NpgsqlConnection
(configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
connection.Open();
using var command = new NpgsqlCommand
{
Connection = connection
};
command.CommandText = "DROP TABLE IF EXISTS Coupon";
command.ExecuteNonQuery();
command.CommandText = @"CREATE TABLE Coupon(Id SERIAL PRIMARY KEY,
ProductName VARCHAR(24) NOT NULL,
Description TEXT,
Amount INT)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('IPhone X', 'IPhone Discount', 150);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('Samsung 10', 'Samsung Discount', 100);";
command.ExecuteNonQuery();
logger.LogInformation("Migrated postresql database.");
}
catch (NpgsqlException ex)
{
logger.LogError(ex, "An error occurred while migrating the postresql database");
if (retryForAvailability < 50)
{
retryForAvailability++;
System.Threading.Thread.Sleep(2000);
MigrateDatabase<TContext>(host, retryForAvailability);
}
}
}
return host;
}
}
}
| 38.3 | 144 | 0.512868 | [
"MIT"
] | ritzm1974/AspnetMicroservices | src/Services/Discount/Discount.API/Extensions/HostExtensions.cs | 2,683 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Elasticsearch.Net.Connection.RequestState;
using Elasticsearch.Net.ConnectionPool;
using Elasticsearch.Net.Exceptions;
using Elasticsearch.Net.Providers;
using Elasticsearch.Net.Serialization;
using System.Threading.Tasks;
using Elasticsearch.Net.Connection.Configuration;
namespace Elasticsearch.Net.Connection.RequestHandlers
{
internal class RequestHandlerBase
{
protected const int BufferSize = 4096;
protected static readonly string MaxRetryExceptionMessage = "Failed after retrying {2} times: '{0} {1}'. {3}";
protected static readonly string TookTooLongExceptionMessage = "Retry timeout {4} was hit after retrying {2} times: '{0} {1}'. {3}";
protected static readonly string MaxRetryInnerMessage = "InnerException: {0}, InnerMessage: {1}, InnerStackTrace: {2}";
protected readonly IConnectionConfigurationValues _settings;
protected readonly IConnection _connection;
protected readonly IConnectionPool _connectionPool;
protected readonly IElasticsearchSerializer _serializer;
protected readonly IMemoryStreamProvider _memoryStreamProvider;
protected readonly ITransportDelegator _delegator;
protected readonly bool _throwMaxRetry;
protected RequestHandlerBase(
IConnectionConfigurationValues settings,
IConnection connection,
IConnectionPool connectionPool,
IElasticsearchSerializer serializer,
IMemoryStreamProvider memoryStreamProvider,
ITransportDelegator delegator)
{
_settings = settings;
_connection = connection;
_connectionPool = connectionPool;
_serializer = serializer;
_memoryStreamProvider = memoryStreamProvider;
_delegator = delegator;
this._throwMaxRetry = !(this._connectionPool is SingleNodeConnectionPool);
}
protected byte[] PostData(object data)
{
if (data == null) return null;
var bytes = data as byte[];
if (bytes != null) return bytes;
var s = data as string;
if (s != null) return s.Utf8Bytes();
var ss = data as IEnumerable<string>;
if (ss != null) return (string.Join("\n", ss) + "\n").Utf8Bytes();
var so = data as IEnumerable<object>;
if (so == null) return this._serializer.Serialize(data);
var joined = string.Join("\n", so
.Select(soo => this._serializer.Serialize(soo, SerializationFormatting.None).Utf8String())) + "\n";
return joined.Utf8Bytes();
}
protected static bool IsValidResponse(ITransportRequestState requestState, IElasticsearchResponse streamResponse)
{
return streamResponse.Success
|| StatusCodeAllowed(requestState.RequestConfiguration, streamResponse.HttpStatusCode);
}
protected static bool StatusCodeAllowed(IRequestConfiguration requestConfiguration, int? statusCode)
{
if (requestConfiguration == null)
return false;
return requestConfiguration.AllowedStatusCodes.HasAny(i => i == statusCode);
}
protected bool TypeOfResponseCopiesDirectly<T>()
{
var type = typeof(T);
return type == typeof(string) || type == typeof(byte[]) || typeof(Stream).IsAssignableFrom(typeof(T));
}
protected bool SetStringOrByteResult<T>(ElasticsearchResponse<T> original, byte[] bytes)
{
var type = typeof(T);
if (type == typeof(string))
{
this.SetStringResult(original as ElasticsearchResponse<string>, bytes);
return true;
}
if (type == typeof(byte[]))
{
this.SetByteResult(original as ElasticsearchResponse<byte[]>, bytes);
return true;
}
return false;
}
/// <summary>
/// Determines whether the stream response is our final stream response:
/// IF response is success or known error
/// OR maxRetries is 0 and retried is 0 (maxRetries could change in between retries to 0)
/// AND sniff on connection fault does not find more nodes (causing maxRetry to grow)
/// AND maxretries is no retried
/// </summary>
protected bool DoneProcessing<T>(
ElasticsearchResponse<Stream> streamResponse,
TransportRequestState<T> requestState,
int maxRetries,
int retried)
{
return (streamResponse != null && streamResponse.SuccessOrKnownError)
|| (maxRetries == 0
&& retried == 0
&& !this._delegator.SniffOnFaultDiscoveredMoreNodes(requestState, retried, streamResponse)
);
}
protected void ThrowMaxRetryExceptionWhenNeeded<T>(TransportRequestState<T> requestState, int maxRetries)
{
var tookToLong = this._delegator.TookTooLongToRetry(requestState);
//not out of date and we havent depleted our retries, get the hell out of here
if (!tookToLong && requestState.Retried < maxRetries) return;
var innerExceptions = requestState.SeenExceptions.Where(e => e != null).ToList();
var innerException = !innerExceptions.HasAny()
? null
: (innerExceptions.Count() == 1)
? innerExceptions.First()
: new AggregateException(requestState.SeenExceptions);
//When we are not using pooling we forcefully rethrow the exception
if (!requestState.UsingPooling && innerException != null && maxRetries == 0)
throw innerException;
var exceptionMessage = tookToLong
? CreateTookTooLongExceptionMessage(requestState, innerException)
: CreateMaxRetryExceptionMessage(requestState, innerException);
throw new MaxRetryException(exceptionMessage, innerException);
}
protected string CreateInnerExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
if (e == null) return null;
var aggregate = e as AggregateException;
if (aggregate == null)
return "\r\n" + MaxRetryInnerMessage.F(e.GetType().Name, e.Message, e.StackTrace);
aggregate = aggregate.Flatten();
var innerExceptions = aggregate.InnerExceptions
.Select(ae => MaxRetryInnerMessage.F(ae.GetType().Name, ae.Message, ae.StackTrace))
.ToList();
return "\r\n" + string.Join("\r\n", innerExceptions);
}
protected string CreateMaxRetryExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
string innerException = CreateInnerExceptionMessage(requestState, e);
var exceptionMessage = MaxRetryExceptionMessage
.F(requestState.Method, requestState.Path, requestState.Retried, innerException);
return exceptionMessage;
}
protected string CreateTookTooLongExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
string innerException = CreateInnerExceptionMessage(requestState, e);
var timeout = this._settings.MaxRetryTimeout.GetValueOrDefault(TimeSpan.FromMilliseconds(this._settings.Timeout));
var exceptionMessage = TookTooLongExceptionMessage
.F(requestState.Method, requestState.Path, requestState.Retried, innerException, timeout);
return exceptionMessage;
}
protected void OptionallyCloseResponseStreamAndSetSuccess<T>(
ITransportRequestState requestState,
ElasticsearchServerError error,
ElasticsearchResponse<T> typedResponse,
ElasticsearchResponse<Stream> streamResponse)
{
if (streamResponse.Response != null && !typeof(Stream).IsAssignableFrom(typeof(T)))
streamResponse.Response.Close();
if (error != null)
{
typedResponse.Success = false;
if (typedResponse.OriginalException == null)
typedResponse.OriginalException = new ElasticsearchServerException(error);
}
//TODO UNIT TEST OR BEGONE
if (!typedResponse.Success
&& requestState.RequestConfiguration != null
&& requestState.RequestConfiguration.AllowedStatusCodes.HasAny(i => i == streamResponse.HttpStatusCode))
{
typedResponse.Success = true;
}
}
protected void SetStringResult(ElasticsearchResponse<string> response, byte[] rawResponse)
{
response.Response = rawResponse.Utf8String();
}
protected void SetByteResult(ElasticsearchResponse<byte[]> response, byte[] rawResponse)
{
response.Response = rawResponse;
}
protected ElasticsearchServerError GetErrorFromStream<T>(Stream stream)
{
try
{
var e = this._serializer.Deserialize<OneToOneServerException>(stream);
return ElasticsearchServerError.Create(e);
}
// ReSharper disable once EmptyGeneralCatchClause
// parsing failure of exception should not be fatal, its a best case helper.
catch { }
return null;
}
/// <summary>
/// Sniffs when the cluster state is stale, when sniffing returns a 401 return a response for T to return directly
/// </summary>
protected ElasticsearchResponse<T> TrySniffOnStaleClusterState<T>(TransportRequestState<T> requestState)
{
try
{
//If connectionSettings is configured to sniff periodically, sniff when stale.
this._delegator.SniffOnStaleClusterState(requestState);
return null;
}
catch(ElasticsearchAuthException e)
{
return this.HandleAuthenticationException(requestState, e);
}
}
protected ElasticsearchResponse<T> HandleAuthenticationException<T>(TransportRequestState<T> requestState, ElasticsearchAuthException exception)
{
if (requestState.ClientSettings.ThrowOnElasticsearchServerExceptions)
throw exception.ToElasticsearchServerException();
var response = ElasticsearchResponse.CloneFrom<T>(exception.Response, default(T));
response.Request = requestState.PostData;
response.RequestUrl = requestState.Path;
response.RequestMethod = requestState.Method;
return response;
}
}
} | 36.120623 | 146 | 0.749111 | [
"Apache-2.0"
] | bgiromini/NEST | src/Elasticsearch.Net/Connection/RequestHandlers/RequestHandlerBase.cs | 9,283 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using HarmonyLib;
namespace Explorer
{
public class Hooks
{
// *************** FIX DEBUG AREA SWITCH NAMES *********** //
[HarmonyPatch(typeof(DT_CharacterCheats), "InitAreaSwitches")]
public class DT_CharacterCheats_InitAreaSwitches
{
[HarmonyPostfix]
public static void Postfix(DT_CharacterCheats __instance)
{
var self = __instance;
var families = At.GetValue(typeof(DT_CharacterCheats), self, "m_ddFamilies") as Dropdown[];
foreach (var dd in families)
{
if (dd == null) { continue; }
var trigger = dd.GetComponent<EventTrigger>();
if (trigger == null) { continue; }
var _event = new EventTrigger.Entry()
{
eventID = EventTriggerType.PointerUp
};
_event.callback.AddListener(delegate (BaseEventData data) { OnAreaSelected(dd); });
trigger.triggers.Add(_event);
}
}
}
private static void OnAreaSelected(Dropdown dd)
{
foreach (var option in dd.options)
{
if (SceneBuildNames.ContainsKey(option.text))
{
option.text = SceneBuildNames[option.text];
}
}
}
public static Dictionary<string, string> SceneBuildNames = new Dictionary<string, string>
{
{ "CierzoTutorial", "Shipwreck Beach" },
{ "CierzoNewTerrain", "Cierzo" },
{ "CierzoDestroyed", "Cierzo (Destroyed)" },
{ "ChersoneseNewTerrain", "Chersonese" },
{ "Chersonese_Dungeon1", "Vendavel Fortress" },
{ "Chersonese_Dungeon2", "Blister Burrow" },
{ "Chersonese_Dungeon3", "Ghost Pass" },
{ "Chersonese_Dungeon4_BlueChamber", "Blue Chamber’s Conflux Path" },
{ "Chersonese_Dungeon4_HolyMission", "Holy Mission’s Conflux Path" },
{ "Chersonese_Dungeon4_Levant", "Heroic Kingdom’s Conflux Path" },
{ "Chersonese_Dungeon5", "Voltaic Hatchery" },
{ "Chersonese_Dungeon4_CommonPath", "Conflux Chambers" },
{ "Chersonese_Dungeon6", "Corrupted Tombs" },
{ "Chersonese_Dungeon8", "Cierzo Storage" },
{ "Chersonese_Dungeon9", "Montcalm Clan Fort" },
{ "ChersoneseDungeonsSmall", "Chersonese Misc. Dungeons" },
{ "ChersoneseDungeonsBosses", "Unknown Arena" },
{ "Monsoon", "Monsoon" },
{ "HallowedMarshNewTerrain", "Hallowed Marsh" },
{ "Hallowed_Dungeon1", "Jade Quarry" },
{ "Hallowed_Dungeon2", "Giants’ Village" },
{ "Hallowed_Dungeon3", "Reptilian Lair" },
{ "Hallowed_Dungeon4_Interior", "Dark Ziggurat Interior" },
{ "Hallowed_Dungeon5", "Spire of Light" },
{ "Hallowed_Dungeon6", "Ziggurat Passage" },
{ "Hallowed_Dungeon7", "Dead Roots" },
{ "HallowedDungeonsSmall", "Marsh Misc. Dungeons" },
{ "HallowedDungeonsBosses", "Unknown Arena" },
{ "Levant", "Levant" },
{ "Abrassar", "Abrassar" },
{ "Abrassar_Dungeon1", "Undercity Passage" },
{ "Abrassar_Dungeon2", "Electric Lab" },
{ "Abrassar_Dungeon3", "The Slide" },
{ "Abrassar_Dungeon4", "Stone Titan Caves" },
{ "Abrassar_Dungeon5", "Ancient Hive" },
{ "Abrassar_Dungeon6", "Sand Rose Cave" },
{ "AbrassarDungeonsSmall", "Abrassar Misc. Dungeons" },
{ "AbrassarDungeonsBosses", "Unknown Arena" },
{ "Berg", "Berg" },
{ "Emercar", "Enmerkar Forest" },
{ "Emercar_Dungeon1", "Royal Manticore’s Lair" },
{ "Emercar_Dungeon2", "Forest Hives" },
{ "Emercar_Dungeon3", "Cabal of Wind Temple" },
{ "Emercar_Dungeon4", "Face of the Ancients" },
{ "Emercar_Dungeon5", "Ancestor’s Resting Place" },
{ "Emercar_Dungeon6", "Necropolis" },
{ "EmercarDungeonsSmall", "Enmerkar Misc. Dungeons" },
{ "EmercarDungeonsBosses", "Unknown Arena" },
{ "DreamWorld", "In Between" },
};
// ****************** SKIP LOGOS HOOK ********************** //
[HarmonyPatch(typeof(StartupVideo), "Start")]
public class StartupVideo_Start
{
[HarmonyPrefix]
public static void Prefix()
{
StartupVideo.HasPlayedOnce = true;
}
}
// ********************* QUEST HOOKS ********************* //
[HarmonyPatch(typeof(SendQuestEventInteraction), "OnActivate")]
public class SendQuestEventInteraction_OnActivate
{
public static void Prefix(SendQuestEventInteraction __instance)
{
var self = __instance;
var _ref = At.GetValue(typeof(SendQuestEventInteraction), self, "m_questReference") as QuestEventReference;
var _event = _ref.Event;
var s = _ref.EventUID;
if (_event != null && s != null)
{
LogQuestEvent(_event, -1);
}
}
}
[HarmonyPatch(typeof(NodeCanvas.Tasks.Actions.SendQuestEvent), "OnExecute")]
public class SendQuestEvent_OnExecute
{
[HarmonyPrefix]
public static void Prefix(NodeCanvas.Tasks.Actions.SendQuestEvent __instance)
{
var self = __instance;
var _event = self.QuestEventRef.Event;
//var s = self.QuestEventRef.EventUID;
if (_event != null)
{
LogQuestEvent(_event, self.StackAmount);
}
}
}
public static void LogQuestEvent(QuestEventSignature _event, int stack = -1)
{
if (Explorer.QuestDebugging)
{
Debug.LogWarning(
"------ ADDING QUEST EVENT -------" +
"\r\nName: " + _event.EventName +
"\r\nDescription: " + _event.Description +
(stack == -1 ? "" : "\r\nStack: " + stack) +
"\r\n---------------------------");
}
}
}
}
| 39.046784 | 123 | 0.519545 | [
"MIT"
] | botchi09/Outward-Mods | Explorer/Explorer/Hooks.cs | 6,691 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.Coyote.Actors;
using Microsoft.Coyote.Runtime;
using Microsoft.Coyote.SystematicTesting;
namespace Microsoft.Coyote.Samples.CloudMessaging
{
public static class Program
{
[Test]
public static void Execute(IActorRuntime runtime)
{
var testScenario = new RaftTestScenario();
testScenario.RunTest(runtime, 5, 2);
}
}
}
| 23.9 | 57 | 0.677824 | [
"MIT"
] | Bhaskers-Blu-Org2/coyote-samples | CloudMessaging/Raft.Mocking/Program.cs | 480 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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
using System;
using System.Collections.Generic;
using System.Text;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Tests.Bson;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
[TestFixture]
public class JPathExecuteTests : TestFixtureBase
{
[Test]
public void ParseWithEmptyArrayContent()
{
var json = @"{
'controls': [
{
'messages': {
'addSuggestion': {
'en-US': 'Add'
}
}
},
{
'header': {
'controls': []
},
'controls': [
{
'controls': [
{
'defaultCaption': {
'en-US': 'Sort by'
},
'sortOptions': [
{
'label': {
'en-US': 'Name'
}
}
]
}
]
}
]
}
]
}";
JObject jToken = JObject.Parse(json);
IList<JToken> tokens = jToken.SelectTokens("$..en-US").ToList();
Assert.AreEqual(3, tokens.Count);
Assert.AreEqual("Add", (string)tokens[0]);
Assert.AreEqual("Sort by", (string)tokens[1]);
Assert.AreEqual("Name", (string)tokens[2]);
}
[Test]
public void SelectTokenAfterEmptyContainer()
{
string json = @"{
'cont': [],
'test': 'no one will find me'
}";
JObject o = JObject.Parse(json);
IList<JToken> results = o.SelectTokens("$..test").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual("no one will find me", (string)results[0]);
}
[Test]
public void EvaluatePropertyWithRequired()
{
string json = "{\"bookId\":\"1000\"}";
JObject o = JObject.Parse(json);
string bookId = (string)o.SelectToken("bookId", true);
Assert.AreEqual("1000", bookId);
}
[Test]
public void EvaluateEmptyPropertyIndexer()
{
JObject o = new JObject(
new JProperty("", 1));
JToken t = o.SelectToken("['']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateEmptyString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("");
Assert.AreEqual(o, t);
t = o.SelectToken("['']");
Assert.AreEqual(null, t);
}
[Test]
public void EvaluateEmptyStringWithMatchingEmptyProperty()
{
JObject o = new JObject(
new JProperty(" ", 1));
JToken t = o.SelectToken("[' ']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWhitespaceString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken(" ");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("$");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarTypeString()
{
JObject o = new JObject(
new JProperty("$values", new JArray(1, 2, 3)));
JToken t = o.SelectToken("$values[1]");
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWildcardProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1),
new JProperty("Blah2", 2));
IList<JToken> t = o.SelectTokens("$.*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void QuoteName()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("['Blah']");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject.");
}
[Test]
public void EvaluateWildcardIndexOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
}
[Test]
public void EvaluateSliceOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
public void EvaluateMultipleResultsError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens.");
}
[Test]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray.");
}
[Test]
public void EvaluateNoResultsWithMultipleArrayIndexes()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxerWithError()
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxer()
{
JConstructor c = new JConstructor("Blah");
Assert.IsNull(c.SelectToken("[1]"));
}
[Test]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluatePropertyWithoutError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JValue v = (JValue)o.SelectToken("Blah", true);
Assert.AreEqual(1, v.Value);
}
[Test]
public void EvaluateMissingPropertyIndexWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluateMultiPropertyIndexOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray.");
}
[Test]
public void EvaluateArraySliceWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results.");
a = new JArray();
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results.");
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
public void EvaluateArrayOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray.");
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateArraySlice()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
IList<JToken> t = null;
t = a.SelectTokens("[-3:]").ToList();
Assert.AreEqual(3, t.Count);
Assert.AreEqual(7, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(9, (int)t[2]);
t = a.SelectTokens("[-1:-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(9, (int)t[0]);
t = a.SelectTokens("[-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(8, (int)t[0]);
t = a.SelectTokens("[1:1]").ToList();
Assert.AreEqual(0, t.Count);
t = a.SelectTokens("[1:2]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(2, (int)t[0]);
t = a.SelectTokens("[::-1]").ToList();
Assert.AreEqual(9, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(7, (int)t[2]);
Assert.AreEqual(6, (int)t[3]);
Assert.AreEqual(5, (int)t[4]);
Assert.AreEqual(4, (int)t[5]);
Assert.AreEqual(3, (int)t[6]);
Assert.AreEqual(2, (int)t[7]);
Assert.AreEqual(1, (int)t[8]);
t = a.SelectTokens("[::-2]").ToList();
Assert.AreEqual(5, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(7, (int)t[1]);
Assert.AreEqual(5, (int)t[2]);
Assert.AreEqual(3, (int)t[3]);
Assert.AreEqual(1, (int)t[4]);
}
[Test]
public void EvaluateWildcardArray()
{
JArray a = new JArray(1, 2, 3, 4);
List<JToken> t = a.SelectTokens("[*]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.AreEqual(3, (int)t[2]);
Assert.AreEqual(4, (int)t[3]);
}
[Test]
public void EvaluateArrayMultipleIndexes()
{
JArray a = new JArray(1, 2, 3, 4);
IEnumerable<JToken> t = a.SelectTokens("[1,2,0]");
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Count());
Assert.AreEqual(2, (int)t.ElementAt(0));
Assert.AreEqual(3, (int)t.ElementAt(1));
Assert.AreEqual(1, (int)t.ElementAt(2));
}
[Test]
public void EvaluateScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void EvaluateWildcardScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(5, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
}
[Test]
public void EvaluateScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3]));
}
[Test]
public void EvaluateWildcardScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(9, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
Assert.IsTrue(JToken.DeepEquals(o3, t[5]));
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7]));
Assert.AreEqual(3, (int)t[8]);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new[] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void ExistsQuery()
{
JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0]));
}
[Test]
public void EqualsQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", "ho")),
new JObject(new JProperty("hi", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0]));
}
[Test]
public void NotEqualsQuery()
{
JArray a = new JArray(
new JArray(new JObject(new JProperty("hi", "ho"))),
new JArray(new JObject(new JProperty("hi", "ha"))));
IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0]));
}
[Test]
public void NoPathQuery()
{
JArray a = new JArray(1, 2, 3);
IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(2, (int)t[0]);
Assert.AreEqual(3, (int)t[1]);
}
[Test]
public void MultipleQueries()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
// json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/
// first query resolves array to ints
// int has no children to query
IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(0, t.Count);
}
[Test]
public void GreaterQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20)
[Test]
public void GreaterQueryBigInteger()
{
JArray a = new JArray(
new JObject(new JProperty("hi", new BigInteger(1))),
new JObject(new JProperty("hi", new BigInteger(2))),
new JObject(new JProperty("hi", new BigInteger(3))));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#endif
[Test]
public void GreaterOrEqualQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 2.0)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3]));
}
[Test]
public void NestedQuery()
{
JArray a = new JArray(
new JObject(
new JProperty("name", "Bad Boys"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "Independence Day"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "The Rock"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Nick Cage")))))
);
IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual("Bad Boys", (string)t[0]);
Assert.AreEqual("Independence Day", (string)t[1]);
}
[Test]
public void PathWithConstructor()
{
JArray a = JArray.Parse(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]");
JValue v = (JValue)a.SelectToken("[1].Property2[1][0]");
Assert.AreEqual(1L, v.Value);
}
[Test]
public void WildcardWithProperty()
{
JObject o = JObject.Parse(@"{
""station"": 92000041000001,
""containers"": [
{
""id"": 1,
""text"": ""Sort system"",
""containers"": [
{
""id"": ""2"",
""text"": ""Yard 11""
},
{
""id"": ""92000020100006"",
""text"": ""Sort yard 12""
},
{
""id"": ""92000020100005"",
""text"": ""Yard 13""
}
]
},
{
""id"": ""92000020100011"",
""text"": ""TSP-1""
},
{
""id"":""92000020100007"",
""text"": ""Passenger 15""
}
]
}");
IList<JToken> tokens = o.SelectTokens("$..*[?(@.text)]").ToList();
int i = 0;
Assert.AreEqual("Sort system", (string)tokens[i++]["text"]);
Assert.AreEqual("TSP-1", (string)tokens[i++]["text"]);
Assert.AreEqual("Passenger 15", (string)tokens[i++]["text"]);
Assert.AreEqual("Yard 11", (string)tokens[i++]["text"]);
Assert.AreEqual("Sort yard 12", (string)tokens[i++]["text"]);
Assert.AreEqual("Yard 13", (string)tokens[i++]["text"]);
Assert.AreEqual(6, tokens.Count);
}
[Test]
public void QueryAgainstNonStringValues()
{
IList<object> values = new List<object>
{
"ff2dc672-6e15-4aa2-afb0-18f4f69596ad",
new Guid("ff2dc672-6e15-4aa2-afb0-18f4f69596ad"),
"http://localhost",
new Uri("http://localhost"),
"2000-12-05T05:07:59Z",
new DateTime(2000, 12, 5, 5, 7, 59, DateTimeKind.Utc),
#if !NET20
"2000-12-05T05:07:59-10:00",
new DateTimeOffset(2000, 12, 5, 5, 7, 59, -TimeSpan.FromHours(10)),
#endif
"SGVsbG8gd29ybGQ=",
Encoding.UTF8.GetBytes("Hello world"),
"365.23:59:59",
new TimeSpan(365, 23, 59, 59)
};
JObject o = new JObject(
new JProperty("prop",
new JArray(
values.Select(v => new JObject(new JProperty("childProp", v)))
)
)
);
IList<JToken> t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='http://localhost')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59Z')]").ToList();
Assert.AreEqual(2, t.Count);
#if !NET20
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59-10:00')]").ToList();
Assert.AreEqual(2, t.Count);
#endif
t = o.SelectTokens("$.prop[?(@.childProp =='SGVsbG8gd29ybGQ=')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='365.23:59:59')]").ToList();
Assert.AreEqual(2, t.Count);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
}
} | 32.995585 | 165 | 0.49438 | [
"MIT"
] | CallumCarmicheal/Keyboard-Tracker | dep/JSON.Net/Source/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs | 29,894 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.NetAppFiles.Models
{
/// <summary>
/// ARM tracked resource
/// </summary>
public class PSNetAppFilesAccount
{
/// <summary>
/// Gets or sets the Resource group name
/// </summary>
public string ResourceGroupName { get; set; }
/// <summary>
/// Gets or sets Resource location
/// </summary>
public string Location { get; set; }
/// <summary>
/// Gets resource Id
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets resource name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets resource type
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets resource tags
/// </summary>
public object Tags { get; set; }
/// <summary>
/// Gets or sets resource etag
/// </summary>
/// <remarks>
/// A unique read-only string that changes whenever the resource is updated.
/// </remarks>
public string Etag { get; set; }
/// <summary>
/// Gets azure lifecycle management
/// </summary>
public string ProvisioningState { get; set; }
/// <summary>
/// Gets or sets active directory
/// </summary>
public List<PSNetAppFilesActiveDirectory> ActiveDirectories { get; set; }
/// <summary>
/// Gets or sets System Data
/// </summary>
public PSSystemData SystemData { get; set; }
}
} | 32.519481 | 86 | 0.525958 | [
"MIT"
] | AlanFlorance/azure-powershell | src/NetAppFiles/NetAppFiles/Models/PSNetAppFilesAccount.cs | 2,428 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eto.Forms;
using aa = Android.App;
using ac = Android.Content;
using ao = Android.OS;
using ar = Android.Runtime;
using av = Android.Views;
using aw = Android.Widget;
using ag = Android.Graphics;
namespace Eto.Android.Forms.Controls
{
/// <summary>
/// Handler for <see cref="Panel"/>
/// </summary>
/// <copyright>(c) 2013 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class PanelHandler : AndroidPanel<av.View, Panel, Panel.ICallback>, Panel.IHandler
{
public override av.View ContainerControl { get { return InnerFrame; } }
protected override void SetContent(av.View content)
{
}
}
} | 25.033333 | 90 | 0.720373 | [
"BSD-3-Clause"
] | 745564106/Eto | src/Eto.Android/Forms/Controls/PanelHandler.cs | 751 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace SkorubaIdentityServer4Admin.STS.Identity.Quickstart.Consent
{
public class ProcessConsentResult
{
public bool IsRedirect => RedirectUri != null;
public string RedirectUri { get; set; }
public bool ShowView => ViewModel != null;
public ConsentViewModel ViewModel { get; set; }
public bool HasValidationError => ValidationError != null;
public string ValidationError { get; set; }
}
}
| 33.368421 | 107 | 0.697161 | [
"MIT"
] | H-Ahmadi/GodOfWar | STS/templates/template-publish/content/src/SkorubaIdentityServer4Admin.STS.Identity/Quickstart/Consent/ProcessConsentResult.cs | 636 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SGEP.Banco;
namespace SGEP.Migrations
{
[DbContext(typeof(ContextoBD))]
[Migration("20190911173637_Migracao")]
partial class Migracao
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.11-servicing-32099")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SGEP.Models.Funcionario", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Cargo");
b.Property<string>("Nome");
b.HasKey("Id");
b.ToTable("Funcionario");
});
modelBuilder.Entity("SGEP.Models.Material", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Nome");
b.Property<decimal>("Preco")
.HasColumnType("decimal(27, 2)");
b.Property<decimal>("Quantidade");
b.Property<string>("Unidade");
b.HasKey("Id");
b.ToTable("Material");
});
modelBuilder.Entity("SGEP.Models.Projeto", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime?>("DataFim");
b.Property<DateTime>("DataInicio");
b.Property<string>("Estado")
.IsRequired();
b.Property<string>("Nome");
b.Property<DateTime>("PrazoEstimado");
b.HasKey("Id");
b.ToTable("Projeto");
});
#pragma warning restore 612, 618
}
}
}
| 29.151899 | 76 | 0.477638 | [
"MIT"
] | RevolverOcelotIII/SGEP | SGEP/Migrations/20190911173637_Migracao.Designer.cs | 2,305 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace XecMe.Configuration
{
/// <summary>
/// Custom configuration element that has just 2 properties viz. name and value
/// </summary>
public class KeyValueConfigurationElement: ConfigurationElement
{
#region Constants
private const string VALUE = "value";
private const string NAME = "name";
#endregion
/// <summary>
/// Gets or sets the value of the property associated with the configuration element
/// </summary>
[ConfigurationProperty(VALUE, IsRequired = true)]
public string Value
{
get { return (string)base[VALUE]; }
set { base[VALUE] = value; }
}
/// <summary>
/// Gets or sets the name of the property associated with the configuration element
/// </summary>
[ConfigurationProperty(NAME, IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)base[NAME]; }
set { base[NAME] = value; }
}
}
}
| 28.625 | 92 | 0.59738 | [
"MIT"
] | slolam/xecme | src/Configuration/KeyValueConfigurationElement.cs | 1,147 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// AlipayDataDataserviceDmpserviceCreateModel Data Structure.
/// </summary>
public class AlipayDataDataserviceDmpserviceCreateModel : AlipayObject
{
/// <summary>
/// 转化id event_type = 1时必填
/// </summary>
[JsonPropertyName("conversion_id")]
public long ConversionId { get; set; }
/// <summary>
/// 转化时间 event_type = 1时必填
/// </summary>
[JsonPropertyName("conversion_time")]
public string ConversionTime { get; set; }
/// <summary>
/// 转化类型,0-表单提交,1-客户资讯搜集,2-商品加购物车,3-订单提交,4-我要投保,5-保险交易笔数,6-保险交易金额,7-基金交易笔数,8-基金交易金额 event_type = 1时必填
/// </summary>
[JsonPropertyName("conversion_type")]
public string ConversionType { get; set; }
/// <summary>
/// 设备id device_id和user_id不能同时为空
/// </summary>
[JsonPropertyName("device_id")]
public string DeviceId { get; set; }
/// <summary>
/// 设备类型, 0:imei, 1:idfa, 2:imei_md5, 3:imei_sha256, 4:idfa_md5, 5:idfa_sha256 设备类型和device_id是同时存在 device_id和user_id不能同时为空
/// </summary>
[JsonPropertyName("device_type")]
public long DeviceType { get; set; }
/// <summary>
/// 0-落地页到达事件 1-转化事件
/// </summary>
[JsonPropertyName("event_type")]
public long EventType { get; set; }
/// <summary>
/// 扩展字段,json格式存储,列表里面包含kv
/// </summary>
[JsonPropertyName("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 1:转化, 0:非转化 event_type = 1时必填
/// </summary>
[JsonPropertyName("is_conversion")]
public long IsConversion { get; set; }
/// <summary>
/// 请求id
/// </summary>
[JsonPropertyName("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 数据来源,如来源数立,可以SL
/// </summary>
[JsonPropertyName("source")]
public string Source { get; set; }
/// <summary>
/// 当前访问的url encode后的字符串
/// </summary>
[JsonPropertyName("track_url")]
public string TrackUrl { get; set; }
/// <summary>
/// 用户id 设备id和用户id不能同时为空
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
| 29.493976 | 131 | 0.553513 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/AlipayDataDataserviceDmpserviceCreateModel.cs | 2,808 | C# |
namespace Service
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Wonder")]
public partial class Wonder
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
}
}
| 21.684211 | 55 | 0.645631 | [
"MIT"
] | bashnia007/Citadels | CitadelsApp/Service/Wonder.cs | 412 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Win32;
//using System.Linq;
using Au.Types;
namespace Au.Util
{
/// <summary>
/// Activates our manifest which tells to use comctl32.dll version 6.
/// The manifest is embedded in this dll, resource id 2.
/// </summary>
internal sealed class ActCtx_ :IDisposable
{
IntPtr _cookie;
public static ActCtx_ Activate()
{
if(s_actCtx.Handle == default || !Api.ActivateActCtx(s_actCtx.Handle, out var cookie)) return default;
return new ActCtx_() { _cookie = cookie };
}
public void Dispose()
{
if(_cookie != default) {
Api.DeactivateActCtx(0, _cookie);
_cookie = default;
}
}
static _ActCtx s_actCtx = new _ActCtx();
class _ActCtx
{
public IntPtr Handle;
public _ActCtx()
{
Api.ACTCTX a = default;
a.cbSize = Api.SizeOf<Api.ACTCTX>();
a.lpSource = Assembly.GetExecutingAssembly().Location;
a.lpResourceName = (IntPtr)2;
a.dwFlags = Api.ACTCTX_FLAG_RESOURCE_NAME_VALID;
var h = Api.CreateActCtx(a);
if(h != (IntPtr)(-1)) Handle = h;
}
~_ActCtx()
{
if(Handle != default) {
Api.ReleaseActCtx(Handle);
Handle = default;
}
}
}
}
}
| 20.828571 | 105 | 0.683128 | [
"MIT"
] | alexfordc/Au | _Au/Util/Internal/ActCtx_.cs | 1,460 | C# |
// <auto-generated />
// Built from: hl7.fhir.r4.core version: 4.0.1
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Fhir.R4.Serialization;
namespace Fhir.R4.Models
{
/// <summary>
/// Describes a comparison of an immunization event against published recommendations to determine if the administration is "valid" in relation to those recommendations.
/// </summary>
[JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ImmunizationEvaluation>))]
public class ImmunizationEvaluation : DomainResource, IFhirJsonSerializable {
/// <summary>
/// Resource Type Name
/// </summary>
public string ResourceType => "ImmunizationEvaluation";
/// <summary>
/// Indicates the authority who published the protocol (e.g. ACIP).
/// </summary>
public Reference Authority { get; set; }
/// <summary>
/// The date the evaluation of the vaccine administration event was performed.
/// </summary>
public string Date { get; set; }
/// <summary>
/// Extension container element for Date
/// </summary>
public Element _Date { get; set; }
/// <summary>
/// Additional information about the evaluation.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Extension container element for Description
/// </summary>
public Element _Description { get; set; }
/// <summary>
/// The use of an integer is preferred if known. A string should only be used in cases where an integer is not available (such as when documenting a recurring booster dose).
/// </summary>
public uint? DoseNumberPositiveInt { get; set; }
/// <summary>
/// The use of an integer is preferred if known. A string should only be used in cases where an integer is not available (such as when documenting a recurring booster dose).
/// </summary>
public string DoseNumberString { get; set; }
/// <summary>
/// Extension container element for DoseNumberString
/// </summary>
public Element _DoseNumberString { get; set; }
/// <summary>
/// Indicates if the dose is valid or not valid with respect to the published recommendations.
/// </summary>
public CodeableConcept DoseStatus { get; set; }
/// <summary>
/// Provides an explanation as to why the vaccine administration event is valid or not relative to the published recommendations.
/// </summary>
public List<CodeableConcept> DoseStatusReason { get; set; }
/// <summary>
/// A unique identifier assigned to this immunization evaluation record.
/// </summary>
public List<Identifier> Identifier { get; set; }
/// <summary>
/// The vaccine administration event being evaluated.
/// </summary>
public Reference ImmunizationEvent { get; set; }
/// <summary>
/// The individual for whom the evaluation is being done.
/// </summary>
public Reference Patient { get; set; }
/// <summary>
/// One possible path to achieve presumed immunity against a disease - within the context of an authority.
/// </summary>
public string Series { get; set; }
/// <summary>
/// Extension container element for Series
/// </summary>
public Element _Series { get; set; }
/// <summary>
/// The use of an integer is preferred if known. A string should only be used in cases where an integer is not available (such as when documenting a recurring booster dose).
/// </summary>
public uint? SeriesDosesPositiveInt { get; set; }
/// <summary>
/// The use of an integer is preferred if known. A string should only be used in cases where an integer is not available (such as when documenting a recurring booster dose).
/// </summary>
public string SeriesDosesString { get; set; }
/// <summary>
/// Extension container element for SeriesDosesString
/// </summary>
public Element _SeriesDosesString { get; set; }
/// <summary>
/// Indicates the current status of the evaluation of the vaccination administration event.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Extension container element for Status
/// </summary>
public Element _Status { get; set; }
/// <summary>
/// The vaccine preventable disease the dose is being evaluated against.
/// </summary>
public CodeableConcept TargetDisease { get; set; }
/// <summary>
/// Serialize to a JSON object
/// </summary>
public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
{
if (includeStartObject)
{
writer.WriteStartObject();
}
if (!string.IsNullOrEmpty(ResourceType))
{
writer.WriteString("resourceType", (string)ResourceType!);
}
((Fhir.R4.Models.DomainResource)this).SerializeJson(writer, options, false);
if ((Identifier != null) && (Identifier.Count != 0))
{
writer.WritePropertyName("identifier");
writer.WriteStartArray();
foreach (Identifier valIdentifier in Identifier)
{
valIdentifier.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if (!string.IsNullOrEmpty(Status))
{
writer.WriteString("status", (string)Status!);
}
if (_Status != null)
{
writer.WritePropertyName("_status");
_Status.SerializeJson(writer, options);
}
if (Patient != null)
{
writer.WritePropertyName("patient");
Patient.SerializeJson(writer, options);
}
if (!string.IsNullOrEmpty(Date))
{
writer.WriteString("date", (string)Date!);
}
if (_Date != null)
{
writer.WritePropertyName("_date");
_Date.SerializeJson(writer, options);
}
if (Authority != null)
{
writer.WritePropertyName("authority");
Authority.SerializeJson(writer, options);
}
if (TargetDisease != null)
{
writer.WritePropertyName("targetDisease");
TargetDisease.SerializeJson(writer, options);
}
if (ImmunizationEvent != null)
{
writer.WritePropertyName("immunizationEvent");
ImmunizationEvent.SerializeJson(writer, options);
}
if (DoseStatus != null)
{
writer.WritePropertyName("doseStatus");
DoseStatus.SerializeJson(writer, options);
}
if ((DoseStatusReason != null) && (DoseStatusReason.Count != 0))
{
writer.WritePropertyName("doseStatusReason");
writer.WriteStartArray();
foreach (CodeableConcept valDoseStatusReason in DoseStatusReason)
{
valDoseStatusReason.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if (!string.IsNullOrEmpty(Description))
{
writer.WriteString("description", (string)Description!);
}
if (_Description != null)
{
writer.WritePropertyName("_description");
_Description.SerializeJson(writer, options);
}
if (!string.IsNullOrEmpty(Series))
{
writer.WriteString("series", (string)Series!);
}
if (_Series != null)
{
writer.WritePropertyName("_series");
_Series.SerializeJson(writer, options);
}
if (DoseNumberPositiveInt != null)
{
writer.WriteNumber("doseNumberPositiveInt", (uint)DoseNumberPositiveInt!);
}
if (!string.IsNullOrEmpty(DoseNumberString))
{
writer.WriteString("doseNumberString", (string)DoseNumberString!);
}
if (_DoseNumberString != null)
{
writer.WritePropertyName("_doseNumberString");
_DoseNumberString.SerializeJson(writer, options);
}
if (SeriesDosesPositiveInt != null)
{
writer.WriteNumber("seriesDosesPositiveInt", (uint)SeriesDosesPositiveInt!);
}
if (!string.IsNullOrEmpty(SeriesDosesString))
{
writer.WriteString("seriesDosesString", (string)SeriesDosesString!);
}
if (_SeriesDosesString != null)
{
writer.WritePropertyName("_seriesDosesString");
_SeriesDosesString.SerializeJson(writer, options);
}
if (includeStartObject)
{
writer.WriteEndObject();
}
}
/// <summary>
/// Deserialize a JSON property
/// </summary>
public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
{
switch (propertyName)
{
case "authority":
Authority = new Fhir.R4.Models.Reference();
Authority.DeserializeJson(ref reader, options);
break;
case "date":
Date = reader.GetString();
break;
case "_date":
_Date = new Fhir.R4.Models.Element();
_Date.DeserializeJson(ref reader, options);
break;
case "description":
Description = reader.GetString();
break;
case "_description":
_Description = new Fhir.R4.Models.Element();
_Description.DeserializeJson(ref reader, options);
break;
case "doseNumberPositiveInt":
DoseNumberPositiveInt = reader.GetUInt32();
break;
case "doseNumberString":
DoseNumberString = reader.GetString();
break;
case "_doseNumberString":
_DoseNumberString = new Fhir.R4.Models.Element();
_DoseNumberString.DeserializeJson(ref reader, options);
break;
case "doseStatus":
DoseStatus = new Fhir.R4.Models.CodeableConcept();
DoseStatus.DeserializeJson(ref reader, options);
break;
case "doseStatusReason":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
DoseStatusReason = new List<CodeableConcept>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Fhir.R4.Models.CodeableConcept objDoseStatusReason = new Fhir.R4.Models.CodeableConcept();
objDoseStatusReason.DeserializeJson(ref reader, options);
DoseStatusReason.Add(objDoseStatusReason);
if (!reader.Read())
{
throw new JsonException();
}
}
if (DoseStatusReason.Count == 0)
{
DoseStatusReason = null;
}
break;
case "identifier":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
Identifier = new List<Identifier>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Fhir.R4.Models.Identifier objIdentifier = new Fhir.R4.Models.Identifier();
objIdentifier.DeserializeJson(ref reader, options);
Identifier.Add(objIdentifier);
if (!reader.Read())
{
throw new JsonException();
}
}
if (Identifier.Count == 0)
{
Identifier = null;
}
break;
case "immunizationEvent":
ImmunizationEvent = new Fhir.R4.Models.Reference();
ImmunizationEvent.DeserializeJson(ref reader, options);
break;
case "patient":
Patient = new Fhir.R4.Models.Reference();
Patient.DeserializeJson(ref reader, options);
break;
case "series":
Series = reader.GetString();
break;
case "_series":
_Series = new Fhir.R4.Models.Element();
_Series.DeserializeJson(ref reader, options);
break;
case "seriesDosesPositiveInt":
SeriesDosesPositiveInt = reader.GetUInt32();
break;
case "seriesDosesString":
SeriesDosesString = reader.GetString();
break;
case "_seriesDosesString":
_SeriesDosesString = new Fhir.R4.Models.Element();
_SeriesDosesString.DeserializeJson(ref reader, options);
break;
case "status":
Status = reader.GetString();
break;
case "_status":
_Status = new Fhir.R4.Models.Element();
_Status.DeserializeJson(ref reader, options);
break;
case "targetDisease":
TargetDisease = new Fhir.R4.Models.CodeableConcept();
TargetDisease.DeserializeJson(ref reader, options);
break;
default:
((Fhir.R4.Models.DomainResource)this).DeserializeJsonProperty(ref reader, options, propertyName);
break;
}
}
/// <summary>
/// Deserialize a JSON object
/// </summary>
public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
string propertyName;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
this.DeserializeJsonProperty(ref reader, options, propertyName);
}
}
throw new JsonException();
}
}
}
| 30.588636 | 177 | 0.610892 | [
"MIT"
] | QPC-database/fhir-codegen | test/perfTestCS/R4/Models/ImmunizationEvaluation.cs | 13,459 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client20181.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class IEdmTerm
{
/// <summary>
/// Initializes a new instance of the IEdmTerm class.
/// </summary>
public IEdmTerm()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the IEdmTerm class.
/// </summary>
/// <param name="schemaElementKind">Possible values include: 'None',
/// 'TypeDefinition', 'Term', 'Action', 'EntityContainer',
/// 'Function'</param>
public IEdmTerm(IEdmTypeReference type = default(IEdmTypeReference), string appliesTo = default(string), string defaultValue = default(string), IEdmTermSchemaElementKind? schemaElementKind = default(IEdmTermSchemaElementKind?), string namespaceProperty = default(string), string name = default(string))
{
Type = type;
AppliesTo = appliesTo;
DefaultValue = defaultValue;
SchemaElementKind = schemaElementKind;
NamespaceProperty = namespaceProperty;
Name = name;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Type")]
public IEdmTypeReference Type { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "AppliesTo")]
public string AppliesTo { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "DefaultValue")]
public string DefaultValue { get; private set; }
/// <summary>
/// Gets possible values include: 'None', 'TypeDefinition', 'Term',
/// 'Action', 'EntityContainer', 'Function'
/// </summary>
[JsonProperty(PropertyName = "SchemaElementKind")]
public IEdmTermSchemaElementKind? SchemaElementKind { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Namespace")]
public string NamespaceProperty { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Name")]
public string Name { get; private set; }
}
}
| 33.666667 | 310 | 0.595583 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20181/Models/IEdmTerm.cs | 2,626 | C# |
#if !NET20
using System;
using System.Collections.Generic;
using KellermanSoftware.CompareNetObjects;
namespace AggregateSource.Testing.Comparers
{
/// <summary>
/// Compares exception using a <see cref="ICompareLogic"/> object and reports the differences.
/// </summary>
public class CompareNetObjectsBasedExceptionComparer : IExceptionComparer
{
private readonly ICompareLogic _logic;
/// <summary>
/// Initializes a new instance of the <see cref="CompareNetObjectsBasedExceptionComparer"/> class.
/// </summary>
/// <param name="logic">The compare logic.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="logic"/> is <c>null</c>.</exception>
public CompareNetObjectsBasedExceptionComparer(ICompareLogic logic)
{
if (logic == null) throw new ArgumentNullException("logic");
_logic = logic;
}
/// <summary>
/// Compares the expected to the actual exception.
/// </summary>
/// <param name="expected">The expected exception.</param>
/// <param name="actual">The actual exception.</param>
/// <returns>
/// An enumeration of <see cref="ExceptionComparisonDifference">differences</see>, or empty if none found.
/// </returns>
public IEnumerable<ExceptionComparisonDifference> Compare(Exception expected, Exception actual)
{
var result = _logic.Compare(expected, actual);
if (!result.AreEqual)
{
foreach (var difference in result.Differences)
{
yield return new ExceptionComparisonDifference(
expected,
actual,
difference.ToString());
}
}
}
}
}
#endif | 37.8 | 127 | 0.6 | [
"BSD-3-Clause"
] | ChrisMcKee/AggregateSource | src/Testing/AggregateSource.Testing/Comparers/CompareNetObjectsBasedExceptionComparer.cs | 1,892 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.MachineLearningServices.V20210301Preview.Inputs
{
/// <summary>
/// Defines an early termination policy based on slack criteria, and a frequency and delay interval for evaluation.
/// </summary>
public sealed class BanditPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Number of intervals by which to delay the first evaluation.
/// </summary>
[Input("delayEvaluation")]
public Input<int>? DelayEvaluation { get; set; }
/// <summary>
/// Interval (number of runs) between policy evaluations.
/// </summary>
[Input("evaluationInterval")]
public Input<int>? EvaluationInterval { get; set; }
/// <summary>
///
/// Expected value is 'Bandit'.
/// </summary>
[Input("policyType", required: true)]
public Input<string> PolicyType { get; set; } = null!;
/// <summary>
/// Absolute distance allowed from the best performing run.
/// </summary>
[Input("slackAmount")]
public Input<double>? SlackAmount { get; set; }
/// <summary>
/// Ratio of the allowed distance from the best performing run.
/// </summary>
[Input("slackFactor")]
public Input<double>? SlackFactor { get; set; }
public BanditPolicyArgs()
{
}
}
}
| 31.5 | 119 | 0.609053 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/MachineLearningServices/V20210301Preview/Inputs/BanditPolicyArgs.cs | 1,701 | C# |
/*
* Copyright (c) 2015 Andrew Johnson
*
* 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 Newtonsoft.Json;
using System;
using System.Linq;
using System.Runtime.Serialization;
namespace Indexer
{
/// <summary>
/// Represents an index file residing on disk
/// </summary>
[Serializable]
[JsonObject(MemberSerialization.OptIn)]
internal sealed class IndexEntries : IEquatable<IndexEntries>, ISerializable
{
public IndexEntries()
{
Entries = new IndexEntry[0];
}
public IndexEntries(SerializationInfo info, StreamingContext context)
{
Entries = (IndexEntry[])info.GetValue("Entries", typeof(IndexEntry[]));
}
/// <summary>
/// The array of entries in this index file
/// </summary>
[JsonProperty(PropertyName = "Entries", Required = Required.Always)]
public IndexEntry[] Entries { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Entries", Entries);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals(obj as IndexEntries);
}
public override int GetHashCode()
{
int runningHashCode = 0;
foreach (var e in Entries)
{
runningHashCode = runningHashCode ^ e.GetHashCode();
}
return runningHashCode;
}
public bool Equals(IndexEntries other)
{
if (other == null || GetType() != other.GetType())
{
return false;
}
if (this == other)
{
return true;
}
return Enumerable.SequenceEqual(Entries, other.Entries);
}
public override string ToString()
{
return string.Format("Index Entries with {0}", Entries);
}
}
}
| 32.505051 | 85 | 0.597265 | [
"MIT"
] | helios2k6/MobileImageProcessor | Indexer/IndexFile.cs | 3,220 | C# |
using System;
using DexNetwork.DexInterpreter.Commands;
namespace DexNetwork.DexInterpreter
{
public class CommandResolver
{
public CommandBase ResolveCommand(string input, IDexPromise dexPromise)
{
if (input.Contains("\n"))
return new MacroCommand(dexPromise);
string[] split = input.Split(' ');
if (InitCommand.CmdName.Equals(split[0].ToLower()))
return new InitCommand(dexPromise);
if (DexStatusInstructionCommand.CmdName.Equals(split[0].ToLower()))
return new DexStatusInstructionCommand(Verbosity.Critical, dexPromise);
if (LoginCommand.CmdName.Equals(split[0].ToLower()))
return new LoginCommand(dexPromise);
if (DexInfoInstructionCommand.CmdName.Equals(split[0].ToLower()))
return new DexInfoInstructionCommand(Verbosity.Critical, dexPromise);
if (DexTargetInstructionCommand.CmdName.Equals(split[0].ToLower()))
return new DexTargetInstructionCommand(Verbosity.Critical, dexPromise);
if (TargetCommand.CmdName.Equals(split[0].ToLower()))
return new TargetCommand(dexPromise);
if (DexLookInstructionCommand.CmdName.Equals(split[0].ToLower()))
return new DexLookInstructionCommand(Verbosity.Critical, dexPromise);
if (HackCommand.CmdName.Equals(split[0].ToLower()))
return new HackCommand(dexPromise);
if (ShowGraphUICommand.CmdName.Equals(split[0].ToLower()))
return new ShowGraphUICommand(dexPromise);
if (split[0].ToLower().StartsWith("#"))
return new DexHackInstructionCommand(Verbosity.Critical, dexPromise);
if (split[0].ToLower().StartsWith("!"))
return new DexDirectInstructionCommand(Verbosity.Critical, dexPromise);
return null;
}
}
} | 38.431373 | 87 | 0.638265 | [
"Apache-2.0"
] | Krivda/gUmMY | DexNetwork/DexInterpreter/CommandResolver.cs | 1,962 | C# |
using OpenKh.Common;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xe.BinaryMapper;
namespace OpenKh.Kh2
{
public class ObjectCollision
{
[Data] public byte Group { get; set; }
[Data] public byte Parts { get; set; }
[Data] public short Argument { get; set; }
[Data] public byte Type { get; set; }
[Data] public byte Shape { get; set; }
[Data] public short Bone { get; set; }
[Data] public short PositionX { get; set; }
[Data] public short PositionY { get; set; }
[Data] public short PositionZ { get; set; }
[Data] public short PositionHeight { get; set; }
[Data] public short Radius { get; set; }
[Data] public short Height { get; set; }
public static List<ObjectCollision> Read(Stream stream)
{
var count = stream.ReadInt32();
stream.Position += 0x40 - 4;
return Enumerable
.Range(0, count)
.Select(x => BinaryMapping.ReadObject<ObjectCollision>(stream))
.ToList();
}
public static void Write(Stream stream, ICollection<ObjectCollision> collisions)
{
stream.Write(collisions.Count);
stream.Write(1);
stream.Position += 0x40 - 8;
foreach (var item in collisions)
BinaryMapping.WriteObject(stream, item);
}
}
}
| 32.177778 | 88 | 0.571823 | [
"Apache-2.0"
] | 1234567890num/OpenKh | OpenKh.Kh2/ObjectCollision.cs | 1,448 | 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.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Core.Test
{
public class TokenExtensionTests
{
[Fact]
public void CanStoreMultipleTokens()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
Assert.Equal("1", props.GetTokenValue("One"));
Assert.Equal("2", props.GetTokenValue("Two"));
Assert.Equal("3", props.GetTokenValue("Three"));
Assert.Equal(3, props.GetTokens().Count());
}
[Fact]
public void SubsequentStoreTokenDeletesPreviousTokens()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
props.StoreTokens(new[] { new AuthenticationToken { Name = "Zero", Value = "0" } });
Assert.Equal("0", props.GetTokenValue("Zero"));
Assert.Null(props.GetTokenValue("One"));
Assert.Null(props.GetTokenValue("Two"));
Assert.Null(props.GetTokenValue("Three"));
Assert.Single(props.GetTokens());
}
[Fact]
public void CanUpdateTokens()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
tok1.Value = ".1";
tok2.Value = ".2";
tok3.Value = ".3";
props.StoreTokens(tokens);
Assert.Equal(".1", props.GetTokenValue("One"));
Assert.Equal(".2", props.GetTokenValue("Two"));
Assert.Equal(".3", props.GetTokenValue("Three"));
Assert.Equal(3, props.GetTokens().Count());
}
[Fact]
public void CanUpdateTokenValues()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
Assert.True(props.UpdateTokenValue("One", ".11"));
Assert.True(props.UpdateTokenValue("Two", ".22"));
Assert.True(props.UpdateTokenValue("Three", ".33"));
Assert.Equal(".11", props.GetTokenValue("One"));
Assert.Equal(".22", props.GetTokenValue("Two"));
Assert.Equal(".33", props.GetTokenValue("Three"));
Assert.Equal(3, props.GetTokens().Count());
}
[Fact]
public void UpdateTokenValueReturnsFalseForUnknownToken()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
Assert.False(props.UpdateTokenValue("ONE", ".11"));
Assert.False(props.UpdateTokenValue("Jigglypuff", ".11"));
Assert.Null(props.GetTokenValue("ONE"));
Assert.Null(props.GetTokenValue("Jigglypuff"));
Assert.Equal(3, props.GetTokens().Count());
}
[Fact]
public async Task GetTokenWorksWithDefaultAuthenticateScheme()
{
var context = new DefaultHttpContext();
var services = new ServiceCollection().AddOptions()
.AddAuthenticationCore(o =>
{
o.DefaultScheme = "simple";
o.AddScheme("simple", s => s.HandlerType = typeof(SimpleAuth));
});
context.RequestServices = services.BuildServiceProvider();
Assert.Equal("1", await context.GetTokenAsync("One"));
Assert.Equal("2", await context.GetTokenAsync("Two"));
Assert.Equal("3", await context.GetTokenAsync("Three"));
}
[Fact]
public async Task GetTokenWorksWithExplicitScheme()
{
var context = new DefaultHttpContext();
var services = new ServiceCollection().AddOptions()
.AddAuthenticationCore(o => o.AddScheme("simple", s => s.HandlerType = typeof(SimpleAuth)));
context.RequestServices = services.BuildServiceProvider();
Assert.Equal("1", await context.GetTokenAsync("simple", "One"));
Assert.Equal("2", await context.GetTokenAsync("simple", "Two"));
Assert.Equal("3", await context.GetTokenAsync("simple", "Three"));
}
private class SimpleAuth : IAuthenticationHandler
{
public Task<AuthenticateResult> AuthenticateAsync()
{
var props = new AuthenticationProperties();
var tokens = new List<AuthenticationToken>();
var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
tokens.Add(tok1);
tokens.Add(tok2);
tokens.Add(tok3);
props.StoreTokens(tokens);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), props, "simple")));
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task ForbidAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
return Task.FromResult(0);
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignOutAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
}
}
}
| 39.855721 | 133 | 0.564848 | [
"Apache-2.0"
] | AhmedKhalil777/aspnetcore | src/Http/Authentication.Core/test/TokenExtensionTests.cs | 8,011 | C# |
using System;
using System.IO; // this one needs a lot of work to move to System.IO.Abstractions
using NGenerics.DataStructures.Trees;
using NUnit.Framework;
using Autofac;
using PicklesDoc.Pickles.DirectoryCrawler;
using PicklesDoc.Pickles.DocumentationBuilders.JSON;
using PicklesDoc.Pickles.Test.Helpers;
using Should.Fluent;
namespace PicklesDoc.Pickles.Test.Formatters.JSON
{
[TestFixture]
public class when_formatting_a_folder_structure_with_features : BaseFixture
{
private const string ROOT_PATH = @"FakeFolderStructures";
private const string OUTPUT_DIRECTORY = @"JSONFeatureOutput";
private readonly string filePath = Path.Combine(OUTPUT_DIRECTORY, JSONDocumentationBuilder.JsonFileName);
[TestFixtureSetUp]
public void Setup()
{
GeneralTree<INode> features = Container.Resolve<DirectoryTreeCrawler>().Crawl(ROOT_PATH);
var outputDirectory = new DirectoryInfo(OUTPUT_DIRECTORY);
if (!outputDirectory.Exists) outputDirectory.Create();
var configuration = new Configuration
{
OutputFolder = new DirectoryInfo(OUTPUT_DIRECTORY),
DocumentationFormat = DocumentationFormat.JSON
};
var jsonDocumentationBuilder = new JSONDocumentationBuilder(configuration, null, RealFileSystem);
jsonDocumentationBuilder.Build(features);
}
[TestFixtureTearDown]
public void TearDown()
{
//Cleanup output folder
if (Directory.Exists(OUTPUT_DIRECTORY))
{
Directory.Delete(OUTPUT_DIRECTORY, true);
}
}
[Test]
public void a_single_file_should_have_been_created()
{
File.Exists(this.filePath).Should().Be.True();
}
[Test]
public void should_contain_the_features()
{
string content = File.ReadAllText(this.filePath);
content.AssertJSONKeyValue("Name", "Addition");
}
}
} | 34.206349 | 113 | 0.62877 | [
"Apache-2.0"
] | marcusoftnet/pickles | src/Pickles/Pickles.Test/Formatters/JSON/when_formatting_a_folder_structure_with_features.cs | 2,157 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using FluentAssertions;
using Microsoft.Common.Core.Test.Utility;
using Microsoft.R.Core.Formatting;
namespace Microsoft.R.Core.Test.Formatting {
[ExcludeFromCodeCoverage]
public class FormatFilesFiles {
// change to true in debugger if you want all baseline tree files regenerated
private static bool _regenerateBaselineFiles = false;
public static void FormatFile(CoreTestFilesFixture fixture, string name) {
FormatFile(fixture, name, new RFormatOptions());
}
public static void FormatFile(CoreTestFilesFixture fixture, string name, RFormatOptions options) {
Action a = () => FormatFileImplementation(fixture, name, options);
a.ShouldNotThrow();
}
private static void FormatFileImplementation(CoreTestFilesFixture fixture, string name, RFormatOptions options) {
string testFile = fixture.GetDestinationPath(name);
string baselineFile = testFile + ".formatted";
string text = fixture.LoadDestinationFile(name);
RFormatter formatter = new RFormatter(options);
string actual = formatter.Format(text);
if (_regenerateBaselineFiles) {
// Update this to your actual enlistment if you need to update baseline
string enlistmentPath = @"C:\RTVS\src\R\Core\Test\Files\Formatting";
baselineFile = Path.Combine(enlistmentPath, Path.GetFileName(testFile)) + ".formatted";
TestFiles.UpdateBaseline(baselineFile, actual);
} else {
TestFiles.CompareToBaseLine(baselineFile, actual);
}
}
}
}
| 41.23913 | 121 | 0.67844 | [
"MIT"
] | AlexanderSher/RTVS-Old | src/R/Core/Test/Formatting/FormatFilesFiles.cs | 1,899 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Ram20150501.Models
{
public class UnbindMFADeviceRequest : TeaModel {
[NameInMap("UserName")]
[Validation(Required=false)]
public string UserName { get; set; }
}
}
| 18.894737 | 54 | 0.690808 | [
"Apache-2.0"
] | atptro/alibabacloud-sdk | ram-20150501/csharp/core/Models/UnbindMFADeviceRequest.cs | 359 | C# |
namespace Exrin.Insights
{
using System;
using System.Threading;
using System.Threading.Tasks;
internal sealed class Timer : CancellationTokenSource
{
internal Timer(Action<object> callback, object state, int millisecondsDueTime, int millisecondsPeriod, bool waitForCallbackBeforeNextPeriod = false)
{
Task.Delay(millisecondsDueTime, Token).ContinueWith(async (t, s) =>
{
var tuple = (Tuple<Action<object>, object>)s;
while (!IsCancellationRequested)
{
if (waitForCallbackBeforeNextPeriod)
tuple.Item1(tuple.Item2);
else
await Task.Factory.StartNew(() => tuple.Item1(tuple.Item2)); //TODO: Double check that this is only awaiting the Task Creation and not the execution
await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
}
}, Tuple.Create(callback, state), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
}
protected override void Dispose(bool disposing)
{
if (disposing)
Cancel();
base.Dispose(disposing);
}
}
}
| 36.486486 | 187 | 0.608148 | [
"MIT"
] | adamped/exrin | Exrin/Exrin.Framework/Insights/Timer.cs | 1,352 | 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.FindReferences;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.FindReferences;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
{
public class FindReferencesCommandHandlerTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public async Task TestFindReferencesSynchronousCall()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync("class C { C() { new C(); } }"))
{
var findReferencesPresenter = new MockDefinitionsAndReferencesPresenter();
var handler = new FindReferencesCommandHandler(
TestWaitIndicator.Default,
SpecializedCollections.SingletonEnumerable(findReferencesPresenter),
SpecializedCollections.EmptyEnumerable<Lazy<IStreamingFindReferencesPresenter>>(),
workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
var textView = workspace.Documents[0].GetTextView();
textView.Caret.MoveTo(new SnapshotPoint(textView.TextSnapshot, 7));
handler.ExecuteCommand(new FindReferencesCommandArgs(
textView,
textView.TextBuffer), () => { });
AssertResult(findReferencesPresenter.DefinitionsAndReferences, "C", ".ctor");
}
}
private bool AssertResult(
DefinitionsAndReferences definitionsAndReferences,
params string[] definitions)
{
return definitionsAndReferences.Definitions.Select(r => r.DisplayParts.JoinText())
.SetEquals(definitions);
}
}
} | 44.358491 | 160 | 0.684815 | [
"Apache-2.0"
] | jbevain/roslyn | src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs | 2,351 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
public class SearchSave
{
public uint unitCtrlrUid;
public global::UnityEngine.Vector3 pos;
public global::System.Collections.Generic.List<global::ItemSave> items;
public bool wasSearched;
}
| 17.8 | 72 | 0.794007 | [
"CC0-1.0"
] | FreyaFreed/mordheim | Assembly-CSharp/SearchSave.cs | 269 | C# |
namespace Pierres.ViewModels
{
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
} | 20.666667 | 40 | 0.655914 | [
"Unlicense"
] | Medeirosseth/MonsieurPierres.Solution | Pierres/ViewModels/LoginViewModel.cs | 186 | C# |
using BeatPulse;
using FluentAssertions;
using FunctionalTests.Base;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace FunctionalTests.BeatPulse.Kafka
{
[Collection("execution")]
public class kafka_liveness_should
{
private readonly ExecutionFixture _fixture;
public kafka_liveness_should(ExecutionFixture fixture)
{
_fixture = fixture ?? throw new ArgumentNullException(nameof(fixture));
}
[SkipOnAppVeyor]
public async Task return_false_if_kafka_is_unavailable()
{
var config = new Dictionary<string, object>()
{
{ "bootstrap.servers", "localhost:0000"},
{ "message.send.max.retries", 0 },
{ "default.topic.config", new Dictionary<string, object>()
{
{ "message.timeout.ms", 5000 }
}
}
};
var webHostBuilder = new WebHostBuilder()
.UseStartup<DefaultStartup>()
.UseBeatPulse()
.ConfigureServices(services =>
{
services.AddBeatPulse(context =>
{
context.AddKafka(config);
});
});
var server = new TestServer(webHostBuilder);
var response = await server.CreateRequest($"{BeatPulseKeys.BEATPULSE_DEFAULT_PATH}")
.GetAsync();
response.StatusCode
.Should().Be(HttpStatusCode.ServiceUnavailable);
}
[SkipOnAppVeyor]
public async Task return_true_if_kafka_is_available()
{
var config = new Dictionary<string, object>()
{
{ "bootstrap.servers", "localhost:9092"}
};
var webHostBuilder = new WebHostBuilder()
.UseStartup<DefaultStartup>()
.UseBeatPulse()
.ConfigureServices(services =>
{
services.AddBeatPulse(context =>
{
context.AddKafka(config);
});
});
var server = new TestServer(webHostBuilder);
var response = await server.CreateRequest($"{BeatPulseKeys.BEATPULSE_DEFAULT_PATH}")
.GetAsync();
response.EnsureSuccessStatusCode();
}
}
}
| 30.252874 | 96 | 0.543313 | [
"Apache-2.0"
] | BTDevelop/BeatPulse | tests/FunctionalTests/BeatPulse.Kafka/BeatPulseLivenessTests.cs | 2,634 | C# |
using JPProject.Sso.Domain.Commands.UserManagement;
namespace JPProject.Sso.Domain.Validations.UserManagement
{
public class ChangePasswordCommandValidation : PasswordCommandValidation<ChangePasswordCommand>
{
public ChangePasswordCommandValidation()
{
ValidateUsername();
ValidateOldPassword();
ValidatePassword();
}
}
} | 28.214286 | 99 | 0.691139 | [
"MIT"
] | abdullahgb/JPProject.Core | src/SSO/JPProject.Sso.Domain/Validations/UserManagement/ChangePasswordCommandValidation.cs | 397 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.SwaggerUI;
namespace Byndyusoft.AspNetCore.Mvc.Formatters.ProtoBuf.Swagger
{
/// <summary>
/// ApplicationBuilderExtensions
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
/// UseSwagger
/// </summary>
public static IApplicationBuilder UseSwagger(
this IApplicationBuilder builder,
IApiVersionDescriptionProvider apiVersionDescriptionProvider)
{
builder.UseSwagger()
.UseSwaggerUI(options =>
{
foreach (var apiVersionDescription in apiVersionDescriptionProvider.ApiVersionDescriptions)
options.SwaggerEndpoint($"/swagger/{apiVersionDescription.GroupName}/swagger.json", apiVersionDescription.GroupName.ToUpperInvariant());
options.DisplayRequestDuration();
options.DefaultModelRendering(ModelRendering.Model);
options.DefaultModelExpandDepth(3);
});
return builder;
}
}
} | 36.969697 | 163 | 0.621311 | [
"MIT"
] | Byndyusoft/Byndyusoft.AspNetCore.Mvc.Formatters.ProtoBuf | example/Swagger/ApplicationBuilderExtensions.cs | 1,222 | C# |
using Extensible.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Extensible.Loaders
{
public class DirectoryLoader<T> : ILoader<T> where T : class
{
private readonly string[] _paths;
private readonly bool _recursive;
private readonly string _moduleFilter;
private const string ModuleFilter = "*.dll";
public DirectoryLoader(string path, bool recursive = false, string moduleFilter = ModuleFilter) :
this(new string[] { path }, recursive, moduleFilter)
{
}
public DirectoryLoader(string[] paths, bool recursive = false, string moduleFilter = ModuleFilter)
{
_paths = paths;
_recursive = recursive;
_moduleFilter = moduleFilter;
}
public IEnumerable<IModule<T>> Load(T events)
{
var modules = new List<IModule<T>>();
foreach (var path in _paths)
{
if (!Directory.Exists(path)) throw new ArgumentException($"Directory {path} does not exist");
modules.AddRange(LoadDirectory(path, events));
}
return modules;
}
private IEnumerable<IModule<T>> LoadDirectory(string path, T events)
{
var modules = new List<IModule<T>>();
var assemblies = Directory.GetFiles(path, _moduleFilter);
foreach (var assembly in assemblies)
{
try
{
var m = Assembly.LoadFile(assembly);
var moduleClasses = m.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IModule<T>)));
foreach (var c in moduleClasses)
{
var module = InitializeModule(m, c);
module.Initialize(events);
modules.Add(module);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
if (_recursive)
{
var directories = Directory.GetDirectories(path);
foreach (var directory in directories)
{
modules.AddRange(LoadDirectory(directory, events));
}
}
return modules;
}
private IModule<T> InitializeModule(Assembly assembly, Type type)
{
if (!type.GetInterfaces().Contains(typeof(IModule<T>))) return default;
try
{
var instance = Activator.CreateInstance(type);
if (instance is IModule<T> module)
{
return instance as IModule<T>;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return default;
}
}
} | 32.216495 | 113 | 0.49504 | [
"MIT"
] | mrb0nj/Extensibility | src/Extensible/Loaders/DirectoryLoader.cs | 3,125 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Herbarium
{
using System;
using System.Collections.Generic;
public partial class family
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public family()
{
this.genus = new HashSet<genus>();
}
public int id { get; set; }
public Nullable<int> majorid { get; set; }
public string name { get; set; }
public virtual major major { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<genus> genus { get; set; }
}
}
| 35.46875 | 128 | 0.570925 | [
"MIT"
] | ahmetcanaydemir/Herbarium | Database/Model/family.cs | 1,137 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using ProtoBuf.Meta;
namespace AgGateway.ADAPT.ADMPlugin.Protobuf.V2.Logistics
{
public static class GpsSourceType
{
public static void Configure(RuntimeTypeModel model)
{
var type = model.Add(typeof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource), Constants.UseDefaults);
type.AddField(1, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.SourceType));
type.AddField(2, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.EstimatedPrecision));
type.AddField(3, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.HorizontalAccuracy));
type.AddField(4, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.VerticalAccuracy));
type.AddField(5, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.NumberOfSatellites));
type.AddField(6, nameof(AgGateway.ADAPT.ApplicationDataModel.Logistics.GpsSource.GpsUtcTime));
}
}
}
| 46.227273 | 116 | 0.794494 | [
"EPL-1.0"
] | ADAPT/ADMPlugin | ADMPlugin/Protobuf/V2/Logistics/GpsSourceType.cs | 1,017 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndTravel
{
public class Forest : Location, IGatheringLocation
{
public Forest(string name)
: base(name, LocationType.Forest)
{
}
public ItemType GatheredType
{
get
{
return ItemType.Wood;
}
}
public ItemType RequiredItem
{
get
{
return ItemType.Weapon;
}
}
public Item ProduceItem(string name)
{
return new Wood(name);
}
}
}
| 18.368421 | 54 | 0.505731 | [
"MIT"
] | Valsinev/C-OOP | Exams/12 december 2013/2/TradeAndTravel-Skeleton/TradeAndTravel/Forest.cs | 700 | C# |
using Mazes;
using Mazes.Algorithms;
using System.Threading.Tasks;
namespace AldousBroderDemo
{
class Program
{
static async Task Main(string[] args)
{
var grid = new Grid(20, 20);
new AldousBroder().On(grid);
var image = await grid.ToImageAsync();
image.Save("AldousBroder.png");
}
}
}
| 19.684211 | 50 | 0.569519 | [
"MIT"
] | Nekketsu/MazesForProgrammers | src/AldousBroderDemo/Program.cs | 376 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace EliteTradingGUI
{
public class EdInfo : IDisposable
{
private IntPtr _instance;
private GCHandle _callback;
public EdInfo(Action<string> callback)
{
var temp = (NativeEliteTrading.ProgressCallback)(x => callback(x));
_callback = GCHandle.Alloc(temp);
_instance = NativeEliteTrading.initialize_info(temp);
}
private EdInfo(IntPtr instance, GCHandle callback)
{
_instance = instance;
_callback = callback;
}
public void Dispose()
{
NativeEliteTrading.destroy_info(_instance);
_callback.Free();
}
public static bool DatabaseExists()
{
return NativeEliteTrading.database_exists() != 0;
}
public static EdInfo ImportData(Action<string> callback)
{
var temp = (NativeEliteTrading.ProgressCallback)(x => callback(x));
var handle = GCHandle.Alloc(temp);
var instance = NativeEliteTrading.import_data(temp);
return new EdInfo(instance, handle);
}
public void RecomputeAllRoutes(double maxStopDistance, ulong minProfitPerUnit)
{
NativeEliteTrading.recompute_all_routes(_instance, maxStopDistance, minProfitPerUnit);
}
public class Location
{
public readonly EdInfo Info;
public bool IsStation;
public ulong Id;
private string _name;
private string _systemName;
internal Location(EdInfo info)
{
Info = info;
}
public string Name
{
get
{
if (_name == null)
{
if (!IsStation)
_systemName = _name = Info.GetSystemName(Id);
else
_name = Info.GetStationName(Id);
}
return _name;
}
}
public string SystemName
{
get
{
if (_systemName == null)
{
if (!IsStation)
return Name;
_systemName = Info.GetSystemName(Info.GetSystemForStation(Id));
}
return _systemName;
}
}
public override string ToString()
{
if (!IsStation)
return "System \"" + Name + "\"";
return "Station \"" + Name + "\" in system \"" + SystemName + "\"";
}
}
public List<Location> GetSuggestions(string s)
{
int returnedSuggestions;
var suggestions = NativeEliteTrading.get_suggestions(out returnedSuggestions, _instance, s);
try
{
var ret = new List<Location>();
ret.Capacity = returnedSuggestions;
for (int i = 0; i < returnedSuggestions; i++)
{
var id = Marshal.ReadInt64(suggestions, i*8);
ret.Add(
new Location(this)
{
IsStation = id < 0,
Id = (ulong) Math.Abs(id) - 1,
}
);
}
return ret;
}
finally
{
NativeEliteTrading.destroy_suggestions(suggestions, returnedSuggestions);
}
}
private string GetName(bool isStation, ulong id)
{
var ptr = NativeEliteTrading.get_name(_instance, isStation ? 1 : 0, id);
if (ptr == IntPtr.Zero)
throw new IndexOutOfRangeException("Invalid ID.");
try
{
return Marshal.PtrToStringAnsi(ptr);
}
finally
{
NativeEliteTrading.destroy_string(_instance, ptr);
}
}
public string GetSystemName(ulong id)
{
return GetName(false, id);
}
public string GetStationName(ulong id)
{
return GetName(true, id);
}
public ulong GetSystemForStation(ulong id)
{
var ret = NativeEliteTrading.get_system_for_station(_instance, id);
if (ret == ulong.MaxValue)
throw new IndexOutOfRangeException("Invalid ID.");
return ret;
}
private List<RouteNode> SearchRoutes(bool isStation, ulong id, NativeEliteTrading.RouteSearchConstraints constraints)
{
int size;
var routes = NativeEliteTrading.search_nearby_routes(_instance, out size, id, isStation ? 1 : 0, constraints);
try
{
var ret = new List<RouteNode>();
if (routes == IntPtr.Zero)
return ret;
ret.Capacity = size;
for (int i = 0; i < size; i++)
{
var element = Marshal.ReadIntPtr(routes, i*IntPtr.Size);
ret.Add(new RouteNode(this, element));
}
return ret;
}
finally
{
NativeEliteTrading.destroy_routes(_instance, routes, size);
}
}
public List<RouteNode> SearchRoutes(Location currentLocation, NativeEliteTrading.RouteSearchConstraints constraints)
{
return SearchRoutes(currentLocation.IsStation, currentLocation.Id, constraints);
}
public string GetCommodityName(ulong commodityId)
{
return NativeEliteTrading.get_commodity_name(_instance, commodityId);
}
public List<SystemPoint> GetSystemPointList()
{
int size;
var pointer = NativeEliteTrading.get_system_point_list(_instance, out size);
try
{
var type = typeof (SystemPoint);
var structSize = Marshal.SizeOf(type);
var ret = new List<SystemPoint>();
ret.Capacity = size;
for (int i = 0; i < size; i++)
ret.Add((SystemPoint)Marshal.PtrToStructure(pointer + i * structSize, type));
return ret;
}
finally
{
NativeEliteTrading.destroy_system_point_list(_instance, pointer, size);
}
}
}
}
| 32.87963 | 126 | 0.479442 | [
"BSD-2-Clause"
] | Helios-vmg/EliteTrading | EliteTradingGUI/EdInfo.cs | 7,104 | C# |
using System;
using System.Collections.Generic;
/*
struct ContentView : View {
@State var celsius: Double = 0
var body: some View {
VStack {
Slider(value: $celsius, from: -100, through: 100, by: 0.1)
Text("\(celsius) Celsius is \(celsius * 9 / 5 + 32) Fahrenheit")
}
}
}
*/
namespace HotUI.Samples
{
public class SliderSample1 : View
{
readonly State<float> celsius = 50;
[Body]
View body() => new VStack
{
//new Slider(value: 12, from: -100, through: 100, by: 0.1f),
//new Slider(value: () => 12f, from: -100, through: 100, by: 0.1f),
//new Slider(value: new Binding<float>( getValue: () => 12f, setValue:null), from: -100, through: 100, by: 0.1f),
new Slider(value: celsius, from: -100, through: 100, by: 0.1f),
new Text(()=>$"{celsius.Value} Celsius"),
new Text(()=>$"{celsius.Value * 9 / 5 + 32} Fahrenheit"),
};
}
} | 29.555556 | 130 | 0.50188 | [
"MIT"
] | BenBtg/HotUI | sample/HotUI.Samples/SliderSample1.cs | 1,066 | C# |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Versions.Selector;
namespace Orleans.Runtime.Versions.Selector
{
internal class VersionSelectorManager
{
private readonly VersionSelectorStrategy strategyFromConfig;
private readonly IServiceProvider serviceProvider;
private readonly Dictionary<int, IVersionSelector> versionSelectors;
public IVersionSelector Default { get; set; }
public VersionSelectorManager(IServiceProvider serviceProvider, IOptions<GrainVersioningOptions> options)
{
this.serviceProvider = serviceProvider;
this.strategyFromConfig = serviceProvider.GetRequiredServiceByName<VersionSelectorStrategy>(options.Value.DefaultVersionSelectorStrategy);
Default = ResolveVersionSelector(serviceProvider, this.strategyFromConfig);
versionSelectors = new Dictionary<int, IVersionSelector>();
}
public IVersionSelector GetSelector(int interfaceId)
{
IVersionSelector selector;
return this.versionSelectors.TryGetValue(interfaceId, out selector)
? selector
: Default;
}
public void SetSelector(VersionSelectorStrategy strategy)
{
var selector = ResolveVersionSelector(this.serviceProvider, strategy ?? this.strategyFromConfig);
Default = selector;
}
public void SetSelector(int interfaceId, VersionSelectorStrategy strategy)
{
if (strategy == null)
{
versionSelectors.Remove(interfaceId);
}
else
{
var selector = ResolveVersionSelector(this.serviceProvider, strategy);
versionSelectors[interfaceId] = selector;
}
}
private static IVersionSelector ResolveVersionSelector(IServiceProvider serviceProvider,
VersionSelectorStrategy strategy)
{
var policyType = strategy.GetType();
return serviceProvider.GetRequiredServiceByKey<Type, IVersionSelector>(policyType);
}
}
} | 37.440678 | 150 | 0.672703 | [
"MIT"
] | 1007lu/orleans | src/Orleans.Runtime/Versions/Selector/VersionDirectorManager.cs | 2,209 | C# |
using AutoMapper;
using Chat.Web.Data;
using Chat.Web.Models;
using Chat.Web.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Chat.Web.Hubs
{
[Authorize]
public class ChatHub : Hub
{
public readonly static List<UserViewModel> _Connections = new List<UserViewModel>();
private readonly static Dictionary<string, string> _ConnectionsMap = new Dictionary<string, string>();
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public ChatHub(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task SendPrivate(string receiverName, string message)
{
if (_ConnectionsMap.TryGetValue(receiverName, out string userId))
{
// Who is the sender;
var sender = _Connections.Where(u => u.Username == IdentityName).First();
if (!string.IsNullOrEmpty(message.Trim()))
{
// Build the message
var messageViewModel = new MessageViewModel()
{
Content = Regex.Replace(message, @"<.*?>", string.Empty),
From = sender.FullName,
Avatar = sender.Avatar,
Room = "",
Timestamp = DateTime.Now.ToLongTimeString()
};
// Send the message
await Clients.Client(userId).SendAsync("newMessage", messageViewModel);
await Clients.Caller.SendAsync("newMessage", messageViewModel);
}
}
}
public async Task Join(string roomName)
{
try
{
var user = _Connections.Where(u => u.Username == IdentityName).FirstOrDefault();
if (user != null && user.CurrentRoom != roomName)
{
// Remove user from others list
if (!string.IsNullOrEmpty(user.CurrentRoom))
await Clients.OthersInGroup(user.CurrentRoom).SendAsync("removeUser", user);
// Join to new chat room
await Leave(user.CurrentRoom);
await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
user.CurrentRoom = roomName;
// Tell others to update their list of users
await Clients.OthersInGroup(roomName).SendAsync("addUser", user);
}
}
catch (Exception ex)
{
await Clients.Caller.SendAsync("onError", "You failed to join the chat room!" + ex.Message);
}
}
public async Task Leave(string roomName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName);
}
public IEnumerable<UserViewModel> GetUsers(string roomName)
{
return _Connections.Where(u => u.CurrentRoom == roomName).ToList();
}
public override Task OnConnectedAsync()
{
try
{
var user = _context.Users.Where(u => u.UserName == IdentityName).FirstOrDefault();
var userViewModel = _mapper.Map<ApplicationUser, UserViewModel>(user);
userViewModel.Device = GetDevice();
userViewModel.CurrentRoom = "";
if (!_Connections.Any(u => u.Username == IdentityName))
{
_Connections.Add(userViewModel);
_ConnectionsMap.Add(IdentityName, Context.ConnectionId);
}
Clients.Caller.SendAsync("getProfileInfo", user.FullName, user.Avatar);
}
catch (Exception ex)
{
Clients.Caller.SendAsync("onError", "OnConnected:" + ex.Message);
}
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
try
{
var user = _Connections.Where(u => u.Username == IdentityName).First();
_Connections.Remove(user);
// Tell other users to remove you from their list
Clients.OthersInGroup(user.CurrentRoom).SendAsync("removeUser", user);
// Remove mapping
_ConnectionsMap.Remove(user.Username);
}
catch (Exception ex)
{
Clients.Caller.SendAsync("onError", "OnDisconnected: " + ex.Message);
}
return base.OnDisconnectedAsync(exception);
}
private string IdentityName
{
get { return Context.User.Identity.Name; }
}
private string GetDevice()
{
var device = Context.GetHttpContext().Request.Headers["Device"].ToString();
if (!string.IsNullOrEmpty(device) && (device.Equals("Desktop") || device.Equals("Mobile")))
return device;
return "Web";
}
}
}
| 35.302632 | 110 | 0.544167 | [
"MIT"
] | AKouki/SignalR-Chat | Chat.Web/Hubs/ChatHub.cs | 5,368 | C# |
using System.Collections.Generic;
public class Team
{
private string name;
private List<Person> firstTeam;
private List<Person> reserveTeam;
public Team(string name)
{
this.name = name;
this.firstTeam = new List<Person>();
this.reserveTeam = new List<Person>();
}
public IList<Person> ReserveTeam
{
get { return this.reserveTeam.AsReadOnly(); }
}
public IList<Person> FirstTeam
{
get { return this.firstTeam.AsReadOnly(); }
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public void AddPlayer(Person person)
{
if (person.Age < 40)
{
firstTeam.Add(person);
}
else
{
reserveTeam.Add(person);
}
}
}
| 17.458333 | 53 | 0.544153 | [
"MIT"
] | msotiroff/Softuni-learning | C# DB Module/DB Advanced - Entity Framework Core/C# OOP Intro - Encapsulation and Validation/Homework/OOP-Encapsulation-Lab/04.FirstAndReserveTeam/Team.cs | 840 | C# |
using Ammy.Build;
using Ammy.Language;
namespace Ammy.VisualStudio.Service.Compilation
{
public interface ICompilationListener
{
string FilePath { get; }
void Update(AmmyFile<Top> file);
}
} | 20.818182 | 48 | 0.659389 | [
"MIT"
] | AmmyUI/AmmyUI | src/IDE/Ammy.VisualStudio.Service/Compilation/ICompilationListener.cs | 229 | C# |
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace Notes.Views
{
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
}
async void OnButtonClicked(object sender, EventArgs e)
{
// Launch the specified URL in the system browser.
await Launcher.OpenAsync("https://aka.ms/xamarin-quickstart");
}
}
}
| 21.619048 | 74 | 0.605727 | [
"Apache-2.0"
] | 1ostrich/xamarin-forms-samples | GetStarted/Notes/App/Notes/Views/AboutPage.xaml.cs | 456 | C# |
using System;
using System.Transactions;
using Microsoft.EntityFrameworkCore;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Uow;
using Abp.MultiTenancy;
using TigerAdmin.EntityFrameworkCore.Seed.Host;
using TigerAdmin.EntityFrameworkCore.Seed.Tenants;
namespace TigerAdmin.EntityFrameworkCore.Seed
{
public static class SeedHelper
{
public static void SeedHostDb(IIocResolver iocResolver)
{
WithDbContext<TigerAdminDbContext>(iocResolver, SeedHostDb);
}
public static void SeedHostDb(TigerAdminDbContext context)
{
context.SuppressAutoSetTenantId = true;
// Host seed
new InitialHostDbBuilder(context).Create();
// Default tenant seed (in host database).
new DefaultTenantBuilder(context).Create();
new TenantRoleAndUserBuilder(context, 1).Create();
}
private static void WithDbContext<TDbContext>(IIocResolver iocResolver, Action<TDbContext> contextAction)
where TDbContext : DbContext
{
using (var uowManager = iocResolver.ResolveAsDisposable<IUnitOfWorkManager>())
{
using (var uow = uowManager.Object.Begin(TransactionScopeOption.Suppress))
{
var context = uowManager.Object.Current.GetDbContext<TDbContext>(MultiTenancySides.Host);
contextAction(context);
uow.Complete();
}
}
}
}
}
| 31.571429 | 113 | 0.645766 | [
"Apache-2.0"
] | AllenHongjun/ddu | TigerAdminZero/5.8.1/aspnet-core/src/TigerAdmin.EntityFrameworkCore/EntityFrameworkCore/Seed/SeedHelper.cs | 1,549 | C# |
/*
* Ory APIs
*
* Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers.
*
* The version of the OpenAPI document: v0.0.1-alpha.30
* Contact: [email protected]
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Ory.Client.Client.OpenAPIDateConverter;
namespace Ory.Client.Model
{
/// <summary>
/// ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody
/// </summary>
[DataContract(Name = "submitSelfServiceSettingsFlowWithPasswordMethodBody")]
public partial class ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody : IEquatable<ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody" /> class.
/// </summary>
[JsonConstructorAttribute]
protected ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody()
{
this.AdditionalProperties = new Dictionary<string, object>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody" /> class.
/// </summary>
/// <param name="csrfToken">CSRFToken is the anti-CSRF token.</param>
/// <param name="method">Method Should be set to password when trying to update a password. (required).</param>
/// <param name="password">Password is the updated password (required).</param>
public ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody(string csrfToken = default(string), string method = default(string), string password = default(string))
{
// to ensure "method" is required (not null)
if (method == null) {
throw new ArgumentNullException("method is a required property for ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody and cannot be null");
}
this.Method = method;
// to ensure "password" is required (not null)
if (password == null) {
throw new ArgumentNullException("password is a required property for ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody and cannot be null");
}
this.Password = password;
this.CsrfToken = csrfToken;
this.AdditionalProperties = new Dictionary<string, object>();
}
/// <summary>
/// CSRFToken is the anti-CSRF token
/// </summary>
/// <value>CSRFToken is the anti-CSRF token</value>
[DataMember(Name = "csrf_token", EmitDefaultValue = false)]
public string CsrfToken { get; set; }
/// <summary>
/// Method Should be set to password when trying to update a password.
/// </summary>
/// <value>Method Should be set to password when trying to update a password.</value>
[DataMember(Name = "method", IsRequired = true, EmitDefaultValue = false)]
public string Method { get; set; }
/// <summary>
/// Password is the updated password
/// </summary>
/// <value>Password is the updated password</value>
[DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)]
public string Password { get; set; }
/// <summary>
/// Gets or Sets additional properties
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalProperties { 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 ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody {\n");
sb.Append(" CsrfToken: ").Append(CsrfToken).Append("\n");
sb.Append(" Method: ").Append(Method).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).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 virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody);
}
/// <summary>
/// Returns true if ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody instances are equal
/// </summary>
/// <param name="input">Instance of ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody input)
{
if (input == null)
return false;
return
(
this.CsrfToken == input.CsrfToken ||
(this.CsrfToken != null &&
this.CsrfToken.Equals(input.CsrfToken))
) &&
(
this.Method == input.Method ||
(this.Method != null &&
this.Method.Equals(input.Method))
) &&
(
this.Password == input.Password ||
(this.Password != null &&
this.Password.Equals(input.Password))
)
&& (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any());
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CsrfToken != null)
hashCode = hashCode * 59 + this.CsrfToken.GetHashCode();
if (this.Method != null)
hashCode = hashCode * 59 + this.Method.GetHashCode();
if (this.Password != null)
hashCode = hashCode * 59 + this.Password.GetHashCode();
if (this.AdditionalProperties != null)
hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 42.26455 | 179 | 0.61342 | [
"Apache-2.0"
] | ory/sdk | clients/client/dotnet/src/Ory.Client/Model/ClientSubmitSelfServiceSettingsFlowWithPasswordMethodBody.cs | 7,988 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer.Extensions
{
public static class AuthenticateResultExtensions
{
public static (string provider, string providerUserId, List<Claim> claims) FindUserFromExternalProvider(this AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
//var user = _users.FindByExternalProvider(provider, providerUserId);
return (provider, providerUserId, claims);
}
}
}
| 38.947368 | 143 | 0.664189 | [
"Apache-2.0"
] | bozhiqian/ASP.NET-Core-Auth | TodoWithIdentityServer/IdentityServer/Extensions/AuthenticateResultExtensions.cs | 1,482 | C# |
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Com.ChinaPalmPay.Platform.RentCar.Model
{
[Table(Name = "T_Cup")]
[Serializable]
public class Cup
{
[Column(IsPrimaryKey = true, IsDbGenerated = false)]
public string id { get; set; }
[Column]
//交易类型
public string txnType { get; set; }
[Column]
//产品类型
public string bizType { get; set; }
[Column]
//商户代码
public string merId { get; set; }
[Column]
//商户订单号
public string orderId { get; set; }
//订单发送时间
[Column]
public string txnTime { get; set; }
[Column]
//交易金额
public int txnAmt { get; set; }
[Column]
//交易查询流水号
public string queryId { get; set; }
[Column]
//响应吗
public string respCode { get; set; }
[Column]
//响应信息
public string respMsg { get; set; }
//清算金额
[Column]
public int settleAmt { get; set; }
//清算日期
[Column]
public string settleDate { get; set; }
//账号
[Column]
public string accNo { get; set; }
//支付卡类型
[Column]
public string payCardType { get; set; }
//支付方式
[Column]
public string payType { get; set; }
//支付卡标识
[Column]
public string payCardNo { get; set; }
//支付卡名称
[Column]
public string payCardIssueName { get; set; }
//绑定标识号
[Column]
public string bindId { get; set; }
[Column]
public string cupParams { get; set; }
}
}
| 24.71831 | 60 | 0.517949 | [
"MIT"
] | gp15237125756/Blog | Com.ChinaPalmPay.Platform.RentCar/Com.ChinaPalmPay.Platform.RentCar.Model/Cup.cs | 1,907 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Hyak.Common;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Security;
using System.Security.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Properties;
namespace Microsoft.Azure.Commands.Common.Authentication
{
/// <summary>
/// A token provider that uses ADAL to retrieve
/// tokens from Azure Active Directory for user
/// credentials.
/// </summary>
internal class UserTokenProvider : ITokenProvider
{
public UserTokenProvider()
{
}
public IAccessToken GetAccessToken(
AdalConfiguration config,
string promptBehavior,
Action<string> promptAction,
string userId,
SecureString password,
string credentialType)
{
if (credentialType != AzureAccount.AccountType.User)
{
throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
}
return new AdalAccessToken(AcquireToken(config, promptAction, userId, password), this, config);
}
private readonly static TimeSpan expirationThreshold = TimeSpan.FromMinutes(5);
private bool IsExpired(AdalAccessToken token)
{
#if DEBUG
if (Environment.GetEnvironmentVariable("FORCE_EXPIRED_ACCESS_TOKEN") != null)
{
return true;
}
#endif
var expiration = token.AuthResult.ExpiresOn;
var currentTime = DateTimeOffset.UtcNow;
var timeUntilExpiration = expiration - currentTime;
TracingAdapter.Information(Resources.UPNTokenExpirationCheckTrace, expiration, currentTime, expirationThreshold,
timeUntilExpiration);
return timeUntilExpiration < expirationThreshold;
}
private void Renew(AdalAccessToken token)
{
TracingAdapter.Information(
Resources.UPNRenewTokenTrace,
token.AuthResult.AccessTokenType,
token.AuthResult.ExpiresOn,
true,
token.AuthResult.TenantId,
token.UserId);
var user = token.AuthResult.UserInfo;
if (user != null)
{
TracingAdapter.Information(
Resources.UPNRenewTokenUserInfoTrace,
user.DisplayableId,
user.FamilyName,
user.GivenName,
user.IdentityProvider,
user.UniqueId);
}
if (IsExpired(token))
{
TracingAdapter.Information(Resources.UPNExpiredTokenTrace);
AuthenticationResult result = AcquireToken(token.Configuration, null, token.UserId, null, true);
if (result == null)
{
throw new AuthenticationException(Resources.ExpiredRefreshToken);
}
else
{
token.AuthResult = result;
}
}
}
private AuthenticationContext CreateContext(AdalConfiguration config)
{
return new AuthenticationContext(config.AdEndpoint + config.AdDomain,
config.ValidateAuthority, config.TokenCache);
}
// We have to run this in a separate thread to guarantee that it's STA. This method
// handles the threading details.
private AuthenticationResult AcquireToken(AdalConfiguration config, Action<string> promptAction,
string userId, SecureString password, bool renew = false)
{
AuthenticationResult result = null;
Exception ex = null;
result = SafeAquireToken(config, promptAction, userId, password, out ex);
if (ex != null)
{
var adex = ex as AdalException;
if (adex != null)
{
if (adex.ErrorCode == AdalError.AuthenticationCanceled)
{
throw new AadAuthenticationCanceledException(adex.Message, adex);
}
}
if (ex is AadAuthenticationException)
{
throw ex;
}
throw new AadAuthenticationFailedException(GetExceptionMessage(ex), ex);
}
return result;
}
private AuthenticationResult SafeAquireToken(
AdalConfiguration config,
Action<string> promptAction,
string userId,
SecureString password,
out Exception ex)
{
try
{
ex = null;
return DoAcquireToken(config, userId, password, promptAction);
}
catch (AdalException adalEx)
{
if (adalEx.ErrorCode == AdalError.UserInteractionRequired ||
adalEx.ErrorCode == AdalError.MultipleTokensMatched)
{
string message = Resources.AdalUserInteractionRequired;
if (adalEx.ErrorCode == AdalError.MultipleTokensMatched)
{
message = Resources.AdalMultipleTokens;
}
ex = new AadAuthenticationFailedWithoutPopupException(message, adalEx);
}
else if (adalEx.ErrorCode == AdalError.MissingFederationMetadataUrl ||
adalEx.ErrorCode == AdalError.FederatedServiceReturnedError)
{
ex = new AadAuthenticationFailedException(Resources.CredentialOrganizationIdMessage, adalEx);
}
else
{
ex = adalEx;
}
}
catch (Exception threadEx)
{
ex = threadEx;
}
return null;
}
private AuthenticationResult DoAcquireToken(
AdalConfiguration config,
string userId,
SecureString password,
Action<string> promptAction,
bool renew = false)
{
AuthenticationResult result;
var context = CreateContext(config);
TracingAdapter.Information(
Resources.UPNAcquireTokenContextTrace,
context.Authority,
context.CorrelationId,
context.ValidateAuthority);
TracingAdapter.Information(
Resources.UPNAcquireTokenConfigTrace,
config.AdDomain,
config.AdEndpoint,
config.ClientId,
config.ClientRedirectUri);
if (promptAction == null || renew)
{
result =context.AcquireTokenSilentAsync(config.ResourceClientUri, config.ClientId,
new UserIdentifier(userId, UserIdentifierType.OptionalDisplayableId))
.ConfigureAwait(false).GetAwaiter().GetResult();
}
else if (string.IsNullOrEmpty(userId) || password == null)
{
var code = context.AcquireDeviceCodeAsync(config.ResourceClientUri, config.ClientId)
.ConfigureAwait(false).GetAwaiter().GetResult();
promptAction(code?.Message);
result = context.AcquireTokenByDeviceCodeAsync(code)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
else
{
UserCredential credential = new UserCredential(userId);
result = context.AcquireTokenAsync(config.ResourceClientUri, config.ClientId, credential)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
return result;
}
private string GetExceptionMessage(Exception ex)
{
string message = ex.Message;
if (ex.InnerException != null)
{
message += ": " + ex.InnerException.Message;
}
return message;
}
/// <summary>
/// Implementation of <see cref="IAccessToken"/> using data from ADAL
/// </summary>
private class AdalAccessToken : IAccessToken
{
internal readonly AdalConfiguration Configuration;
internal AuthenticationResult AuthResult;
private readonly UserTokenProvider tokenProvider;
public AdalAccessToken(AuthenticationResult authResult, UserTokenProvider tokenProvider, AdalConfiguration configuration)
{
AuthResult = authResult;
this.tokenProvider = tokenProvider;
Configuration = configuration;
}
public void AuthorizeRequest(Action<string, string> authTokenSetter)
{
tokenProvider.Renew(this);
authTokenSetter(AuthResult.AccessTokenType, AuthResult.AccessToken);
}
public string AccessToken { get { return AuthResult.AccessToken; } }
public string UserId { get { return AuthResult.UserInfo.DisplayableId; } }
public string TenantId { get { return AuthResult.TenantId; } }
public string LoginType
{
get
{
if (AuthResult.UserInfo.IdentityProvider != null)
{
return Authentication.LoginType.LiveId;
}
return Authentication.LoginType.OrgId;
}
}
}
}
}
| 38.712766 | 134 | 0.544014 | [
"MIT"
] | Philippe-Morin/azure-powershell | src/Common/Commands.Common.Authentication/Authentication/UserTokenProvider.Netcore.cs | 10,638 | 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 servicediscovery-2017-03-14.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.ServiceDiscovery.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ServiceDiscovery.Model.Internal.MarshallTransformations
{
/// <summary>
/// ServiceChange Marshaller
/// </summary>
public class ServiceChangeMarshaller : IRequestMarshaller<ServiceChange, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(ServiceChange requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetDescription())
{
context.Writer.WritePropertyName("Description");
context.Writer.Write(requestObject.Description);
}
if(requestObject.IsSetDnsConfig())
{
context.Writer.WritePropertyName("DnsConfig");
context.Writer.WriteObjectStart();
var marshaller = DnsConfigChangeMarshaller.Instance;
marshaller.Marshall(requestObject.DnsConfig, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetHealthCheckConfig())
{
context.Writer.WritePropertyName("HealthCheckConfig");
context.Writer.WriteObjectStart();
var marshaller = HealthCheckConfigMarshaller.Instance;
marshaller.Marshall(requestObject.HealthCheckConfig, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static ServiceChangeMarshaller Instance = new ServiceChangeMarshaller();
}
} | 34.857143 | 115 | 0.640369 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ServiceDiscovery/Generated/Model/Internal/MarshallTransformations/ServiceChangeMarshaller.cs | 2,928 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Clase que representa el estado de "patrulla"
/// del soldado. Es su estado por defecto,
/// realiza un recorrido entre los distintos
/// puntos establecidos en Unity.
/// </summary>
public class PatrollingState : State
{
#region Variables
private readonly SoldierController _enemyController;
private int _patrollingIndex;
#endregion
#region Methods
public PatrollingState(SoldierController enemyController, MyStateMachine stateMachine, int patrollingIndex) : base(stateMachine)
{
_patrollingIndex = patrollingIndex;
_enemyController = enemyController;
_enemyController.mesh.material = _enemyController.patrollingMaterial;
_enemyController.stateTextAnimator.SetBool("Alert", false);
_enemyController.stateTextAnimator.SetBool("Persecution", false);
_enemyController.stateTextAnimator.SetBool("None", true);
_enemyController.Agent.speed = _enemyController.normalSpeed;
_enemyController.playerDetected = false;
_enemyController.Agent.stoppingDistance = 1f;
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
_enemyController.Agent.SetDestination(_enemyController.points[_patrollingIndex].position);
Collider[] hitColliders = Physics.OverlapSphere(_enemyController.transform.position, 2.6f, 1 << 25);
if (hitColliders.Length > 0)
{
foreach (Collider col in hitColliders)
{
if (col.transform == _enemyController.points[_patrollingIndex])
{
stateMachine.SetState(new RestingState(_enemyController, stateMachine));
}
}
}
}
#endregion
}
| 34.528302 | 132 | 0.689071 | [
"Apache-2.0"
] | gerlogu/Shooter | Game/Assets/Game/Scripts/IA/Enemy/Soldier/PatrollingState.cs | 1,832 | C# |
using AutoMapper;
using DIGNDB.App.SmitteStop.Core.Contracts;
using DIGNDB.App.SmitteStop.DAL.Repositories;
using DIGNDB.App.SmitteStop.Domain;
using DIGNDB.App.SmitteStop.Domain.Db;
using DIGNDB.App.SmitteStop.Domain.Settings;
using FederationGatewayApi.Config;
using FederationGatewayApi.Contracts;
using FederationGatewayApi.Mappers;
using FederationGatewayApi.Models;
using FederationGatewayApi.Services;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using TemporaryExposureKeyGatewayBatchProtoDto = FederationGatewayApi.Models.Proto.TemporaryExposureKeyGatewayBatchDto;
namespace DIGNDB.App.SmitteStop.Testing.ServiceTest.Gateway
{
public class SetupMockedServices
{
public ExposureKeyMock _exposureKeyMock { get; set; }
public WebContextMock _webContextMock { get; set; }
public CountryMockFactory _countryFactory { get; set; }
public MockRandomGenerator _rndGenerator { get; set; }
public SetupMockedServices()
{
_exposureKeyMock = new ExposureKeyMock();
_webContextMock = new WebContextMock();
_countryFactory = new CountryMockFactory();
_rndGenerator = new MockRandomGenerator();
}
public void SetupWebContextReaderMock(Mock<IGatewayWebContextReader> gatewayContextReader)
{
gatewayContextReader.Setup(mock => mock.GetItemsFromRequest(It.IsAny<string>())).Returns((string response) =>
{
return response == null
? new List<TemporaryExposureKeyGatewayDto>()
: _exposureKeyMock.MockListOfTemporaryExposureKeyDto();
});
gatewayContextReader.Setup(mock => mock.ReadHttpContextStream(It.IsAny<HttpResponseMessage>())).Returns((HttpResponseMessage responseMessage) =>
{
if (responseMessage?.RequestMessage == null)
{
throw new Exception();
}
return _webContextMock.MockValidBodyJson();
});
}
public void SetupWebContextReaderMockWithBadContext(Mock<IGatewayWebContextReader> gatewayContextReader)
{
gatewayContextReader.Setup(mock => mock.GetItemsFromRequest(It.IsAny<string>())).Returns((string response) =>
{
throw new Exception();
});
}
public void SetupKeyFilterMock(Mock<IKeyFilter> keyFilter)
{
IList<string> errorMessageList = new List<string>();
keyFilter.Setup(mock => mock.MapKeys(It.IsAny<IList<TemporaryExposureKeyGatewayDto>>())).Returns((IList<TemporaryExposureKeyGatewayDto> keys) =>
{
return _exposureKeyMock.MockListOfTemporaryExposureKeys();
});
keyFilter.Setup(mock => mock.ValidateKeys(It.IsAny<IList<TemporaryExposureKey>>(), out errorMessageList)).Returns((IList<TemporaryExposureKey> keys, IList<string> errorMessageList) =>
{
return _exposureKeyMock.MockListOfTemporaryExposureKeys();
});
}
public void SetupEpochConverterMock(Mock<IEpochConverter> epochConverter)
{
epochConverter.Setup(mock => mock.ConvertToEpoch(It.IsAny<DateTime>())).Returns((DateTime date) =>
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date - epoch).TotalSeconds);
});
epochConverter.Setup(mock => mock.ConvertFromEpoch(It.IsAny<long>())).Returns((long epochTime) =>
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(epochTime);
});
}
public void SetupTemopraryExposureKeyRepositoryMock(Mock<ITemporaryExposureKeyRepository> tempKeyRepository)
{
tempKeyRepository.Setup(mock => mock.AddTemporaryExposureKeysAsync(It.IsAny<List<TemporaryExposureKey>>())).Returns((List<TemporaryExposureKey> keys) =>
{
return Task.CompletedTask;
});
List<TemporaryExposureKey> keys = new List<TemporaryExposureKey>();
for (int i = 0; i < _exposureKeyMock.MockListLength - 2; i++)
{
keys.Add(_exposureKeyMock.MockValidKey());
}
keys.Add(ExposureKeyMock._potentialDuplicate01);
keys.Add(ExposureKeyMock._potentialDuplicate02);
tempKeyRepository.Setup(mock => mock.GetAllKeysNextBatch(It.IsAny<int>(), It.IsAny<int>()))
.Returns((int numberOfRecordsToSkip, int batchSize) => keys);
tempKeyRepository.Setup(mock => mock.GetNextBatchOfKeysWithRollingStartNumberThresholdAsync(It.IsAny<long>(), It.IsAny<int>(), It.IsAny<int>()))
.Returns(() => Task.Run(() => keys as IList<TemporaryExposureKey>));
}
public void SetupSignatureServiceMock(Mock<ISignatureService> signatureService)
{
signatureService.Setup(mock => mock.Sign(It.IsAny<TemporaryExposureKeyGatewayBatchProtoDto>(), It.IsAny<SortOrder>())).Returns((TemporaryExposureKeyGatewayBatchProtoDto protoKeyBatch, SortOrder sortOrder) =>
{
return _rndGenerator.GenerateKeyData(16);
});
}
public void SetupEncodingServiceMock(Mock<IEncodingService> encodingService)
{
encodingService.Setup(mock => mock.DecodeFromBase64(It.IsAny<string>())).Returns((string encodedData) =>
{
if (encodedData == null) return null;
byte[] encodedBytes = Convert.FromBase64String(encodedData);
return System.Text.Encoding.UTF8.GetString(encodedBytes);
});
encodingService.Setup(mock => mock.EncodeToBase64(It.IsAny<string>())).Returns((string plainText) =>
{
if (plainText == null) return null;
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return plainTextBytes == null ? null : Convert.ToBase64String(plainTextBytes);
});
encodingService.Setup(mock => mock.EncodeToBase64(It.IsAny<byte[]>())).Returns((byte[] textBytes) =>
{
return textBytes == null ? null : Convert.ToBase64String(textBytes);
});
}
public void SetupSettingsServiceMock(Mock<ISettingsService> settingsService)
{
settingsService.Setup(mock => mock.GetGatewayUploadState());
settingsService.Setup(mock => mock.SaveGatewaySyncState(It.IsAny<GatewayUploadState>()));
}
public void SetupStoreServiceMock(Mock<IEFGSKeyStoreService> storeService)
{
storeService.Setup(mock => mock.FilterAndSaveKeys(It.IsAny<IList<TemporaryExposureKeyGatewayDto>>()));
}
public void SetupKeyValidatorMock(Mock<IKeyValidator> keyValidator)
{
var errorMessage = String.Empty;
keyValidator.Setup(mock => mock.ValidateKeyAPI(It.IsAny<TemporaryExposureKey>(), out errorMessage)).Returns((TemporaryExposureKey key, string errorMessage) =>
{
if (key.KeyData.Length == 16)
{
return true;
}
return false;
});
keyValidator.Setup(mock => mock.ValidateKeyGateway(It.IsAny<TemporaryExposureKey>(), out errorMessage)).Returns((TemporaryExposureKey key, string errorMessage) =>
{
if (key.Origin != _countryFactory.GenerateCountry(7, "DK") && key.KeyData.Length == 16)
{
return true;
}
return false;
});
}
public void SetupHttpGatewayClientMock(Mock<IGatewayHttpClient> client)
{
var empty = true;
client.Setup(mock => mock.SendAsync(It.IsAny<HttpRequestMessage>())).Returns((HttpRequestMessage message) =>
{
var header = message.Headers.GetValues("batchTag").SingleOrDefault();
var endBatchTagValue = $"{DateTime.UtcNow.Date.ToString("yyyy-MM-dd").Replace("-", string.Empty)}-{2}";
var responseMessage = new HttpResponseMessage();
if (header == endBatchTagValue)
{
responseMessage = _webContextMock.MockHttpResponse(empty);
}
else
{
responseMessage = _webContextMock.MockHttpResponse();
}
return Task.FromResult(responseMessage);
});
client.Setup(mock => mock.GetAsync(It.IsAny<string>())).Returns(Task.FromResult(_webContextMock.MockHttpResponse()));
}
public void SetupMapperAndCountryRepositoryMock(Mock<ICountryRepository> countryRepository)
{
var denmark = new Country() { Id = 2, Code = "DK" };
var germany = new Country() { Id = 3, Code = "DE" };
var netherlands = new Country() { Id = 4, Code = "NL" };
var NonExistingCountryCode = "XY";
countryRepository
.Setup(repo => repo.FindByIsoCode(It.Is<string>(code => code == "NL")))
.Returns(netherlands);
countryRepository
.Setup(repo => repo.FindByIsoCode(It.Is<string>(code => code == "DE")))
.Returns(germany);
countryRepository
.Setup(repo => repo.FindByIsoCode(It.Is<string>(code => code == "DK")))
.Returns(denmark);
countryRepository
.Setup(repo => repo.FindByIsoCode(It.Is<string>(code => code != "DE" && code != "NL" && code != "DK")))
.Returns(new Country() { Id = 0, Code = NonExistingCountryCode });
var mockedVisitedCountries = new List<Country>
{
denmark,
germany,
netherlands
};
countryRepository
.Setup(repo => repo.FindByIsoCodes(It.IsAny<IList<string>>()))
.Returns(
(IList<string> param) => mockedVisitedCountries.Where(country => param.Contains(country.Code))
);
}
public IMapper CreateAutoMapperWithDependencies(ICountryRepository repository)
{
IServiceCollection services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(repository);
services.AddAutoMapper(typeof(TemporaryExposureKeyToEuGatewayMapper));
IServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetService<IMapper>();
}
public EuGatewayConfig CreateEuGatewayConfig()
{
var euGatewayConfig = new EuGatewayConfig
{
Url = "https://acc-efgs-ws.tech.ec.europa.eu/",
AuthenticationCertificateFingerprint = "A3C3E533CC9FEACA026F99F688F4488B5FC16BD0E6A80E6E0FC03760983DBF3F",
SigningCertificateFingerprint = "979673B55DB0B7E2B35B12CF2A342655F059314BC46323C43BCD3BFC82374BFB"
};
return euGatewayConfig;
}
private void AddErrorList(IList<string> errorList)
{
errorList.Add("Bad error!");
errorList.Add("Scary error!");
errorList.Add("EndOfTheWorld error!");
}
}
}
| 43.661818 | 220 | 0.593487 | [
"MIT"
] | folkehelseinstituttet/Fhi.Smittestopp.Backend | DIGNDB.App.SmitteStop.Testing/ServiceTest/Gateway/SetupMockedServices.cs | 12,009 | C# |
namespace Sitecore.Feature.Catalog.Models.JsonResults
{
using Foundation.CommerceServer.Extensions;
using Foundation.CommerceServer.Managers;
using Sitecore.Commerce.Entities.GiftCards;
using Sitecore.Commerce.Services;
using Sitecore.Diagnostics;
using Sitecore.Feature.Base.Models.JsonResults;
/// <summary>
/// The Json result of a request to retrieve gift card information.
/// </summary>
public class GiftCardBaseJsonResult : BaseJsonResult
{
/// <summary>
/// Initializes a new instance of the <see cref="GiftCardBaseJsonResult"/> class.
/// </summary>
public GiftCardBaseJsonResult()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GiftCardBaseJsonResult"/> class.
/// </summary>
/// <param name="result">The service provider result.</param>
public GiftCardBaseJsonResult(ServiceProviderResult result)
: base(result)
{
}
/// <summary>
/// Gets or sets the external identifier.
/// </summary>
/// <value>
/// The external identifier.
/// </value>
public string ExternalId { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the customer identifier.
/// </summary>
/// <value>
/// The customer identifier.
/// </value>
public string CustomerId { get; set; }
/// <summary>
/// Gets or sets the name of the shop.
/// </summary>
/// <value>
/// The name of the shop.
/// </value>
public string ShopName { get; set; }
/// <summary>
/// Gets or sets the currency code.
/// </summary>
/// <value>
/// The currency code.
/// </value>
public string CurrencyCode { get; set; }
/// <summary>
/// Gets or sets the balance.
/// </summary>
/// <value>
/// The balance.
/// </value>
public decimal Balance { get; set; }
/// <summary>
/// Gets or sets the formatted balance.
/// </summary>
/// <value>
/// The formatted balance.
/// </value>
public string FormattedBalance { get; set; }
/// <summary>
/// Gets or sets the original amount.
/// </summary>
/// <value>
/// The original amount.
/// </value>
public string OriginalAmount { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description { get; set; }
/// <summary>
/// Initializes the specified gift card.
/// </summary>
/// <param name="giftCard">The gift card.</param>
public virtual void Initialize(GiftCard giftCard)
{
Assert.ArgumentNotNull(giftCard, "giftCard");
var currencyCode = StorefrontManager.GetCustomerCurrency();
this.ExternalId = giftCard.ExternalId;
this.Name = giftCard.Name;
this.CustomerId = giftCard.CustomerId;
this.ShopName = giftCard.ShopName;
this.CurrencyCode = giftCard.CurrencyCode;
this.Balance = giftCard.Balance;
this.FormattedBalance = giftCard.Balance.ToCurrency(currencyCode);
this.OriginalAmount = giftCard.OriginalAmount.ToCurrency(currencyCode);
this.Description = giftCard.Description;
}
}
} | 30.376 | 89 | 0.537003 | [
"Apache-2.0"
] | epam/Sitecore-Reference-Storefront-on-Habitat | src/Feature/Catalog/code/Models/JsonResults/GiftCardBaseJsonResult.cs | 3,799 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.EventGrid.V20200401Preview.Outputs
{
[OutputType]
public sealed class EventChannelSourceResponse
{
/// <summary>
/// The identifier of the resource that's the source of the events.
/// This represents a unique resource in the partner's resource model.
/// </summary>
public readonly string? Source;
[OutputConstructor]
private EventChannelSourceResponse(string? source)
{
Source = source;
}
}
}
| 28.482759 | 81 | 0.673123 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/EventGrid/V20200401Preview/Outputs/EventChannelSourceResponse.cs | 826 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace IdentityTest.WebApp.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "IdentityTest.WebApp.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.60177 | 149 | 0.666462 | [
"MIT"
] | Code-Inside/Samples | 2016/IdentityTest/IdentityTest.WebApp/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,509 | C# |
// Author: Gennady Gorlachev ([email protected])
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace WL
{
public class ImageFile
{
/// <summary>
/// Класс обслуживания файла пленки с тестом
/// </summary>
/// <param name="path"></param>
public ImageFile(string path)
{
_path = path;
_uri = new Uri(_path);
_image = BitmapFrame.Create(_uri);
}
public override string ToString()
{
return Path;
}
private String _path;
public String Path { get { return _path; } }
private Uri _uri;
public Uri Uri { get { return _uri; } }
private BitmapFrame _image;
public BitmapFrame Image { get { return _image; } }
}
public class WLParams : INotifyPropertyChanged
{
bool _flipVertical = false;
bool _flipHorisontal = false;
/// <summary>
/// Флаг отражения по горизонтали
/// </summary>
public bool FlipVertical
{
get { return this._flipVertical; }
set
{
this._flipVertical = value;
OnPropertyChanged("FlipVertical");
}
}
/// <summary>
/// Флаг отражения по горизонтали
/// </summary>
public bool FlipHorisontal
{
get { return this._flipHorisontal; }
set
{
this._flipHorisontal = value;
OnPropertyChanged("FlipHorisontal");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
/// <summary>
/// Клас положения изоцентра формирующего устройства в пространстве (IEC).
/// </summary>
public class IsocenterParams : INotifyPropertyChanged
{
private double _x;
private double _y;
private double _z;
/// <summary>
/// Положение изоцентра по X
/// </summary>
public double X
{
get { return this._x; }
set
{
this._x = value;
OnPropertyChanged("X");
}
}
/// <summary>
/// Положение изоцентра по Y
/// </summary>
public double Y
{
get { return this._y; }
set
{
this._y = value;
OnPropertyChanged("Y");
}
}
/// <summary>
/// Положение изоцентра по Z
/// </summary>
public double Z
{
get { return this._z; }
set
{
this._z = value;
OnPropertyChanged("Z");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
/// <summary>
/// Все данные, относящиеся к отдельно взятому полю,
/// включая координаты изображения на общем снимке,
/// параметры подгонки положения изображения MLC и конического коллиматора.
/// </summary>
public class BeamParams : INotifyPropertyChanged
{
#region Local variables
private double _ga;
private double _ca;
private double _ta;
private Point _o;
private double _fa;
private double _fca;
private Point _cc;
private Point _mlc;
private double _ps;
#endregion
#region Constructors
public BeamParams()
{
Ga = 0;
Ca = 0;
Ta = 0;
}
public BeamParams(double ga, double ca, double ta)
{
Ga = ga;
Ca = ca;
Ta = ta;
}
public BeamParams(BeamParams b)
{
this.Set(b);
}
#endregion
#region Properties
/// <summary>
/// Угол поворота головки в градусах.
/// </summary>
public double Ga
{
get { return this._ga; }
set
{
this._ga = value;
OnPropertyChanged("Ga");
}
}
/// <summary>
/// Угол поворота коллиматора в градусах.
/// </summary>
public double Ca
{
get { return this._ca; }
set
{
this._ca = value;
OnPropertyChanged("Ca");
}
}
/// <summary>
/// Угол поворота стола в градусах.
/// </summary>
public double Ta
{
get { return this._ta; }
set
{
this._ta = value;
OnPropertyChanged("Ta");
}
}
/// <summary>
/// Положение центра поля (середины шарика) на изображении в пикселах
/// </summary>
public Point O
{
get { return this._o; }
set
{
this._o = value;
OnPropertyChanged("O");
}
}
/// <summary>
/// Угол направления на головку в градусах.
/// Когда головка сверху изображения угол равен нулю,
/// далее с шагом 90 градусов по часовой стрелке.
/// </summary>
public double FA
{
get { return this._fa; }
set
{
this._fa = value;
OnPropertyChanged("FA");
}
}
/// <summary>
/// Небольшой угол коррекции поворота пленки от идеального положения.
/// Используется для описания направления на головку совместно с FA.
/// </summary>
public double FCA
{
get { return this._fca; }
set
{
this._fca = value;
OnPropertyChanged("FCA");
}
}
/// <summary>
/// Положение центра поля конического коллиматора в см в системе координат коллиматора
/// </summary>
public Point CC
{
get { return this._cc; }
set
{
this._cc = value;
OnPropertyChanged("CC");
}
}
/// <summary>
/// Положение центра поля MLC в см в системе координат коллиматора
/// </summary>
public Point Mlc
{
get { return this._mlc; }
set
{
this._mlc = value;
OnPropertyChanged("Mlc");
}
}
/// <summary>
/// Размер пиксела изображения в см (стартует с 25.4 / DPI * 1.08).
/// </summary>
public double PS
{
get { return this._ps; }
set
{
this._ps = value;
OnPropertyChanged("PS");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
/// <summary>
/// Выжимка properties, связанных с подгонкой
/// </summary>
public double[] FitParameters
{
get
{
//return new double[] { _o.X, _o.Y, _cc.X, _cc.Y, _mlc.X, _mlc.Y, _ps, _fca };
return new double[] { _cc.X, _cc.Y, _mlc.X, _mlc.Y, _ps, _fca };
}
set
{
//_o = new Point(value[0], value[1]);
//_cc = new Point(value[2], value[3]);
//_mlc = new Point(value[4], value[5]);
//_ps = value[6];
//_fca = value[7];
_cc = new Point(value[0], value[1]);
_mlc = new Point(value[2], value[3]);
_ps = value[4];
_fca = value[5];
}
}
#endregion
#region Utilities
/// <summary>
/// Создание полноценной копии объекта
/// </summary>
/// <returns></returns>
public BeamParams Clone()
{
BeamParams b = new BeamParams();
b.Set(this);
return b;
}
/// <summary>
/// Создание полноценной копии объекта
/// </summary>
/// <returns></returns>
public void Set(BeamParams b)
{
Ga = b.Ga;
Ca = b.Ca;
Ta = b.Ta;
FA = b.FA;
FCA = b.FCA;
PS = b.PS;
if (b.O != null) O = new Point(b.O.X, b.O.Y);
if (b.CC != null) CC = new Point(b.CC.X, b.CC.Y);
if (b.Mlc != null) Mlc = new Point(b.Mlc.X, b.Mlc.Y);
}
/// <summary>
/// Преобразование координат из системы MLC в систему пучка
/// </summary>
/// <param name="p">точка в системе MLC</param>
/// <returns>точка в системе пучка</returns>
public Point PointFromMlcToBeam(Point p)
{
double a = (FA + FCA) * System.Math.PI / 180.0;
double sca = System.Math.Sin(a), cca = System.Math.Cos(a);
double xm = Mlc.X + p.X, ym = Mlc.Y + p.Y;
return new Point(xm * cca + ym * sca, -xm * sca + ym * cca);
}
/// <summary>
/// Преобразование координат из системы CC в систему пучка
/// </summary>
/// <param name="p">точка в системе CC</param>
/// <returns>точка в системе пучка</returns>
public Point PointFromCCToBeam(Point p)
{
double a = (FA + FCA) * System.Math.PI / 180.0;
double sca = System.Math.Sin(a), cca = System.Math.Cos(a);
double xm = CC.X + p.X, ym = CC.Y + p.Y;
return new Point(xm * cca + ym * sca, -xm * sca + ym * cca);
}
#endregion
}
[ValueConversion(typeof(double), typeof(String))]
public class TaConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("Ta = {0}", (double)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
| 26.691932 | 103 | 0.468902 | [
"MIT"
] | RadOncSys/WL | WL/Data.cs | 12,023 | C# |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using Covid19Radar.Common;
namespace Covid19Radar.Droid
{
#if DEBUG
[Application(Debuggable = true)]
#else
[Application(Debuggable = false)]
#endif
public class MainApplication : Application
{
public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
}
}
} | 25.21875 | 99 | 0.728625 | [
"MPL-2.0-no-copyleft-exception",
"MPL-2.0",
"Apache-2.0"
] | zipperpull/cocoa | Covid19Radar/Covid19Radar.Android/MainApplication.cs | 809 | 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("CDirectory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CDirectory")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("2b899b27-79a8-47d2-94a4-b04e1aa017b9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.472222 | 84 | 0.743514 | [
"MIT"
] | repletsin5/xTerminal | CDirectory/Properties/AssemblyInfo.cs | 1,352 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Borders : MonoBehaviour {
void OnTriggerEnter(Collider other) {
//colisión de cabeza de la serpiente a una pared
if (other.CompareTag("SnakeHead")){
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
| 24.266667 | 68 | 0.771978 | [
"MIT"
] | lytves/snake | Assets/Scripts/Borders.cs | 367 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics.Tensors;
using System.Text;
using NnCase.Converter.K210.Model.Layers;
using NnCase.Converter.Model;
using NnCase.Converter.Model.Layers;
namespace NnCase.Converter.Transforms
{
public class K210EliminateConv2dUploadTransform : Transform
{
protected override bool SkipSelfContainedCheck => true;
protected override bool OnTryMatch(Layer layer, TransformContext context)
{
try
{
if (layer is K210Conv2d conv2d)
{
context.Inputs.Add(conv2d.Input);
context.MatchedLayers.Add(layer);
foreach (var nextLayer in conv2d.Output.Connections.Select(o => o.To.Owner))
{
if (nextLayer is K210Upload upload)
{
context.Outputs.Add(upload.Output);
}
else
{
continue;
}
context.MatchedLayers.Add(nextLayer);
return true;
}
return false;
}
return false;
}
catch
{
return false;
}
}
public override void Process(TransformContext context)
{
var conv2d = (K210Conv2d)context.MatchedLayers[0];
var upload = (K210Upload)context.MatchedLayers[1];
var input = conv2d.Output;
var output = upload.Output;
var oldOuts = output.Connections.Select(o => o.To).ToList();
foreach (var oldOut in oldOuts)
oldOut.SetConnection(input);
}
}
}
| 29.375 | 96 | 0.499468 | [
"Apache-2.0"
] | svija/nncase | src/NnCase.Converter.K210/Transforms/K210EliminateConv2dUploadTransform.cs | 1,882 | C# |
namespace HumanResources
{
public sealed class Person
{
public string Name;
public string MBTI;
public string Descriptor;
}
} | 18 | 33 | 0.617284 | [
"MIT"
] | Timwi/KtaneHumanResources | Assets/Person.cs | 164 | 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("CorrelatorSharp.ApplicationInsights")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CorrelatorSharp.ApplicationInsights")]
[assembly: AssemblyCopyright("Copyright © Ivan Zlatev 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c320063b-3d4c-4207-9ba6-3051758ac813")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")] | 41.594595 | 85 | 0.736842 | [
"MIT"
] | CorrelatorSharp/CorrelatorSharp.ApplicationInsights | CorrelatorSharp.ApplicationInsights/Properties/AssemblyInfo.cs | 1,542 | C# |
namespace PetStore.Models
{
using System;
using Newtonsoft.Json;
public class Order
{
[JsonProperty("id")]
public Int64 Id { get; set; }
[JsonProperty("petId")]
public Int64 PetId { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
[JsonProperty("shipDate")]
public DateTimeOffset ShipDate { get; set; }
[JsonProperty("status")]
public OrderStatus Status { get; set; }
[JsonProperty("complete")]
public bool Complete { get; set; }
}
}
| 20 | 52 | 0.548333 | [
"Apache-2.0"
] | bghadami/HomeChallenge | Task 3/Petstore-ApiTest/Models/Order.cs | 602 | C# |
using System;
using System.Collections.Generic;
using Emeraude.Configuration.Exceptions;
using Emeraude.Configuration.Options;
using Emeraude.Infrastructure.Identity.ExternalProviders;
using Microsoft.AspNetCore.Identity;
namespace Emeraude.Infrastructure.Identity.Options;
/// <summary>
/// Options for identity infrastructure of Emeraude.
/// </summary>
public class EmIdentityOptions : IEmOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="EmIdentityOptions"/> class.
/// </summary>
public EmIdentityOptions()
{
this.AdditionalRoles = new Dictionary<string, string[]>();
this.ExternalProvidersAuthenticators = new List<IExternalProviderAuthenticator>();
this.SourceIdentityOptions = new IdentityOptions();
this.AccessTokenOptions = new AccessTokenOptions();
this.RefreshTokenOptions = new RefreshTokenOptions();
this.SetDefaults();
}
/// <summary>
/// Dictionary that contains all additional roles and their claims.
/// </summary>
public Dictionary<string, string[]> AdditionalRoles { get; set; }
/// <summary>
/// Internal options for identity management of ASP.NET.
/// </summary>
public IdentityOptions SourceIdentityOptions { get; set; }
/// <summary>
/// Access token options for the API authentication.
/// </summary>
public AccessTokenOptions AccessTokenOptions { get; set; }
/// <summary>
/// Refresh token options for configure the access token refreshing.
/// </summary>
public RefreshTokenOptions RefreshTokenOptions { get; set; }
/// <summary>
/// Collection of all external provider authenticators implementations used in the framework.
/// </summary>
public List<IExternalProviderAuthenticator> ExternalProvidersAuthenticators { get; }
/// <summary>
/// Add additional role to the roles of the system. It is preferred to be added before first initialization of the system.
/// </summary>
/// <param name="roleName"></param>
/// <param name="claims"></param>
public void AddRole(string roleName, string[] claims)
{
this.AdditionalRoles[roleName] = claims;
}
/// <inheritdoc/>
public void Validate()
{
if (this.AccessTokenOptions == null ||
string.IsNullOrWhiteSpace(this.AccessTokenOptions.Key) ||
string.IsNullOrWhiteSpace(this.AccessTokenOptions.Issuer))
{
throw new EmInvalidConfigurationException("There is not a correct setup for the access token options of the identity infrastructure");
}
}
private void SetDefaults()
{
this.SourceIdentityOptions.User.RequireUniqueEmail = true;
this.SourceIdentityOptions.Password.RequireDigit = true;
this.SourceIdentityOptions.Password.RequiredLength = EmIdentityConstants.PasswordRequiredLength;
this.SourceIdentityOptions.Password.RequireNonAlphanumeric = false;
this.SourceIdentityOptions.Password.RequireUppercase = false;
this.SourceIdentityOptions.Password.RequireLowercase = false;
this.SourceIdentityOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(EmIdentityConstants.DefaultLockoutTimeSpanMinutes);
this.SourceIdentityOptions.Lockout.MaxFailedAccessAttempts = EmIdentityConstants.MaxFailedAccessAttempts;
this.SourceIdentityOptions.SignIn.RequireConfirmedEmail = true;
this.SourceIdentityOptions.SignIn.RequireConfirmedAccount = true;
}
} | 40.37931 | 146 | 0.71392 | [
"Apache-2.0"
] | emeraudeframework/emeraude | src/Emeraude.Infrastructure.Identity/Options/EmIdentityOptions.cs | 3,515 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF13
{
class Program
{
static void Main(string[] args)
{
}
}
}
| 14.1875 | 39 | 0.634361 | [
"MIT"
] | zmrbak/EntityFramework | 配套代码/EF13/EF13/Program.cs | 229 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace awesome_site
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 18.894737 | 57 | 0.662953 | [
"Unlicense"
] | aa-festival/awesome-site | src/awesome-site/Program.cs | 359 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization.Converters;
namespace System.Text.Json.Node
{
/// <summary>
/// Represents a mutable JSON object.
/// </summary>
[DebuggerDisplay("JsonObject[{Count}]")]
[DebuggerTypeProxy(typeof(DebugView))]
public sealed partial class JsonObject : JsonNode
{
private JsonElement? _jsonElement;
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that is empty.
/// </summary>
/// <param name="options">Options to control the behavior.</param>
public JsonObject(JsonNodeOptions? options = null) : base(options) { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that contains the specified <paramref name="properties"/>.
/// </summary>
/// <param name="properties">The properties to be added.</param>
/// <param name="options">Options to control the behavior.</param>
public JsonObject(IEnumerable<KeyValuePair<string, JsonNode?>> properties, JsonNodeOptions? options = null)
{
foreach (KeyValuePair<string, JsonNode?> node in properties)
{
Add(node.Key, node.Value);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that contains properties from the specified <see cref="JsonElement"/>.
/// </summary>
/// <returns>
/// The new instance of the <see cref="JsonObject"/> class that contains properties from the specified <see cref="JsonElement"/>.
/// </returns>
/// <param name="element">The <see cref="JsonElement"/>.</param>
/// <param name="options">Options to control the behavior.</param>
/// <returns>A <see cref="JsonObject"/>.</returns>
public static JsonObject? Create(JsonElement element, JsonNodeOptions? options = null)
{
if (element.ValueKind == JsonValueKind.Null)
{
return null;
}
if (element.ValueKind == JsonValueKind.Object)
{
return new JsonObject(element, options);
}
throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Object)));
}
internal JsonObject(JsonElement element, JsonNodeOptions? options = null) : base(options)
{
Debug.Assert(element.ValueKind == JsonValueKind.Object);
_jsonElement = element;
}
/// <summary>
/// Returns the value of a property with the specified name.
/// </summary>
/// <param name="propertyName">The name of the property to return.</param>
/// <param name="jsonNode">The JSON value of the property with the specified name.</param>
/// <returns>
/// <see langword="true"/> if a property with the specified name was found; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) =>
((IDictionary<string, JsonNode?>)this).TryGetValue(propertyName, out jsonNode);
/// <inheritdoc/>
public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (_jsonElement.HasValue)
{
// Write the element without converting to nodes.
_jsonElement.Value.WriteTo(writer);
}
else
{
options ??= JsonSerializerOptions.s_defaultOptions;
writer.WriteStartObject();
foreach (KeyValuePair<string, JsonNode?> item in this)
{
writer.WritePropertyName(item.Key);
JsonNodeConverter.Instance.Write(writer, item.Value, options);
}
writer.WriteEndObject();
}
}
internal JsonNode? GetItem(string propertyName)
{
if (TryGetPropertyValue(propertyName, out JsonNode? value))
{
return value;
}
// Return null for missing properties.
return null;
}
internal override void GetPath(List<string> path, JsonNode? child)
{
if (child != null)
{
string propertyName = FindNode(child)!.Value.Key;
if (propertyName.IndexOfAny(ReadStack.SpecialCharacters) != -1)
{
path.Add($"['{propertyName}']");
}
else
{
path.Add($".{propertyName}");
}
}
if (Parent != null)
{
Parent.GetPath(path, this);
}
}
internal void SetItem(string propertyName, JsonNode? value)
{
if (propertyName == null)
{
throw new ArgumentNullException(nameof(propertyName));
}
JsonNode? existing = SetNode(propertyName, value);
DetachParent(existing);
}
private void DetachParent(JsonNode? item)
{
if (item != null)
{
item.Parent = null;
}
// Prevent previous child from being returned from these cached variables.
ClearLastValueCache();
}
[ExcludeFromCodeCoverage] // Justification = "Design-time"
private class DebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private JsonObject _node;
public DebugView(JsonObject node)
{
_node = node;
}
public string Json => _node.ToJsonString();
public string Path => _node.GetPath();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private DebugViewProperty[] Items
{
get
{
DebugViewProperty[] properties = new DebugViewProperty[_node.Count];
int i = 0;
foreach (KeyValuePair<string, JsonNode?> item in _node)
{
properties[i].PropertyName = item.Key;
properties[i].Value = item.Value;
i++;
}
return properties;
}
}
[DebuggerDisplay("{Display,nq}")]
private struct DebugViewProperty
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public JsonNode? Value;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string PropertyName;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string Display
{
get
{
if (Value == null)
{
return $"{PropertyName} = null";
}
if (Value is JsonValue)
{
return $"{PropertyName} = {Value.ToJsonString()}";
}
if (Value is JsonObject jsonObject)
{
return $"{PropertyName} = JsonObject[{jsonObject.Count}]";
}
JsonArray jsonArray = (JsonArray)Value;
return $"{PropertyName} = JsonArray[{jsonArray.Count}]";
}
}
}
}
}
}
| 34.850427 | 149 | 0.521153 | [
"MIT"
] | Saran51/runtime | src/libraries/System.Text.Json/src/System/Text/Json/Node/JsonObject.cs | 8,157 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Cake.Common.IO.Paths;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
namespace Cake.Common.IO
{
/// <summary>
/// Contains extension methods for working with directories.
/// </summary>
[CakeAliasCategory("Directory Operations")]
public static class DirectoryAliases
{
/// <summary>
/// Gets a directory path from string.
/// </summary>
/// <example>
/// <code>
/// // Get the temp directory.
/// var root = Directory("./");
/// var temp = root + Directory("temp");
///
/// // Clean the directory.
/// CleanDirectory(temp);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The path.</param>
/// <returns>A directory path.</returns>
[CakeMethodAlias]
[CakeNamespaceImport("Cake.Common.IO.Paths")]
public static ConvertableDirectoryPath Directory(this ICakeContext context, string path)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return new ConvertableDirectoryPath(new DirectoryPath(path));
}
/// <summary>
/// Deletes the specified directories.
/// </summary>
/// <example>
/// <code>
/// var directoriesToDelete = new DirectoryPath[]{
/// Directory("be"),
/// Directory("gone")
/// };
/// DeleteDirectories(directoriesToDelete, recursive:true);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
/// <param name="recursive">Will perform a recursive delete if set to <c>true</c>.</param>
[Obsolete("Use the overload that accepts DeleteDirectorySettings instead.")]
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectories(this ICakeContext context, IEnumerable<DirectoryPath> directories, bool recursive = false)
{
if (directories == null)
{
throw new ArgumentNullException(nameof(directories));
}
DeleteDirectories(context, directories, new DeleteDirectorySettings { Recursive = recursive });
}
/// <summary>
/// Deletes the specified directories.
/// </summary>
/// <example>
/// <code>
/// var directoriesToDelete = new DirectoryPath[]{
/// Directory("be"),
/// Directory("gone")
/// };
/// DeleteDirectories(directoriesToDelete, new DeleteDirectorySettings {
/// Recursive = true,
/// Force = true
/// });
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
/// <param name="settings">The delete settings.</param>
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectories(this ICakeContext context, IEnumerable<DirectoryPath> directories, DeleteDirectorySettings settings)
{
if (directories == null)
{
throw new ArgumentNullException(nameof(directories));
}
foreach (var directory in directories)
{
DeleteDirectory(context, directory, settings);
}
}
/// <summary>
/// Deletes the specified directories.
/// </summary>
/// <example>
/// <code>
/// var directoriesToDelete = new []{
/// "be",
/// "gone"
/// };
/// DeleteDirectories(directoriesToDelete, recursive:true);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
/// <param name="recursive">Will perform a recursive delete if set to <c>true</c>.</param>
[Obsolete("Use the overload that accepts DeleteDirectorySettings instead.")]
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectories(this ICakeContext context, IEnumerable<string> directories, bool recursive = false)
{
DeleteDirectories(context, directories, new DeleteDirectorySettings { Recursive = recursive });
}
/// <summary>
/// Deletes the specified directories.
/// </summary>
/// <example>
/// <code>
/// var directoriesToDelete = new []{
/// "be",
/// "gone"
/// };
/// DeleteDirectories(directoriesToDelete, new DeleteDirectorySettings {
/// Recursive = true,
/// Force = true
/// });
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
/// <param name="settings">The delete settings.</param>
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectories(this ICakeContext context, IEnumerable<string> directories, DeleteDirectorySettings settings)
{
if (directories == null)
{
throw new ArgumentNullException(nameof(directories));
}
var paths = directories.Select(p => new DirectoryPath(p));
foreach (var directory in paths)
{
DeleteDirectory(context, directory, settings);
}
}
/// <summary>
/// Deletes the specified directory.
/// </summary>
/// <example>
/// <code>
/// DeleteDirectory("./be/gone", recursive:true);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
/// <param name="recursive">Will perform a recursive delete if set to <c>true</c>.</param>
[Obsolete("Use the overload that accepts DeleteDirectorySettings instead.")]
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectory(this ICakeContext context, DirectoryPath path, bool recursive = false)
{
DeleteDirectory(context, path, new DeleteDirectorySettings { Recursive = recursive });
}
/// <summary>
/// Deletes the specified directory.
/// </summary>
/// <example>
/// <code>
/// DeleteDirectory("./be/gone", new DeleteDirectorySettings {
/// Recursive = true,
/// Force = true
/// });
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
/// <param name="settings">The delete settings.</param>
[CakeMethodAlias]
[CakeAliasCategory("Delete")]
public static void DeleteDirectory(this ICakeContext context, DirectoryPath path, DeleteDirectorySettings settings)
{
DirectoryDeleter.Delete(context, path, settings);
}
/// <summary>
/// Cleans the directories matching the specified pattern.
/// Cleaning the directory will remove all its content but not the directory itself.
/// </summary>
/// <example>
/// <code>
/// CleanDirectories("./src/**/bin/debug");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="pattern">The pattern to match.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectories(this ICakeContext context, string pattern)
{
var directories = context.GetDirectories(pattern);
if (directories.Count == 0)
{
context.Log.Verbose("The provided pattern did not match any directories.");
return;
}
CleanDirectories(context, directories);
}
/// <summary>
/// Cleans the directories matching the specified pattern.
/// Cleaning the directory will remove all its content but not the directory itself.
/// </summary>
/// <example>
/// <code>
/// Func<IFileSystemInfo, bool> exclude_node_modules =
/// fileSystemInfo=>!fileSystemInfo.Path.FullPath.EndsWith(
/// "node_modules",
/// StringComparison.OrdinalIgnoreCase);
/// CleanDirectories("./src/**/bin/debug", exclude_node_modules);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="pattern">The pattern to match.</param>
/// <param name="predicate">The predicate used to filter directories based on file system information.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectories(this ICakeContext context, string pattern, Func<IFileSystemInfo, bool> predicate)
{
var directories = context.GetDirectories(pattern, new GlobberSettings { Predicate = predicate });
if (directories.Count == 0)
{
context.Log.Verbose("The provided pattern did not match any directories.");
return;
}
CleanDirectories(context, directories);
}
/// <summary>
/// Cleans the specified directories.
/// Cleaning a directory will remove all its content but not the directory itself.
/// </summary>
/// <example>
/// <code>
/// var directoriesToClean = GetDirectories("./src/**/bin/");
/// CleanDirectories(directoriesToClean);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectories(this ICakeContext context, IEnumerable<DirectoryPath> directories)
{
if (directories == null)
{
throw new ArgumentNullException(nameof(directories));
}
foreach (var directory in directories)
{
CleanDirectory(context, directory);
}
}
/// <summary>
/// Cleans the specified directories.
/// Cleaning a directory will remove all its content but not the directory itself.
/// </summary>
/// <example>
/// <code>
/// var directoriesToClean = new []{
/// "./src/Cake/obj",
/// "./src/Cake.Common/obj"
/// };
/// CleanDirectories(directoriesToClean);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directories">The directory paths.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectories(this ICakeContext context, IEnumerable<string> directories)
{
if (directories == null)
{
throw new ArgumentNullException(nameof(directories));
}
var paths = directories.Select(p => new DirectoryPath(p));
foreach (var directory in paths)
{
CleanDirectory(context, directory);
}
}
/// <summary>
/// Cleans the specified directory.
/// </summary>
/// <example>
/// <code>
/// CleanDirectory("./src/Cake.Common/obj");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectory(this ICakeContext context, DirectoryPath path)
{
DirectoryCleaner.Clean(context, path);
}
/// <summary>
/// Cleans the specified directory.
/// </summary>
/// <example>
/// <code>
/// CleanDirectory("./src/Cake.Common/obj", fileSystemInfo=>!fileSystemInfo.Hidden);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
/// <param name="predicate">Predicate used to determine which files/directories should get deleted.</param>
[CakeMethodAlias]
[CakeAliasCategory("Clean")]
public static void CleanDirectory(this ICakeContext context, DirectoryPath path, Func<IFileSystemInfo, bool> predicate)
{
DirectoryCleaner.Clean(context, path, predicate);
}
/// <summary>
/// Creates the specified directory.
/// </summary>
/// <example>
/// <code>
/// CreateDirectory("publish");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
[CakeMethodAlias]
[CakeAliasCategory("Create")]
public static void CreateDirectory(this ICakeContext context, DirectoryPath path)
{
DirectoryCreator.Create(context, path);
}
/// <summary>
/// Creates the specified directory if it does not exist.
/// </summary>
/// <example>
/// <code>
/// EnsureDirectoryExists("publish");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The directory path.</param>
[CakeMethodAlias]
[CakeAliasCategory("Exists")]
public static void EnsureDirectoryExists(this ICakeContext context, DirectoryPath path)
{
if (!DirectoryExists(context, path))
{
CreateDirectory(context, path);
}
}
/// <summary>
/// Copies the contents of a directory, including subdirectories to the specified location.
/// </summary>
/// <example>
/// <code>
/// CopyDirectory("source_path", "destination_path");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="source">The source directory path.</param>
/// <param name="destination">The destination directory path.</param>
[CakeMethodAlias]
[CakeAliasCategory("Copy")]
public static void CopyDirectory(this ICakeContext context, DirectoryPath source, DirectoryPath destination)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (source.IsRelative)
{
source = source.MakeAbsolute(context.Environment);
}
// Get the subdirectories for the specified directory.
var sourceDir = context.FileSystem.GetDirectory(source);
if (!sourceDir.Exists)
{
throw new System.IO.DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ source.FullPath);
}
var dirs = sourceDir.GetDirectories("*", SearchScope.Current);
var destinationDir = context.FileSystem.GetDirectory(destination);
if (!destinationDir.Exists)
{
destinationDir.Create();
}
// Get the files in the directory and copy them to the new location.
var files = sourceDir.GetFiles("*", SearchScope.Current);
foreach (var file in files)
{
var temppath = destinationDir.Path.CombineWithFilePath(file.Path.GetFilename());
context.Log.Verbose("Copying file {0} to {1}", file.Path, temppath);
file.Copy(temppath, true);
}
// Copy all of the subdirectories
foreach (var subdir in dirs)
{
var temppath = destination.Combine(subdir.Path.GetDirectoryName());
CopyDirectory(context, subdir.Path, temppath);
}
}
/// <summary>
/// Determines whether the given path refers to an existing directory.
/// </summary>
/// <example>
/// <code>
/// var dir = "publish";
/// if (!DirectoryExists(dir))
/// {
/// CreateDirectory(dir);
/// }
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The <see cref="DirectoryPath"/> to check.</param>
/// <returns><c>true</c> if <paramref name="path"/> refers to an existing directory;
/// <c>false</c> if the directory does not exist or an error occurs when trying to
/// determine if the specified path exists.</returns>
[CakeMethodAlias]
[CakeAliasCategory("Exists")]
public static bool DirectoryExists(this ICakeContext context, DirectoryPath path)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return context.FileSystem.GetDirectory(path).Exists;
}
/// <summary>
/// Makes the path absolute (if relative) using the current working directory.
/// </summary>
/// <example>
/// <code>
/// var path = MakeAbsolute(Directory("./resources"));
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="path">The path.</param>
/// <returns>An absolute directory path.</returns>
[CakeMethodAlias]
[CakeAliasCategory("Path")]
public static DirectoryPath MakeAbsolute(this ICakeContext context, DirectoryPath path)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return path.MakeAbsolute(context.Environment);
}
/// <summary>
/// Moves an existing directory to a new location, providing the option to specify a new directory name.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="directoryPath">The directory path.</param>
/// <param name="targetDirectoryPath">The target directory path.</param>
/// <example>
/// <code>
/// MoveDirectory("mydir", "newparent/newdir");
/// </code>
/// </example>
[CakeMethodAlias]
[CakeAliasCategory("Move")]
public static void MoveDirectory(this ICakeContext context, DirectoryPath directoryPath, DirectoryPath targetDirectoryPath)
{
DirectoryMover.MoveDirectory(context, directoryPath, targetDirectoryPath);
}
/// <summary>
/// Gets a list of all the directories inside a directory.
/// </summary>
/// <example>
/// <code>
/// var directories = GetSubDirectories("some/dir");
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directoryPath">The directory path.</param>
/// <returns>An absolute directory path.</returns>
[CakeMethodAlias]
[CakeAliasCategory("List")]
public static DirectoryPathCollection GetSubDirectories(this ICakeContext context, DirectoryPath directoryPath)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (directoryPath == null)
{
throw new ArgumentNullException(nameof(directoryPath));
}
directoryPath = directoryPath.MakeAbsolute(context.Environment);
// Get the directory and verify it exist.
var directory = context.FileSystem.GetDirectory(directoryPath);
if (!directory.Exists)
{
const string format = "The directory '{0}' does not exist.";
var message = string.Format(System.Globalization.CultureInfo.InvariantCulture, format, directoryPath.FullPath);
throw new System.IO.DirectoryNotFoundException(message);
}
var directories = directory.GetDirectories("*", SearchScope.Current, fsi => true).Select(d => new DirectoryPath(d.Path.FullPath)).ToList();
return new DirectoryPathCollection(directories);
}
/// <summary>
/// Expands all environment variables in the provided <see cref="DirectoryPath"/>.
/// </summary>
/// <example>
/// <code>
/// var path = new DirectoryPath("%APPDATA%/foo");
/// var expanded = path.ExpandEnvironmentVariables(environment);
/// </code>
/// </example>
/// <param name="context">The context.</param>
/// <param name="directoryPath">The path.</param>
/// <returns>A new <see cref="DirectoryPath"/> with each environment variable replaced by its value.</returns>
[CakeMethodAlias]
[CakeAliasCategory("Path")]
public static DirectoryPath ExpandEnvironmentVariables(this ICakeContext context, DirectoryPath directoryPath)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (directoryPath == null)
{
throw new ArgumentNullException(nameof(directoryPath));
}
return directoryPath.ExpandEnvironmentVariables(context.Environment);
}
}
} | 37.860427 | 151 | 0.55571 | [
"MIT"
] | AsiaRudenko/cake | src/Cake.Common/IO/DirectoryAliases.cs | 23,059 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Storage
{
/// <summary>
/// <para>
/// A transaction against the database.
/// </para>
/// <para>
/// Instances of this class are typically obtained from <see cref="DatabaseFacade.BeginTransaction" /> and it is not designed
/// to be directly constructed in your application code.
/// </para>
/// </summary>
public class RelationalTransaction : IDbContextTransaction, IInfrastructure<DbTransaction>
{
private readonly DbTransaction _dbTransaction;
private readonly bool _transactionOwned;
private readonly ISqlGenerationHelper _sqlGenerationHelper;
private bool _connectionClosed;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="RelationalTransaction" /> class.
/// </summary>
/// <param name="connection"> The connection to the database. </param>
/// <param name="transaction"> The underlying <see cref="DbTransaction" />. </param>
/// <param name="transactionId"> The correlation ID for the transaction. </param>
/// <param name="logger"> The logger to write to. </param>
/// <param name="transactionOwned">
/// A value indicating whether the transaction is owned by this class (i.e. if it can be disposed when this class is disposed).
/// </param>
/// <param name="sqlGenerationHelper"> The SQL generation helper to use. </param>
public RelationalTransaction(
IRelationalConnection connection,
DbTransaction transaction,
Guid transactionId,
IDiagnosticsLogger<DbLoggerCategory.Database.Transaction> logger,
bool transactionOwned,
ISqlGenerationHelper sqlGenerationHelper
)
{
Check.NotNull(connection, nameof(connection));
Check.NotNull(transaction, nameof(transaction));
Check.NotNull(logger, nameof(logger));
Check.NotNull(sqlGenerationHelper, nameof(sqlGenerationHelper));
if (connection.DbConnection != transaction.Connection)
{
throw new InvalidOperationException(
RelationalStrings.TransactionAssociatedWithDifferentConnection
);
}
Connection = connection;
TransactionId = transactionId;
_dbTransaction = transaction;
Logger = logger;
_transactionOwned = transactionOwned;
_sqlGenerationHelper = sqlGenerationHelper;
}
/// <summary>
/// The connection.
/// </summary>
protected virtual IRelationalConnection Connection { get; }
/// <summary>
/// The logger.
/// </summary>
protected virtual IDiagnosticsLogger<DbLoggerCategory.Database.Transaction> Logger { get; }
/// <inheritdoc />
public virtual Guid TransactionId { get; }
/// <inheritdoc />
public virtual void Commit()
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = Logger.TransactionCommitting(
Connection,
_dbTransaction,
TransactionId,
startTime
);
if (!interceptionResult.IsSuppressed)
{
_dbTransaction.Commit();
}
Logger.TransactionCommitted(
Connection,
_dbTransaction,
TransactionId,
startTime,
stopwatch.Elapsed
);
}
catch (Exception e)
{
Logger.TransactionError(
Connection,
_dbTransaction,
TransactionId,
"Commit",
e,
startTime,
stopwatch.Elapsed
);
throw;
}
ClearTransaction();
}
/// <inheritdoc />
public virtual void Rollback()
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = Logger.TransactionRollingBack(
Connection,
_dbTransaction,
TransactionId,
startTime
);
if (!interceptionResult.IsSuppressed)
{
_dbTransaction.Rollback();
}
Logger.TransactionRolledBack(
Connection,
_dbTransaction,
TransactionId,
startTime,
stopwatch.Elapsed
);
}
catch (Exception e)
{
Logger.TransactionError(
Connection,
_dbTransaction,
TransactionId,
"Rollback",
e,
startTime,
stopwatch.Elapsed
);
throw;
}
ClearTransaction();
}
/// <inheritdoc />
public virtual async Task CommitAsync(CancellationToken cancellationToken = default)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = await Logger
.TransactionCommittingAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
if (!interceptionResult.IsSuppressed)
{
await _dbTransaction.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await Logger
.TransactionCommittedAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
}
catch (Exception e)
{
await Logger
.TransactionErrorAsync(
Connection,
_dbTransaction,
TransactionId,
"Commit",
e,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
throw;
}
await ClearTransactionAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public virtual async Task RollbackAsync(CancellationToken cancellationToken = default)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = await Logger
.TransactionRollingBackAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
if (!interceptionResult.IsSuppressed)
{
await _dbTransaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
}
await Logger
.TransactionRolledBackAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
}
catch (Exception e)
{
await Logger
.TransactionErrorAsync(
Connection,
_dbTransaction,
TransactionId,
"Rollback",
e,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
throw;
}
await ClearTransactionAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public virtual void CreateSavepoint(string name)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = Logger.CreatingTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateCreateSavepointStatement(
name
);
command.ExecuteNonQuery();
}
Logger.CreatedTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
}
catch (Exception e)
{
Logger.TransactionError(
Connection,
_dbTransaction,
TransactionId,
"CreateSavepoint",
e,
startTime,
stopwatch.Elapsed
);
throw;
}
}
/// <inheritdoc />
public virtual async Task CreateSavepointAsync(
string name,
CancellationToken cancellationToken = default
)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = await Logger
.CreatingTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateCreateSavepointStatement(
name
);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
await Logger
.CreatedTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
}
catch (Exception e)
{
await Logger
.TransactionErrorAsync(
Connection,
_dbTransaction,
TransactionId,
"CreateSavepoint",
e,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public virtual void RollbackToSavepoint(string name)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = Logger.RollingBackToTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateRollbackToSavepointStatement(
name
);
command.ExecuteNonQuery();
}
Logger.RolledBackToTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
}
catch (Exception e)
{
Logger.TransactionError(
Connection,
_dbTransaction,
TransactionId,
"RollbackToSavepoint",
e,
startTime,
stopwatch.Elapsed
);
throw;
}
}
/// <inheritdoc />
public virtual async Task RollbackToSavepointAsync(
string name,
CancellationToken cancellationToken = default
)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = await Logger
.RollingBackToTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateRollbackToSavepointStatement(
name
);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
await Logger
.RolledBackToTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
}
catch (Exception e)
{
await Logger
.TransactionErrorAsync(
Connection,
_dbTransaction,
TransactionId,
"RollbackToSavepoint",
e,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public virtual void ReleaseSavepoint(string name)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = Logger.ReleasingTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateReleaseSavepointStatement(
name
);
command.ExecuteNonQuery();
}
Logger.ReleasedTransactionSavepoint(
Connection,
_dbTransaction,
TransactionId,
startTime
);
}
catch (Exception e)
{
Logger.TransactionError(
Connection,
_dbTransaction,
TransactionId,
"ReleaseSavepoint",
e,
startTime,
stopwatch.Elapsed
);
throw;
}
}
/// <inheritdoc />
public virtual async Task ReleaseSavepointAsync(
string name,
CancellationToken cancellationToken = default
)
{
var startTime = DateTimeOffset.UtcNow;
var stopwatch = Stopwatch.StartNew();
try
{
var interceptionResult = await Logger
.ReleasingTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
if (!interceptionResult.IsSuppressed)
{
using var command = Connection.DbConnection.CreateCommand();
command.Transaction = _dbTransaction;
command.CommandText = _sqlGenerationHelper.GenerateReleaseSavepointStatement(
name
);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
await Logger
.ReleasedTransactionSavepointAsync(
Connection,
_dbTransaction,
TransactionId,
startTime,
cancellationToken
)
.ConfigureAwait(false);
}
catch (Exception e)
{
await Logger
.TransactionErrorAsync(
Connection,
_dbTransaction,
TransactionId,
"ReleaseSavepoint",
e,
startTime,
stopwatch.Elapsed,
cancellationToken
)
.ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public virtual bool SupportsSavepoints => true;
/// <inheritdoc />
public virtual void Dispose()
{
if (!_disposed)
{
_disposed = true;
if (_transactionOwned)
{
_dbTransaction.Dispose();
Logger.TransactionDisposed(
Connection,
_dbTransaction,
TransactionId,
DateTimeOffset.UtcNow
);
}
ClearTransaction();
}
}
/// <inheritdoc />
public virtual async ValueTask DisposeAsync()
{
if (!_disposed)
{
_disposed = true;
if (_transactionOwned)
{
await _dbTransaction.DisposeAsync().ConfigureAwait(false);
Logger.TransactionDisposed(
Connection,
_dbTransaction,
TransactionId,
DateTimeOffset.UtcNow
);
}
await ClearTransactionAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Remove the underlying transaction from the connection
/// </summary>
protected virtual void ClearTransaction()
{
Check.DebugAssert(
Connection.CurrentTransaction == null || Connection.CurrentTransaction == this,
"Connection.CurrentTransaction is unexpected instance"
);
Connection.UseTransaction(null);
if (!_connectionClosed)
{
_connectionClosed = true;
Connection.Close();
}
}
/// <summary>
/// Remove the underlying transaction from the connection
/// </summary>
protected virtual async Task ClearTransactionAsync(
CancellationToken cancellationToken = default
)
{
Check.DebugAssert(
Connection.CurrentTransaction == null || Connection.CurrentTransaction == this,
"Connection.CurrentTransaction is unexpected instance"
);
await Connection.UseTransactionAsync(null, cancellationToken).ConfigureAwait(false);
if (!_connectionClosed)
{
_connectionClosed = true;
await Connection.CloseAsync().ConfigureAwait(false);
}
}
DbTransaction IInfrastructure<DbTransaction>.Instance => _dbTransaction;
}
}
| 32.596317 | 139 | 0.455264 | [
"Apache-2.0"
] | belav/efcore | src/EFCore.Relational/Storage/RelationalTransaction.cs | 23,013 | C# |
using Microsoft.Toolkit.Mvvm.Input;
namespace DtKata.ViewModel;
public partial class VmKata
{
[ICommand]
private void ButtonTaster(string taster)
{
switch (taster)
{
case "S1": (_modelKata.S1, ClickModeS1) = ButtonClickMode(ClickModeS1); break;
case "S2": (_modelKata.S2, ClickModeS2) = ButtonClickMode(ClickModeS2); break;
case "S3": (_modelKata.S3, ClickModeS3) = ButtonClickModeInvertiert(ClickModeS3); break;
case "S4": (_modelKata.S4, ClickModeS4) = ButtonClickModeInvertiert(ClickModeS4); break;
}
}
[ICommand]
private void ButtonSchalter(string schalter)
{
switch (schalter)
{
case "S5": _modelKata.S5 = !_modelKata.S5; break;
case "S6": _modelKata.S6 = !_modelKata.S6; break;
case "S7": _modelKata.S7 = !_modelKata.S7; break;
case "S8": _modelKata.S8 = !_modelKata.S8; break;
}
}
}
| 31.290323 | 100 | 0.612371 | [
"MIT"
] | AutomatisierungsLabor/PlcDigitalTwinAutoTest | PlcDigitalTwinAutoTest/DtKata/ViewModel/VmKommandos.cs | 972 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace DiagnosticsNet.Tests
{
[TestClass]
public sealed class DiagnosticObserver_Tests : TestClassBase
{
[TestMethod]
public void TestMethod()
{
var listener = CreateDiagnosticListener();
var handler = CreateDiagnosticHandler();
var observer = CreateDiagnosticObserver(handler.Object, listener);
using (var manager = CreateDiagnosticManager())
{
manager.Subscribe(observer);
listener.IsEnabled("Test");
}
handler.Verify(x => x.IsEnabled("Test"), Times.Once);
}
[TestMethod]
public void TestMethod1()
{
var listener = CreateDiagnosticListener();
var handler = CreateDiagnosticHandler();
var observer = CreateDiagnosticObserver(handler.Object, listener);
var value = new { };
using (var manager = CreateDiagnosticManager())
{
manager.Subscribe(observer);
listener.Write("Test", value);
}
handler.Verify(x => x.Write("Test", value), Times.Once);
}
}
}
| 27.130435 | 78 | 0.566506 | [
"MIT"
] | Chakrygin/DiagnosticsNet | tests/DiagnosticsNet.Tests/DiagnosticObserver_Tests.cs | 1,248 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace PushNotification.ApnFcmHttpV2
{
/// <summary>
/// _fcmClient = new FcmClientSendToSingleRegistrationId(fcm_config);
/// var sentresult = await _fcmClient.Send(message.DeviceToken, message.Title, message.Body, message.Message);
/// result = sentresult.Ok;
///
/// </summary>
public class FCMsClient : IDisposable
{
public FCMsClient(GcmConfiguration configuration)
{
Configuration = configuration;
_http = new HttpClient();
_http.DefaultRequestHeaders.UserAgent.Clear();
_http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("FcmClient", "3.0.1"));
_http.DefaultRequestHeaders.Remove("Authorization");
_http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + Configuration.SenderAuthToken);
_httpCheckToken = new HttpClient();
_httpCheckToken.DefaultRequestHeaders.UserAgent.Clear();
_httpCheckToken.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("FcmClient", "3.0.1"));
_httpCheckToken.DefaultRequestHeaders.Remove("Authorization");
_httpCheckToken.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + Configuration.SenderAuthToken);
}
public GcmConfiguration Configuration { get; private set; }
HttpClient _http;
HttpClient _httpCheckToken;
public string CheckToken(string token)
{
//
return string.Empty;
// return await (await _httpCheckToken.SendAsync($"https://iid.googleapis.com/iid/info/{token}", HttpMethod.Get)).Content.ReadAsStringAsync();
}
//public async Task<SendInternalResult> Send(string deviceIdOrFcmToken, string notiTitle, string notiBody, JObject message)
//{
// var payloadData = message;
// payloadData["title"] = notiTitle;
// payloadData["body"] = notiBody;
// var r = await SendInternal(new GcmNotification
// {
// RegistrationIds = new List<string> { deviceIdOrFcmToken },
// Data = payloadData
// });
// return r;
//}
/// <summary>
///
/// </summary>
/// <param name="deviceIdOrFcmToken"></param>
/// <param name="notiTitle"></param>
/// <param name="notiBody"></param>
/// <param name="dataJson"></param>
/// <returns></returns>
public async Task<SendInternalResult> Send(string deviceIdOrFcmToken, string notiTitle, string notiBody, string dataJson)
{
return await Send(new List<string> { deviceIdOrFcmToken }, notiTitle, notiBody, dataJson);
}
public async Task<SendInternalResult> Send(List<string> deviceIdOrFcmTokens, string notiTitle, string notiBody, string dataJson)
{
var payloadData = JObject.Parse(dataJson);
//payloadData["title"] = notiTitle;
//payloadData["body"] = notiBody;
var msg = new GcmNotification
{
RegistrationIds = deviceIdOrFcmTokens,
Data = payloadData,
};
if (!string.IsNullOrEmpty(notiTitle) && !string.IsNullOrEmpty(notiBody))
{
var notiObject = new JObject();
//notiObject["title"] = notiTitle;
//notiObject["body"] = notiBody;
msg.Notification = notiObject;
}
var r = await SendInternal(msg);
return r;
}
async Task<SendInternalResult> SendInternal(GcmNotification notification)
{
var str = string.Empty;
try
{
var json = notification.GetJson();
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await _http.PostAsync(Configuration.GcmUrl, content);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
Console.WriteLine($"System.Net.HttpStatusCode.Unauthorized {notification}");
}
str = await response.Content.ReadAsStringAsync();
var responseJson = JObject.Parse(str);
var result = new GcmResponse()
{
ResponseCode = GcmResponseCode.Ok,
OriginalNotification = notification
};
result.NumberOfCanonicalIds = responseJson.Value<long>("canonical_ids");
result.NumberOfFailures = responseJson.Value<long>("failure");
result.NumberOfSuccesses = responseJson.Value<long>("success");
var jsonResults = responseJson["results"] as JArray ?? new JArray();
foreach (var r in jsonResults)
{
var msgResult = new GcmMessageResult();
msgResult.MessageId = r.Value<string>("message_id");
msgResult.CanonicalRegistrationId = r.Value<string>("registration_id");
msgResult.ResponseStatus = GcmResponseStatus.Ok;
if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
msgResult.ResponseStatus = GcmResponseStatus.CanonicalRegistrationId;
else if (r["error"] != null)
{
var err = r.Value<string>("error") ?? "";
msgResult.ResponseStatus = GetGcmResponseStatus(err);
}
result.Results.Add(msgResult);
}
var firstResult = result.Results.FirstOrDefault();
if (response.IsSuccessStatusCode && firstResult != null && firstResult.ResponseStatus == GcmResponseStatus.Ok)
{ // Success
return new SendInternalResult { Ok = true, rawResult = str };
}
return new SendInternalResult { Ok = false, rawResult = str };
}
catch (Exception ex)
{
return new SendInternalResult { Ok = false, rawResult = str + " " + ex.Message + ex.StackTrace };
}
}
static GcmResponseStatus GetGcmResponseStatus(string str)
{
var enumType = typeof(GcmResponseStatus);
foreach (var name in Enum.GetNames(enumType))
{
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
if (enumMemberAttribute.Value.Equals(str, StringComparison.InvariantCultureIgnoreCase))
return (GcmResponseStatus)Enum.Parse(enumType, name);
}
//Default
return GcmResponseStatus.Error;
}
public void Dispose()
{
_http = null;
}
}
public enum GcmResponseCode
{
Ok,
Error,
BadRequest,
ServiceUnavailable,
InvalidAuthToken,
InternalServiceError
}
public class GcmResponse
{
public GcmResponse()
{
MulticastId = -1;
NumberOfSuccesses = 0;
NumberOfFailures = 0;
NumberOfCanonicalIds = 0;
OriginalNotification = null;
Results = new List<GcmMessageResult>();
ResponseCode = GcmResponseCode.Ok;
}
[JsonProperty("multicast_id")]
public long MulticastId { get; set; }
[JsonProperty("success")]
public long NumberOfSuccesses { get; set; }
[JsonProperty("failure")]
public long NumberOfFailures { get; set; }
[JsonProperty("canonical_ids")]
public long NumberOfCanonicalIds { get; set; }
[JsonIgnore]
public GcmNotification OriginalNotification { get; set; }
[JsonProperty("results")]
public List<GcmMessageResult> Results { get; set; }
[JsonIgnore]
public GcmResponseCode ResponseCode { get; set; }
}
public interface INotification
{
bool IsDeviceRegistrationIdValid();
object Tag { get; set; }
}
public class GcmNotification : INotification
{
public static GcmNotification ForSingleResult(GcmResponse response, int resultIndex)
{
var result = new GcmNotification();
result.Tag = response.OriginalNotification.Tag;
result.MessageId = response.OriginalNotification.MessageId;
if (response.OriginalNotification.RegistrationIds != null && response.OriginalNotification.RegistrationIds.Count >= (resultIndex + 1))
result.RegistrationIds.Add(response.OriginalNotification.RegistrationIds[resultIndex]);
result.CollapseKey = response.OriginalNotification.CollapseKey;
result.Data = response.OriginalNotification.Data;
result.DelayWhileIdle = response.OriginalNotification.DelayWhileIdle;
result.ContentAvailable = response.OriginalNotification.ContentAvailable;
result.DryRun = response.OriginalNotification.DryRun;
result.Priority = response.OriginalNotification.Priority;
result.To = response.OriginalNotification.To;
result.NotificationKey = response.OriginalNotification.NotificationKey;
return result;
}
public static GcmNotification ForSingleRegistrationId(GcmNotification msg, string registrationId)
{
var result = new GcmNotification();
result.Tag = msg.Tag;
result.MessageId = msg.MessageId;
result.RegistrationIds.Add(registrationId);
result.To = null;
result.CollapseKey = msg.CollapseKey;
result.Data = msg.Data;
result.DelayWhileIdle = msg.DelayWhileIdle;
result.ContentAvailable = msg.ContentAvailable;
result.DryRun = msg.DryRun;
result.Priority = msg.Priority;
result.NotificationKey = msg.NotificationKey;
return result;
}
public GcmNotification()
{
RegistrationIds = new List<string>();
CollapseKey = string.Empty;
Data = null;
DelayWhileIdle = null;
}
public bool IsDeviceRegistrationIdValid()
{
return RegistrationIds != null && RegistrationIds.Any();
}
[JsonIgnore]
public object Tag { get; set; }
[JsonProperty("message_id")]
public string MessageId { get; internal set; }
/// <summary>
/// Registration ID of the Device(s). Maximum of 1000 registration Id's per notification.
/// </summary>
[JsonProperty("registration_ids")]
public List<string> RegistrationIds { get; set; }
/// <summary>
/// Registration ID or Group/Topic to send notification to. Overrides RegsitrationIds.
/// </summary>
/// <value>To.</value>
[JsonProperty("to")]
public string To { get; set; }
/// <summary>
/// Only the latest message with the same collapse key will be delivered
/// </summary>
[JsonProperty("collapse_key")]
public string CollapseKey { get; set; }
/// <summary>
/// JSON Payload to be sent in the message
/// </summary>
[JsonProperty("data")]
public JObject Data { get; set; }
/// <summary>
/// Notification JSON payload
/// </summary>
/// <value>The notification payload.</value>
[JsonProperty("notification")]
public JObject Notification { get; set; }
/// <summary>
/// If true, GCM will only be delivered once the device's screen is on
/// </summary>
[JsonProperty("delay_while_idle")]
public bool? DelayWhileIdle { get; set; }
/// <summary>
/// Time in seconds that a message should be kept on the server if the device is offline. Default (and maximum) is 4 weeks.
/// </summary>
[JsonProperty("time_to_live")]
public int? TimeToLive { get; set; }
/// <summary>
/// If true, dry_run attribute will be sent in payload causing the notification not to be actually sent, but the result returned simulating the message
/// </summary>
[JsonProperty("dry_run")]
public bool? DryRun { get; set; }
/// <summary>
/// A string that maps a single user to multiple registration IDs associated with that user. This allows a 3rd-party server to send a single message to multiple app instances (typically on multiple devices) owned by a single user.
/// </summary>
[Obsolete("Deprecated on GCM Server API. Use Device Group Messaging to send to multiple devices.")]
public string NotificationKey { get; set; }
/// <summary>
/// A string containing the package name of your application. When set, messages will only be sent to registration IDs that match the package name
/// </summary>
[JsonProperty("restricted_package_name")]
public string RestrictedPackageName { get; set; }
/// <summary>
/// On iOS, use this field to represent content-available in the APNS payload. When a notification or message is sent and this is set to true, an inactive client app is awoken. On Android, data messages wake the app by default. On Chrome, currently not supported.
/// </summary>
/// <value>The content available.</value>
[JsonProperty("content_available")]
public bool? ContentAvailable { get; set; }
/// <summary>
/// Corresponds to iOS APNS priorities (Normal is 5 and high is 10). Default is Normal.
/// </summary>
/// <value>The priority.</value>
[JsonProperty("priority"), JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public GcmNotificationPriority? Priority { get; set; }
public string GetJson()
{
// If 'To' was used instead of RegistrationIds, let's make RegistrationId's null
// so we don't serialize an empty array for this property
// otherwise, google will complain that we specified both instead
if (RegistrationIds != null && RegistrationIds.Count <= 0 && !string.IsNullOrEmpty(To))
RegistrationIds = null;
// Ignore null values
return JsonConvert.SerializeObject(this,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
public override string ToString()
{
return GetJson();
}
}
public enum GcmNotificationPriority
{
[EnumMember(Value = "normal")]
Normal = 5,
[EnumMember(Value = "high")]
High = 10
}
public class GcmMessageResult
{
[JsonProperty("message_id", NullValueHandling = NullValueHandling.Ignore)]
public string MessageId { get; set; }
[JsonProperty("registration_id", NullValueHandling = NullValueHandling.Ignore)]
public string CanonicalRegistrationId { get; set; }
[JsonIgnore]
public GcmResponseStatus ResponseStatus { get; set; }
[JsonProperty("error", NullValueHandling = NullValueHandling.Ignore)]
public string Error
{
get
{
switch (ResponseStatus)
{
case GcmResponseStatus.Ok:
return null;
case GcmResponseStatus.Unavailable:
return "Unavailable";
case GcmResponseStatus.QuotaExceeded:
return "QuotaExceeded";
case GcmResponseStatus.NotRegistered:
return "NotRegistered";
case GcmResponseStatus.MissingRegistrationId:
return "MissingRegistration";
case GcmResponseStatus.MissingCollapseKey:
return "MissingCollapseKey";
case GcmResponseStatus.MismatchSenderId:
return "MismatchSenderId";
case GcmResponseStatus.MessageTooBig:
return "MessageTooBig";
case GcmResponseStatus.InvalidTtl:
return "InvalidTtl";
case GcmResponseStatus.InvalidRegistration:
return "InvalidRegistration";
case GcmResponseStatus.InvalidDataKey:
return "InvalidDataKey";
case GcmResponseStatus.InternalServerError:
return "InternalServerError";
case GcmResponseStatus.DeviceQuotaExceeded:
return null;
case GcmResponseStatus.CanonicalRegistrationId:
return null;
case GcmResponseStatus.Error:
return "Error";
default:
return null;
}
}
}
}
public enum GcmResponseStatus
{
[EnumMember(Value = "Ok")]
Ok,
[EnumMember(Value = "Error")]
Error,
[EnumMember(Value = "QuotaExceeded")]
QuotaExceeded,
[EnumMember(Value = "DeviceQuotaExceeded")]
DeviceQuotaExceeded,
[EnumMember(Value = "InvalidRegistration")]
InvalidRegistration,
[EnumMember(Value = "NotRegistered")]
NotRegistered,
[EnumMember(Value = "MessageTooBig")]
MessageTooBig,
[EnumMember(Value = "MissingCollapseKey")]
MissingCollapseKey,
[EnumMember(Value = "MissingRegistration")]
MissingRegistrationId,
[EnumMember(Value = "Unavailable")]
Unavailable,
[EnumMember(Value = "MismatchSenderId")]
MismatchSenderId,
[EnumMember(Value = "CanonicalRegistrationId")]
CanonicalRegistrationId,
[EnumMember(Value = "InvalidDataKey")]
InvalidDataKey,
[EnumMember(Value = "InvalidTtl")]
InvalidTtl,
[EnumMember(Value = "InternalServerError")]
InternalServerError,
[EnumMember(Value = "InvalidPackageName")]
InvalidPackageName
}
public class GcmConfiguration
{
private const string GCM_SEND_URL = "https://gcm-http.googleapis.com/gcm/send";
public GcmConfiguration(string senderAuthTokenOrApiKey)
{
this.SenderAuthToken = senderAuthTokenOrApiKey;
this.GcmUrl = GCM_SEND_URL;
this.ValidateServerCertificate = false;
}
public GcmConfiguration(string optionalSenderID, string senderAuthToken, string optionalApplicationIdPackageName)
{
this.SenderID = optionalSenderID;
this.SenderAuthToken = senderAuthToken;
this.ApplicationIdPackageName = optionalApplicationIdPackageName;
this.GcmUrl = GCM_SEND_URL;
this.ValidateServerCertificate = false;
}
public string SenderID { get; private set; }
public string SenderAuthToken { get; private set; }
public string ApplicationIdPackageName { get; private set; }
public bool ValidateServerCertificate { get; set; }
public string GcmUrl { get; set; }
public void OverrideUrl(string url)
{
GcmUrl = url;
}
}
}
| 36.441818 | 271 | 0.591079 | [
"MIT"
] | badpaybad/push-notification-dotnetcore-for-apn-fcm | APN_FCM_PushNotification/PushNotification.ApnFcmHttpV2/Fcm/FCMsClient.cs | 20,045 | C# |
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
namespace System.Web.Razor.Test
{
internal static class CodeCompileUnitExtensions
{
public static string GenerateCode<T>(this CodeCompileUnit ccu) where T : CodeDomProvider, new()
{
StringBuilder output = new StringBuilder();
using (StringWriter writer = new StringWriter(output))
{
T provider = new T();
provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions() { IndentString = " " });
}
return output.ToString();
}
}
}
| 28.869565 | 120 | 0.618976 | [
"Apache-2.0"
] | douchedetector/mvc-razor | test/System.Web.Razor.Test/CodeCompileUnitExtensions.cs | 666 | C# |
namespace Rollbar.DTOs
{
using System;
using System.Collections.Generic;
using System.Text;
using Rollbar.Common;
/// <summary>
/// Class Notifier.
/// Implements the <see cref="Rollbar.DTOs.ExtendableDtoBase" />
/// </summary>
/// <seealso cref="Rollbar.DTOs.ExtendableDtoBase" />
public class Notifier
: ExtendableDtoBase
{
/// <summary>
/// The DTO reserved properties.
/// </summary>
public static class ReservedProperties
{
/// <summary>
/// The name
/// </summary>
public static readonly string Name = "name";
/// <summary>
/// The version
/// </summary>
public static readonly string Version = "version";
/// <summary>
/// The configuration
/// </summary>
public static readonly string Configuration = "configured_options";
}
/// <summary>
/// The notifier name
/// </summary>
private const string notifierName = "Rollbar.NET";
/// <summary>
/// The notifier assembly version
/// </summary>
private static readonly string NotifierAssemblyVersion;
/// <summary>
/// Detects the notifier assembly version.
/// </summary>
/// <returns>System.String.</returns>
private static string DetectNotifierAssemblyVersion()
{
return RuntimeEnvironmentUtility.GetTypeAssemblyVersion(typeof(Data));
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return this[ReservedProperties.Name] as string; }
private set { this[ReservedProperties.Name] = value; }
}
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public string Version
{
get { return this[ReservedProperties.Version] as string; }
private set { this[ReservedProperties.Version] = value; }
}
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>The configuration.</value>
public IRollbarConfig Configuration
{
get { return this[ReservedProperties.Configuration] as IRollbarConfig; }
set { this[ReservedProperties.Configuration] = value; }
}
/// <summary>
/// Initializes static members of the <see cref="Notifier"/> class.
/// </summary>
static Notifier()
{
Notifier.NotifierAssemblyVersion = Notifier.DetectNotifierAssemblyVersion();
}
/// <summary>
/// Initializes a new instance of the <see cref="Notifier"/> class.
/// </summary>
public Notifier()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Notifier"/> class.
/// </summary>
/// <param name="arbitraryKeyValuePairs">The arbitrary key value pairs.</param>
public Notifier(IDictionary<string, object> arbitraryKeyValuePairs)
: base(arbitraryKeyValuePairs)
{
this.Name = notifierName;
this.Version = Notifier.NotifierAssemblyVersion;
}
}
}
| 30.918919 | 88 | 0.543415 | [
"MIT"
] | jamesthurley/Rollbar.NET | Rollbar/DTOs/Notifier.cs | 3,434 | C# |
#region references
using acDb = Autodesk.AutoCAD.DatabaseServices;
using AeccShapeStyle = Autodesk.Civil.DatabaseServices.Styles.ShapeStyle;
#endregion
namespace Camber.Civil.Styles.Objects
{
public sealed class ShapeStyle : Style
{
#region properties
internal AeccShapeStyle AeccShapeStyle => AcObject as AeccShapeStyle;
#endregion
#region constructors
internal ShapeStyle(AeccShapeStyle aeccShapeStyle, bool isDynamoOwned = false) : base(aeccShapeStyle, isDynamoOwned) { }
internal static ShapeStyle GetByObjectId(acDb.ObjectId styleId)
=> StyleSupport.Get<ShapeStyle, AeccShapeStyle>
(styleId, (style) => new ShapeStyle(style));
#endregion
#region methods
public override string ToString() => $"ShapeStyle(Name = {Name})";
#endregion
}
}
| 31.925926 | 128 | 0.693735 | [
"BSD-3-Clause"
] | mzjensen/Camber | Camber/Civil/Styles/Objects/ShapeStyle.cs | 864 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Api.NSwag
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().ConfigureKestrel(serverOptions => {
serverOptions.Limits.MinRequestBodyDataRate = null;
});
});
}
}
| 28.482759 | 88 | 0.627119 | [
"MIT"
] | MaxymGorn/IdentityServer4-Swagger-Integration | Api.NSwag/Program.cs | 826 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using act.core.data;
using Amazon.Lambda;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace act.core.etl.lambda
{
internal static class Bootstrap
{
public static IServiceCollection ConfigureLambdaArgumentProcessor(this IServiceCollection services,
params IDictionary<string, Func<IServiceScope, Argument, Task<int>>>[] dictionary)
{
return services
.AddSingleton<IArgumentProcessor>(sp =>
{
var it = new ArgumentProcessor(sp);
it.RegisterProcessorFunction("databaseupdate", async (scope, arg) =>
{
await scope.ServiceProvider.GetRequiredService<ActDbContext>().Database.MigrateAsync();
return 0;
})
.RegisterProcessorFunction("gather",
async (scope, arg) =>
(await scope.ServiceProvider.GetRequiredService<IGatherer>().Gather(arg.Index)).Length)
.RegisterProcessorFunction("email", async (scope, arg) =>
{
if (arg.Index == 1)
return await scope.ServiceProvider.GetService<IGatherer>().NotifyNotReportingNodes();
if (arg.Index == 0)
return await scope.ServiceProvider.GetService<IGatherer>().NotifyUnassignedNodes();
return 0;
})
.RegisterProcessorFunction("reset",
async (scope, arg) =>
await scope.ServiceProvider.GetService<IGatherer>().ResetComplianceStatus())
.RegisterProcessorFunction("purgedetails",
async (scope, arg) =>
await scope.ServiceProvider.GetService<IGatherer>().PurgeOldComplianceDetails())
.RegisterProcessorFunction("purgeruns",
async (scope, arg) =>
await scope.ServiceProvider.GetService<IGatherer>().PurgeOldComplianceRuns())
.RegisterProcessorFunction("purgeinactive",
async (scope, arg) =>
await scope.ServiceProvider.GetService<IGatherer>().PurgeInactiveNodes())
.RegisterProcessorFunctions(dictionary);
return it;
});
}
public static IServiceCollection ConfigureLambda(this IServiceCollection services, IConfiguration config)
{
return services
.AddSingleton(config)
.AddLogging(opt =>
{
opt.AddConfiguration(config);
opt.AddConsole();
})
.AddDefaultAWSOptions(config.GetAWSOptions())
.AddAWSService<IAmazonLambda>()
.AddActDbContext(config, 120)
.ConfigureGatherer();
}
}
} | 47.126761 | 119 | 0.530185 | [
"MIT"
] | Saravanandss/assetcompliancetracker | src/act.core.etl.lambda/Bootstrap.cs | 3,348 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync.Concurrent.DispatcherManagers
{
internal sealed class SharedThreadFiberManager : IDispatcherManager
{
public bool DisposeDispatcher => false;
private readonly IMonoThreadFiber _Fiber;
public SharedThreadFiberManager(Action<Thread> onCreate = null)
{
_Fiber = Fiber.CreateMonoThreadedFiber(onCreate);
}
public IDispatcher GetDispatcher() => _Fiber;
public Task DisposeAsync() => _Fiber.DisposeAsync();
}
}
| 26.772727 | 71 | 0.696095 | [
"MIT"
] | David-Desmaisons/ComposableAsync | ComposableAsync.Concurrent/DispatcherManagers/SharedThreadFiberManager.cs | 591 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Quantumart.QP8.BLL.Factories;
using Quantumart.QP8.BLL.Factories.FolderFactory;
using Quantumart.QP8.BLL.Repository;
using Quantumart.QP8.BLL.Repository.ArticleRepositories;
using Quantumart.QP8.BLL.Repository.ArticleRepositories.SearchParsers;
using Quantumart.QP8.BLL.Repository.ContentRepositories;
using Quantumart.QP8.BLL.Repository.FieldRepositories;
using Quantumart.QP8.BLL.Services.DTO;
using Quantumart.QP8.Constants;
// ReSharper disable PossibleInvalidOperationException
// ReSharper disable PossibleMultipleEnumeration
namespace Quantumart.QP8.BLL.Services
{
public class EntityObjectService
{
/// <summary>
/// Проверяет уникальность имен
/// </summary>
/// <param name="item">сущность</param>
/// <returns>true или false</returns>
public static bool CheckNameUniqueness(EntityObject item) => EntityObjectRepository.CheckNameUniqueness(item);
/// <summary>
/// Возвращает сущность
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <param name="loadChilds">признак, разрешающий загрузку дочерних сущностей</param>
/// <param name="filter">фильтр</param>
/// <returns>сущность</returns>
public static EntityTreeItem GetByTypeAndIdForTree(string entityTypeCode, int entityId, bool loadChilds, string filter)
{
if (entityTypeCode == EntityTypeCode.Article)
{
return ArticleRepository.GetByIdForTree(entityId, loadChilds, filter);
}
if (entityTypeCode == EntityTypeCode.SiteFolder || entityTypeCode == EntityTypeCode.ContentFolder)
{
var folderRepository = FolderFactory.Create(entityTypeCode).CreateRepository();
var folder = folderRepository.GetById(entityId);
if (!loadChilds)
{
return Mapper.Map<Folder, EntityTreeItem>(folder);
}
return Mapper.Map<Folder, EntityTreeItem>(folderRepository.GetSelfAndChildrenWithSync(folder.ParentEntityId, folder.Id));
}
return null;
}
public static IList<EntityTreeItem> GetEntityTreeItems(ChildListQuery query) => ArticleTreeFactory.Create(query).Process();
/// <summary>
/// Возвращает упрощенный список сущностей
/// </summary>
public static List<ListItem> SimpleList(SimpleListQuery query)
{
var itemList = new List<ListItem>();
if (query.EntityTypeCode == EntityTypeCode.ContentGroup)
{
itemList = ContentRepository.GetGroupSimpleList(query.ParentEntityId, query.SelectedEntitiesIds).ToList();
}
else if (query.EntityTypeCode == EntityTypeCode.Article || query.EntityTypeCode == EntityTypeCode.ArchiveArticle)
{
itemList = ArticleRepository.GetSimpleList(query);
}
else if (query.EntityTypeCode == EntityTypeCode.Content)
{
itemList.AddRange(ContentRepository.GetSimpleList(query.ParentEntityId, query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.Site)
{
itemList.AddRange(SiteRepository.GetSimpleList(query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.User)
{
itemList.AddRange(UserRepository.GetSimpleList(query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.UserGroup)
{
itemList.AddRange(UserGroupRepository.GetSimpleList(query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.TemplateObjectFormat)
{
itemList.AddRange(ObjectFormatRepository.GetObjectFormats(query.ParentEntityId, query.ActualListId, query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.Page)
{
itemList.AddRange(PageTemplateRepository.GetPageSimpleList(query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.StatusType)
{
itemList.AddRange(StatusTypeRepository.GetStatusSimpleList(query.SelectedEntitiesIds));
}
else if (query.EntityTypeCode == EntityTypeCode.Field)
{
itemList.AddRange(FieldRepository.GetList(query.SelectedEntitiesIds).Select(c => new ListItem(c.Id.ToString(), c.Name)));
}
return itemList;
}
/// <summary>
/// Проверяет существование сущности
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <returns>результат проверки (true - существует; false - не существует)</returns>
public static bool CheckExistence(string entityTypeCode, int entityId) => EntityObjectRepository.CheckExistence(entityTypeCode, entityId);
/// <summary>
/// Проверяет сущность на наличие рекурсивных связей
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <returns>результат проверки (true - есть рекурсивные связи; false - нет)</returns>
public static bool CheckPresenceSelfRelations(string entityTypeCode, int entityId) => EntityObjectRepository.CheckPresenceSelfRelations(entityTypeCode, entityId);
/// <summary>
/// Проверяет сущность на наличие вариаций
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <returns>результат проверки (true - есть вариации; false - нет)</returns>
public static bool CheckForVariations(string entityTypeCode, int entityId) => EntityObjectRepository.CheckForVariations(entityTypeCode, entityId);
/// <summary>
/// Возвращает название сущности
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <param name="parentEntityId"></param>
/// <returns>название сущности</returns>
public static string GetName(string entityTypeCode, int entityId, int parentEntityId) => EntityObjectRepository.GetName(entityTypeCode, entityId, parentEntityId);
/// <summary>
/// Возвращает идентификатор родительской сущности
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <returns>идентификатор родительской сущности</returns>
public static int? GetParentId(string entityTypeCode, int entityId) => EntityObjectRepository.GetParentId(entityTypeCode, entityId);
public static int[] GetParentIdsForTree(ParentIdsForTreeQuery query) => EntityObjectRepository.GetParentIdsForTree(query);
/// <summary>
/// Возвращает цепочку сущностей для хлебных крошек
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <param name="parentEntityId">идентификатор родительской сущности</param>
/// <param name="actionCode"></param>
/// <returns>цепочка сущностей</returns>
public static IEnumerable<EntityInfo> GetBreadCrumbsList(string entityTypeCode, long entityId, long? parentEntityId, string actionCode)
{
if (!string.IsNullOrWhiteSpace(actionCode))
{
if (actionCode.Equals(ActionCode.ChildContentPermissions, StringComparison.InvariantCultureIgnoreCase))
{
entityTypeCode = EntityTypeCode.Content;
}
else if (actionCode.Equals(ActionCode.ChildArticlePermissions, StringComparison.InvariantCultureIgnoreCase))
{
entityTypeCode = EntityTypeCode.Article;
}
}
return EntityObjectRepository.GetParentsChain(entityTypeCode, entityId, parentEntityId);
}
/// <summary>
/// Возвращает информацию о текущей и родительской сущности
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <param name="parentEntityId">идентификатор родительской сущности</param>
/// <returns>информация о текущей и родительской сущности</returns>
public static IEnumerable<EntityInfo> GetParentInfo(string entityTypeCode, long entityId, long? parentEntityId) => EntityObjectRepository.GetParentsChain(entityTypeCode, entityId, parentEntityId, true);
/// <summary>
/// Возвращает информацию о текущей сущности и всех предках
/// </summary>
/// <param name="entityTypeCode">код типа сущности</param>
/// <param name="entityId">идентификатор сущности</param>
/// <param name="parentEntityId">идентификатор родительской сущности</param>
/// <returns>информация о текущей и родительской сущности</returns>
public static IEnumerable<EntityInfo> GetParentsChain(string entityTypeCode, long entityId, long? parentEntityId) => EntityObjectRepository.GetParentsChain(entityTypeCode, entityId, parentEntityId);
public static void UnlockAllEntitiesLockedByCurrentUser()
{
var id = QPContext.CurrentUserId;
if (id != 0)
{
EntityObjectRepository.UnlockAllEntitiesLockedByUser(id);
}
}
/// <summary>
/// Проверить возможность восстановления а втосохраненных сущностей
/// </summary>
/// <param name="recordHeaders"></param>
/// <returns></returns>
public static IEnumerable<long> AutosaveRestoringCheck(IList<AutosavedEntityRecordHeader> recordHeaders)
{
if (recordHeaders != null && recordHeaders.Any())
{
// Проверка для существующих сущностей
var approvedExisted = recordHeaders
.Where(h => !h.IsNew && h.Modified.HasValue)
.GroupBy(h => h.EntityTypeCode, StringComparer.InvariantCultureIgnoreCase)
.Select(g => new EntityObjectRepository.VariousTypeEntityQueryParam
{
EntityTypeCode = g.Key,
EntityIDs = g.Select(h2 => h2.EntityId).Distinct()
})
.GetVariousTypeList()
.Where(e =>
{
// проверка на возможность восстановить сущность
var rh = recordHeaders.First(h => h.EntityId == e.Id && h.EntityTypeCode.Equals(e.EntityTypeCode, StringComparison.InvariantCultureIgnoreCase));
return rh.Modified.Value <= e.Modified
&& ( // проверка на lock
e is LockableEntityObject
&& !((LockableEntityObject)e).LockedByAnyoneElse
|| !(e is LockableEntityObject)
)
&& !e.IsReadOnly;
}).Select(e => recordHeaders
.First(h => !h.IsNew && h.EntityId == e.Id && h.EntityTypeCode.Equals(e.EntityTypeCode, StringComparison.InvariantCultureIgnoreCase))
.RecordId
);
// Проверка для новых сущностей (существует ли parent)
var code2ParentCode = EntityTypeRepository.GetList().ToDictionary(t => t.Code, t => t.ParentCode, StringComparer.InvariantCultureIgnoreCase);
foreach (var h in recordHeaders)
{
h.ParentEntityTypeCode = code2ParentCode[h.EntityTypeCode];
}
var approvedNew = recordHeaders
.Where(h => h.IsNew)
.GroupBy(h => h.ParentEntityTypeCode, StringComparer.InvariantCultureIgnoreCase)
.Select(g => new EntityObjectRepository.VariousTypeEntityQueryParam
{
EntityTypeCode = g.Key,
EntityIDs = g.Select(h2 => h2.ParentEntityId).Distinct()
})
.GetVariousTypeList()
.SelectMany(e => recordHeaders
.Where(h =>
h.IsNew &&
h.ParentEntityId == e.Id &&
h.ParentEntityTypeCode.Equals(e.EntityTypeCode, StringComparison.InvariantCultureIgnoreCase)
)
.Select(h => h.RecordId)
);
return approvedExisted.Concat(approvedNew).ToArray();
}
return Enumerable.Empty<long>();
}
public static string GetArticleFieldValue(int contentId, string fieldName, int articleId) => ArticleRepository.GetFieldValue(articleId, contentId, fieldName);
public static Dictionary<int, string> GetContentFieldValues(int contentId, string fieldName) => ArticleRepository.GetContentFieldValues(contentId, fieldName);
public static string GetArticleLinkedItems(int linkId, int articleId) => ArticleRepository.GetLinkedItems(new [] {linkId}, articleId)[linkId];
public static int GetArticleIdByFieldValue(int contentId, string fieldName, string fieldValue) => ArticleRepository.GetArticleIdByFieldValue(contentId, fieldName, fieldValue);
}
}
| 49.950355 | 210 | 0.624521 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | QuantumArt/QP | bll/Services/EntityObjectService.cs | 15,402 | C# |
/*
Copyright 2016 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.Windows.Input;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Threading.Tasks;
namespace AddDeleteFieldToFromFeatureClass
{
/// <summary>
/// This sample shows how to use Geo Processing to add and remove a fields from a geodatabase.
/// </summary>
/// <remarks>
/// 1. Download the Community Sample data (see under the "Resources" section for downloading sample data). The sample data contains a project called "FeatureTest.aprx" with data suitable for this sample. Make sure that the Sample data is unzipped in c:\data and "C:\Data\FeatureTest\FeatureTest.aprx" is available.
/// 1. Open this solution in Visual Studio 2015.
/// 1. Click the build menu and select Build Solution.
/// 1. Click the Start button to open ArCGIS Pro. ArcGIS Pro will open.
/// 1. Open the "C:\Data\FeatureTest\FeatureTest.aprx" project.
/// 1. Click on the Add-in tab and verify that a "FeatureClass Schema" group was added.
/// 1. Open the "Attribute table" for the topmost (first) layer. This will later allow you to view the schema change in real time.
/// 
/// 1. Note the field names in the attribute table for the first layer.
/// 1. Click the "Add a new field" button and check that the field "Alias Name Added Field" was added to the attribute table.
/// 
/// 1. Click the "Delete the new Field" button and check that the field "Alias Name Added Field" is successfully removed from the attribute table.
/// 
/// </remarks>
internal class Module1 : Module
{
private static Module1 _this = null;
/// <summary>
/// Retrieve the singleton instance to this module here
/// </summary>
public static Module1 Current
{
get
{
return _this ?? (_this = (Module1)FrameworkApplication.FindModule("AddDeleteFieldToFromFeatureClass_Module"));
}
}
#region Overrides
/// <summary>
/// Called by Framework when ArcGIS Pro is closing
/// </summary>
/// <returns>False to prevent Pro from closing, otherwise True</returns>
protected override bool CanUnload()
{
//TODO - add your business logic
//return false to ~cancel~ Application close
return true;
}
#endregion Overrides
}
}
| 40.126582 | 320 | 0.675079 | [
"Apache-2.0"
] | hnasr/arcgis-pro-sdk-community-samples | Geodatabase/AddDeleteFieldToFromFeatureClass/Module1.cs | 3,170 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Comformation.IntrinsicFunctions;
namespace Comformation.S3.Bucket
{
/// <summary>
/// AWS::S3::Bucket CorsRule
/// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html
/// </summary>
public class CorsRule
{
/// <summary>
/// AllowedHeaders
/// Headers that are specified in the Access-Control-Request-Headers header. These headers are allowed
/// in a preflight OPTIONS request. In response to any preflight OPTIONS request, Amazon S3 returns any
/// requested headers that are allowed.
/// Required: No
/// Type: List of String
/// Update requires: No interruption
/// </summary>
[JsonProperty("AllowedHeaders")]
public List<Union<string, IntrinsicFunction>> AllowedHeaders { get; set; }
/// <summary>
/// AllowedMethods
/// An HTTP method that you allow the origin to run.
/// Allowed values: GET | PUT | HEAD | POST | DELETE
/// Required: Yes
/// Type: List of String
/// Update requires: No interruption
/// </summary>
[JsonProperty("AllowedMethods")]
public List<Union<string, IntrinsicFunction>> AllowedMethods { get; set; }
/// <summary>
/// AllowedOrigins
/// One or more origins you want customers to be able to access the bucket from.
/// Required: Yes
/// Type: List of String
/// Update requires: No interruption
/// </summary>
[JsonProperty("AllowedOrigins")]
public List<Union<string, IntrinsicFunction>> AllowedOrigins { get; set; }
/// <summary>
/// ExposedHeaders
/// One or more headers in the response that you want customers to be able to access from their
/// applications (for example, from a JavaScript XMLHttpRequest object).
/// Required: No
/// Type: List of String
/// Update requires: No interruption
/// </summary>
[JsonProperty("ExposedHeaders")]
public List<Union<string, IntrinsicFunction>> ExposedHeaders { get; set; }
/// <summary>
/// Id
/// A unique identifier for this rule. The value must be no more than 255 characters.
/// Required: No
/// Type: String
/// Update requires: No interruption
/// </summary>
[JsonProperty("Id")]
public Union<string, IntrinsicFunction> Id { get; set; }
/// <summary>
/// MaxAge
/// The time in seconds that your browser is to cache the preflight response for the specified resource.
/// Required: No
/// Type: Integer
/// Update requires: No interruption
/// </summary>
[JsonProperty("MaxAge")]
public Union<int, IntrinsicFunction> MaxAge { get; set; }
}
}
| 36.518519 | 114 | 0.604124 | [
"MIT"
] | stanb/Comformation | src/Comformation/Generated/S3/Bucket/CorsRule.cs | 2,958 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WLW.Twitter.Bitly.Plugin.TwitterConfig;
namespace WLW.Twitter.Bitly.Plugin
{
public partial class SettingsForm : Form
{
WLWPluginSettings wlw_settings;
TwitterSettings t_settings;
public SettingsForm(WLWPluginSettings settings) : this()
{
wlw_settings = settings;
this.t_settings = new TwitterSettings();
this.t_settings.AccessSecret = wlw_settings.TwitterAccessSecretOption;
this.t_settings.AccessToken = wlw_settings.TwitterAccessTokenOption;
this.StartPosition = FormStartPosition.CenterParent;
}
public SettingsForm()
{
InitializeComponent();
}
private void SettingsForm_Load(object sender, EventArgs e)
{
}
//
//
// Twitter Configuration Methods
//
//
private void SaveTwitterAccessInfo(TwitterSettings ts)
{
this.wlw_settings.TwitterAccessSecretOption = ts.AccessSecret;
this.wlw_settings.TwitterAccessTokenOption = ts.AccessToken;
}
private void AuthorizeTwitterButton_Click(object sender, EventArgs e)
{
string statusMsg = string.Empty;
IWin32Window dialogOwner = sender as IWin32Window;
bool itWorked = PerformTwitterAuthorization(dialogOwner);
if (itWorked)
{
statusMsg = "The WLW Twitter and Bitly Plugin was successfully authorized.\n\n" +
"You will not have to do this again unless you revoke\n" +
"access for this plugin on Twitter.com.";
SaveTwitterAccessInfo(this.t_settings);
MessageBox.Show(this, statusMsg, "Authorize Plugin at Twitter");
}
}
private bool PerformTwitterAuthorization(IWin32Window dialogOwner)
{
OAuth.Manager oauth = new OAuth.Manager(TwitterSettings.TWITTER_CONSUMER_KEY, TwitterSettings.TWITTER_CONSUMER_SECRET);
var dlg = new OAuth.TwitterOauthForm(oauth);
dlg.ShowDialog(dialogOwner);
if (dlg.DialogResult == DialogResult.OK)
{
dlg.StoreTokens(this.t_settings);
}
dlg.Dispose();
if (!this.t_settings.Completed)
{
MessageBox.Show("You must grant approval for this plugin with Twitter\n" +
"before it can tweet your blog posts.",
"Authorize Plugin at Twitter",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return false;
}
return true;
}
//
//
// Bitly Configuration Methods
//
//
private void AuthorizeBitlyButton_Click(object sender, EventArgs e)
{
string statusMsg = string.Empty;
IWin32Window dialogOwner = sender as IWin32Window;
bool itWorked = PerformBitlyAuthorization(dialogOwner);
if (itWorked)
{
statusMsg = "The WLW Twitter and Bitly Plugin was successfully authorized.";
SaveTwitterAccessInfo(this.t_settings);
MessageBox.Show(this, statusMsg, "Authorize Plugin at Bitly");
}
}
private bool PerformBitlyAuthorization(IWin32Window dialogOwner)
{
var redirectUri = "http://howstevegotburnedtoday.com/wp-empty.php";
var clientId = "e45f8037dcfc96336d3979ef3f4d8c905e7d8d01";
var clientSecret = "d6af409cf64a873810fe8b2a17585d8c1f36e01a";
bool success = false;
BitlyOAuthForm authForm = new BitlyOAuthForm();
authForm.ClientId = clientId;
authForm.ClientSecret = clientSecret;
authForm.RedirectUri = redirectUri;
DialogResult result = authForm.ShowDialog(dialogOwner);
if (result == DialogResult.OK)
{
this.wlw_settings.BitlyAccessTokenOption = authForm.BitlyAccessToken;
this.wlw_settings.BitlyUserOption = authForm.BitlyUser;
success = true;
}
else
{
MessageBox.Show("You must grant approval for this plugin with Bitly\n" +
"before it can shorten the URL of you blog posts.",
"Authorize Plugin at Bitly",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
success = false;
}
authForm.Dispose();
return success;
}
private void ConfigureTwitterPostTemplate_Click(object sender, EventArgs e)
{
IWin32Window dialogOwner = sender as IWin32Window;
TwitterPostSettingsForm settingsForm = new TwitterPostSettingsForm();
settingsForm.PostTemplate = wlw_settings.TwitterPostFormat;
DialogResult result = settingsForm.ShowDialog(dialogOwner);
if (result == DialogResult.OK)
{
wlw_settings.TwitterPostFormat = settingsForm.PostTemplate;
string statusMsg = "The Twitter post template was saved.";
MessageBox.Show(this, statusMsg, "Configure Twitter Post Template");
}
settingsForm.Dispose();
}
}
}
| 32.169399 | 132 | 0.566672 | [
"MIT"
] | sstjean/WLWTwitterBitlyPlugin | WLW.Twitter.Bitly.Plugin/SettingsForm.cs | 5,889 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Text;
namespace Microsoft.Azure.Services.AppAuthentication.Unit.Tests
{
/// <summary>
/// Helper class to generate tokens for unit testing
/// </summary>
public class TokenHelper
{
/// <summary>
/// The hardcoded user token has expiry replaced by [exp], so we can replace it with some value to test functionality.
/// </summary>
/// <param name="accessToken"></param>
/// <param name="secondsFromCurrent"></param>
/// <returns></returns>
private static string UpdateTokenTime(string accessToken, long secondsFromCurrent)
{
var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
byte[] tokenAsBytes = Convert.FromBase64String(accessToken);
string tokenAsString = Encoding.ASCII.GetString(tokenAsBytes);
tokenAsString = tokenAsString.Replace("[exp]", $"{(long)timeSpan.TotalSeconds + secondsFromCurrent}");
tokenAsBytes = Encoding.ASCII.GetBytes(tokenAsString);
return Convert.ToBase64String(tokenAsBytes);
}
internal static string GetUserToken()
{
// Gets a user token that will expire in 10 seconds from now.
return GetUserToken(10);
}
internal static string GetUserToken(long secondsFromCurrent)
{
// This is a dummy user token, where exp claim is set to [exp], so can be changed for testing
string midPart =
"eyJhdWQiOiJodHRwczovL2RhdGFiYXNlLndpbmRvd3MubmV0LyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE1MDMxOTAwNjAsIm5iZiI6MTUwMzE5MDA2MCwiZXhwIjpbZXhwXSwiX2NsYWltX25hbWVzIjp7Imdyb3VwcyI6InNyYzEifSwiX2NsYWltX3NvdXJjZXMiOnsic3JjMSI6eyJlbmRwb2ludCI6Imh0dHBzOi8vZ3JhcGgud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3VzZXJzLzljZWI0NGFmLTQ0MzctNGNjYy1hNDlhLTlhOWJkZTA2NzUyZS9nZXRNZW1iZXJPYmplY3RzIn19LCJhY3IiOiIxIiwiYWlvIjoiWTJGZ1lMRGVWT2Q4ei85cncvLzNzODdaZURHWDNTcS9taHZwSWg2bHU5am55UFNHdmxNQSIsImFtciI6WyJ3aWEiLCJtZmEiXSwiYXBwaWQiOiIwNGIwNzc5NS04ZGRiLTQ2MWEtYmJlZS0wMmY5ZTFiZjdiNDYiLCJhcHBpZGFjciI6IjAiLCJlX2V4cCI6MjYyODAwLCJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwiaW5fY29ycCI6InRydWUiLCJpcGFkZHIiOiIxMC4xMC4wLjAiLCJuYW1lIjoiSm9obiBEb2UiLCJvaWQiOiI5Y2ViNDRhZi00NDM3LTRjY2MtYTQ5YS05YTliZGUwNjc1MmUiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiJfVkJwSVNBZUlfS1VBVHZPdl93RWJzdlE1YlZjUERSLUhuRTVBUmszb21FIiwidGlkIjoiNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3IiwidW5pcXVlX25hbWUiOiJqb2huZG9lQGNvbnRvc28uY29tIiwidXBuIjoiam9obmRvZUBjb250b3NvLmNvbSIsInZlciI6IjEuMCJ9";
midPart = UpdateTokenTime(midPart, secondsFromCurrent);
return
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USIsImtpZCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USJ9" + "." + midPart + "." + "gGo1wCH2k8kqt6JUdjBMavZX9Sq2L_tKLvVDPUJv3NurZT5JGYyS7gJ11RMrVaxyG48dnlWat1vEBcB-YLOkpL-2gR_sSAoAStPuz8yXAFHxluw-WOqiWxlm2leENqwMmCrMYinm8ohkrScpfRFm6-4fzgczdhNi0vjkTHaycYnrPrH9cZHSL9Qyzt6MH6pEyGct4zmgASI1Vlrga5_x_x8xj-FscIRYorrvx61fThaor8M4FjzglNgum4j5yecn1pIcp75CK43xb7e4jdsfL2nl6wgn5mZj_59b_aKNa3_VA-NmZTlxjvjlL_AHdDkYPlku_B75-0EbfKN2IR5eLw";
}
internal static string GetUserTokenResponse(long secondsFromCurrent, bool formatForVisualStudio = false)
{
string tokenResult =
"{ \"accessToken\": \"{accesstoken}\", \"expiresOn\": \"{expireson}\", \"subscription\": \"1135bf8c-f190-46f2-bfd6-d57c57852c04\", \"tenant\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\", \"tokenType\": \"Bearer\"}";
tokenResult = tokenResult.Replace("{accesstoken}", GetUserToken(secondsFromCurrent));
tokenResult = tokenResult.Replace("{expireson}", DateTimeOffset.Now.AddSeconds(secondsFromCurrent).ToString());
if (formatForVisualStudio)
{
tokenResult = tokenResult.Replace("accessToken", "access_token");
tokenResult = tokenResult.Replace("expiresOn", "expires_on");
}
return tokenResult;
}
/// <summary>
/// Sample IMDS /instance response
/// </summary>
/// <returns></returns>
internal static string GetInstanceMetadataResponse()
{
return
"{\"compute\":{\"location\":\"westus\",\"name\":\"TestBedVm\",\"resourceGroupName\":\"testbed\",\"subscriptionId\":\"bdd789f3-d9d1-4bea-ac14-30a39ed66d33\"}}";
}
/// <summary>
/// The response has claims as expected from App Service MSI response
/// </summary>
/// <returns></returns>
internal static string GetMsiAppServicesTokenResponse()
{
return
"{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSIsImtpZCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSJ9.eyJhdWQiOiJodHRwczovL3ZhdWx0LmF6dXJlLm5ldCIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE0OTIyNjYwNjEsIm5iZiI6MTQ5MjI2NjA2MSwiZXhwIjoxNDkyMjY5OTYxLCJhaW8iOiJZMlpnWUNoTk91Yy9ZKzJMOVM3Ty8yWTBDL2lhQUFBPSIsImFwcGlkIjoiZjBiMWY4NGEtZWM3NC00Y2VmLTgwMzQtYWRiYWQxNjhjZTMzIiwiYXBwaWRhY3IiOiIyIiwiZV9leHAiOjI2MjgwMCwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3LyIsIm9pZCI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInN1YiI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInRpZCI6IjcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0NyIsInZlciI6IjEuMCJ9.TjnKtpTJ_dvQc3GQO9QSA0Sm9MISNakF8IT9-abzkaWqmwruhB2Tls9QTHe-P_xp09Jrt6JPhC8Z5mTTWgKqV_LV-KbJe_NmlYMTU_X5AcaPIQoi2ctSv62-wnnl-2IQjEEkyX7Vc0ixnPdWOG5LCO4ctTmURRO-tWN_jIK5up-wb0-ks1STFSBGJZtJ0xNTdTb9SSG4HpHzbLdkEmg-oAvOBX2OmwaNbBsU3chi4G5MoLtm5oXvL36z9vsf2bN_H7Sg-mss1Ua7OOwFVPMrx0rrIqXzKYQUSvNFAHLebKcp2SccpYWrgp7lKQGrbQhJsYYkzl-R-NTB5fUPUB7B3Q\",\"expires_on\":\"1589671972\",\"resource\":\"https://vault.azure.net\",\"token_type\":\"Bearer\",\"client_id\":\"F0B1F84A-EC74-4CEF-8034-ADBAD168CE33\"}";
}
/// <summary>
/// The response has claims as expected from Azure VM MSI response
/// </summary>
/// <returns></returns>
internal static string GetMsiAzureVmTokenResponse()
{
return
"{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSIsImtpZCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSJ9.eyJhdWQiOiJodHRwczovL3ZhdWx0LmF6dXJlLm5ldCIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE0OTIyNjYwNjEsIm5iZiI6MTQ5MjI2NjA2MSwiZXhwIjoxNDkyMjY5OTYxLCJhaW8iOiJZMlpnWUNoTk91Yy9ZKzJMOVM3Ty8yWTBDL2lhQUFBPSIsImFwcGlkIjoiZjBiMWY4NGEtZWM3NC00Y2VmLTgwMzQtYWRiYWQxNjhjZTMzIiwiYXBwaWRhY3IiOiIyIiwiZV9leHAiOjI2MjgwMCwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3LyIsIm9pZCI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInN1YiI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInRpZCI6IjcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0NyIsInZlciI6IjEuMCJ9.TjnKtpTJ_dvQc3GQO9QSA0Sm9MISNakF8IT9-abzkaWqmwruhB2Tls9QTHe-P_xp09Jrt6JPhC8Z5mTTWgKqV_LV-KbJe_NmlYMTU_X5AcaPIQoi2ctSv62-wnnl-2IQjEEkyX7Vc0ixnPdWOG5LCO4ctTmURRO-tWN_jIK5up-wb0-ks1STFSBGJZtJ0xNTdTb9SSG4HpHzbLdkEmg-oAvOBX2OmwaNbBsU3chi4G5MoLtm5oXvL36z9vsf2bN_H7Sg-mss1Ua7OOwFVPMrx0rrIqXzKYQUSvNFAHLebKcp2SccpYWrgp7lKQGrbQhJsYYkzl-R-NTB5fUPUB7B3Q\",\"refresh_token\":\"\",\"expires_in\":\"3600\",\"expires_on\":\"1492269961\",\"not_before\":\"1492266061\",\"resource\":\"https://vault.azure.net\",\"token_type\":\"Bearer\"}";
}
/// <summary>
/// The response has claims as expected from App Service MSI response with user-assigned managed identity
/// </summary>
/// <returns></returns>
internal static string GetManagedIdentityAppServicesTokenResponse()
{
return
//[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Secret is used for tests only")]
"{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ii1zeE1KTUxDSURXTVRQdlp5SjZ0eC1DRHh3MCIsImtpZCI6Ii1zeE1KTUxDSURXTVRQdlp5SjZ0eC1DRHh3MCJ9.eyJhdWQiOiJodHRwczovL3ZhdWx0LmF6dXJlLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUwMjc3NjYwLCJuYmYiOjE1NTAyNzc2NjAsImV4cCI6MTU1MDMwNjc2MCwiYWlvIjoiNDJKZ1lPaWZHRnlZUFgrSnRsbXQvdTFucjdjMkFBQT0iLCJhcHBpZCI6Ijk0MjM0M2IxLTRhZjItNDkwYy1iNmQ5LTkyNTBiOGYyODA4YyIsImFwcGlkYWNyIjoiMiIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJvaWQiOiJiMzllNTZiZS1jZThiLTQyYjAtYjY3ZS0xYWI5YmU4ODUxZmQiLCJzdWIiOiJiMzllNTZiZS1jZThiLTQyYjAtYjY3ZS0xYWI5YmU4ODUxZmQiLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1dGkiOiJUVW9za19PbGkwNlMzZGh6TXVsOEFBIiwidmVyIjoiMS4wIiwieG1zX21pcmlkIjoiL3N1YnNjcmlwdGlvbnMvYmRkNzg5ZjMtZDlkMS00YmVhLWFjMTQtMzBhMzllZDY2ZDMzL3Jlc291cmNlZ3JvdXBzL3Rlc3RiZWQvcHJvdmlkZXJzL01pY3Jvc29mdC5NYW5hZ2VkSWRlbnRpdHkvdXNlckFzc2lnbmVkSWRlbnRpdGllcy9UZXN0QmVkTWFuYWdlZElkZW50aXR5In0.l1E07vTtwSCFasXuFMw1QQXzZutZxFYRjtJhO0L5jyni6L9FO8B2azuIb6ot2KoS5TY-jcvJiLuX-e1Nxu4GlrVAMBukRKjxsyHhYQJ9vppVu7vPFG9EY-GCcamsgkoh6ItbYhDD6sRBqUjTGG2I7lvKNhLg2g92KZiwDhXVtfDPwWLMrnZKmuwOOBwU5UZ61poAmZvw5NO5a8pvXqJ1s5koKo8aPjnCdkJ5WA2SvLbGM_VMo5O6WgLgB4UTC_LnNvsp5nzie2W6Z-VnM_Ar3w1KMeP6_xJZAyEVsxQIgIF3hy12iekpvViwXXUzvthjpeoFobvn65l6NX7fIrNZNQ\",\"expires_on\":\"2/16/2019 8:46:00 AM +00:00\",\"resource\":\"https://vault.azure.net/\",\"token_type\":\"Bearer\"}";
}
/// <summary>
/// The response has claims as expected from Azure VM MSI response with user-assigned managed identity
/// </summary>
/// <returns></returns>
internal static string GetManagedIdentityAzureVmTokenResponse()
{
return
//[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Secret is used for tests only")]
"{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ii1zeE1KTUxDSURXTVRQdlp5SjZ0eC1DRHh3MCIsImtpZCI6Ii1zeE1KTUxDSURXTVRQdlp5SjZ0eC1DRHh3MCJ9.eyJhdWQiOiJodHRwczovL3ZhdWx0LmF6dXJlLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUwMjc4NDkwLCJuYmYiOjE1NTAyNzg0OTAsImV4cCI6MTU1MDMwNzU5MCwiYWlvIjoiNDJKZ1lBaU9YWmxSWXBlZitYcWZaZEFpTnMyN0FBPT0iLCJhcHBpZCI6Ijk0MjM0M2IxLTRhZjItNDkwYy1iNmQ5LTkyNTBiOGYyODA4YyIsImFwcGlkYWNyIjoiMiIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJvaWQiOiJiMzllNTZiZS1jZThiLTQyYjAtYjY3ZS0xYWI5YmU4ODUxZmQiLCJzdWIiOiJiMzllNTZiZS1jZThiLTQyYjAtYjY3ZS0xYWI5YmU4ODUxZmQiLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1dGkiOiJaUHZPY0tPUE4wYVZicm9lZmhNQUFBIiwidmVyIjoiMS4wIiwieG1zX21pcmlkIjoiL3N1YnNjcmlwdGlvbnMvYmRkNzg5ZjMtZDlkMS00YmVhLWFjMTQtMzBhMzllZDY2ZDMzL3Jlc291cmNlZ3JvdXBzL3Rlc3RiZWQvcHJvdmlkZXJzL01pY3Jvc29mdC5NYW5hZ2VkSWRlbnRpdHkvdXNlckFzc2lnbmVkSWRlbnRpdGllcy9UZXN0QmVkTWFuYWdlZElkZW50aXR5In0.TxlAPmz2_xAgIQUtrz0zP7Y2iid7tiQg3SEMOAMW6P69NngKBR8JZWMZ20K01rHarrxsb_7IaKwFpK4MHadv-ZNcjXeGgA_FdnxKkluNArjCAj-2n3wLeZVE3o8kbmrBCuosEwUCyH69wHINABmz3xLnO5c9OUQXjK7-Z73DfV1ZYWXXBE2HzQlNAyKbTcd4GQng22REahKFj4snuDTt_dvXg1s8pkrnqsz-fCHf1QHK6mk_ds-Y4uz40SyLlVJ_i4PxZtLZYcl-kS-ol0qEKdxYE6ghAVzuwF6DbX-2LAw2QY2mcMIOttyCw4r1V-lTVuTenrG2uOM7syBTJ-4y4A\",\"client_id\":\"942343b1-4af2-490c-b6d9-9250b8f2808c\",\"expires_in\":\"28800\",\"expires_on\":\"1550307590\",\"ext_expires_in\":\"28800\",\"not_before\":\"1550278490\",\"resource\":\"https://vault.azure.net/\",\"token_type\":\"Bearer\"}";
}
/// <summary>
/// The response from MSI missing token
/// </summary>
/// <returns></returns>
internal static string GetMsiMissingTokenResponse()
{
return
"{\"refresh_token\":\"\",\"expires_in\":\"3600\",\"expires_on\":\"1492269961\",\"not_before\":\"1492266061\",\"resource\":\"https://vault.azure.net\",\"token_type\":\"Bearer\"}";
}
/// <summary>
/// The response has claims as expected from MSI response with invalid json
/// </summary>
/// <returns></returns>
internal static string GetInvalidMsiTokenResponse()
{
return
//[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Secret is used for tests only")]
"{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSIsImtpZCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSJ9.eyJhdWQiOiJodHRwczovL3ZhdWx0LmF6dXJlLm5ldCIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE0OTIyNjYwNjEsIm5iZiI6MTQ5MjI2NjA2MSwiZXhwIjoxNDkyMjY5OTYxLCJhaW8iOiJZMlpnWUNoTk91Yy9ZKzJMOVM3Ty8yWTBDL2lhQUFBPSIsImFwcGlkIjoiZjBiMWY4NGEtZWM3NC00Y2VmLTgwMzQtYWRiYWQxNjhjZTMzIiwiYXBwaWRhY3IiOiIyIiwiZV9leHAiOjI2MjgwMCwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3LyIsIm9pZCI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInN1YiI6ImY4NDYwMGM1LWE5ZDgtNDEyOS1hMTk5LWNjNDE4MDYwNzQxMSIsInRpZCI6IjcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0NyIsInZlciI6IjEuMCJ9.TjnKtpTJ_dvQc3GQO9QSA0Sm9MISNakF8IT9-abzkaWqmwruhB2Tls9QTHe-P_xp09Jrt6JPhC8Z5mTTWgKqV_LV-KbJe_NmlYMTU_X5AcaPIQoi2ctSv62-wnnl-2IQjEEkyX7Vc0ixnPdWOG5LCO4ctTmURRO-tWN_jIK5up-wb0-ks1STFSBGJZtJ0xNTdTb9SSG4HpHzbLdkEmg-oAvOBX2OmwaNbBsU3chi4G5MoLtm5oXvL36z9vsf2bN_H7Sg-mss1Ua7OOwFVPMrx0rrIqXzKYQUSvNFAHLebKcp2SccpYWrgp7lKQGrbQhJsYYkzl-R-NTB5fUPUB7B3Q\",\"refresh_token\"\"\",\"expires_in\":\"3600\",\"expires_on\":\"1492269961\",\"not_before\":\"1492266061\",\"resource\":\"https://vault.azure.net\",\"token_type\":\"Bearer\"";
}
/// <summary>
/// The response has claims as expected from Client Credentials flow response.
/// </summary>
/// <returns></returns>
internal static string GetAppToken()
{
return
//[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Secret is used for tests only")]
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USIsImtpZCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USJ9.eyJhdWQiOiJodHRwczovL2RhdGFiYXNlLndpbmRvd3MubmV0LyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE1MDMxOTAwNjAsIm5iZiI6MTUwMzE5MDA2MCwiZXhwIjoxNTAzMTkzOTYwLCJfY2xhaW1fbmFtZXMiOnsiZ3JvdXBzIjoic3JjMSJ9LCJfY2xhaW1fc291cmNlcyI6eyJzcmMxIjp7ImVuZHBvaW50IjoiaHR0cHM6Ly9ncmFwaC53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvdXNlcnMvOWNlYjQ0YWYtNDQzNy00Y2NjLWE0OWEtOWE5YmRlMDY3NTJlL2dldE1lbWJlck9iamVjdHMifX0sImFjciI6IjEiLCJhaW8iOiJZMkZnWUxEZVZPZDh6Lzlydy8vM3M4N1plREdYM1NxL21odnBJaDZsdTlqbnlQU0d2bE1BIiwiYW1yIjpbIndpYSIsIm1mYSJdLCJhcHBpZCI6IjA0YjA3Nzk1LThkZGItNDYxYS1iYmVlLTAyZjllMWJmN2I0NiIsImFwcGlkYWNyIjoiMCIsImVfZXhwIjoyNjI4MDAsImZhbWlseV9uYW1lIjoiU2hhcm1hIiwiZ2l2ZW5fbmFtZSI6IlZhcnVuIiwiaW5fY29ycCI6InRydWUiLCJpcGFkZHIiOiIxNjcuMjIwLjAuMjExIiwibmFtZSI6IlZhcnVuIFNoYXJtYSIsIm9pZCI6IjljZWI0NGFmLTQ0MzctNGNjYy1hNDlhLTlhOWJkZTA2NzUyZSIsIm9ucHJlbV9zaWQiOiJTLTEtNS0yMS0yMTI3NTIxMTg0LTE2MDQwMTI5MjAtMTg4NzkyNzUyNy0xODMzNjYyMSIsInB1aWQiOiIxMDAzM0ZGRjgwMUI5MTg4Iiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwic3ViIjoiX1ZCcElTQWVJX0tVQVR2T3Zfd0Vic3ZRNWJWY1BEUi1IbkU1QVJrM29tRSIsInRpZCI6IjcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0NyIsInVuaXF1ZV9uYW1lIjoidmFydW5zaEBtaWNyb3NvZnQuY29tIiwidXBuIjoidmFydW5zaEBtaWNyb3NvZnQuY29tIiwidmVyIjoiMS4wIn0.gGo1wCH2k8kqt6JUdjBMavZX9Sq2L_tKLvVDPUJv3NurZT5JGYyS7gJ11RMrVaxyG48dnlWat1vEBcB-YLOkpL-2gR_sSAoAStPuz8yXAFHxluw-WOqiWxlm2leENqwMmCrMYinm8ohkrScpfRFm6-4fzgczdhNi0vjkTHaycYnrPrH9cZHSL9Qyzt6MH6pEyGct4zmgASI1Vlrga5_x_x8xj-FscIRYorrvx61fThaor8M4FjzglNgum4j5yecn1pIcp75CK43xb7e4jdsfL2nl6wgn5mZj_59b_aKNa3_VA-NmZTlxjvjlL_AHdDkYPlku_B75-0EbfKN2IR5eLw";
}
/// <summary>
/// Invalid AppToken.
/// </summary>
/// <returns></returns>
internal static string GetInvalidAppToken()
{
return
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USIsImtpZCI6IlZXVkljMVdEMVRrc2JiMzAxc2FzTTVrT3E1USJ9";
}
}
}
| 102.950617 | 1,794 | 0.818983 | [
"MIT"
] | Aishwarya-C-S/azure-sdk-for-net | sdk/mgmtcommon/AppAuthentication/Azure.Services.AppAuthentication.Unit.Tests/TokenHelper.cs | 16,680 | C# |
using System;
using System.Collections.Generic;
namespace Cats.Models
{
public partial class Delivery
{
public Delivery()
{
this.DeliveryDetails = new List<DeliveryDetail>();
}
public System.Guid DeliveryID { get; set; }
public string ReceivingNumber { get; set; }
public Nullable<int> DonorID { get; set; }
public int TransporterID { get; set; }
public string PlateNoPrimary { get; set; }
public string PlateNoTrailler { get; set; }
public string DriverName { get; set; }
public int FDPID { get; set; }
public Nullable<System.Guid> DispatchID { get; set; }
public string WayBillNo { get; set; }
public string RequisitionNo { get; set; }
public Nullable<int> HubID { get; set; }
public string InvoiceNo { get; set; }
public string DeliveryBy { get; set; }
public Nullable<System.DateTime> DeliveryDate { get; set; }
public string ReceivedBy { get; set; }
public Nullable<System.DateTime> ReceivedDate { get; set; }
public Nullable<System.DateTime> DocumentReceivedDate { get; set; }
public Nullable<int> DocumentReceivedBy { get; set; }
public virtual Donor Donor { get; set; }
public virtual FDP FDP { get; set; }
public virtual Hub Hub { get; set; }
public int? Status { get; set; }
public int? ActionType { get; set; }
public string ActionTypeRemark { get; set; }
public Nullable<Guid> TransactionGroupID { get; set; }
public virtual ICollection<DeliveryDetail> DeliveryDetails { get; set; }
public virtual ICollection<TransporterPaymentRequest> TransporterPaymentRequests { get; set; }
}
}
| 41.116279 | 102 | 0.628959 | [
"Apache-2.0"
] | IYoni/cats | Models/Cats.Models/Delivery.cs | 1,768 | C# |
using OrchardCore.Workflows.Display;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.ViewModels;
namespace OrchardCore.Workflows.Drivers
{
public class IfElseTaskDisplay : ActivityDisplayDriver<IfElseTask, IfElseTaskViewModel>
{
protected override void EditActivity(IfElseTask activity, IfElseTaskViewModel model)
{
model.ConditionExpression = activity.Condition.Expression;
}
protected override void UpdateActivity(IfElseTaskViewModel model, IfElseTask activity)
{
activity.Condition = new WorkflowExpression<bool>(model.ConditionExpression);
}
}
}
| 32.952381 | 94 | 0.745665 | [
"BSD-3-Clause"
] | 1426463237/OrchardCore | src/OrchardCore.Modules/OrchardCore.Workflows/Drivers/IfElseTaskDisplay.cs | 692 | C# |
namespace CI.HttpClient
{
public enum HttpAction
{
Delete,
Get,
Patch,
Post,
Put
}
} | 11.5 | 26 | 0.449275 | [
"MIT"
] | Omoikane-llc/pjExp20180722 | MRTK_practice20180722/Assets/HttpClient/Enums/HttpAction.cs | 140 | C# |
using Microsoft.AspNetCore.Hosting;
using Ninject;
using Ninject.Web.AspNetCore.Hosting;
using Ninject.Web.Common.SelfHost;
using System;
using System.Linq;
namespace SampleApplication_AspNetCore
{
public class Program
{
public static void Main(string[] args)
{
// The hosting model can be explicitly configured with the SERVER_HOSTING_MODEL environment variable.
// See https://www.andrecarlucci.com/en/setting-environment-variables-for-asp-net-core-when-publishing-on-iis/ for
// setting the variable in IIS.
var model = Environment.GetEnvironmentVariable("SERVER_HOSTING_MODEL");
// Command line arguments have higher precedence than environment variables
model = args.FirstOrDefault(arg => arg.StartsWith("--use"))?.Substring(5) ?? model;
var hostConfiguration = new AspNetCoreHostConfiguration(args)
.UseStartup<Startup>()
.UseWebHostBuilder(CreateWebHostBuilder)
.BlockOnStart();
switch (model)
{
case "Kestrel":
hostConfiguration.UseKestrel();
break;
case "HttpSys":
hostConfiguration.UseHttpSys();
break;
case "IIS":
case "IISExpress":
hostConfiguration.UseIIS();
break;
default:
throw new ArgumentException($"Unknown hosting model '{model}'");
}
var host = new NinjectSelfHostBootstrapper(CreateKernel, hostConfiguration);
host.Start();
}
public static IKernel CreateKernel()
{
var settings = new NinjectSettings();
// Unfortunately, in .NET Core projects, referenced NuGet assemblies are not copied to the output directory
// in a normal build which means that the automatic extension loading does not work _reliably_ and it is
// much more reasonable to not rely on that and load everything explicitly.
settings.LoadExtensions = false;
var kernel = new StandardKernel(settings);
kernel.Load(typeof(AspNetCoreHostConfiguration).Assembly);
return kernel;
}
public static IWebHostBuilder CreateWebHostBuilder()
{
return new DefaultWebHostConfiguration(null)
.ConfigureAll()
.GetBuilder()
.UseWebRoot(@"..\SampleApplication-Shared\wwwroot");
}
}
}
| 29.232877 | 117 | 0.730084 | [
"MIT"
] | DominicUllmann/Ninject.Web.AspNetCore | src/SampleApplication-AspNetCore31/Program.cs | 2,136 | C# |
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Validators gurantee that.
namespace Zapdate.Server.Models.Request
{
public class ExchangeRefreshTokenRequestDto
{
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
}
}
| 27.181818 | 96 | 0.715719 | [
"MIT"
] | Anapher/Zapdate | src/Zapdate.Server/Models/Request/ExchangeRefreshTokenRequestDto.cs | 299 | C# |
using System;
namespace MRRCManagement
{
public class Navigation
{
private string currentMenu { set; get; } = "Home";
private Program program = new Program();
public void navigation(Program program)
{
// controls the navigation of the program and determines what menus are initiated
Console.Clear();
// determine which menu to go to from home
switch (this.currentMenu)
{
// home menu
case "Home":
{
HomeMenu();
break;
}
// customer menu
case "CustomerMenu":
{
CustomerMenu();
break;
}
// fleet menu
case "FleetMenu":
{
FleetMenu();
break;
}
// Rental menu
case "RentalMenu":
{
RentalMenu();
break;
}
default:
{
return;
}
}
// Listening for user key press within navigation
ConsoleKeyInfo keyPressed;
do
{
keyPressed = Console.ReadKey();
string keyPressedString = keyPressed.Key.ToString();
// Checks for home or exit program input from customer
switch (keyPressedString)
{
case "Backspace":
case "H":
{
this.currentMenu = "Home";
Navigation();
return;
}
case "Q":
case "Escape":
{
SaveAllFiles();
return;
}
}
// Navigation checks followed by listening for user input
switch (this.currentMenu)
{
// if at Home menu
case "Home":
{
// Activities from Home menu
switch (keyPressedString)
{
case "A":
{
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
case "B":
{
this.currentMenu = "FleetMenu";
Navigation();
return;
}
case "C":
{
this.currentMenu = "RentalMenu";
Navigation();
return;
}
default:
{
Navigation();
return;
}
}
}
// If at Customer menu
case "CustomerMenu":
{
// Activities from Customer menu
switch (keyPressedString)
{
// if display all customers is selected
case "A":
{
CustomersDisplay();
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
// if display select customer is selected
case "B":
{
CustomerDisplay();
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
// if add customer is selected
case "C":
{
CustomerCreate();
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
// if modify customer is selected
case "D":
{
CustomerModify();
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
// if remove customer is selected
case "E":
{
CustomerRemove();
this.currentMenu = "CustomerMenu";
Navigation();
return;
}
default:
{
Navigation();
return;
}
}
}
// If at Fleet menu
case "FleetMenu":
{
// Activities from Customer menu
switch (keyPressedString)
{
// if display all vehicles is selected
case "A":
{
FleetDisplay();
this.currentMenu = "FleetMenu";
Navigation();
return;
}
// if create new vehicle is selected
case "B":
{
FleetCreate();
this.currentMenu = "FleetMenu";
Navigation();
return;
}
// if modify fleet vehicle is selected
case "C":
{
FleetModify();
this.currentMenu = "FleetMenu";
Navigation();
return;
}
// if remove fleet vehicle is selected
case "D":
{
FleetRemove();
this.currentMenu = "FleetMenu";
Navigation();
return;
}
default:
{
Navigation();
return;
}
}
}
// If at Rental menu
case "RentalMenu":
{
// Activities from Customer menu
switch (keyPressedString)
{
// if search for suitable rental is selected
case "A":
{
RentalSearch();
this.currentMenu = "RentalMenu";
Navigation();
return;
}
// if rent a vehicle is selected
case "B":
{
RentalRent();
this.currentMenu = "RentalMenu";
Navigation();
return;
}
// if return a vehicle is selected
case "C":
{
RentalReturn();
this.currentMenu = "RentalMenu";
Navigation();
return;
}
// if return report of rented vehicles is selected
case "D":
{
RentalReport();
this.currentMenu = "RentalMenu";
Navigation();
return;
}
default:
{
Navigation();
return;
}
}
}
}
} while (true);
}
}
}
}
| 37.611111 | 93 | 0.229321 | [
"MIT"
] | jackgl2001/Vehicle-Fleet-Management-Tool | MRRCManagement/Navigation.cs | 10,834 | C# |
using System.Linq;
using L2dotNET.model.npcs;
using L2dotNET.model.player;
using L2dotNET.Network.serverpackets;
using L2dotNET.tables;
namespace L2dotNET.Network.clientpackets
{
class RequestBuyItem : PacketBase
{
private readonly GameClient _client;
private readonly int _listId;
private readonly int _count;
private readonly int[] _items;
public RequestBuyItem(Packet packet, GameClient client)
{
_client = client;
_listId = packet.ReadInt();
_count = packet.ReadInt();
_items = new int[_count * 2];
for (int i = 0; i < _count; i++)
{
_items[i * 2] = packet.ReadInt();
_items[(i * 2) + 1] = packet.ReadInt();
}
}
public override void RunImpl()
{
L2Player player = _client.CurrentPlayer;
}
}
} | 26.285714 | 63 | 0.566304 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SamerMoustafa/L2Ninja | src/L2dotNET/Network/clientpackets/RequestBuyItem.cs | 922 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OpenCvSharp.Util;
// ReSharper disable UnusedMember.Global
namespace OpenCvSharp
{
/// <summary>
/// XML/YAML File Storage Class.
/// </summary>
public class FileStorage : DisposableCvObject
{
#region Init & Disposal
/// <summary>
/// Default constructor.
/// You should call FileStorage::open() after initialization.
/// </summary>
public FileStorage()
{
ptr = NativeMethods.core_FileStorage_new1();
}
/// <summary>
/// The full constructor
/// </summary>
/// <param name="source">Name of the file to open or the text string to read the data from.
/// Extension of the file (.xml or .yml/.yaml) determines its format
/// (XML or YAML respectively). Also you can append .gz to work with
/// compressed files, for example myHugeMatrix.xml.gz.
/// If both FileStorage::WRITE and FileStorage::MEMORY flags are specified,
/// source is used just to specify the output file format
/// (e.g. mydata.xml, .yml etc.).</param>
/// <param name="flags"></param>
/// <param name="encoding">Encoding of the file. Note that UTF-16 XML encoding is not supported
/// currently and you should use 8-bit encoding instead of it.</param>
public FileStorage(string source, Mode flags, string? encoding = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
ptr = NativeMethods.core_FileStorage_new2(source, (int)flags, encoding);
}
/// <summary>
/// Releases unmanaged resources
/// </summary>
protected override void DisposeUnmanaged()
{
NativeMethods.core_FileStorage_delete(ptr);
base.DisposeUnmanaged();
}
#endregion
#region Properties
/// <summary>
/// Returns the specified element of the top-level mapping
/// </summary>
/// <param name="nodeName"></param>
/// <returns></returns>
public FileNode? this[string nodeName]
{
get
{
ThrowIfDisposed();
if (nodeName == null)
throw new ArgumentNullException(nameof(nodeName));
var node = NativeMethods.core_FileStorage_indexer(ptr, nodeName);
GC.KeepAlive(this);
if (node == IntPtr.Zero)
return null;
return new FileNode(node);
}
}
/// <summary>
/// the currently written element
/// </summary>
public string? ElName
{
get
{
ThrowIfDisposed();
unsafe
{
var buf = NativeMethods.core_FileStorage_elname(ptr);
if (buf == null)
return null;
var res = StringHelper.PtrToStringAnsi(buf);
GC.KeepAlive(this);
return res;
}
}
}
/// <summary>
/// the writer state
/// </summary>
public States State
{
get
{
ThrowIfDisposed();
var res = NativeMethods.core_FileStorage_state(ptr);
GC.KeepAlive(this);
return (States)res;
}
}
#endregion
#region Methods
/// <summary>
/// operator that performs PCA. The previously stored data, if any, is released
/// </summary>
/// <param name="fileName"></param>
/// <param name="flags"></param>
/// <param name="encoding">Encoding of the file. Note that UTF-16 XML encoding is not supported
/// currently and you should use 8-bit encoding instead of it.</param>
/// <returns></returns>
public virtual bool Open(string fileName, Mode flags, string? encoding = null)
{
ThrowIfDisposed();
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
var ret = NativeMethods.core_FileStorage_open(ptr, fileName, (int)flags, encoding);
GC.KeepAlive(this);
return ret != 0;
}
/// <summary>
/// Returns true if the object is associated with currently opened file.
/// </summary>
/// <returns></returns>
public virtual bool IsOpened()
{
ThrowIfDisposed();
var res = NativeMethods.core_FileStorage_isOpened(ptr) != 0;
GC.KeepAlive(this);
return res;
}
/// <summary>
/// Closes the file and releases all the memory buffers
/// </summary>
public virtual void Release()
{
ThrowIfDisposed();
Dispose();
}
/// <summary>
/// Closes the file, releases all the memory buffers and returns the text string
/// </summary>
/// <returns></returns>
public string ReleaseAndGetString()
{
ThrowIfDisposed();
try
{
using (var stdString = new StdString())
{
NativeMethods.core_FileStorage_releaseAndGetString_stdString(ptr, stdString.CvPtr);
return stdString.ToString();
}
}
finally
{
Dispose();
}
}
/// <summary>
/// Returns the first element of the top-level mapping
/// </summary>
/// <returns></returns>
public FileNode? GetFirstTopLevelNode()
{
ThrowIfDisposed();
var node = NativeMethods.core_FileStorage_getFirstTopLevelNode(ptr);
GC.KeepAlive(this);
if (node == IntPtr.Zero)
return null;
return new FileNode(node);
}
/// <summary>
/// Returns the top-level mapping. YAML supports multiple streams
/// </summary>
/// <param name="streamIdx"></param>
/// <returns></returns>
public FileNode? Root(int streamIdx = 0)
{
ThrowIfDisposed();
var node = NativeMethods.core_FileStorage_root(ptr, streamIdx);
GC.KeepAlive(this);
if (node == IntPtr.Zero)
return null;
return new FileNode(node);
}
/// <summary>
/// Writes one or more numbers of the specified format to the currently written structure
/// </summary>
/// <param name="fmt"></param>
/// <param name="vec"></param>
/// <param name="len"></param>
public void WriteRaw(string fmt, IntPtr vec, long len)
{
ThrowIfDisposed();
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="flags"></param>
/// <param name="typeName"></param>
public void StartWriteStruct(string name, int flags, string typeName)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_startWriteStruct(ptr, name, flags, typeName);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
public void EndWriteStruct()
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_endWriteStruct(ptr);
GC.KeepAlive(this);
}
/// <summary>
/// Returns the normalized object name for the specified file name
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetDefaultObjectName(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
if (!File.Exists(fileName))
throw new FileNotFoundException("", fileName);
var buf = new StringBuilder(1 << 16);
NativeMethods.core_FileStorage_getDefaultObjectName(fileName, buf, buf.Capacity);
return buf.ToString();
}
#region Write
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, int value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
NativeMethods.core_FileStorage_write_int(ptr, name, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, float value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
NativeMethods.core_FileStorage_write_float(ptr, name, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, double value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
NativeMethods.core_FileStorage_write_double(ptr, name, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, string value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
NativeMethods.core_FileStorage_write_String(ptr, name, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, Mat value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
NativeMethods.core_FileStorage_write_Mat(ptr, name, value.CvPtr);
GC.KeepAlive(this);
GC.KeepAlive(value);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, SparseMat value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
NativeMethods.core_FileStorage_write_SparseMat(ptr, name, value.CvPtr);
GC.KeepAlive(this);
GC.KeepAlive(value);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, IEnumerable<KeyPoint> value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
using (var valueVector = new VectorOfKeyPoint(value))
{
NativeMethods.core_FileStorage_write_vectorOfKeyPoint(ptr, name, valueVector.CvPtr);
GC.KeepAlive(this);
}
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Write(string name, IEnumerable<DMatch> value)
{
ThrowIfDisposed();
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
using (var valueVector = new VectorOfDMatch(value))
{
NativeMethods.core_FileStorage_write_vectorOfDMatch(ptr, name, valueVector.CvPtr);
GC.KeepAlive(this);
}
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void WriteScalar(int value)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_writeScalar_int(ptr, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void WriteScalar(float value)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_writeScalar_float(ptr, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void WriteScalar(double value)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_writeScalar_double(ptr, value);
GC.KeepAlive(this);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void WriteScalar(string value)
{
ThrowIfDisposed();
if (value == null)
throw new ArgumentNullException(nameof(value));
NativeMethods.core_FileStorage_writeScalar_String(ptr, value);
GC.KeepAlive(this);
}
#endregion
#region Add
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(string val)
{
if (val == null)
throw new ArgumentNullException(nameof(val));
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_String(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(int val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_int(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(float val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_float(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(double val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_double(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Mat val)
{
if (val == null)
throw new ArgumentNullException(nameof(val));
ThrowIfDisposed();
val.ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Mat(ptr, val.CvPtr);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(SparseMat val)
{
if (val == null)
throw new ArgumentNullException(nameof(val));
ThrowIfDisposed();
val.ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_SparseMat(ptr, val.CvPtr);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Range val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Range(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(KeyPoint val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_KeyPoint(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(DMatch val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_DMatch(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(IEnumerable<KeyPoint> val)
{
if (val == null)
throw new ArgumentNullException(nameof(val));
ThrowIfDisposed();
using (var valVec = new VectorOfKeyPoint(val))
{
NativeMethods.core_FileStorage_shift_vectorOfKeyPoint(ptr, valVec.CvPtr);
}
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(IEnumerable<DMatch> val)
{
if (val == null)
throw new ArgumentNullException(nameof(val));
ThrowIfDisposed();
using (var valVec = new VectorOfDMatch(val))
{
NativeMethods.core_FileStorage_shift_vectorOfDMatch(ptr, valVec.CvPtr);
}
GC.KeepAlive(this);
return this;
}
/// <summary>
/// /Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point2i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point2f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point2f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point2d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point2d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point3i val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point3i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point3f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point3f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Point3d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Point3d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Size val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Size2i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Size2f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Size2f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Size2d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Size2d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Rect val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Rect2i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Rect2f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Rect2f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Rect2d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Rect2d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Scalar val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Scalar(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2i val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3i val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4i val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6i val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6i(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6d val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6d(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6f val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6f(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2b val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2b(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3b val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3b(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4b val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4b(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6b val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6b(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2s val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2s(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3s val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3s(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4s val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4s(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6s val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6s(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec2w val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec2w(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec3w val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec3w(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec4w val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec4w(ptr, val);
GC.KeepAlive(this);
return this;
}
/// <summary>
/// Writes data to a file storage.
/// </summary>
/// <param name="val"></param>
public FileStorage Add(Vec6w val)
{
ThrowIfDisposed();
NativeMethods.core_FileStorage_shift_Vec6w(ptr, val);
GC.KeepAlive(this);
return this;
}
#endregion
#endregion
/// <summary>
///
/// </summary>
[Flags]
public enum States
{
/// <summary>
///
/// </summary>
Undefined = 0,
/// <summary>
///
/// </summary>
ValueExpected = 1,
/// <summary>
///
/// </summary>
NameExpected = 2,
/// <summary>
///
/// </summary>
InsideMap = 4
}
#if LANG_JP
/// <summary>
/// FileStorageのモード
/// </summary>
#else
/// <summary>
/// File storage mode
/// </summary>
#endif
[Flags]
public enum Mode
{
#if LANG_JP
/// <summary>
/// データ読み込みのためのファイルオープン
/// </summary>
#else
/// <summary>
/// The storage is open for reading
/// </summary>
#endif
Read = 0,
#if LANG_JP
/// <summary>
/// データ書き込みのためのファイルオープン
/// </summary>
#else
/// <summary>
/// The storage is open for writing
/// </summary>
#endif
Write = 1,
#if LANG_JP
/// <summary>
/// データ追加書き込みのためのファイルオープン
/// </summary>
#else
/// <summary>
/// The storage is open for appending
/// </summary>
#endif
Append = 2,
/// <summary>
/// flag, read data from source or write data to the internal buffer
/// (which is returned by FileStorage::release)
/// </summary>
Memory = 4,
/// <summary>
/// mask for format flags
/// </summary>
FormatMask = (7 << 3),
/// <summary>
/// flag, auto format
/// </summary>
FormatAuto = 0,
/// <summary>
/// flag, XML format
/// </summary>
FormatXml = (1 << 3),
/// <summary>
/// flag, YAML format
/// </summary>
FormatYaml = (2 << 3),
}
}
}
| 30.592625 | 105 | 0.479638 | [
"MIT"
] | nrandell/openvinoopencvsharp | OpenVinoOpenCvSharp/Modules/core/FileStorage.cs | 34,973 | C# |
int arrayMaximalAdjacentDifference(int[] inputArray) {
int max = 0;
for(int i = 0; i < inputArray.Length - 1; i++){
int higherNo = Math.Max(inputArray[i], inputArray[i+1]);
int lowerNo = Math.Min(inputArray[i], inputArray[i+1]);
if(higherNo - lowerNo > max) max = higherNo - lowerNo;
}
return max;
}
| 27.615385 | 64 | 0.579387 | [
"Unlicense"
] | DKLynch/CodeSignal-Tasks | Intro/5. Island Of Knowledge/20. Array Maximal Adjacent Differences/arrayMaximalAdjacentDifference.cs | 359 | C# |
// -----------------------------------------------------------------------
// <copyright file="AboutControlViewModel.cs" company="">
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Christoph Gattnar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// </copyright>
// -----------------------------------------------------------------------
namespace Gat.Controls
{
public class About : AboutControlViewModel
{
public void Show()
{
Gat.Controls.AboutControlView about = new Gat.Controls.AboutControlView();
AboutControlViewModel vm = (AboutControlViewModel)about.FindResource("ViewModel");
vm.AdditionalNotes = this.AdditionalNotes;
vm.ApplicationLogo = this.ApplicationLogo;
vm.Copyright = this.Copyright;
vm.Description = this.Description;
vm.HyperlinkText = this.HyperlinkText;
vm.Publisher = this.Publisher;
vm.PublisherLogo = this.PublisherLogo;
vm.Title = this.Title;
vm.Version = this.Version;
vm.Window.Content = about;
vm.Window.Show();
}
}
}
| 41.428571 | 118 | 0.693103 | [
"MIT"
] | bzquan/GherkinEditor | GherkinEditor/GherkinEditor/ViewModel/AboutSample.cs | 2,032 | C# |
namespace SampleFix
{
using System;
using System.ComponentModel;
using System.Windows.Media;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Fix;
using StockSharp.Messages;
using StockSharp.Xaml.Charting;
partial class ChartWindow
{
private readonly FixTrader _trader;
private readonly CandleSeries _candleSeries;
private readonly ChartCandleElement _candleElem;
private readonly long _transactionId;
public ChartWindow(CandleSeries candleSeries, DateTimeOffset? from = null, DateTimeOffset? to = null)
{
InitializeComponent();
_candleSeries = candleSeries ?? throw new ArgumentNullException(nameof(candleSeries));
_trader = MainWindow.Instance.Trader;
Chart.ChartTheme = ChartThemes.ExpressionDark;
var area = new ChartArea();
Chart.Areas.Add(area);
_candleElem = new ChartCandleElement
{
AntiAliasing = false,
UpFillColor = Colors.White,
UpBorderColor = Colors.Black,
DownFillColor = Colors.Black,
DownBorderColor = Colors.Black,
};
area.Elements.Add(_candleElem);
_trader.NewMessage += ProcessNewMessage;
_trader.SubscribeMarketData(candleSeries.Security, new MarketDataMessage
{
TransactionId = _transactionId = _trader.TransactionIdGenerator.GetNextId(),
DataType = MarketDataTypes.CandleTimeFrame,
//SecurityId = GetSecurityId(series.Security),
Arg = candleSeries.Arg,
IsSubscribe = true,
From = from,
To = to,
}.ValidateBounds());
}
private void ProcessNewMessage(Message message)
{
var candleMsg = message as CandleMessage;
if (candleMsg?.OriginalTransactionId != _transactionId)
return;
Chart.Draw(_candleElem, candleMsg.ToCandle(_candleSeries));
}
protected override void OnClosing(CancelEventArgs e)
{
_trader.NewMessage -= ProcessNewMessage;
base.OnClosing(e);
}
}
} | 25.520548 | 103 | 0.742888 | [
"Apache-2.0"
] | 1M15M3/StockSharp | Samples/Fix/SampleFix/ChartWindow.xaml.cs | 1,865 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Extensions.Internal;
internal sealed class CopyOnWriteDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TKey : notnull
{
private readonly IDictionary<TKey, TValue> _sourceDictionary;
private readonly IEqualityComparer<TKey> _comparer;
private IDictionary<TKey, TValue>? _innerDictionary;
public CopyOnWriteDictionary(
IDictionary<TKey, TValue> sourceDictionary,
IEqualityComparer<TKey> comparer)
{
if (sourceDictionary == null)
{
throw new ArgumentNullException(nameof(sourceDictionary));
}
if (comparer == null)
{
throw new ArgumentNullException(nameof(comparer));
}
_sourceDictionary = sourceDictionary;
_comparer = comparer;
}
private IDictionary<TKey, TValue> ReadDictionary
{
get
{
return _innerDictionary ?? _sourceDictionary;
}
}
private IDictionary<TKey, TValue> WriteDictionary
{
get
{
if (_innerDictionary == null)
{
_innerDictionary = new Dictionary<TKey, TValue>(_sourceDictionary,
_comparer);
}
return _innerDictionary;
}
}
public ICollection<TKey> Keys
{
get
{
return ReadDictionary.Keys;
}
}
public ICollection<TValue> Values
{
get
{
return ReadDictionary.Values;
}
}
public int Count
{
get
{
return ReadDictionary.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public TValue this[TKey key]
{
get
{
return ReadDictionary[key];
}
set
{
WriteDictionary[key] = value;
}
}
public bool ContainsKey(TKey key)
{
return ReadDictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
WriteDictionary.Add(key, value);
}
public bool Remove(TKey key)
{
return WriteDictionary.Remove(key);
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
return ReadDictionary.TryGetValue(key, out value);
}
public void Add(KeyValuePair<TKey, TValue> item)
{
WriteDictionary.Add(item);
}
public void Clear()
{
WriteDictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ReadDictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
ReadDictionary.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return WriteDictionary.Remove(item);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return ReadDictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
| 21.77707 | 106 | 0.585551 | [
"MIT"
] | Akarachudra/kontur-aspnetcore-fork | src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionary.cs | 3,419 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace DotNet.Jenkins.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "DotNet.Jenkins.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.513274 | 149 | 0.665949 | [
"MIT"
] | dingyuliang/jenkins-examples | src/DotNet/DotNet.Jenkins/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,499 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.