content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the support-2013-04-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AWSSupport.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AWSSupport.Model.Internal.MarshallTransformations { /// <summary> /// DescribeTrustedAdvisorCheckResult Request Marshaller /// </summary> public class DescribeTrustedAdvisorCheckResultRequestMarshaller : IMarshaller<IRequest, DescribeTrustedAdvisorCheckResultRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeTrustedAdvisorCheckResultRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeTrustedAdvisorCheckResultRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.AWSSupport"); string target = "AWSSupport_20130415.DescribeTrustedAdvisorCheckResult"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2013-04-15"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCheckId()) { context.Writer.WritePropertyName("checkId"); context.Writer.Write(publicRequest.CheckId); } if(publicRequest.IsSetLanguage()) { context.Writer.WritePropertyName("language"); context.Writer.Write(publicRequest.Language); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeTrustedAdvisorCheckResultRequestMarshaller _instance = new DescribeTrustedAdvisorCheckResultRequestMarshaller(); internal static DescribeTrustedAdvisorCheckResultRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeTrustedAdvisorCheckResultRequestMarshaller Instance { get { return _instance; } } } }
36.873874
181
0.638163
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AWSSupport/Generated/Model/Internal/MarshallTransformations/DescribeTrustedAdvisorCheckResultRequestMarshaller.cs
4,093
C#
using StarDust.CasparCG.net.Models; using System; using System.Collections.Generic; namespace StarDust.CasparCG.net.AmcpProtocol { /// <summary> /// Use when we receive the templates information /// </summary> public class TLSEventArgs : EventArgs { /// <summary> /// Ctor /// </summary> /// <param name="templates"></param> public TLSEventArgs(List<TemplateBaseInfo> templates) { this.Templates = templates; } /// <summary> /// List of the template present on the server /// </summary> public List<TemplateBaseInfo> Templates { get; } } }
23.068966
61
0.585949
[ "MIT" ]
dust63/StartDust.CasparCG.net
src/StarDust.CasparCg.net.AmcpProtocol/EventArgs/TLSEventArgs.cs
671
C#
// Generated by gencs from std_msgs/Byte.msg // DO NOT EDIT THIS FILE BY HAND! using System; using System.Collections; using System.Collections.Generic; using SIGVerse.RosBridge; using UnityEngine; namespace SIGVerse.RosBridge { namespace std_msgs { [System.Serializable] public class Byte : RosMessage { public sbyte data; public Byte() { this.data = 0; } public Byte(sbyte data) { this.data = data; } new public static string GetMessageType() { return "std_msgs/Byte"; } new public static string GetMD5Hash() { return "ad736a2e8818154c487bb80fe42ce43b"; } } // class Byte } // namespace std_msgs } // namespace SIGVerse.ROSBridge
16.113636
46
0.681241
[ "MIT" ]
Ohara124c41/TUB-MSc_Thesis
SEK_01_MkI/Assets/SIGVerse/Common/ROSBridge/messaging/std_msgs/Byte.cs
709
C#
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dataproc.V1.Snippets { using Google.Cloud.Dataproc.V1; using System.Threading.Tasks; public sealed partial class GeneratedWorkflowTemplateServiceClientStandaloneSnippets { /// <summary>Snippet for GetWorkflowTemplateAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetWorkflowTemplateAsync() { // Create client WorkflowTemplateServiceClient workflowTemplateServiceClient = await WorkflowTemplateServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/regions/[REGION]/workflowTemplates/[WORKFLOW_TEMPLATE]"; // Make the request WorkflowTemplate response = await workflowTemplateServiceClient.GetWorkflowTemplateAsync(name); } } }
40.775
124
0.710607
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dataproc/v1/google-cloud-dataproc-v1-csharp/Google.Cloud.Dataproc.V1.StandaloneSnippets/WorkflowTemplateServiceClient.GetWorkflowTemplateAsyncSnippet.g.cs
1,631
C#
namespace LeetCode.Naive.Problems; /// <summary> /// Problem: https://leetcode.com/problems/reorganize-string/ /// Submission: https://leetcode.com/submissions/detail/238308970/ /// </summary> internal class P0767 { public class Solution { public string ReorganizeString(string S) { var dict = S.Select(_ => _) .GroupBy(_ => _) .ToDictionary(_ => _.Key, _ => _.Count()); var topChar = dict .OrderByDescending(_ => _.Value) .First(); if (S.Length % 2 == 0 && topChar.Value > S.Length / 2) return ""; if (S.Length % 2 == 1 && topChar.Value > S.Length / 2 + 1) return ""; char ch = default(char); char[] arr = new char[S.Length]; for (var i = 0; i < arr.Length; i++) { if (ch == default(char)) { ch = dict.OrderByDescending(_ => _.Value).First().Key; dict[ch]--; arr[i] = ch; continue; } ch = dict.Where(_ => _.Key != ch).OrderByDescending(_ => _.Value).First().Key; dict[ch]--; arr[i] = ch; } return new string(arr); } } }
24.591837
87
0.491286
[ "MIT" ]
viacheslave/algo
leetcode/c#/Problems/P0767.cs
1,205
C#
using System.Threading.Tasks; using AJ3.Core.Contracts; using AJ3.WebApp.Models.Student; using AutoMapper; using Microsoft.AspNetCore.Mvc; namespace AJ3.WebApp.Components { public class StudentMiniProfileViewComponent : ViewComponent { private readonly IStudentManager _studentManager; private readonly IMapper _mapper; public StudentMiniProfileViewComponent(IStudentManager studentManager, IMapper mapper) { _studentManager = studentManager; _mapper = mapper; } public async Task<IViewComponentResult> InvokeAsync(int id) { var studentDetails = _mapper.Map<StudentDetailViewModel>(await _studentManager.GetByIdAsync(id).ConfigureAwait(false)); return await Task.FromResult<IViewComponentResult>(View("Detail",studentDetails)).ConfigureAwait(false); } } }
33.296296
116
0.705228
[ "MIT" ]
DennisPitallano/DSSMS
AJ3/AJ3.WebApp/Components/StudentMiniProfileViewComponent.cs
901
C#
using System.Collections.Generic; using AdaptiveExpressions.Converters; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs.Debugging; using Microsoft.Bot.Builder.Dialogs.Declarative; using Microsoft.Bot.Builder.Dialogs.Declarative.Converters; using Microsoft.Bot.Builder.Dialogs.Declarative.Resources; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; namespace Bot.Builder.Community.Components.CallDialogs { /// <summary> /// <see cref="BotComponent"/> implementation for the <see cref="CallDialogs"/> component. /// </summary> public class CallDialogsBotComponent : BotComponent { public override void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.AddSingleton<DeclarativeType>(new DeclarativeType<AddDialogCall>(AddDialogCall.Kind)); services.AddSingleton<DeclarativeType>(new DeclarativeType<CallDialogs>(CallDialogs.Kind)); services.AddSingleton<JsonConverterFactory, JsonConverterFactory<ObjectExpressionConverter<object>>>(); } } }
40.892857
115
0.774672
[ "MIT" ]
Amit-singh96/Test1
libraries/Bot.Builder.Community.Components.CallDialogs/CallDialogsBotComponent.cs
1,147
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. #nullable enable using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteDesignerAttributeService : ServiceBase, IRemoteDesignerAttributeService { public RemoteDesignerAttributeService( Stream stream, IServiceProvider serviceProvider) : base(serviceProvider, stream) { StartService(); } public Task StartScanningForDesignerAttributesAsync(CancellationToken cancellation) { return RunServiceAsync(() => { var registrationService = GetWorkspace().Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); var analyzerProvider = new RemoteDesignerAttributeIncrementalAnalyzerProvider(this.EndPoint); registrationService.AddAnalyzerProvider( analyzerProvider, new IncrementalAnalyzerProviderMetadata( nameof(RemoteDesignerAttributeIncrementalAnalyzerProvider), highPriorityForActiveFile: false, workspaceKinds: WorkspaceKind.RemoteWorkspace)); return Task.CompletedTask; }, cancellation); } } }
36.636364
124
0.681762
[ "MIT" ]
06needhamt/roslyn
src/Workspaces/Remote/ServiceHub/Services/DesignerAttribute/RemoteDesignerAttributeService.cs
1,614
C#
namespace System.Windows.Forms { [Flags] public enum DrawItemState { Checked = 8, ComboBoxEdit = 4096, Default = 32, Disabled = 4, Focus = 16, Grayed = 2, HotLight = 64, Inactive = 128, NoAccelerator = 256, NoFocusRect = 512, Selected = 1, None = 0, } }
18.35
31
0.479564
[ "MIT" ]
Meragon/Unity-WinForms
System/Windows/Forms/DrawItemState.cs
369
C#
//----------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //----------------------------------------------------------------------- namespace HR.TA.Common.Provisioning.Entities.FalconEntities.Attract { using System.Runtime.Serialization; using HR.TA.TalentEntities.Enum; [DataContract] public class NoteAttachment { [DataMember(Name = "AttachmentID", EmitDefaultValue = false, IsRequired = false)] public string AttachmentID { get; set; } [DataMember(Name = "CandidateNoteID", EmitDefaultValue = false, IsRequired = false)] public string CandidateNoteID { get; set; } [DataMember(Name = "FileName", EmitDefaultValue = false, IsRequired = false)] public string FileName { get; set; } [DataMember(Name = "ArtifactType", EmitDefaultValue = false, IsRequired = false)] public ArtifactType ArtifactType { get; set; } [DataMember(Name = "NoteUri", EmitDefaultValue = false, IsRequired = false)] public string NoteUri { get; set; } } }
37.666667
92
0.588496
[ "MIT" ]
QPC-database/msrecruit-scheduling-engine
common/HR.TA.CommonLibrary/HR.TA.Talent/FalconEntities/Attract/NoteAttachment.cs
1,130
C#
using Prism.Mvvm; using Xamarin.Forms; namespace Prism.DI.Forms.Tests.Mocks.Views { public class AutowireViewTablet : Page { public AutowireViewTablet() { ViewModelLocator.SetAutowireViewModel(this, true); } } }
18.714286
62
0.641221
[ "MIT" ]
Adam--/Prism
tests/Forms/Prism.DI.Forms.Tests/Mocks/Views/AutowireViewTablet.cs
264
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 Xunit; using Enumerable = Tutorial.LinqToObjects.EnumerableExtensions; using static Tutorial.LinqToObjects.EnumerableExtensions; // namespace System.Linq.Tests namespace Tutorial.Tests.LinqToObjects { public class LongCountTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; Assert.Equal(q.LongCount(), q.LongCount()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x) select x; Assert.Equal(q.LongCount(), q.LongCount()); } public static IEnumerable<object[]> LongCount_TestData() { yield return new object[] { new int[0], null, 0L }; yield return new object[] { new int[] { 3 }, null, 1L }; Func<int, bool> isEvenFunc = IsEven; yield return new object[] { new int[0], isEvenFunc, 0L }; yield return new object[] { new int[] { 4 }, isEvenFunc, 1L }; yield return new object[] { new int[] { 5 }, isEvenFunc, 0L }; yield return new object[] { new int[] { 2, 5, 7, 9, 29, 10 }, isEvenFunc, 2L }; yield return new object[] { new int[] { 2, 20, 22, 100, 50, 10 }, isEvenFunc, 6L }; } [Theory] [MemberData(nameof(LongCount_TestData))] public static void LongCount(IEnumerable<int> source, Func<int, bool> predicate, long expected) { if (predicate == null) { Assert.Equal(expected, source.LongCount()); } else { Assert.Equal(expected, source.LongCount(predicate)); } } [Fact] public void NullableArray_IncludesNullValues() { int?[] data = { -10, 4, 9, null, 11 }; Assert.Equal(5, data.LongCount()); } // [Fact] public void NullSource_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).LongCount()); Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).LongCount(i => i != 0)); } // [Fact] public void NullPredicate_ThrowsArgumentNullException() { Func<int, bool> predicate = null; Assert.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).LongCount(predicate)); } } }
35.360465
114
0.558369
[ "MIT" ]
Dixin/FunctionalProgramming-LINQ
Tutorial.Tests.External.Shared/LinqToObjects/LongCountTests.cs
3,041
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace System.Fabric.ImageBuilderExe { using Microsoft.Win32; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Fabric.Common; using System.Fabric.Common.Tracing; using System.Fabric.ImageStore; using System.Fabric.Interop; using System.Fabric.Management.ImageBuilder; using System.Fabric.Management.ImageBuilder.SingleInstance; using System.Fabric.Management.ImageStore; using System.Fabric.Management.WindowsFabricValidator; using System.Fabric.Strings; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Threading; internal class ImageBuilderExe { internal static FabricEvents.ExtensionsEvents TraceSource; private static readonly string TraceType = "ImageBuilderExe"; private static readonly Dictionary<Type, int> ManagedToNativeExceptionTranslation = new Dictionary<Type, int>() { { typeof(ArgumentException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.E_INVALIDARG) }, { typeof(FileNotFoundException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_FILE_NOT_FOUND) }, { typeof(DirectoryNotFoundException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_DIRECTORY_NOT_FOUND) }, { typeof(OperationCanceledException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.E_ABORT) }, { typeof(PathTooLongException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_PATH_TOO_LONG) }, { typeof(UnauthorizedAccessException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.E_ACCESSDENIED) }, { typeof(TimeoutException), unchecked((int) NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_TIMEOUT) } }; private static readonly HashSet<string> SupportedCommandArgs = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { StringConstants.SchemaPath, StringConstants.WorkingDir, StringConstants.StoreRoot, StringConstants.Operation, StringConstants.AppTypeName, StringConstants.AppTypeVersion, StringConstants.AppId, StringConstants.NameUri, StringConstants.AppParam, StringConstants.BuildPath, StringConstants.DownloadPath, StringConstants.Output, StringConstants.Input, StringConstants.Progress, StringConstants.ErrorDetails, StringConstants.SecuritySettingsParam, StringConstants.CurrentAppInstanceVersion, StringConstants.CodePath, StringConstants.ConfigPath, StringConstants.CurrentFabricVersion, StringConstants.TargetFabricVersion, StringConstants.InfrastructureManifestFile, StringConstants.Timeout, StringConstants.DisableChecksumValidation, StringConstants.DisableServerSideCopy, StringConstants.ConfigVersion, StringConstants.ComposeFilePath, StringConstants.OverrideFilePath, StringConstants.RepositoryPassword, StringConstants.RepositoryUserName, StringConstants.OutputComposeFilePath, StringConstants.IsRepositoryPasswordEncrypted, StringConstants.CleanupComposeFiles, StringConstants.GenerateDnsNames, StringConstants.SFVolumeDiskServiceEnabled, StringConstants.AppName, StringConstants.CurrentAppTypeVersion, StringConstants.TargetAppTypeVersion, StringConstants.SingleInstanceApplicationDescription, StringConstants.UseOpenNetworkConfig, StringConstants.UseLocalNatNetworkConfig, StringConstants.GenerationConfig, StringConstants.MountPointForSettings, }; static ImageBuilderExe() { TraceConfig.InitializeFromConfigStore(); ImageBuilderExe.TraceSource = new FabricEvents.ExtensionsEvents(FabricEvents.Tasks.ImageBuilder); #if !DotNetCoreClr ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; #endif } /// return 0 if program completes successfully, -1 otherwise. public static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("This is for internal use only"); return -1; } #if DEBUG // To add a sleep time while debugging add a "Sleep" key (in milliseconds) to the following registry location: HKLM\\Software\\Microsoft\\Service Fabric try { using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(FabricConstants.FabricRegistryKeyPath, true)) { var sleepRegVal = registryKey.GetValue("Sleep"); if (sleepRegVal != null) { int sleepinms = int.Parse(sleepRegVal.ToString()); ImageBuilderExe.TraceSource.WriteNoise(ImageBuilderExe.TraceType, "ImageBuilderExe: Sleep time requested: {0}", sleepinms.ToString()); Thread.Sleep(sleepinms); } } } catch (Exception e) { ImageBuilderExe.TraceSource.WriteNoise(ImageBuilderExe.TraceType, "ImageBuilderExe: Exception code:{0}, msg:{1} when attempting to read registry value \"Sleep\" in {2}.", e.HResult, e.Message, FabricConstants.FabricRegistryKeyPath); } #endif // Parameters // /schemaPath:<The xsd schema file of Windows Fabric ServiceModel> - optional. Default: <Current Working Directory>\ServiceFabricServiceModel.xsd // /workingDir:<The root of working directory of the node> - optional. Default: <Current Working Directory> // /storeRoot:<The root path of ImageStore> - optional // /output: <The root folder|file where output will be placed> - required // /input: <The root folder|file where input will be read from> - required for Delete // /progress: <The file where operation progress will be read from> - optional. Used by BuildApplicationType and DownloadAndBuildApplicationType. // /operation:<BuildApplicationTypeInfo | BuildApplicationType | BuildApplication | BuildComposeDeployment | ValidateComposeDeployment | UpgradeApplication | GetFabricVersion | ProvisionFabric | UpgradeFabric | Delete | TestErrorDetails | DownloadAndBuildApplicationType> - required // /timeout:<ticks> - optional /* ImageBuilder arguments for DownloadAndBuildApplicationType */ // /downloadPath: <path to .sfpkg file from a store that supports GET method> - required // /appTypeName:<Application Type Name> - required. Expected application type name in the downloaded package. // /appTypeVersion:<Application Type Version> - required. Expected application type version in the downloaded package. // /progress: <The file where operation progress will be read from> - optional. // /output: <The root folder|file where output will be placed> - required // /timeout:<ticks> - optional /* ImageBuilder arguments for BuildComposeDeployment */ // /cf:<Compose File path> - required // /of:<Overrides File path> - optional // /appTypeName:<Application Type Name> - required // /appTypeVersion:<Application Type Version> - required // /output: <The root folder|file where output application package will be placed> - required // /ocf:<Output Merged compose file path> - required // /repoUserName:<Repository User Name> - optional // /repoPwd:<Repository Password> - optional // /pwdEncrypted:<Is Repository Password encrypted> - optional // /cleanup:<Cleanup the compose files> - optional // /timeout:<ticks> - optional /* ImageBuilder arguments for ValidateComposeDeployment */ // /cf:<Compose File path> - required // /of:<Overrides File path> - optional // /appTypeName:<Application Type Name> - optional // /appTypeVersion:<Application Type Version> - optional // /cleanup:<Cleanup the compose files> - optional // /timeout:<ticks> - optional /* ImageBuilder arguments for Application */ // /appTypeName:<Application Type Name> - required for BuildApplication and UpgradeApplication operation // /appTypeVersion:<Application Type Version> - required for BuildApplication and UpgradeApplication operation // /appId:<Application ID> - required for BuildApplication and UpgradeApplication operation // /nameUri:<Name URI> - required for BuildApplication operation // /appParam:<semi-colon separated key-value pair>. Multiple such parameters can be passed. Key cannot have ';'. // /buildPath: <The root folder of build layout> - required for ApplicationTypeInfo and BuildApplicationType operation // /currentAppInstanceVersion: <The current app instance of the Application that needs to be upgraded> - required for UpgradeApplication operation /* ImageBuilder arguments for Fabric Upgrade */ // /codePath: <The path to MSP for FabricUpgrade> // /configPath: <The path to ClusterManifest for FabricUpgrade> // /currentFabricVersion: <The current FabricVersion> // /targetFabricVersion: <The target FabricVersion> // /im: <Path to InfrastructureManifest.xml file> // Dictionary<string, string> commandArgs = null; Exception exception = null; string errorDetailsFile = null; try { commandArgs = ParseParameters(args); // Ensure that required parameters are present EnsureRequiredCommandLineParameters(commandArgs); Dictionary<string, string> applicationParameters = ParseAppParameters(commandArgs); errorDetailsFile = commandArgs.ContainsKey(StringConstants.ErrorDetails) ? commandArgs[StringConstants.ErrorDetails] : null; string workingDirectory = commandArgs.ContainsKey(StringConstants.WorkingDir) ? commandArgs[StringConstants.WorkingDir] : Directory.GetCurrentDirectory(); string imageStoreConnectionString; if (commandArgs.ContainsKey(StringConstants.StoreRoot)) { imageStoreConnectionString = commandArgs[StringConstants.StoreRoot]; } else { ImageBuilderExe.TraceSource.WriteInfo(ImageBuilderExe.TraceType, "Loading ImageStoreConnectionString from config."); bool isEncrypted; NativeConfigStore configStore = NativeConfigStore.FabricGetConfigStore(); var configValue = configStore.ReadString("Management", "ImageStoreConnectionString", out isEncrypted); if (isEncrypted) { var secureString = NativeConfigStore.DecryptText(configValue); var secureCharArray = FabricValidatorUtility.SecureStringToCharArray(secureString); imageStoreConnectionString = new string(secureCharArray); } else { imageStoreConnectionString = configValue; } if (string.IsNullOrEmpty(imageStoreConnectionString)) { throw new ArgumentException(StringResources.Error_MissingImageStoreConnectionStringInManifest); } } StringBuilder stringToTrace = new StringBuilder(); foreach (var commandArg in commandArgs) { // Skipping tracing StoreRoot since it could be a secret value if (!ImageBuilderUtility.Equals(commandArg.Key, StringConstants.StoreRoot)) { stringToTrace.AppendFormat("{0}:{1}", commandArg.Key, commandArg.Value); stringToTrace.AppendLine(); } } ImageBuilderExe.TraceSource.WriteInfo( ImageBuilderExe.TraceType, "ImageBuilderExe called with - {0}", stringToTrace.ToString()); string currentExecutingDirectory = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); string schemaPath = commandArgs.ContainsKey(StringConstants.SchemaPath) ? commandArgs[StringConstants.SchemaPath] : Path.Combine( currentExecutingDirectory, StringConstants.DefaultSchemaPath); TimeSpan timeout = commandArgs.ContainsKey(StringConstants.Timeout) ? TimeSpan.FromTicks(long.Parse(commandArgs[StringConstants.Timeout])) : TimeSpan.MaxValue; Timer timer = null; if (timeout != TimeSpan.MaxValue) { ImageBuilderExe.TraceSource.WriteInfo( ImageBuilderExe.TraceType, "ImageBuilderExe enabled timeout monitor: {0}", timeout); timer = new Timer(OnTimeout, errorDetailsFile, timeout, TimeSpan.FromMilliseconds(-1)); } IImageStore imageStore = ImageStoreFactoryProxy.CreateImageStore( imageStoreConnectionString, null, workingDirectory, true /*isInternal*/); ImageBuilder imageBuilder = new ImageBuilder(imageStore, schemaPath, workingDirectory); string operationValue = commandArgs[StringConstants.Operation]; bool sfVolumeDiskServiceEnabled = commandArgs.ContainsKey(StringConstants.SFVolumeDiskServiceEnabled) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.SFVolumeDiskServiceEnabled]) : false; imageBuilder.IsSFVolumeDiskServiceEnabled = sfVolumeDiskServiceEnabled; if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationDownloadAndBuildApplicationType)) { string progressFile = commandArgs.ContainsKey(StringConstants.Progress) ? commandArgs[StringConstants.Progress] : null; bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.DisableChecksumValidation]) : false; imageBuilder.DownloadAndBuildApplicationType( commandArgs[StringConstants.DownloadPath], commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.AppTypeVersion], commandArgs[StringConstants.Output], timeout, progressFile, shouldSkipChecksumValidation); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationTypeInfo)) { imageBuilder.GetApplicationTypeInfo(commandArgs[StringConstants.BuildPath], timeout, commandArgs[StringConstants.Output]); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationType)) { string outputFile = commandArgs.ContainsKey(StringConstants.Output) ? commandArgs[StringConstants.Output] : null; string progressFile = commandArgs.ContainsKey(StringConstants.Progress) ? commandArgs[StringConstants.Progress] : null; bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.DisableChecksumValidation]) : false; bool shouldSkipServerSideCopy = commandArgs.ContainsKey(StringConstants.DisableServerSideCopy) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.DisableServerSideCopy]) : false; imageBuilder.BuildApplicationType(commandArgs[StringConstants.BuildPath], timeout, outputFile, progressFile, shouldSkipChecksumValidation, shouldSkipServerSideCopy); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildSingleInstanceApplication)) { bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.GenerateDnsNames]) : false; bool useOpenNetworkConfig = commandArgs.ContainsKey(StringConstants.UseOpenNetworkConfig) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.UseOpenNetworkConfig]) : false; bool useLocalNatNetworkConfig = commandArgs.ContainsKey(StringConstants.UseLocalNatNetworkConfig) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.UseLocalNatNetworkConfig]) : false; Application application = null; using (StreamReader file = File.OpenText(commandArgs[StringConstants.SingleInstanceApplicationDescription])) { JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new DiagnosticsSinkJsonConverter()); serializer.Converters.Add(new VolumeMountJsonConverter()); application = (Application)serializer.Deserialize(file, typeof(Application)); } GenerationConfig config = null; if (commandArgs.ContainsKey(StringConstants.GenerationConfig)) { using (StreamReader file = File.OpenText(commandArgs[StringConstants.GenerationConfig])) { JsonSerializer serializer = new JsonSerializer(); config = (GenerationConfig)serializer.Deserialize(file, typeof(GenerationConfig)); } } imageBuilder.BuildSingleInstanceApplication( application, commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.AppTypeVersion], commandArgs[StringConstants.AppId], new Uri(commandArgs[StringConstants.AppName]), generateDnsNames, timeout, commandArgs[StringConstants.BuildPath], commandArgs[StringConstants.Output], useOpenNetworkConfig, useLocalNatNetworkConfig, commandArgs[StringConstants.MountPointForSettings], config); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildSingleInstanceApplicationForUpgrade)) { bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.GenerateDnsNames]) : false; bool useOpenNetworkConfig = commandArgs.ContainsKey(StringConstants.UseOpenNetworkConfig) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.UseOpenNetworkConfig]) : false; bool useLocalNatNetworkConfig = commandArgs.ContainsKey(StringConstants.UseLocalNatNetworkConfig) ? ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.UseLocalNatNetworkConfig]) : false; Application application = null; using (StreamReader file = File.OpenText(commandArgs[StringConstants.SingleInstanceApplicationDescription])) { JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new VolumeMountJsonConverter()); application = (Application)serializer.Deserialize(file, typeof(Application)); } GenerationConfig config = null; if (commandArgs.ContainsKey(StringConstants.GenerationConfig)) { using (StreamReader file = File.OpenText(commandArgs[StringConstants.GenerationConfig])) { JsonSerializer serializer = new JsonSerializer(); config = (GenerationConfig)serializer.Deserialize(file, typeof(GenerationConfig)); } } imageBuilder.BuildSingleInstanceApplicationForUpgrade( application, commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.CurrentAppTypeVersion], commandArgs[StringConstants.TargetAppTypeVersion], commandArgs[StringConstants.AppId], int.Parse(commandArgs[StringConstants.CurrentAppInstanceVersion], CultureInfo.InvariantCulture), new Uri(commandArgs[StringConstants.AppName]), generateDnsNames, timeout, commandArgs[StringConstants.BuildPath], commandArgs[StringConstants.Output], useOpenNetworkConfig, useLocalNatNetworkConfig, commandArgs[StringConstants.MountPointForSettings], config); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplication)) { imageBuilder.BuildApplication( commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.AppTypeVersion], commandArgs[StringConstants.AppId], new Uri(commandArgs[StringConstants.NameUri]), applicationParameters, timeout, commandArgs[StringConstants.Output]); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeApplication)) { imageBuilder.UpgradeApplication( commandArgs[StringConstants.AppId], commandArgs[StringConstants.AppTypeName], int.Parse(commandArgs[StringConstants.CurrentAppInstanceVersion], CultureInfo.InvariantCulture), commandArgs[StringConstants.AppTypeVersion], applicationParameters, timeout, commandArgs[StringConstants.Output]); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationDelete)) { imageBuilder.Delete(commandArgs[StringConstants.Input], timeout); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationCleanupApplicationPackage)) { imageBuilder.DeleteApplicationPackage(commandArgs[StringConstants.BuildPath], timeout); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetFabricVersion)) { imageBuilder.GetFabricVersionInfo( commandArgs[StringConstants.CodePath], commandArgs[StringConstants.ConfigPath], timeout, commandArgs[StringConstants.Output]); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationProvisionFabric)) { string configurationCsvFilePath = Path.Combine(currentExecutingDirectory, StringConstants.ConfigurationsFileName); imageBuilder.ProvisionFabric( commandArgs[StringConstants.CodePath], commandArgs[StringConstants.ConfigPath], configurationCsvFilePath, commandArgs[StringConstants.InfrastructureManifestFile], timeout); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetClusterManifest)) { imageBuilder.GetClusterManifestContents( commandArgs[StringConstants.ConfigVersion], commandArgs[StringConstants.Output], timeout); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeFabric)) { string configurationCsvFilePath = Path.Combine(currentExecutingDirectory, StringConstants.ConfigurationsFileName); imageBuilder.UpgradeFabric( commandArgs[StringConstants.CurrentFabricVersion], commandArgs[StringConstants.TargetFabricVersion], configurationCsvFilePath, timeout, commandArgs[StringConstants.Output]); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetManifests)) { imageBuilder.GetManifests(commandArgs[StringConstants.Input], timeout); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationValidateComposeDeployment)) { bool cleanupComposeFiles = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.CleanupComposeFiles]); HashSet<string> ignoredKeys; imageBuilder.ValidateComposeDeployment( commandArgs[StringConstants.ComposeFilePath], commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null, commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null, commandArgs.ContainsKey(StringConstants.AppTypeName) ? commandArgs[StringConstants.AppTypeName] : null, commandArgs.ContainsKey(StringConstants.AppTypeVersion) ? commandArgs[StringConstants.AppTypeVersion] : null, timeout, out ignoredKeys, cleanupComposeFiles); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildComposeDeployment)) { bool cleanupComposeFiles = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.CleanupComposeFiles]); bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.DisableChecksumValidation]); bool isPasswordEncrypted = commandArgs.ContainsKey(StringConstants.IsRepositoryPasswordEncrypted) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.IsRepositoryPasswordEncrypted]); bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.GenerateDnsNames]); imageBuilder.BuildComposeDeploymentPackage( commandArgs[StringConstants.ComposeFilePath], commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null, timeout, commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null, commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.AppTypeVersion], commandArgs.ContainsKey(StringConstants.RepositoryUserName) ? commandArgs[StringConstants.RepositoryUserName] : null, commandArgs.ContainsKey(StringConstants.RepositoryPassword) ? commandArgs[StringConstants.RepositoryPassword] : null, isPasswordEncrypted, generateDnsNames, commandArgs[StringConstants.OutputComposeFilePath], commandArgs[StringConstants.Output], cleanupComposeFiles, shouldSkipChecksumValidation); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildComposeApplicationForUpgrade)) { bool cleanupComposeFiles = commandArgs.ContainsKey(StringConstants.CleanupComposeFiles) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.CleanupComposeFiles]); bool shouldSkipChecksumValidation = commandArgs.ContainsKey(StringConstants.DisableChecksumValidation) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.DisableChecksumValidation]); bool isPasswordEncrypted = commandArgs.ContainsKey(StringConstants.IsRepositoryPasswordEncrypted) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.IsRepositoryPasswordEncrypted]); bool generateDnsNames = commandArgs.ContainsKey(StringConstants.GenerateDnsNames) && ImageBuilderUtility.ConvertString<bool>(commandArgs[StringConstants.GenerateDnsNames]); imageBuilder.BuildComposeDeploymentPackageForUpgrade( commandArgs[StringConstants.ComposeFilePath], commandArgs.ContainsKey(StringConstants.OverrideFilePath) ? commandArgs[StringConstants.OverrideFilePath] : null, timeout, commandArgs.ContainsKey(StringConstants.AppName) ? commandArgs[StringConstants.AppName] : null, commandArgs[StringConstants.AppTypeName], commandArgs[StringConstants.CurrentAppTypeVersion], commandArgs[StringConstants.TargetAppTypeVersion], commandArgs.ContainsKey(StringConstants.RepositoryUserName) ? commandArgs[StringConstants.RepositoryUserName] : null, commandArgs.ContainsKey(StringConstants.RepositoryPassword) ? commandArgs[StringConstants.RepositoryPassword] : null, isPasswordEncrypted, generateDnsNames, commandArgs[StringConstants.OutputComposeFilePath], commandArgs[StringConstants.Output], cleanupComposeFiles, shouldSkipChecksumValidation); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.TestErrorDetails)) { throw new Exception(StringConstants.TestErrorDetails); } else { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeCommandLineInvalidOperation, StringConstants.Operation, operationValue)); } } catch (AggregateException ae) { exception = ae.InnerException; StringBuilder exceptionStringBuilder = new StringBuilder("Aggregate exception has "); exceptionStringBuilder.Append(ae.InnerExceptions.Count); exceptionStringBuilder.Append(" exceptions. "); ae.InnerExceptions.ForEach(innerException => exceptionStringBuilder.AppendLine(innerException.Message)); ImageBuilderExe.TraceSource.WriteWarning( ImageBuilderExe.TraceType, "AggregateException: {0}", exceptionStringBuilder.ToString()); } catch (Exception e) { exception = e; } if (exception != null) { OnFailure(exception, errorDetailsFile); return unchecked((int)NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_IMAGEBUILDER_UNEXPECTED_ERROR); } else { ImageBuilderExe.TraceSource.WriteInfo( ImageBuilderExe.TraceType, "ImageBuilderExe operation completed successfully."); return 0; } } public static void EnsureRequiredCommandLineParameters(Dictionary<string, string> commandArgs) { HashSet<string> requiredImageBuilderKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { StringConstants.Operation }; foreach (string requiredKey in requiredImageBuilderKeys) { if (!commandArgs.ContainsKey(requiredKey)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeMissingRequiredArgument, requiredKey)); } } string operationValue = commandArgs[StringConstants.Operation]; if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationTypeInfo)) { string[] requiredBuildApplicationTypeInfoParams = new string[] { StringConstants.BuildPath, StringConstants.Output }; CheckRequiredCommandLineArguments(requiredBuildApplicationTypeInfoParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplicationType)) { string[] requiredBuildApplicationTypeParams = new string[] { StringConstants.BuildPath }; CheckRequiredCommandLineArguments(requiredBuildApplicationTypeParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildApplication)) { string[] requiredBuildApplicationParams = new string[] { StringConstants.AppId, StringConstants.AppTypeName, StringConstants.AppTypeVersion, StringConstants.NameUri, StringConstants.Output }; CheckRequiredCommandLineArguments(requiredBuildApplicationParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationValidateComposeDeployment)) { string[] requiredBuildApplicationParams = new string[] { StringConstants.ComposeFilePath }; CheckRequiredCommandLineArguments(requiredBuildApplicationParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationBuildComposeDeployment)) { string[] requiredBuildApplicationParams = new string[] { StringConstants.ComposeFilePath, StringConstants.AppTypeName, StringConstants.AppTypeVersion, StringConstants.Output, StringConstants.OutputComposeFilePath }; CheckRequiredCommandLineArguments(requiredBuildApplicationParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeApplication)) { string[] requiredUpgradeApplicationParams = new string[] { StringConstants.AppId, StringConstants.AppTypeName, StringConstants.AppTypeVersion, StringConstants.CurrentAppInstanceVersion, StringConstants.Output }; CheckRequiredCommandLineArguments(requiredUpgradeApplicationParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationDelete)) { string[] requiredUpgradeApplicationParams = new string[] { StringConstants.Input }; CheckRequiredCommandLineArguments(requiredUpgradeApplicationParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationGetFabricVersion)) { string[] requiredGetFabricVersionParams = new string[] { StringConstants.Output }; CheckRequiredCommandLineArguments(requiredGetFabricVersionParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationProvisionFabric)) { if (!commandArgs.ContainsKey(StringConstants.CodePath) && !commandArgs.ContainsKey(StringConstants.ConfigPath)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeMissingCodeAndConfigPath, operationValue)); } string[] requiredProvisionFabricParams = new string[] { StringConstants.InfrastructureManifestFile }; CheckRequiredCommandLineArguments(requiredProvisionFabricParams, operationValue, commandArgs); } else if (ImageBuilderUtility.Equals(operationValue, StringConstants.OperationUpgradeFabric)) { string[] requiredUpgradeFabricParams = new string[] { StringConstants.CurrentFabricVersion, StringConstants.TargetFabricVersion }; CheckRequiredCommandLineArguments(requiredUpgradeFabricParams, operationValue, commandArgs); } } private static Dictionary<string, string> ParseParameters(string[] args) { Dictionary<string, string> commandArgs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string arg in args) { int delimiterIndex = arg.IndexOf(":", StringComparison.OrdinalIgnoreCase); if (delimiterIndex == -1) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeInvalidArgument, arg)); } string key = arg.Substring(0, delimiterIndex); string value = arg.Substring(delimiterIndex + 1); if (!SupportedCommandArgs.Contains(key)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeInvalidArgumentUnrecognizedKey, arg, key)); } if (commandArgs.ContainsKey(key)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeInvalidArgumentDuplicate, arg, key)); } commandArgs.Add(key, value); } return commandArgs; } private static Dictionary<string, string> ParseAppParameters(Dictionary<string, string> commandArgs) { Dictionary<string, string> applicationParameters = null; if (commandArgs.ContainsKey(StringConstants.AppParam)) { string workingDirectory = null; if (commandArgs.ContainsKey(StringConstants.WorkingDir)) { workingDirectory = commandArgs[StringConstants.WorkingDir]; } else { workingDirectory = Directory.GetCurrentDirectory(); } string appparametersFile = commandArgs.ContainsKey(StringConstants.AppParam) ? Path.Combine(workingDirectory, commandArgs[StringConstants.AppParam]) : null; ImageBuilderExe.ParseApplicationParametersFile(appparametersFile, out applicationParameters); } return applicationParameters; } private static void ParseApplicationParametersFile(string inputFilePath, out Dictionary<string, string> applicationParameters) { applicationParameters = new Dictionary<string, string>(); if (string.IsNullOrEmpty(inputFilePath)) { return; } if (!File.Exists(inputFilePath)) { throw new FileNotFoundException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeNoApplicationParameterFile), inputFilePath); } using (StreamReader reader = new StreamReader(File.Open(inputFilePath, FileMode.Open))) { string param; while ((param = reader.ReadLine()) != null) { string val; if((val = reader.ReadLine()) == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeFailedParseApplicationParameterFile, inputFilePath, param)); } if(!applicationParameters.ContainsKey(param)) { applicationParameters.Add(param, val); } } // readline } // using StreamReader } private static void CheckRequiredCommandLineArguments(string[] requiredArguments, string operationValue, Dictionary<string, string> commandArgs) { foreach (string requiredArgument in requiredArguments) { if (!commandArgs.ContainsKey(requiredArgument)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, StringResources.Error_ImageBuilderExeMissingRequiredArgumentForOperation, requiredArgument, operationValue)); } } } private static int GetFabricErrorCodeOrEFail(Exception e) { int errorCode = 0; if (!ImageBuilderExe.ManagedToNativeExceptionTranslation.TryGetValue(e.GetType(), out errorCode)) { FabricException fabricException = e as FabricException; if (fabricException != null) { errorCode = (int) fabricException.ErrorCode; } else { // TryGetValue() sets the out parameter to default(T) if the entry is not found // errorCode = unchecked((int)NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_IMAGEBUILDER_UNEXPECTED_ERROR); } } return errorCode; } private static void OnTimeout(object state) { OnFailure(new TimeoutException("ImageBuilderExe self-terminating on timeout"), state as string); try { Environment.Exit(unchecked((int)NativeTypes.FABRIC_ERROR_CODE.FABRIC_E_IMAGEBUILDER_UNEXPECTED_ERROR)); } catch (Exception e) { ImageBuilderExe.TraceSource.WriteError( ImageBuilderExe.TraceType, "ImageBuilderExe failed to exit cleanly: {0}", e); throw; } } private static void OnFailure(Exception exception, string errorDetailsFile) { ImageBuilderExe.TraceSource.WriteWarning( ImageBuilderExe.TraceType, "ImageBuilderExe operation failed with the following exception: {0}", exception); if (!string.IsNullOrEmpty(errorDetailsFile)) { try { var errorDetails = new StringBuilder(exception.Message); var inner = exception.InnerException; while (inner != null) { errorDetails.AppendFormat(" --> {0}: {1}", inner.GetType().Name, inner.Message); inner = inner.InnerException; } ImageBuilderUtility.WriteStringToFile( errorDetailsFile, ImageBuilderExe.GetFabricErrorCodeOrEFail(exception) + "," + errorDetails.ToString(), false, Encoding.Unicode); } catch (Exception innerEx) { ImageBuilderExe.TraceSource.WriteWarning( ImageBuilderExe.TraceType, "Failed to write error details: {0}", innerEx.ToString()); } } } } }
52.006383
294
0.592235
[ "MIT" ]
AndreyTretyak/service-fabric
src/prod/src/managed/ImageBuilderExe/ImageBuilderExe.cs
48,886
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.ComponentModel; namespace Azure.ResourceManager.StackHCI.Models { /// <summary> The type of identity that created the resource. </summary> public readonly partial struct CreatedByType : IEquatable<CreatedByType> { private readonly string _value; /// <summary> Initializes a new instance of <see cref="CreatedByType"/>. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public CreatedByType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string UserValue = "User"; private const string ApplicationValue = "Application"; private const string ManagedIdentityValue = "ManagedIdentity"; private const string KeyValue = "Key"; /// <summary> User. </summary> public static CreatedByType User { get; } = new CreatedByType(UserValue); /// <summary> Application. </summary> public static CreatedByType Application { get; } = new CreatedByType(ApplicationValue); /// <summary> ManagedIdentity. </summary> public static CreatedByType ManagedIdentity { get; } = new CreatedByType(ManagedIdentityValue); /// <summary> Key. </summary> public static CreatedByType Key { get; } = new CreatedByType(KeyValue); /// <summary> Determines if two <see cref="CreatedByType"/> values are the same. </summary> public static bool operator ==(CreatedByType left, CreatedByType right) => left.Equals(right); /// <summary> Determines if two <see cref="CreatedByType"/> values are not the same. </summary> public static bool operator !=(CreatedByType left, CreatedByType right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="CreatedByType"/>. </summary> public static implicit operator CreatedByType(string value) => new CreatedByType(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is CreatedByType other && Equals(other); /// <inheritdoc /> public bool Equals(CreatedByType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
46.672414
132
0.670853
[ "MIT" ]
AntonioVT/azure-sdk-for-net
sdk/azurestackhci/Azure.ResourceManager.StackHCI/src/Generated/Models/CreatedByType.cs
2,707
C#
using System; using System.Collections.Generic; using System.Linq; namespace TicTacToe_Simple { static class Program { static void Main() { List<List<char>> spaces = new List<List<char>>(); // Create 3 rows with 3 columns for(int i = 0; i < 3; ++i) spaces.Add(new List<char>(new char[] { '-', '-', '-' })); int turn = 0; // Keep track of whose turn it is // Game loop while(spaces.BoardState() == 0) { // Say which player's turn it is Console.WriteLine("--- P" + ((turn % 2) + 1) + " ---"); // Get user's position choice int x = 0, y = 0; do { Console.WriteLine("Choose an empty space: "); Console.Write(" X coordinate: "); x = int.Parse(Console.ReadLine()) - 1; Console.Write(" Y coordinate: "); y = int.Parse(Console.ReadLine()) - 1; } while(spaces.GetSpace(x, y) != '-'); // Make the user enter positions until they enter one that is empty spaces[y][x] = turn % 2 == 0 ? 'X' : 'O'; // If it is player 1's turn, set X. Otherwise, set O. ++turn; // Print board foreach(List<char> row in spaces) { foreach(char c in row) Console.Write(c); Console.WriteLine(); } Console.WriteLine(); // Alternatively: // foreach(List<char> row in spaces) // Console.WriteLine(string.Join("", row)); if(spaces.SelectMany(c => c).All(c => c != '-')) // Flatten spaces into a 1D IEnumerable and check if all elements are the empty space { Console.WriteLine("Draw!"); return; // Escape Main(). This stops any more code in Main() from running and that's it. } } Console.WriteLine("Player " + spaces.BoardState() + " wins!"); Console.ReadLine(); } static int BoardState(this List<List<char>> spaces) { int winner = 0; // 0 = no winner // Check rows for(int y = 0; y < 3; ++y) { // Store first character char c = spaces[y][0]; // If c is an empty space, go to the next iteration of the loop if(c == '-') continue; int contiguos = 0; for(int x = 0; x < 3; ++x) if(c == spaces.GetSpace(x, y)) // If current space in row is the same as the first ++contiguos; // Increment contiguos if(contiguos == 3) return c == 'X' ? 1 : 2; // Return 1 if c is X, return 2 otherwise } // Check columns for(int x = 0; x < 3; ++x) { char c = spaces[0][x]; if(c == '-') continue; int contiguos = 0; for(int y = 0; y < 3; ++y) if(c == spaces.GetSpace(x, y)) ++contiguos; if(contiguos == 3) return c == 'X' ? 1 : 2; } // Check diagonals // Note: It wouldn't be very difficult or even that bad to check the // diagonals individually, but they should be checked with for loops // so that the game can be easily expanded for(int x = 0; x < 3; ++x) { char c = spaces[0][x]; // If c is an empty space, go to the next iteration of the loop if(c == '-') continue; char dir = '-'; // Direction of diagonal int contiguos = 1; // Contiguos characters that are the same for(int shift = 1; shift < 3; ++shift) { // Check down-right if((dir == 'r' || dir == '-') && c == spaces.GetSpace(x + shift, shift)) // If c is the same as the character down and to the right { ++contiguos; // Increment contiguos if(dir == '-') // If the direction hasn't been set, set it to right dir = 'r'; continue; } // Check down-left if((dir == 'l' || dir == '-') && c == spaces.GetSpace(x - shift, shift)) // If c is the same as the character down and to the left { ++contiguos; // Increment contiguos if(dir == '-') // If the direction hasn't been set, set it to left dir = 'l'; continue; } } if(contiguos == 3) return c == 'X' ? 1 : 2; } return winner; } static char GetSpace(this List<List<char>> spaces, int x, int y, int xShift = 0, int yShift = 0) // Sets default values for xShift and yShift { int xPos = x + xShift; int yPos = y + yShift; if(xPos < 3 && xPos >= 0 && yPos < 3 && yPos >= 0) // Check that the given point is within the bounds of the board return spaces[yPos][xPos]; // Return the given point return '-'; // Return character for empty board space } } }
38.271523
150
0.422045
[ "Unlicense" ]
ZinoByte/TechClub
TicTacToe/TicTacToe-Simple/Program.cs
5,781
C#
using UnityEngine; using System.Collections; public class Danger : MonoBehaviour { float xStart; float xChange; // Use this for initialization void Start () { xStart = transform.position.x; xChange = Random.Range(1.0f, 2.0f) * Time.deltaTime; } // Update is called once per frame void Update () { float xNew = transform.position.x + xChange; transform.position = new Vector3(xNew, transform.position.y, 0); if (xNew > xStart + 2 || xNew < xStart -2) { xChange *= -1; } } }
22.44
72
0.600713
[ "MIT" ]
Naxos84/unity-for-beginner
2d_jump_and_run/2D-JumpAndRun/Assets/scripts/Danger.cs
563
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("portscan")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("portscan")] [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("79f9f265-c34a-4f63-8a61-24622b8d5d06")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.378378
85
0.727465
[ "BSD-3-Clause" ]
airzero24/portscan
portscan/Properties/AssemblyInfo.cs
1,423
C#
using System; using System.Collections; using System.Collections.Generic; namespace Byteology.GuardClauses { /// <summary> /// Contains extension methods for <see cref="IGuardClause{T}"/> whose generic type argument is <see cref="IEnumerable{T}"/>. /// </summary> public static class EnumerableExtensions { /// <summary> /// Throws an <see cref="ArgumentException"/> if the argument contains any elements. /// Does not throw an exception if the argument is <see langword="null"/>. /// </summary> /// <param name="clause">The guard clause containing the argument to guard.</param> /// <exception cref="ArgumentException">The argument contains any elements.</exception> public static IGuardClause<T> Empty<T>(this IGuardClause<T> clause) where T : IEnumerable { if (clause.Argument?.any() == true) throw new ArgumentException($"{clause.ArgumentName} should be empty."); return clause; } /// <summary> /// Throws an <see cref="ArgumentException"/> if the argument does not contain any elements. /// Does not throw an exception if the argument is <see langword="null"/>. /// </summary> /// <param name="clause">The guard clause containing the argument to guard.</param> /// <exception cref="ArgumentException">The argument does not contain any elements.</exception> public static IGuardClause<T> NotEmpty<T>(this IGuardClause<T> clause) where T : IEnumerable { if (clause.Argument?.any() == false) throw new ArgumentException($"{clause.ArgumentName} should not be empty."); return clause; } /// <summary> /// Passes the argument's elements count to the specified guard clause action. /// Does not throw an exception if the argument is <see langword="null"/>. /// </summary> /// <param name="clause">The guard clause containing the argument to guard.</param> /// <param name="guardClause">The guard clause that the number of elements in the argument should satisfy.</param> public static IGuardClause<T> ElementsCount<T>( this IGuardClause<T> clause, Action<IGuardClause<int>> guardClause) where T : IEnumerable { if (clause.Argument != null) { int elementsCount = clause.Argument.count(); string name = $"The number of elements in {clause.ArgumentName}"; guardClause.Invoke(new GuardClause<int>(elementsCount, name)); } return clause; } /// <summary> /// Throws an <see cref="AggregateException"/> if at least one element of the /// argument does not pass the specified guard clause. /// Does not throw an exception if the argument is <see langword="null"/>. /// </summary> /// <param name="clause">The guard clause containing the argument to guard.</param> /// <param name="guardClause">The guard clause that each elements in the argument should satisfy.</param> /// <exception cref="AggregateException">At least one element of the /// argument does not pass the specified guard clause.</exception> public static IGuardClause<IEnumerable<T>> AllElements<T>( this IGuardClause<IEnumerable<T>> clause, Action<IGuardClause<T>> guardClause) { List<Exception> exceptions = new(); if (clause.Argument != null) { int index = 0; foreach (T element in clause.Argument) { string name = $"{clause.ArgumentName}[{index}]"; try { guardClause.Invoke(new GuardClause<T>(element, name)); } catch (Exception ex) { exceptions.Add(ex); } index++; } } if (exceptions.Count > 0) throw new AggregateException(exceptions); return clause; } private static int count(this IEnumerable source) { if (source is ICollection collection) return collection.Count; int result = 0; IEnumerator enumerator = source.GetEnumerator(); while (enumerator.MoveNext()) result++; return result; } private static bool any(this IEnumerable source) { if (source is ICollection collection) return collection.Count != 0; IEnumerator enumerator = source.GetEnumerator(); return enumerator.MoveNext(); } } }
39.795276
130
0.552829
[ "MIT" ]
Byteology/guard-clauses
Byteology.GuardClauses/Extensions/EnumerableExtensions.cs
5,056
C#
/* Copyright 2019 Gfi Informatique Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace umi3d.common { /// <summary> /// Boolean parameter dto. /// </summary> [System.Serializable] public class BooleanParameterDto : AbstractParameterDto<bool> { public BooleanParameterDto() : base() { } } }
30.111111
72
0.735547
[ "Apache-2.0" ]
UMI3D/UMI3D-Tangram
Projet-Tangram/Assets/UMI3D SDK/common/Dto/interactions/Parameter/BooleanParameterDto.cs
815
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.Net.Sockets; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Internal { internal sealed partial class QuicStreamContext : IPersistentStateFeature, IStreamDirectionFeature, IProtocolErrorCodeFeature, IStreamIdFeature, IStreamAbortFeature { private IDictionary<object, object?>? _persistentState; public bool CanRead { get; private set; } public bool CanWrite { get; private set; } public long Error { get; set; } public long StreamId { get; private set; } IDictionary<object, object?> IPersistentStateFeature.State { get { // Lazily allocate persistent state return _persistentState ?? (_persistentState = new ConnectionItems()); } } public void AbortRead(long errorCode, ConnectionAbortedException abortReason) { lock (_shutdownLock) { if (_stream.CanRead) { _shutdownReadReason = abortReason; _log.StreamAbortRead(this, abortReason.Message); _stream.AbortRead(errorCode); } else { throw new InvalidOperationException("Unable to abort reading from a stream that doesn't support reading."); } } } public void AbortWrite(long errorCode, ConnectionAbortedException abortReason) { lock (_shutdownLock) { if (_stream.CanWrite) { _shutdownWriteReason = abortReason; _log.StreamAbortWrite(this, abortReason.Message); _stream.AbortWrite(errorCode); } else { throw new InvalidOperationException("Unable to abort writing to a stream that doesn't support writing."); } } } private void InitializeFeatures() { _currentIPersistentStateFeature = this; _currentIStreamDirectionFeature = this; _currentIProtocolErrorCodeFeature = this; _currentIStreamIdFeature = this; _currentIStreamAbortFeature = this; _currentITlsConnectionFeature = _connection._currentITlsConnectionFeature; } } }
35.24
168
0.590238
[ "MIT" ]
KristofferStrube/aspnetcore
src/Servers/Kestrel/Transport.Quic/src/Internal/QuicStreamContext.FeatureCollection.cs
2,643
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type EventDeltaCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class EventDeltaCollectionResponse { /// <summary> /// Gets or sets the <see cref="IEventDeltaCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Required.Default)] public IEventDeltaCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
38.171429
153
0.593563
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/EventDeltaCollectionResponse.cs
1,336
C#
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace Tizen.Applications.ComponentBased { /// <summary> /// This class provides methods and properties to get information of the running component. /// </summary> /// <since_tizen> 6 </since_tizen> public class ComponentRunningContext : IDisposable { private const string LogTag = "Tizen.Applications"; private bool _disposed = false; internal IntPtr _contextHandle = IntPtr.Zero; private string _componentId = string.Empty; internal ComponentRunningContext(IntPtr contextHandle) { _contextHandle = contextHandle; } /// <summary> /// A constructor of ComponentRunningContext that takes the component ID. /// </summary> /// <param name="componentId">Component ID.</param> /// <exception cref="ArgumentException">Thrown when failed because of an invalid argument.</exception> /// <exception cref="InvalidOperationException">Thrown when failed because of the "component not exist" error or the system error.</exception> /// <exception cref="OutOfMemoryException">Thrown when failed because of out of memory.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when failed because of permission denied.</exception> /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege> /// <since_tizen> 6 </since_tizen> public ComponentRunningContext(string componentId) { _componentId = componentId; IntPtr contextHandle = IntPtr.Zero; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentManagerGetComponentContext(_componentId, out contextHandle); if (err != Interop.ComponentManager.ErrorCode.None) { throw ComponentManager.ComponentManagerErrorFactory.GetException(err, "Failed to create the ComponentRunningContext of " + _componentId + "."); } _contextHandle = contextHandle; } /// <summary> /// Destructor of the class. /// </summary> ~ComponentRunningContext() { Dispose(false); } /// <summary> /// Enumeration for the component state. /// </summary> /// <since_tizen> 6 </since_tizen> public enum ComponentState { /// <summary> /// The Initialized state. This is the state when the component is constructed but OnCreate() is not called yet. /// </summary> Initialized = 0, /// <summary> /// The created state. This state is reached after OnCreate() is called. /// </summary> Created, /// <summary> /// The started state. This state is reached after OnStart() or OnStartCommand() is called. /// </summary> Started, /// <summary> /// The resumed state. This state is reached after OnResume() is called. /// </summary> Resumed, /// <summary> /// The paused state. This state is reached after OnPause() is called. /// </summary> Paused, /// <summary> /// The destroyed state. This state is reached right before OnDestroy() call. /// </summary> Destroyed } /// <summary> /// Gets the ID of the component. /// </summary> /// <since_tizen> 6 </since_tizen> public string ComponentId { get { if (!string.IsNullOrEmpty(_componentId)) return _componentId; string componentId = string.Empty; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextGetComponentId(_contextHandle, out componentId); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the ComponentId. err = " + err); } _componentId = componentId; return _componentId; } } /// <summary> /// Gets the application ID of the component. /// </summary> /// <since_tizen> 6 </since_tizen> public string ApplicationId { get { string appId = string.Empty; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextGetAppId(_contextHandle, out appId); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the ApplicationId of " + _componentId + ". err = " + err); } return appId; } } /// <summary> /// Gets the instance ID of the component. /// </summary> /// <since_tizen> 6 </since_tizen> public string InstanceId { get { string instanceId = string.Empty; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextGetInstanceId(_contextHandle, out instanceId); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the InstanceId of " + _componentId + ". err = " + err); } return instanceId; } } /// <summary> /// Gets the state of the component. /// </summary> /// <since_tizen> 6 </since_tizen> public ComponentState State { get { int state = 0; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextGetComponentState(_contextHandle, out state); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the State of " + _componentId + ". err = " + err); } return (ComponentState)state; } } /// <summary> /// Checks whether the component is terminated or not. /// </summary> /// <since_tizen> 6 </since_tizen> public bool IsTerminated { get { bool isTerminated = false; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextIsTerminated(_contextHandle, out isTerminated); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the IsTerminated of " + _componentId + ". err = " + err); } return isTerminated; } } /// <summary> /// Checks whether the component is running as sub component of the group. /// </summary> /// <since_tizen> 6 </since_tizen> public bool IsSubComponent { get { bool isSubComponent = false; Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentContextIsSubComponent(_contextHandle, out isSubComponent); if (err != Interop.ComponentManager.ErrorCode.None) { Log.Warn(LogTag, "Failed to get the IsSubComponent of " + _componentId + ". err = " + err); } return isSubComponent; } } /// <summary> /// Resumes the running component. /// </summary> /// <exception cref="ArgumentException">Thrown when failed because of an invalid argument.</exception> /// <exception cref="InvalidOperationException">Thrown when failed because of the system error.</exception> /// <exception cref="OutOfMemoryException">Thrown when failed because of out of memory.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when failed because of permission denied.</exception> /// <privilege>http://tizen.org/privilege/appmanager.launch</privilege> /// <since_tizen> 6 </since_tizen> public void Resume() { Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentManagerResumeComponent(_contextHandle); if (err != Interop.ComponentManager.ErrorCode.None) { throw ComponentManager.ComponentManagerErrorFactory.GetException(err, "Failed to Send the resume request."); } } /// <summary> /// Pauses the running component. /// </summary> /// <exception cref="ArgumentException">Thrown when failed because of an invalid argument.</exception> /// <exception cref="InvalidOperationException">Thrown when failed because of the system error.</exception> /// <exception cref="OutOfMemoryException">Thrown when failed because of out of memory.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when failed because of permission denied.</exception> /// <privilege>http://tizen.org/privilege/appmanager.launch</privilege> /// <since_tizen> 6 </since_tizen> [EditorBrowsable(EditorBrowsableState.Never)] public void Pause() { Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentManagerPauseComponent(_contextHandle); if (err != Interop.ComponentManager.ErrorCode.None) { throw ComponentManager.ComponentManagerErrorFactory.GetException(err, "Failed to Send the pause request."); } } /// <summary> /// Terminates the running component. /// </summary> /// <exception cref="ArgumentException">Thrown when failed because of an invalid argument.</exception> /// <exception cref="InvalidOperationException">Thrown when failed because of the system error.</exception> /// <exception cref="OutOfMemoryException">Thrown when failed because of out of memory.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when failed because of permission denied.</exception> /// <privilege>http://tizen.org/privilege/appmanager.launch</privilege> /// <since_tizen> 6 </since_tizen> [EditorBrowsable(EditorBrowsableState.Never)] public void Terminate() { Interop.ComponentManager.ErrorCode err = Interop.ComponentManager.ComponentManagerTerminateComponent(_contextHandle); if (err != Interop.ComponentManager.ErrorCode.None) { throw ComponentManager.ComponentManagerErrorFactory.GetException(err, "Failed to Send the terminate request."); } } /// <summary> /// Releases all resources used by the ComponentInfo class. /// </summary> /// <since_tizen> 6 </since_tizen> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases all resources used by the ComponentInfo class. /// </summary> /// <param name="disposing">Disposing</param> /// <since_tizen> 6 </since_tizen> private void Dispose(bool disposing) { if (_disposed) return; if (disposing) { } if (_contextHandle != IntPtr.Zero) { Interop.ComponentManager.ComponentContextDestroy(_contextHandle); _contextHandle = IntPtr.Zero; } _disposed = true; } } }
40.044444
159
0.589266
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
src/Tizen.Applications.ComponentBased.ComponentManager/Tizen.Applications/ComponentRunningContext.cs
12,616
C#
namespace Kasp.Identity.Core.Entities.UserEntities.XEntities; public interface IUserRegisterModel { string Email { get; set; } string Password { get; set; } }
27
62
0.765432
[ "MIT" ]
mo3in/Kasp
src/Kasp.Identity.Core/Entities/UserEntities/XEntities/IUserRegisterModel.cs
162
C#
namespace Ridics.Authentication.Core.Configuration { public class DefaultPaginationConfiguration : IPaginationConfiguration { public int MaxItemsOnPage => 100; } }
26.285714
74
0.744565
[ "BSD-3-Clause" ]
RIDICS/Authentication
Solution/Ridics.Authentication.Core/Configuration/DefaultPaginationConfiguration.cs
186
C#
/* MIT LICENSE Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace ExchangeSharp { public sealed partial class ExchangeBithumbAPI : ExchangeAPI { public override string BaseUrl { get; set; } = "https://api.bithumb.com"; public ExchangeBithumbAPI() { MarketSymbolIsUppercase = true; } public override string NormalizeMarketSymbol(string marketSymbol) { marketSymbol = base.NormalizeMarketSymbol(marketSymbol); int pos = marketSymbol.IndexOf(MarketSymbolSeparator); if (pos >= 0) { marketSymbol = marketSymbol.Substring(0, pos); } return marketSymbol; } public override Task<string> ExchangeMarketSymbolToGlobalMarketSymbolAsync(string marketSymbol) { return Task.FromResult("KRW" + GlobalMarketSymbolSeparator + marketSymbol); } public override Task<string> GlobalMarketSymbolToExchangeMarketSymbolAsync(string marketSymbol) { return Task.FromResult(marketSymbol.Substring(marketSymbol.IndexOf(GlobalMarketSymbolSeparator) + 1)); } private string StatusToError(string status) { switch (status) { case "5100": return "Bad Request"; case "5200": return "Not Member"; case "5300": return "Invalid Apikey"; case "5302": return "Method Not Allowed"; case "5400": return "Database Fail"; case "5500": return "Invalid Parameter"; case "5600": return "Custom Notice"; case "5900": return "Unknown Error"; default: return status; } } protected override JToken CheckJsonResponse(JToken result) { if (result != null && !(result is JArray) && result["status"] != null && result["status"].ToStringInvariant() != "0000") { throw new APIException(result["status"].ToStringInvariant() + ": " + result["message"].ToStringInvariant()); } return result["data"]; } private async Task<Tuple<JToken, string>> MakeRequestBithumbAsync(string marketSymbol, string subUrl) { marketSymbol = NormalizeMarketSymbol(marketSymbol); JToken obj = await MakeJsonRequestAsync<JToken>(subUrl.Replace("$SYMBOL$", marketSymbol ?? string.Empty)); return new Tuple<JToken, string>(obj, marketSymbol); } private async Task<ExchangeTicker> ParseTickerAsync(string marketSymbol, JToken data) { /* { "opening_price": "12625000", "closing_price": "12636000", "min_price": "12550000", "max_price": "12700000", "units_traded": "866.21", "acc_trade_value": "10930847017.53", "prev_closing_price": "12625000", "units_traded_24H": "16767.54", "acc_trade_value_24H": "211682650507.99", "fluctate_24H": "3,000", "fluctate_rate_24H": "0.02" } */ ExchangeTicker ticker = await this.ParseTickerAsync(data, marketSymbol, "max_price", "min_price", "min_price", "min_price", "units_traded_24H"); ticker.Volume.Timestamp = data.Parent.Parent["date"].ConvertInvariant<long>().UnixTimeStampToDateTimeMilliseconds(); return ticker; } protected override (string baseCurrency, string quoteCurrency) OnSplitMarketSymbolToCurrencies(string marketSymbol) { return (marketSymbol, "KRW"); } protected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync() { List<string> marketSymbols = new List<string>(); string marketSymbol = "all"; var data = await MakeRequestBithumbAsync(marketSymbol, "/public/ticker/$SYMBOL$"); foreach (JProperty token in data.Item1) { if (token.Name != "date") { marketSymbols.Add(token.Name); } } return marketSymbols; } protected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol) { var data = await MakeRequestBithumbAsync(marketSymbol, "/public/ticker/$SYMBOL$"); return await ParseTickerAsync(data.Item2, data.Item1); } protected override async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> OnGetTickersAsync() { string symbol = "all"; List<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>(); var data = await MakeRequestBithumbAsync(symbol, "/public/ticker/$SYMBOL$"); DateTime date = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(data.Item1["date"].ConvertInvariant<long>()); foreach (JProperty token in data.Item1) { if (token.Name != "date") { ExchangeTicker ticker = await ParseTickerAsync(token.Name, token.Value); ticker.Volume.Timestamp = date; tickers.Add(new KeyValuePair<string, ExchangeTicker>(token.Name, ticker)); } } return tickers; } protected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100) { var data = await MakeRequestBithumbAsync(marketSymbol, "/public/orderbook/$SYMBOL$"); return ExchangeAPIExtensions.ParseOrderBookFromJTokenDictionaries(data.Item1, amount: "quantity", sequence: "timestamp", maxCount: maxCount); } protected override async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> OnGetOrderBooksAsync(int maxCount = 100) { string symbol = "all"; List<KeyValuePair<string, ExchangeOrderBook>> books = new List<KeyValuePair<string, ExchangeOrderBook>>(); var data = await MakeRequestBithumbAsync(symbol, "/public/orderbook/$SYMBOL$"); foreach (JProperty book in data.Item1) { if (book.Name != "timestamp" && book.Name != "payment_currency") { ExchangeOrderBook orderBook = ExchangeAPIExtensions.ParseOrderBookFromJTokenArrays(book.Value); books.Add(new KeyValuePair<string, ExchangeOrderBook>(book.Name, orderBook)); } } return books; } } public partial class ExchangeName { public const string Bithumb = "Bithumb"; } }
45.718391
460
0.622376
[ "MIT" ]
Casimir666/ExchangeSharp
src/ExchangeSharp/API/Exchanges/Bithumb/ExchangeBithumbAPI.cs
7,957
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraResShifter : MonoBehaviour { RenderTexture rendTex; void Start () { } void Update () { } }
12.875
47
0.708738
[ "MIT" ]
denniscarr/dfc291_CodeLab1_final
Static/Assets/Scripts/CameraResShifter.cs
208
C#
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion namespace FluentValidation.Validators { using System; using System.Reflection; using Internal; using Resources; public class LessThanValidator : AbstractComparisonValidator { public LessThanValidator(IComparable value) : base(value, new LanguageStringSource(nameof(LessThanValidator))) { } public LessThanValidator(Func<object, object> valueToCompareFunc, MemberInfo member) : base(valueToCompareFunc, member, new LanguageStringSource(nameof(LessThanValidator))) { } public override bool IsValid(IComparable value, IComparable valueToCompare) { if (valueToCompare == null) return false; return Comparer.GetComparisonResult(value, valueToCompare) < 0; } public override Comparison Comparison { get { return Validators.Comparison.LessThan; } } } }
36.227273
115
0.738394
[ "Apache-2.0" ]
Chris-ZA/FluentValidation
src/FluentValidation/Validators/LessThanValidator.cs
1,594
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Diagnostics; namespace DrivingTestExplorer.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] public class ErrorModel : PageModel { public string? RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
26.555556
88
0.659693
[ "MIT" ]
gustavkullberg/TVDrivingTestExplorer
DrivingTestExplorer/Pages/Error.cshtml.cs
719
C#
// <copyright file="EntitySpawnInfo.cs" company="Kuub Studios"> // Copyright (c) Kuub Studios. All rights reserved. // </copyright> namespace HoardeGame.Gameplay.Themes { /// <summary> /// Contains information about an enemy spawner /// </summary> public class EntitySpawnInfo { /// <summary> /// Gets or sets the type of the enemy /// </summary> public string EntityType { get; set; } /// <summary> /// Gets or sets the minimal size of the cluster /// </summary> public int MinClusterSize { get; set; } /// <summary> /// Gets or sets the maximum size of the cluster /// </summary> public int MaxClusterSize { get; set; } /// <summary> /// Gets or sets the enemy spawn rate /// </summary> public int SpawnRate { get; set; } } }
27.625
64
0.563348
[ "MIT" ]
Huskitch/Horde
HoardeGame/Gameplay/Themes/EntitySpawnInfo.cs
886
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Numerics; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Text; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.Scripting.Utils; [assembly: PythonModule("sys", typeof(IronPython.Modules.SysModule))] namespace IronPython.Modules { public static class SysModule { public const string __doc__ = "Provides access to functions which query or manipulate the Python runtime."; public const int api_version = 0; // argv is set by PythonContext and only on the initial load public static readonly string byteorder = BitConverter.IsLittleEndian ? "little" : "big"; // builtin_module_names is set by PythonContext and updated on reload public const string copyright = "Copyright (c) IronPython Team"; private static string GetPrefix() { string prefix; #if FEATURE_ASSEMBLY_LOCATION try { prefix = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } catch (SecurityException) { prefix = String.Empty; } catch (ArgumentException) { prefix = String.Empty; } catch (MethodAccessException) { prefix = String.Empty; } #else prefix = String.Empty; #endif return prefix; } /// <summary> /// Returns detailed call statistics. Not implemented in IronPython and always returns None. /// </summary> public static object callstats() { return null; } /// <summary> /// Handles output of the expression statement. /// Prints the value and sets the __builtin__._ /// </summary> [PythonHidden] [Documentation(@"displayhook(object) -> None Print an object to sys.stdout and also save it in __builtin__._")] public static void displayhookImpl(CodeContext/*!*/ context, object value) { if (value != null) { PythonOps.Print(context, PythonOps.Repr(context, value)); context.LanguageContext.BuiltinModuleDict["_"] = value; } } public static BuiltinFunction displayhook = BuiltinFunction.MakeFunction( "displayhook", ArrayUtils.ConvertAll(typeof(SysModule).GetMember("displayhookImpl"), (x) => (MethodBase)x), typeof(SysModule) ); public static readonly BuiltinFunction __displayhook__ = displayhook; public const int dllhandle = 0; [PythonHidden] [Documentation(@"excepthook(exctype, value, traceback) -> None Handle an exception by displaying it with a traceback on sys.stderr._")] public static void excepthookImpl(CodeContext/*!*/ context, object exctype, object value, object traceback) { PythonContext pc = context.LanguageContext; PythonOps.PrintWithDest( context, pc.SystemStandardError, pc.FormatException(PythonExceptions.ToClr(value)) ); } public static readonly BuiltinFunction excepthook = BuiltinFunction.MakeFunction( "excepthook", ArrayUtils.ConvertAll(typeof(SysModule).GetMember("excepthookImpl"), (x) => (MethodBase)x), typeof(SysModule) ); public static readonly BuiltinFunction __excepthook__ = excepthook; public static int getcheckinterval() { throw PythonOps.NotImplementedError("IronPython does not support sys.getcheckinterval"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] public static void setcheckinterval(int value) { throw PythonOps.NotImplementedError("IronPython does not support sys.setcheckinterval"); } public static int getrefcount(CodeContext/*!*/ context, object o) { // getrefcount() is used at various places in the CPython test suite, usually to // check that instances are not cloned. Under .NET, we cannot provide that functionality, // but we can at least return a dummy result so that the tests can continue. PythonOps.Warn(context, PythonExceptions.RuntimeWarning, "IronPython does not support sys.getrefcount. A dummy result is returned."); return 1000000; } // warnoptions is set by PythonContext and updated on each reload [Python3Warning("sys.exc_clear() not supported in 3.x; use except clauses")] public static void exc_clear() { PythonOps.ClearCurrentException(); } public static PythonTuple exc_info(CodeContext/*!*/ context) { return PythonOps.GetExceptionInfo(context); } // exec_prefix and executable are set by PythonContext and updated on each reload public static void exit() { exit(null); } public static void exit(object code) { if (code == null) { throw new PythonExceptions._SystemExit().InitAndGetClrException(); } else { // throw as a python exception here to get the args set. throw new PythonExceptions._SystemExit().InitAndGetClrException(code); } } public static string getdefaultencoding(CodeContext/*!*/ context) { return context.LanguageContext.GetDefaultEncodingName(); } public static object getfilesystemencoding() { if(Environment.OSVersion.Platform == PlatformID.Unix) return "utf-8"; return "mbcs"; } [PythonHidden] public static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context) { return _getframeImpl(context, 0); } [PythonHidden] public static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context, int depth) { return _getframeImpl(context, depth, PythonOps.GetFunctionStack()); } internal static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context, int depth, List<FunctionStack> stack) { if (depth < stack.Count) { TraceBackFrame cur = null; for (int i = 0; i < stack.Count - depth; i++) { var elem = stack[i]; if (elem.Frame != null) { // we previously handed out a frame here, hand out the same one now cur = elem.Frame; } else { // create a new frame and save it for future calls cur = new TraceBackFrame( context, Builtin.globals(elem.Context), Builtin.locals(elem.Context), elem.Code, cur ); stack[i] = new FunctionStack(elem.Context, elem.Code, cur); } } return cur; } throw PythonOps.ValueError("call stack is not deep enough"); } public static int getsizeof(object o) { return ObjectOps.__sizeof__(o); } public static PythonTuple getwindowsversion() { var osVer = Environment.OSVersion; return new windows_version( osVer.Version.Major, osVer.Version.Minor, osVer.Version.Build, (int)osVer.Platform #if FEATURE_OS_SERVICEPACK , osVer.ServicePack #else , "" #endif ); } [PythonType("sys.getwindowsversion"), PythonHidden] public class windows_version : PythonTuple { internal windows_version(int major, int minor, int build, int platform, string service_pack) : base(new object[] { major, minor, build, platform, service_pack }) { this.major = major; this.minor = minor; this.build = build; this.platform = platform; this.service_pack = service_pack; } public readonly int major; public readonly int minor; public readonly int build; public readonly int platform; public readonly string service_pack; public const int n_fields = 5; public const int n_sequence_fields = 5; public const int n_unnamed_fields = 0; public override string __repr__(CodeContext context) { return string.Format("sys.getwindowsversion(major={0}, minor={1}, build={2}, platform={3}, service_pack='{4}')", this.major, this.minor, this.build, this.platform, this.service_pack); } } // hex_version is set by PythonContext public const int maxint = Int32.MaxValue; public const int maxsize = Int32.MaxValue; public const int maxunicode = (int)ushort.MaxValue; // modules is set by PythonContext and only on the initial load // path is set by PythonContext and only on the initial load #if !SILVERLIGHT public const string platform = "cli"; #else public const string platform = "silverlight"; #endif public static readonly string prefix = GetPrefix(); // ps1 and ps2 are set by PythonContext and only on the initial load public static void setdefaultencoding(CodeContext context, object name) { if (name == null) throw PythonOps.TypeError("name cannot be None"); string strName = name as string; if (strName == null) throw PythonOps.TypeError("name must be a string"); PythonContext pc = context.LanguageContext; Encoding enc; if (!StringOps.TryGetEncoding(strName, out enc)) { throw PythonOps.LookupError("'{0}' does not match any available encodings", strName); } pc.DefaultEncoding = enc; } #if PROFILE_SUPPORT // not enabled because we don't yet support tracing built-in functions. Doing so is a little // difficult because it's hard to flip tracing on/off for them w/o a perf overhead in the // non-profiling case. public static void setprofile(CodeContext/*!*/ context, TracebackDelegate o) { PythonContext pyContext = context.LanguageContext; pyContext.EnsureDebugContext(); if (o == null) { pyContext.UnregisterTracebackHandler(); } else { pyContext.RegisterTracebackHandler(); } // Register the trace func with the listener pyContext.TracebackListener.SetProfile(o); } #endif public static void settrace(CodeContext/*!*/ context, object o) { context.LanguageContext.SetTrace(o); } public static object call_tracing(CodeContext/*!*/ context, object func, PythonTuple args) { return context.LanguageContext.CallTracing(func, args); } public static object gettrace(CodeContext/*!*/ context) { return context.LanguageContext.GetTrace(); } public static void setrecursionlimit(CodeContext/*!*/ context, int limit) { context.LanguageContext.RecursionLimit = limit; } public static int getrecursionlimit(CodeContext/*!*/ context) { return context.LanguageContext.RecursionLimit; } // stdin, stdout, stderr, __stdin__, __stdout__, and __stderr__ added by PythonContext // version and version_info are set by PythonContext public static PythonTuple subversion = PythonTuple.MakeTuple("IronPython", "", ""); public const string winver = CurrentVersion.Series; #region Special types [PythonHidden, PythonType("flags"), DontMapIEnumerableToIter] public sealed class SysFlags : IList<object> { private const string _className = "sys.flags"; internal SysFlags() { } private const int INDEX_DEBUG = 0; private const int INDEX_PY3K_WARNING = 1; private const int INDEX_DIVISION_WARNING = 2; private const int INDEX_DIVISION_NEW = 3; private const int INDEX_INSPECT = 4; private const int INDEX_INTERACTIVE = 5; private const int INDEX_OPTIMIZE = 6; private const int INDEX_DONT_WRITE_BYTECODE = 7; private const int INDEX_NO_USER_SITE = 8; private const int INDEX_NO_SITE = 9; private const int INDEX_IGNORE_ENVIRONMENT = 10; private const int INDEX_TABCHECK = 11; private const int INDEX_VERBOSE = 12; private const int INDEX_UNICODE = 13; private const int INDEX_BYTES_WARNING = 14; public const int n_fields = 15; public const int n_sequence_fields = 15; public const int n_unnamed_fields = 0; private static readonly string[] _keys = new string[] { "debug", "py3k_warning", "division_warning", "division_new", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site", "ignore_environment", "tabcheck", "verbose", "unicode", "bytes_warning" }; private object[] _values = new object[n_fields] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private PythonTuple __tuple = null; private PythonTuple _tuple { get { _Refresh(); return __tuple; } } private string __string = null; private string _string { get { _Refresh(); return __string; } } public override string ToString() { return _string; } public string __repr__() { return _string; } private bool _modified = true; private void _Refresh() { if (_modified) { __tuple = PythonTuple.MakeTuple(_values); StringBuilder sb = new StringBuilder("sys.flags("); for (int i = 0; i < n_fields; i++) { if (_keys[i] == null) { sb.Append(_values[i]); } else { sb.AppendFormat("{0}={1}", _keys[i], _values[i]); } if (i < n_fields - 1) { sb.Append(", "); } else { sb.Append(')'); } } __string = sb.ToString(); _modified = false; } } private int _GetVal(int index) { return (int)_values[index]; } private void _SetVal(int index, int value) { if ((int)_values[index] != value) { _modified = true; _values[index] = value; } } #region ICollection<object> Members void ICollection<object>.Add(object item) { throw new InvalidOperationException(_className + " is readonly"); } void ICollection<object>.Clear() { throw new InvalidOperationException(_className + " is readonly"); } [PythonHidden] public bool Contains(object item) { return _tuple.Contains(item); } [PythonHidden] public void CopyTo(object[] array, int arrayIndex) { _tuple.CopyTo(array, arrayIndex); } public int Count { [PythonHidden] get { return n_fields; } } bool ICollection<object>.IsReadOnly { get { return true; } } bool ICollection<object>.Remove(object item) { throw new InvalidOperationException(_className + " is readonly"); } #endregion #region IEnumerable Members [PythonHidden] public IEnumerator GetEnumerator() { return _tuple.GetEnumerator(); } #endregion #region IEnumerable<object> Members IEnumerator<object> IEnumerable<object>.GetEnumerator() { return ((IEnumerable<object>)_tuple).GetEnumerator(); } #endregion #region ISequence Members public int __len__() { return n_fields; } public object this[int i] { get { return _tuple[i]; } } public object this[BigInteger i] { get { return this[(int)i]; } } public object __getslice__(int start, int end) { return _tuple.__getslice__(start, end); } public object this[Slice s] { get { return _tuple[s]; } } public object this[object o] { get { return this[Converter.ConvertToIndex(o)]; } } #endregion #region IList<object> Members [PythonHidden] public int IndexOf(object item) { return _tuple.IndexOf(item); } void IList<object>.Insert(int index, object item) { throw new InvalidOperationException(_className + " is readonly"); } void IList<object>.RemoveAt(int index) { throw new InvalidOperationException(_className + " is readonly"); } object IList<object>.this[int index] { get { return _tuple[index]; } set { throw new InvalidOperationException(_className + " is readonly"); } } #endregion #region binary ops public static PythonTuple operator +([NotNull]SysFlags f, [NotNull]PythonTuple t) { return f._tuple + t; } public static PythonTuple operator *([NotNull]SysFlags f, int n) { return f._tuple * n; } public static PythonTuple operator *(int n, [NotNull]SysFlags f) { return f._tuple * n; } public static object operator *([NotNull]SysFlags f, [NotNull]Index n) { return f._tuple * n; } public static object operator *([NotNull]Index n, [NotNull]SysFlags f) { return f._tuple * n; } public static object operator *([NotNull]SysFlags f, object n) { return f._tuple * n; } public static object operator *(object n, [NotNull]SysFlags f) { return f._tuple * n; } #endregion # region comparison and hashing methods public static bool operator >(SysFlags f, PythonTuple t) { return f._tuple > t; } public static bool operator <(SysFlags f, PythonTuple t) { return f._tuple < t; } public static bool operator >=(SysFlags f, PythonTuple t) { return f._tuple >= t; } public static bool operator <=(SysFlags f, PythonTuple t) { return f._tuple <= t; } public override bool Equals(object obj) { if (obj is SysFlags) { return _tuple.Equals(((SysFlags)obj)._tuple); } return _tuple.Equals(obj); } public override int GetHashCode() { return _tuple.GetHashCode(); } # endregion #region sys.flags API public int debug { get { return _GetVal(INDEX_DEBUG); } internal set { _SetVal(INDEX_DEBUG, value); } } public int py3k_warning { get { return _GetVal(INDEX_PY3K_WARNING); } internal set { _SetVal(INDEX_PY3K_WARNING, value); } } public int division_warning { get { return _GetVal(INDEX_DIVISION_WARNING); } internal set { _SetVal(INDEX_DIVISION_WARNING, value); } } public int division_new { get { return _GetVal(INDEX_DIVISION_NEW); } internal set { _SetVal(INDEX_DIVISION_NEW, value); } } public int inspect { get { return _GetVal(INDEX_INSPECT); } internal set { _SetVal(INDEX_INSPECT, value); } } public int interactive { get { return _GetVal(INDEX_INTERACTIVE); } internal set { _SetVal(INDEX_INTERACTIVE, value); } } public int optimize { get { return _GetVal(INDEX_OPTIMIZE); } internal set { _SetVal(INDEX_OPTIMIZE, value); } } public int dont_write_bytecode { get { return _GetVal(INDEX_DONT_WRITE_BYTECODE); } internal set { _SetVal(INDEX_DONT_WRITE_BYTECODE, value); } } public int no_user_site { get { return _GetVal(INDEX_NO_USER_SITE); } internal set { _SetVal(INDEX_NO_USER_SITE, value); } } public int no_site { get { return _GetVal(INDEX_NO_SITE); } internal set { _SetVal(INDEX_NO_SITE, value); } } public int ignore_environment { get { return _GetVal(INDEX_IGNORE_ENVIRONMENT); } internal set { _SetVal(INDEX_IGNORE_ENVIRONMENT, value); } } public int tabcheck { get { return _GetVal(INDEX_TABCHECK); } internal set { _SetVal(INDEX_TABCHECK, value); } } public int verbose { get { return _GetVal(INDEX_VERBOSE); } internal set { _SetVal(INDEX_VERBOSE, value); } } public int unicode { get { return _GetVal(INDEX_UNICODE); } internal set { _SetVal(INDEX_UNICODE, value); } } public int bytes_warning { get { return _GetVal(INDEX_BYTES_WARNING); } internal set { _SetVal(INDEX_BYTES_WARNING, value); } } #endregion } #endregion // These values are based on the .NET 2 BigInteger in Microsoft.Scripting.Math public static longinfo long_info = new longinfo(32, 4); [PythonType("sys.long_info"), PythonHidden] public class longinfo : PythonTuple { internal longinfo(int bits_per_digit, int sizeof_digit) : base(new object[] {bits_per_digit, sizeof_digit}) { this.bits_per_digit = bits_per_digit; this.sizeof_digit = sizeof_digit; } public readonly int bits_per_digit; public readonly int sizeof_digit; public const int n_fields = 2; public const int n_sequence_fields = 2; public const int n_unnamed_fields = 0; public override string __repr__(CodeContext context) { return string.Format("sys.long_info(bits_per_digit={0}, sizeof_digit={1})", this.bits_per_digit, this.sizeof_digit); } } public static floatinfo float_info = new floatinfo( Double.MaxValue, // DBL_MAX 1024, // DBL_MAX_EXP 308, // DBL_MAX_10_EXP // DBL_MIN BitConverter.Int64BitsToDouble(BitConverter.IsLittleEndian ? 0x0010000000000000 : 0x0000000000001000), -1021, // DBL_MIN_EXP -307, // DBL_MIN_10_EXP 15, // DBL_DIG 53, // DBL_MANT_DIG // DBL_EPSILON BitConverter.Int64BitsToDouble(BitConverter.IsLittleEndian ? 0x3cb0000000000000 : 0x000000000000b03c), 2, // FLT_RADIX 1); // FLT_ROUNDS [PythonType("sys.float_info"), PythonHidden] public class floatinfo : PythonTuple { internal floatinfo(double max, int max_exp, int max_10_exp, double min, int min_exp, int min_10_exp, int dig, int mant_dig, double epsilon, int radix, int rounds) : base(new object[] { max, max_exp, max_10_exp, min, min_exp, min_10_exp, dig, mant_dig, epsilon, radix, rounds}) { this.max = max; this.max_exp = max_exp; this.max_10_exp = max_10_exp; this.min = min; this.min_exp = min_exp; this.min_10_exp = min_10_exp; this.dig = dig; this.mant_dig = mant_dig; this.epsilon = epsilon; this.radix = radix; this.rounds = rounds; } public readonly double max; public readonly int max_exp; public readonly int max_10_exp; public readonly double min; public readonly int min_exp; public readonly int min_10_exp; public readonly int dig; public readonly int mant_dig; public readonly double epsilon; public readonly int radix; public readonly int rounds; public const int n_fields = 11; public const int n_sequence_fields = 11; public const int n_unnamed_fields = 0; public override string __repr__(CodeContext context) { return string.Format("sys.float_info(max={0}, max_exp={1}, max_10_exp={2}, " + "min={3}, min_exp={4}, min_10_exp={5}, " + "dig={6}, mant_dig={7}, epsilon={8}, radix={9}, rounds={10})", max, max_exp, max_10_exp, min, min_exp, min_10_exp, dig, mant_dig, epsilon, radix, rounds); } } [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { dict["stdin"] = dict["__stdin__"]; dict["stdout"] = dict["__stdout__"]; dict["stderr"] = dict["__stderr__"]; // !!! These fields do need to be reset on "reload(sys)". However, the initial value is specified by the // engine elsewhere. For now, we initialize them just once to some default value dict["warnoptions"] = new List(0); PublishBuiltinModuleNames(context, dict); context.SetHostVariables(dict); dict["meta_path"] = new List(0); dict["path_hooks"] = new List(0); // add zipimport to the path hooks for importing from zip files. try { PythonModule zipimport = Importer.ImportModule( context.SharedClsContext, context.SharedClsContext.GlobalDict, "zipimport", false, -1) as PythonModule; if (zipimport != null) { object zipimporter = PythonOps.GetBoundAttr( context.SharedClsContext, zipimport, "zipimporter"); List path_hooks = dict["path_hooks"] as List; if (path_hooks != null && zipimporter != null) { path_hooks.Add(zipimporter); } } } catch { // this is not a fatal error, so we don't do anything. } dict["path_importer_cache"] = new PythonDictionary(); } internal static void PublishBuiltinModuleNames(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { object[] keys = new object[context.BuiltinModules.Keys.Count]; int index = 0; foreach (object key in context.BuiltinModules.Keys) { keys[index++] = key; } dict["builtin_module_names"] = PythonTuple.MakeTuple(keys); } } }
36.509685
145
0.541267
[ "Apache-2.0" ]
SueDou/python
Src/IronPython/Modules/sys.cs
30,157
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Krypto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Krypto.Tests { [TestClass()] public class DESTests { [TestMethod()] public void GenerateKeyTest() { DES des = new DES(); string key = "abcdefgh"; string key1 = "hgfedsar"; BitArray[] subKeys = des.GenerateSubKeys(des.StringToBytes(key)); BitArray[] subKeys1 = des.GenerateSubKeys(des.StringToBytes(key1)); for (int i = 0; i < subKeys1.Length; i++) { Assert.AreNotEqual(subKeys[i], subKeys1[i]); } } [TestMethod()] public void RightLeftTest() { DES des = new DES(); BitArray ar = new BitArray(8); ar[0] = true; ar[3] = true; ar[7] = true; BitArray ar2 = new BitArray(4); ar2[0] = true; ar2[3] = true; BitArray ar3 = new BitArray(4); ar3[3] = true; Assert.AreEqual(des.LeftHalf(ar), ar2); Assert.AreEqual(des.RightHalf(ar), ar3); } } }
27.489362
79
0.531734
[ "MIT" ]
EmiNiemand/Krypto
KryptoTests/DESTests.cs
1,294
C#
using System; namespace UIC.Util.Logging { public interface ILoggerFactory { ILogger GetLoggerFor(Type type); ILogger GetLoggerFor(string loggername); } public class NlogLoggerFactory : ILoggerFactory { public ILogger GetLoggerFor(Type type) { return NLogger.CreateLogger(type.Name); } public ILogger GetLoggerFor(string loggername) { return NLogger.CreateLogger(loggername); } } }
22.904762
56
0.642412
[ "MIT" ]
CDE-GMA/UIC.net-mono.c-sharp
UIC/UIC.Util/Logging/ILoggerFactory.cs
483
C#
using System.Linq; using Telerik.Core; using Telerik.Data.Core.Layouts; using Telerik.UI.Automation.Peers; using Telerik.UI.Xaml.Controls.Grid.Commands; using Telerik.UI.Xaml.Controls.Grid.Primitives; using Telerik.UI.Xaml.Controls.Grid.View; using Telerik.UI.Xaml.Controls.Primitives; using Windows.Devices.Input; using Windows.System; using Windows.UI.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation.Peers; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media.Animation; namespace Telerik.UI.Xaml.Controls.Grid { public partial class RadDataGrid { internal VisualStateService visualStateService; internal HitTestService hitTestService; internal CommandService commandService; private Storyboard cellFlyoutShowTimeOutAnimationBoard; private DoubleAnimation cellFlyoutShowTimeOutAnimation; /// <summary> /// Gets the <see cref="HitTestService"/> instance that provides methods for retrieving rows and cells from a given physical location. /// </summary> public HitTestService HitTestService { get { return this.hitTestService; } } internal ColumnHeaderTapContext GenerateColumnHeaderTapContext(DataGridColumn column, PointerDeviceType deviceType) { bool multiple = false; bool canSort = column.CanSort; if (canSort) { switch (this.UserSortMode) { case DataGridUserSortMode.Auto: if (deviceType == PointerDeviceType.Touch) { multiple = true; } else { multiple = KeyboardHelper.IsModifierKeyDown(VirtualKey.Control); } break; case DataGridUserSortMode.Multiple: multiple = true; break; case DataGridUserSortMode.None: canSort = false; break; } } var context = new ColumnHeaderTapContext() { Column = column, CanSort = canSort, IsMultipleSortAllowed = multiple }; return context; } internal FilterButtonTapContext GenerateFilterButtonTapContext(DataGridColumnHeader header) { var context = new FilterButtonTapContext() { FirstFilterControl = header.Column.CreateFilterControl(), Column = header.Column, AssociatedDescriptor = this.FilterDescriptors.FirstOrDefault(d => d.DescriptorPeer == header.Column) }; if (header.Column.SupportsCompositeFilter) { context.SecondFilterControl = header.Column.CreateFilterControl(); } return context; } internal void ExecuteFilter(DataGridColumnHeader header) { var context = this.GenerateFilterButtonTapContext(header); this.commandService.ExecuteCommand(CommandId.FilterButtonTap, context); } internal void OnColumnHeaderTap(DataGridColumnHeader headerCell, TappedRoutedEventArgs e) { var columnHeaderPeer = FrameworkElementAutomationPeer.FromElement(headerCell) as DataGridColumnHeaderAutomationPeer; if (columnHeaderPeer != null) { columnHeaderPeer.RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked); } var context = this.GenerateColumnHeaderTapContext(headerCell.Column, e.PointerDeviceType); context.IsFlyoutOpen = this.ContentFlyout.IsOpen; this.ContentFlyout.Hide(DataGridFlyoutId.All); this.commandService.ExecuteCommand(CommandId.ColumnHeaderTap, context); } internal void OnFilterButtonTap(DataGridColumnHeader header) { this.ExecuteFilter(header); } internal void OnGroupHeaderTap(DataGridGroupHeader header) { var context = header.DataContext as GroupHeaderContext; context.IsExpanded = header.IsExpanded; this.commandService.ExecuteCommand(CommandId.GroupHeaderTap, context); // get the value from the context as the command may have it toggled header.IsExpanded = context.IsExpanded; this.CurrencyService.RefreshCurrentItem(false); this.TryFocus(FocusState.Pointer, false); this.ResetSelectedHeader(); this.ContentFlyout.Hide(DataGridFlyoutId.All); } internal void OnCellsPanelPointerOver(PointerRoutedEventArgs e) { this.cellFlyoutShowTimeOutAnimationBoard.Completed -= this.CellFlyoutTimerAnimationBoardCompleted; this.cellFlyoutShowTimeOutAnimationBoard.Stop(); var hitPoint = e.GetCurrentPoint(this.cellsPanel).Position; var cell = this.hitTestService.GetCellFromPoint(hitPoint.ToRadPoint()); if (cell != null) { this.commandService.ExecuteCommand(CommandId.CellPointerOver, new DataGridCellInfo(cell)); if (cell.Column.IsCellFlyoutEnabled && !(this.ContentFlyout.IsOpen && this.ContentFlyout.Id != DataGridFlyoutId.Cell)) { this.cellFlyoutShowTimeOutAnimationBoard.Completed += this.CellFlyoutTimerAnimationBoardCompleted; this.hoveredCell = cell; this.cellFlyoutShowTimeOutAnimationBoard.Begin(); } } else { this.visualStateService.UpdateHoverDecoration(null); } } internal void OnCellsPanelPointerExited() { // clear the hover effect (if any) this.visualStateService.UpdateHoverDecoration(null); this.cellFlyoutShowTimeOutAnimationBoard.Completed -= this.CellFlyoutTimerAnimationBoardCompleted; this.cellFlyoutShowTimeOutAnimationBoard.Stop(); } internal void OnCellsPanelPointerPressed() { this.TryFocus(FocusState.Pointer, false); } internal void OnCellsPanelHolding(HoldingRoutedEventArgs e) { var cell = this.hitTestService.GetCellFromPoint(e.GetPosition(this.cellsPanel).ToRadPoint()); if (cell != null) { this.commandService.ExecuteCommand(CommandId.CellHolding, new CellHoldingContext(new DataGridCellInfo(cell), e.HoldingState)); } this.TryFocus(FocusState.Pointer, false); } internal void OnCellsPanelTapped(TappedRoutedEventArgs e) { var cell = this.hitTestService.GetCellFromPoint(e.GetPosition(this.cellsPanel).ToRadPoint()); if (cell != null) { this.commandService.ExecuteCommand(CommandId.CellTap, new DataGridCellInfo(cell)); } this.ResetSelectedHeader(); this.TryFocus(FocusState.Pointer, false, e.OriginalSource as FrameworkElement); if (this.contentFlyout.IsOpen) { this.ContentFlyout.Hide(DataGridFlyoutId.All); } } internal void OnCellsPanelDoubleTapped(DoubleTappedRoutedEventArgs e) { var cell = this.hitTestService.GetCellFromPoint(e.GetPosition(this.cellsPanel).ToRadPoint()); if (cell != null) { this.commandService.ExecuteCommand(CommandId.CellDoubleTap, new DataGridCellInfo(cell)); } } internal void OnCellDoubleTap(DataGridCellInfo cell) { this.BeginEdit(cell, ActionTrigger.DoubleTap, null); } internal void OnCellTap(DataGridCellInfo cellInfo) { if (this.editService.IsEditing) { if (this.UserEditMode == DataGridUserEditMode.External) { this.CancelEdit(); } else if (!this.CommitEdit(new DataGridCellInfo(this.CurrentItem, null), ActionTrigger.Tap, null)) { return; } } this.selectionService.Select(cellInfo.Cell); this.CurrencyService.ChangeCurrentItem(cellInfo.RowItemInfo.Item, true, true); if (cellInfo.Column != null) { cellInfo.Column.TryFocusCell(cellInfo, FocusState.Pointer); } } internal void OnCellHolding(DataGridCellInfo cellInfo, HoldingState holdingState) { if (cellInfo.Column.IsCellFlyoutEnabled && holdingState == HoldingState.Started) { this.CommandService.ExecuteCommand(Telerik.UI.Xaml.Controls.Grid.Commands.CommandId.CellFlyoutAction, new CellFlyoutActionContext(cellInfo, true, CellFlyoutGesture.Holding)); } } internal void OnCellsPanelKeyDown(KeyRoutedEventArgs e) { this.ExecuteKeyDown(e); } internal void TryFocus(FocusState state, bool force, FrameworkElement tappedElement = null) { if (!this.IsTabStop) { return; } if (force) { this.Focus(state); } else { var focusedElement = FocusManager.GetFocusedElement() as DependencyObject; if (focusedElement == null || (ElementTreeHelper.FindVisualAncestor<DataGridCellsPanel>(focusedElement) == null && ElementTreeHelper.FindVisualAncestor<DataGridCellsPanel>(tappedElement) == null)) { this.Focus(state); } } } internal void OnGroupIsExpandedChanged() { this.CurrencyService.OnGroupExpandStateChanged(); // TODO: Decide whether to support expand/collapse of groups while editing this.CancelEdit(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal void HandleKeyDown(KeyRoutedEventArgs e) { if (e == null || e.Handled) { return; } // KeyDown is raised twice for VirtualKey.Enter if (e.Key == VirtualKey.Enter && e.KeyStatus.RepeatCount > 0) { return; } ItemInfo? info = null; switch (e.Key) { case VirtualKey.Escape: if (this.editService.IsEditing) { e.Handled = true; this.CancelEdit(ActionTrigger.Keyboard, e.Key); } break; case VirtualKey.F2: if (!this.editService.IsEditing) { e.Handled = true; this.BeginEdit(this.CurrentItem, ActionTrigger.Keyboard, e.Key); } break; case VirtualKey.Tab: if (e.OriginalSource is RadDataGrid) { if (!this.editService.IsEditing) { e.Handled = true; info = this.CurrencyService.CurrentItemInfo == null ? this.model.FindFirstDataItemInView() : this.CurrencyService.CurrentItemInfo; #pragma warning disable CS4014 Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Low, () => { var xamlVisualStateLayer = this.visualStateLayerCache as XamlVisualStateLayer; if (xamlVisualStateLayer != null) { var currencyVisual = xamlVisualStateLayer.CurrencyVisual as DataGridCurrencyControl; if (currencyVisual != null && currencyVisual.Visibility == Visibility.Visible) { currencyVisual.Focus(FocusState.Keyboard); this.RaiseCellPeerFocusChangedEvent(info); } } }); #pragma warning restore CS4014 } } break; case VirtualKey.Down: if (!this.editService.IsEditing) { e.Handled = true; info = this.model.FindPreviousOrNextDataItem(this.CurrentItem, true); } break; case VirtualKey.Up: if (!this.editService.IsEditing) { e.Handled = true; info = this.model.FindPreviousOrNextDataItem(this.CurrentItem, false); } break; case VirtualKey.PageDown: if (!this.editService.IsEditing) { e.Handled = true; info = this.model.FindPageUpOrDownDataItem(this.CurrentItem, true); } break; case VirtualKey.PageUp: if (!this.editService.IsEditing) { e.Handled = true; info = this.model.FindPageUpOrDownDataItem(this.CurrentItem, false); } break; case VirtualKey.Home: if (!this.editService.IsEditing && KeyboardHelper.IsModifierKeyDown(VirtualKey.Control)) { e.Handled = true; info = this.model.FindFirstDataItemInView(); } break; case VirtualKey.End: if (!this.editService.IsEditing && KeyboardHelper.IsModifierKeyDown(VirtualKey.Control)) { e.Handled = true; info = this.model.FindLastDataItemInView(); } break; case VirtualKey.Enter: e.Handled = true; if (this.editService.IsEditing) { this.CommitEdit(new DataGridCellInfo(this.CurrentItem, null), ActionTrigger.Keyboard, e.Key); } else { bool shiftPressed = KeyboardHelper.IsModifierKeyDown(VirtualKey.Shift); info = this.model.FindPreviousOrNextDataItem(this.CurrentItem, !shiftPressed); } break; case VirtualKey.Space: if (e.OriginalSource is RadDataGrid) { if (this.SelectionUnit == DataGridSelectionUnit.Row) { info = this.model.FindItemInfo(this.CurrentItem); if (info != null) { var cell = this.model.CellsController.GetCellsForRow(info.Value.Slot).First(); if (cell != null) { this.OnCellTap(new DataGridCellInfo(cell)); } } } } break; } if (info != null) { this.CurrencyService.ChangeCurrentItem(info.Value.Item, true, true); if (e.Key != VirtualKey.Tab) { this.RaiseCellPeerFocusChangedEvent(info); } } } /// <summary> /// Called before the KeyDown event occurs. /// </summary> /// <param name="e">The data for the event.</param> protected override void OnKeyDown(KeyRoutedEventArgs e) { base.OnKeyDown(e); this.ExecuteKeyDown(e); } private void CellFlyoutTimerAnimationBoardCompleted(object sender, object e) { this.cellFlyoutShowTimeOutAnimationBoard.Completed -= this.CellFlyoutTimerAnimationBoardCompleted; // If another flyout is opened it should prevent showing the cell tooltip by design. if (this.ContentFlyout.IsOpen && this.ContentFlyout.Id != DataGridFlyoutId.Cell) { return; } this.CommandService.ExecuteCommand(CommandId.CellFlyoutAction, new CellFlyoutActionContext(new DataGridCellInfo(this.hoveredCell), true, CellFlyoutGesture.PointerOver)); } private void OnScrollViewerKeyDown(object sender, KeyRoutedEventArgs e) { this.ExecuteKeyDown(e); } private void ExecuteKeyDown(KeyRoutedEventArgs e) { this.commandService.ExecuteCommand(CommandId.KeyDown, e); } private void SubscribeToFrozenHostEvents() { this.FrozenContentHost.Tapped += this.FrozenContentHost_Tapped; this.FrozenContentHost.DoubleTapped += this.FrozenContentHost_DoubleTapped; this.FrozenContentHost.PointerMoved += this.FrozenContentHost_PointerMoved; this.FrozenContentHost.PointerExited += this.FrozenContentHost_PointerExited; this.FrozenContentHost.PointerPressed += this.FrozenContentHost_PointerPressed; this.FrozenContentHost.KeyDown += this.FrozenContentHost_KeyDown; } private void UnsubscribeFromFrozenHostEvents() { var frozenHost = this.FrozenContentHost; if (frozenHost != null) { frozenHost.Tapped -= this.FrozenContentHost_Tapped; frozenHost.DoubleTapped -= this.FrozenContentHost_DoubleTapped; frozenHost.PointerMoved -= this.FrozenContentHost_PointerMoved; frozenHost.PointerExited -= this.FrozenContentHost_PointerExited; frozenHost.PointerPressed -= this.FrozenContentHost_PointerPressed; frozenHost.KeyDown -= this.FrozenContentHost_KeyDown; } } private void RaiseCellPeerFocusChangedEvent(ItemInfo? info) { var dataGridPeer = FrameworkElementAutomationPeer.FromElement(this) as RadDataGridAutomationPeer; if (dataGridPeer != null && dataGridPeer.childrenCache != null) { if (dataGridPeer.childrenCache.Count == 0) { dataGridPeer.GetChildren(); } var cellPeer = dataGridPeer.childrenCache.FirstOrDefault(a => a.Row == info.Value.Slot && a.Column == 0) as DataGridCellInfoAutomationPeer; if (cellPeer != null && cellPeer.ChildTextBlockPeer != null) { cellPeer.RaiseAutomationEvent(AutomationEvents.AutomationFocusChanged); } } } private void FrozenContentHost_KeyDown(object sender, KeyRoutedEventArgs e) { this.OnCellsPanelKeyDown(e); } private void FrozenContentHost_PointerPressed(object sender, PointerRoutedEventArgs e) { this.OnCellsPanelPointerPressed(); } private void FrozenContentHost_PointerExited(object sender, PointerRoutedEventArgs e) { this.OnCellsPanelPointerExited(); } private void FrozenContentHost_PointerMoved(object sender, PointerRoutedEventArgs e) { this.OnCellsPanelPointerOver(e); } private void FrozenContentHost_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { this.OnCellsPanelDoubleTapped(e); } private void FrozenContentHost_Tapped(object sender, TappedRoutedEventArgs e) { this.OnCellsPanelTapped(e); } } }
38.499076
190
0.545852
[ "Apache-2.0" ]
HaoLife/Uno.Telerik.UI-For-UWP
Controls/Grid/Grid.UWP/View/RadDataGrid.Manipulation.cs
20,830
C#
namespace WebServer.Server.Controllers { [AttributeUsage(AttributeTargets.Method)] public class AuthorizeAttribute : Attribute { } }
18.75
47
0.726667
[ "MIT" ]
GosuMonkeyManiak/CSharp-Web-Server
WebServer.Server/Controllers/AuthorizeAttribute.cs
152
C#
using System; using Gen8.Ledger.Core.Domain; using CQRSlite.Events; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace Gen8.Ledger.Core.ReadModel.Events { public class AccountDeleted : IEvent { private ObjectId _objectId; [BsonId] public ObjectId ObjectId { get { if (_objectId.ToString().Equals("000000000000000000000000")) _objectId = ObjectId.GenerateNewId(); return _objectId; } set { _objectId = value; } } public Guid Id { get { return new Guid(AggregateId); } set { AggregateId = value.ToString(); } } public string AggregateId {get; set;} public string UserId { get; set; } public int Version { get; set; } public DateTimeOffset TimeStamp { get; set; } public AccountDeleted() {} public AccountDeleted(Guid id, string userId) { Id = id; AggregateId = id.ToString(); UserId = userId; } } }
23.923077
76
0.495177
[ "Apache-2.0" ]
gen8tech/ledger
src/Gen8.Ledger.Core/Domain/ReadModel/Events/AccountDeleted.cs
1,244
C#
using System; using Newtonsoft.Json; using PetfinderNet.Converters; namespace PetfinderNet.Models { /// <summary> /// This class contains information about a pet's /// photograph. /// </summary> [JsonConverter(typeof(PetPhotoConverter))] public class PetPhoto { /// <summary> /// The URL to the photo. /// </summary> public Uri Url { get; set; } /// <summary> /// The size of the photo (width x height). /// </summary> public string Size { get; set; } /// <summary> /// The ID of the photo. /// </summary> public int Id { get; set; } } }
22.333333
53
0.537313
[ "MIT" ]
mongrelpig/Petfinder.NET
PetfinderNet/Models/PetPhoto.cs
672
C#
using System.Collections.Generic; using UnityEngine; public class WeaponComponent : MonoBehaviour { public static List<WeaponComponent> Instances = new List<WeaponComponent>(); public WeaponObjectState State; public WeaponDefinition Definition { get { return WeaponSystem.Instance.GetWeaponDefinitionByType(State.Type); } } public Rigidbody Rigidbody; public Collider Collider; private void Awake() { Instances.Add(this); Rigidbody = GetComponent<Rigidbody>(); Collider = GetComponent<Collider>(); } private void OnCollisionStay(Collision collision) { WeaponSystem.Instance.WeaponOnCollisionStay(this, collision); } private void OnDestroy() { Instances.Remove(this); WeaponSystem.Instance.WeaponOnDestroy(this); } private void LateUpdate() { if (State != null) { State.RigidBodyState = (Rigidbody != null) ? RigidBodyState.FromRigidbody(Rigidbody) : new RigidBodyState(); } } private void ApplyStateFromServer(object newState) { var newWeaponObjectState = (WeaponObjectState)newState; Client.ApplyRigidbodyState( newWeaponObjectState.RigidBodyState, State.RigidBodyState, Rigidbody, OsFps.Instance.Client.ClientPeer.RoundTripTimeInSeconds ?? 0 ); State = newWeaponObjectState; } }
26
80
0.633289
[ "MIT" ]
ColeDeanShepherd/OSFPS
Assets/Scripts/Weapon/WeaponComponent.cs
1,510
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace Kea.BasicWebService.Service { [Route("api/[controller]")] public class TodoController : Controller { private static readonly List<string> Todos = new List<string> { "Do shopping", "Walk the dog", "Be happy", "Praise Satan" }; [HttpGet] public IEnumerable<string> GetAll() { return Todos; } [HttpPost] public IActionResult AddTodo([FromBody] Todo todo) { Todos.Add(todo.Description); return Ok(); } [HttpDelete("{index}")] public IActionResult DeleteTodo(int index) { Todos.RemoveAt(index); return Ok(); } } }
22.025641
69
0.507567
[ "MIT" ]
Group-666/BasicWebService
Kea.BasicWebService/service/Controllers/TodoController.cs
859
C#
namespace SpaceEngineers.Core.Modules.Test.AutoRegistrationTest { using AutoRegistration.Api.Attributes; using AutoRegistration.Api.Enumerations; [Component(EnLifestyle.Transient)] internal class DerivedFromUnregisteredExternalServiceImpl : BaseUnregisteredExternalServiceImpl { } }
30.7
99
0.80456
[ "MIT" ]
warning-explosive/Core
Tests/Modules.Test/AutoRegistrationTest/DerivedFromUnregisteredExternalServiceImpl.cs
307
C#
using System.Text; namespace UIForia.Elements { public class IntFormatter : IInputFormatter { private static StringBuilder builder = new StringBuilder(32); public string Format(string input) { builder.Clear(); bool foundDigit = false; bool foundSign = false; for (int i = 0; i < input.Length; i++) { char c = input[i]; if (!foundDigit && !foundSign && c == '-') { builder.Append(c); foundSign = true; } else if (char.IsDigit(c)) { builder.Append(c); foundDigit = true; } } return builder.ToString(); } } }
24.3125
69
0.455013
[ "MIT" ]
criedel/UIForia
Packages/UIForia/Src/Elements/IntFormatter.cs
778
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using COLID.Graph.Metadata.Constants; using COLID.ReportingService.Common.DataModels; using COLID.ReportingService.FunctionalTests; using Microsoft.VisualBasic; using VDS.RDF; using Xunit; namespace FunctionalTests.Controllers { public class StatisticsControllerTests : IClassFixture<FunctionTestsFixture> { private readonly HttpClient _client; private readonly FunctionTestsFixture _factory; private readonly string _apiPath = "api/statistics"; public StatisticsControllerTests(FunctionTestsFixture factory) { _factory = factory; _client = _factory.CreateClient(); } #region GetTotalNumberOfResources /// <summary> /// Route GET api/statistics/resource/total /// </summary> [Fact] public async Task GetTotalNumberOfResources_Success() { // Act var result = await _client.GetAsync($"{_apiPath}/resource/total"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(content); Assert.Equal("21", actualTestResult); } #endregion #region GetNumberOfProperties // TODO: Error with InMemoryRepository /// <summary> /// Route GET api/statistics/resource/numberofproperties /// </summary> // [Fact] public async Task GetNumberOfProperties_Success() { // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofproperties"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyStatistics>(content); Assert.Equal(2, actualTestResult.Counts.Count); } #endregion #region GetNumberOfControlledVocabularySelection /// <summary> /// Route GET api/statistics/resource/controlledvocabularyselection /// </summary> [Fact] public async Task GetNumberOfControlledVocabularySelection_Success() { // Arrange var cv = HttpUtility.UrlEncode(Resource.HasConsumerGroup); // Act var result = await _client.GetAsync($"{_apiPath}/resource/controlledvocabularyselection?property={cv}"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyStatistics>(content); Assert.Equal(2, actualTestResult.Counts.Count); } /// <summary> /// Route GET api/statistics/resource/controlledvocabularyselection /// </summary> [Theory] [InlineData("format_error")] [InlineData(null)] [InlineData("")] public async Task GetNumberOfControlledVocabularySelection_Error_BadRequest_InvalidUri(string uri) { // Act var result = await _client.GetAsync($"{_apiPath}/resource/controlledvocabularyselection?property={uri}"); // Assert Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode); } #endregion #region GetNumberOfResourcesInRelationToPropertyLength // TODO: Fix Inline data and add resources /// <summary> /// Route GET api/statistics/resource/numberofresourcesinrelationtopropertylength /// </summary> [Theory] [InlineData(1, 1)] [InlineData(2, 1)] [InlineData(5, 1)] [InlineData(10, 1)] public async Task GetNumberOfResourcesInRelationToPropertyLength_Success(int increment, int expectedResults) { // Arrange var cv = HttpUtility.UrlEncode(Resource.HasLabel); // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofresourcesinrelationtopropertylength?property={cv}&increment={increment}"); // Assert //result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyStatistics>(content); Assert.Equal(expectedResults, actualTestResult.Counts.Count); } [Theory] [InlineData(null)] [InlineData(0)] public async Task GetNumberOfResourcesInRelationToPropertyLength_Error_BadRequest_InvalidIncrement(int increment) { // Arrange var cv = HttpUtility.UrlEncode(Resource.HasLabel); // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofresourcesinrelationtopropertylength?property={cv}&increment={increment}"); // Assert Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode); } [Theory] [InlineData("format_error")] [InlineData(null)] [InlineData("")] public async Task GetNumberOfResourcesInRelationToPropertyLength_Error_BadRequest_InvalidPropertyUri(string property) { // Arrange var increment = 1; // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofresourcesinrelationtopropertylength?property={property}&increment={increment}"); // Assert Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode); } [Theory] [InlineData(1, 1)] [InlineData(2, 1)] [InlineData(5, 1)] [InlineData(10, 1)] public async Task GetNumberOfVersionsOfResources_Success(int increment, int expectedResults) { // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofversionsofresources?increment={increment}"); // Assert //result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyStatistics>(content); Assert.Equal(expectedResults, actualTestResult.Counts.Count); } [Theory] [InlineData(null)] [InlineData(0)] public async Task GetNumberOfVersionsOfResources_Error_BadRequest_InvalidIncrement(int increment) { // Arrange var cv = HttpUtility.UrlEncode(Resource.HasLabel); // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofversionsofresources?increment={increment}"); // Assert Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode); } #endregion #region GetNumberOfPropertyUsageByGroupOfResource [Fact] public async Task GetNumberOfPropertyUsageByGroupOfResource_Success() { // Arrange var group = new Uri("http://pid.bayer.com/kos/19050/LinkTypes"); // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofpropertyusagebygroup?group={group}"); // Assert //result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyStatistics>(content); Assert.Equal(2, actualTestResult.Counts.Count); } [Theory] [InlineData(null)] [InlineData("0")] public async Task GetNumberOfPropertyUsageByGroupOfResource_Error_BadRequest_InvalidIncrement(string group) { // Act var result = await _client.GetAsync($"{_apiPath}/resource/numberofpropertyusagebygroup?group={group}"); // Assert Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode); } #endregion #region GetResourceTypeCharacteristics /// <summary> /// Route GET api/statistics/resource/characteristics/type /// </summary> [Fact] public async Task GetResourceTypeCharacteristics_Success() { // Act var result = await _client.GetAsync($"{_apiPath}/resource/characteristics/type"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PropertyCharacteristic>>(content); //Assert.Equal(15, actualTestResult.FirstOrDefault(t => t.Key)); //Assert.Equal(7, ); //Assert.Equal(2, actualTestResult.Count); } #endregion #region GetConsumerGroupCharacteristics /// <summary> /// Route GET api/statistics/resource/characteristics/consumergroup /// </summary> [Fact] public async Task GetConsumerGroupCharacteristics_Success() { // Act var result = await _client.GetAsync($"{_apiPath}/resource/characteristics/consumergroup"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PropertyCharacteristic>>(content); Assert.Equal(2, actualTestResult.Count); } #endregion #region GetInformationClassificationCharacteristics /// <summary> /// Route GET api/statistics/resource/characteristics/informationclassification /// </summary> [Fact] public async Task GetInformationClassificationCharacteristics_Success() { // Act var result = await _client.GetAsync($"{_apiPath}/resource/characteristics/informationclassification"); // Assert result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var actualTestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PropertyCharacteristic>>(content); Assert.Equal(1, actualTestResult.Count); } #endregion } }
36.877133
158
0.639611
[ "BSD-3-Clause" ]
Bayer-Group/COLID-Reporting-Service
tests/FunctionalTests/Controllers/StatisticsControllerTests.cs
10,807
C#
using restwithapsnet.Model; using System; using System.Collections.Generic; namespace restwithapsnet.Business { public interface IBookBusiness { Book Create(Book book); Book FindById(long id); List<Book> FindAll(); Book Update(Book book); void Delete(long id); } }
16.15
34
0.643963
[ "Apache-2.0" ]
felipegith/ASPNET-CORE
Livros/04 restwithapsnet/restwithapsnet/Business/IBookBusiness.cs
325
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("PrintFirstNonNewLine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PrintFirstNonNewLine")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c261a804-9a49-43ba-a637-8e83deee9ed5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.054054
84
0.75071
[ "MIT" ]
LuGeorgiev/CSharpSelfLearning
ConsoleInputOutput/ConsoleInputOutput/PrintFirstNonNewLine/Properties/AssemblyInfo.cs
1,411
C#
// T4 code generation is enabled for model 'C:\Users\Administrator\documents\visual studio 2013\Projects\Store\Master\Model1.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
79
133
0.767089
[ "Unlicense", "MIT" ]
Speak3asy/Store
Master/Model1.Designer.cs
792
C#
using ArkSavegameToolkitNet.Types; using log4net; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO.MemoryMappedFiles; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet { public class ArkArchive { private static ILog _logger = LogManager.GetLogger(typeof(ArkArchive)); private long _position; private long _size; private MemoryMappedViewAccessor _va; private IReadOnlyList<string> _nameTable; private ArkNameCache _arkNameCache; private ArkStringCache _arkStringCache; private ArkNameTree _exclusivePropertyNameTree; public ArkArchive(MemoryMappedViewAccessor va, long size, ArkNameCache arkNameCache = null, ArkStringCache arkStringCache = null, ArkNameTree exclusivePropertyNameTree = null) { _va = va; _size = size; _arkNameCache = arkNameCache ?? new ArkNameCache(); _arkStringCache = arkStringCache ?? new ArkStringCache(); _exclusivePropertyNameTree = exclusivePropertyNameTree; } public ArkArchive(ArkArchive toClone, MemoryMappedViewAccessor va) { _va = va; _size = toClone._size; _nameTable = toClone._nameTable; _arkNameCache = toClone._arkNameCache; _arkStringCache = toClone._arkStringCache; _exclusivePropertyNameTree = toClone._exclusivePropertyNameTree; } public ArkNameTree ExclusivePropertyNameTree => _exclusivePropertyNameTree; public long Position { get { return _position; } set { if (value < 0 || value >= _size) { _logger.Error($"Attempted to set position outside stream bounds (offset: {value:X}, size: {_size:X})"); throw new OverflowException(); } _position = value; } } public long Size => _size; public IReadOnlyList<string> NameTable { get { return _nameTable; } set { if (value != null) _nameTable = new List<string>(value) as IReadOnlyList<string>; else _nameTable = null; } } public ArkName[] GetNames(long position) { var count = GetInt(position); var names = new ArkName[count]; var oldposition = _position; _position = position + 4; for (var i = 0; i < count; i++) names[i] = GetName(); _position = oldposition; return names; } public ArkName GetName(long position) { if (_nameTable == null) { var nameAsString = GetString(position); return _arkNameCache.Create(nameAsString); } else { var id = GetInt(position); if (id < 1 || id > _nameTable.Count) { _logger.Warn($"Found invalid nametable index {id} at {position:X}"); return null; } var nameString = _nameTable[id - 1]; var nameIndex = GetInt(position + 4); return _arkNameCache.Create(nameString, nameIndex); } } public ArkName GetName() { if (_nameTable == null) { var nameAsString = GetString(); return _arkNameCache.Create(nameAsString); } else { var id = GetInt(); if (id < 1 || id > _nameTable.Count) { _logger.Warn($"Found invalid nametable index {id} at {_position - 4:X}"); return null; } var nameString = _nameTable[id - 1]; var nameIndex = GetInt(); return _arkNameCache.Create(nameString, nameIndex); } } public void SkipName() { if (_nameTable == null) { SkipString(); } else { Position += 8; } } public int GetNameLength(long position) { if (_nameTable == null) { var size = GetInt(position); var multibyte = size < 0; var absSize = Math.Abs(size); var readSize = multibyte ? absSize * 2 : absSize; return 4 + readSize; } else return 8; } public string GetString(long position) { var size = GetInt(position); if (size == 0) return string.Empty; var multibyte = size < 0; var absSize = Math.Abs(size); var readSize = multibyte ? absSize * 2 : absSize; if (readSize + position + 4 >= _size) { _logger.Error($"Trying to read {readSize} bytes at {position + 4:X} with just {_size - (position + 4)} bytes left"); throw new OverflowException(); } if (multibyte) { var buffer = new char[absSize]; var count = _va.ReadArray(position + 4, buffer, 0, absSize); var result = new string(buffer, 0, absSize - 1); //return result; return _arkStringCache.Add(result); } else { var buffer = new byte[absSize]; var count = _va.ReadArray(_position + 4, buffer, 0, absSize); //return Encoding.ASCII.GetString(buffer, 0, absSize - 1); return _arkStringCache.Add(Encoding.ASCII.GetString(buffer, 0, absSize - 1)); } } public string GetString() { var size = GetInt(); if (size == 0) return string.Empty; var multibyte = size < 0; var absSize = Math.Abs(size); var readSize = multibyte ? absSize * 2 : absSize; if (readSize + _position >= _size) { _logger.Error($"Trying to read {readSize} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } if (multibyte) { var buffer = new char[absSize]; var count = _va.ReadArray(_position, buffer, 0, absSize); _position += absSize * 2; var result = new string(buffer, 0, absSize - 1); //return result; return _arkStringCache.Add(result); } else { var buffer = new byte[absSize]; var count = _va.ReadArray(_position, buffer, 0, absSize); _position += absSize; //return Encoding.ASCII.GetString(buffer, 0, absSize - 1); return _arkStringCache.Add(Encoding.ASCII.GetString(buffer, 0, absSize - 1)); } } public void SkipString() { var size = GetInt(); var multibyte = size < 0; var absSize = Math.Abs(size); var readSize = multibyte ? absSize * 2 : absSize; if (absSize > 10000) _logger.Info($"Large String ({absSize}) at {_position - 4:X}"); if (readSize + _position > _size) { _logger.Error($"Trying to skip {readSize} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } Position += readSize; } public int GetInt(long position) { const long size = 4; if (position + size > _size) { _logger.Error($"Trying to read {size} bytes at {position:X} with just {_size - position} bytes left"); throw new OverflowException(); } var value = _va.ReadInt32(position); return value; } public int GetInt() { const long size = 4; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadInt32(_position); _position += size; return value; } public sbyte[] GetBytes(int length) { var buffer = new sbyte[length]; if (_position + length > _size) { _logger.Error($"Trying to read {length} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadArray(_position, buffer, 0, length); _position += length; return buffer; } public sbyte GetByte() { const long size = 1; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadSByte(_position); _position += size; return value; } public long GetLong() { const long size = 8; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadInt64(_position); _position += size; return value; } public short GetShort() { const long size = 2; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadInt16(_position); _position += size; return value; } public double GetDouble() { const long size = 8; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadDouble(_position); _position += size; return value; } public float GetFloat() { const long size = 4; if (_position + size > _size) { _logger.Error($"Trying to read {size} bytes at {_position:X} with just {_size - _position} bytes left"); throw new OverflowException(); } var value = _va.ReadSingle(_position); _position += size; return value; } public bool GetBoolean() { var val = GetInt(); if (val < 0 || val > 1) _logger.Warn($"Boolean at {_position:X} with value {val}, returning true."); return val != 0; } } }
30.587467
183
0.496884
[ "MIT" ]
Betrail/ArkSavegameToolkitNet
ArkSavegameToolkitNet/ArkArchive.cs
11,717
C#
using System; using UnityEngine; namespace FMODUnity { [Serializable] public class EmitterRef { public StudioEventEmitter Target; public ParamRef[] Params; } [AddComponentMenu("FMOD Studio/FMOD Studio Parameter Trigger")] public class StudioParameterTrigger: MonoBehaviour { public EmitterRef[] Emitters; public EmitterGameEvent TriggerEvent; public string CollisionTag; void Start() { HandleGameEvent(EmitterGameEvent.ObjectStart); } void OnDestroy() { HandleGameEvent(EmitterGameEvent.ObjectDestroy); } void OnEnable() { HandleGameEvent(EmitterGameEvent.ObjectEnable); } void OnDisable() { HandleGameEvent(EmitterGameEvent.ObjectDisable); } void OnTriggerEnter(Collider other) { if (String.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerEnter); } } void OnTriggerExit(Collider other) { if (String.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerExit); } } void OnTriggerEnter2D(Collider2D other) { if (String.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerEnter2D); } } void OnTriggerExit2D(Collider2D other) { if (String.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag)) { HandleGameEvent(EmitterGameEvent.TriggerExit2D); } } void OnCollisionEnter() { HandleGameEvent(EmitterGameEvent.CollisionEnter); } void OnCollisionExit() { HandleGameEvent(EmitterGameEvent.CollisionExit); } void OnCollisionEnter2D() { HandleGameEvent(EmitterGameEvent.CollisionEnter2D); } void OnCollisionExit2D() { HandleGameEvent(EmitterGameEvent.CollisionExit2D); } void HandleGameEvent(EmitterGameEvent gameEvent) { if (TriggerEvent == gameEvent) { TriggerParameters(); } } public void TriggerParameters() { for (int i = 0; i < Emitters.Length; i++) { var emitterRef = Emitters[i]; if (emitterRef.Target != null) { for (int j = 0; j < Emitters[i].Params.Length; j++) { emitterRef.Target.SetParameter(Emitters[i].Params[j].Name, Emitters[i].Params[j].Value); } } } } } }
26.146552
112
0.532476
[ "MIT" ]
BlueMonk1107/MySiri
Assets/Plugins/AudioStream/FMOD/FMOD/StudioParameterTrigger.cs
3,035
C#
using Fusee.Math.Core; using System.Collections.Generic; using Xunit; namespace Fusee.Tests.Math.Core { public class OBBTest { private const int fPrecision = 4; private const int dPrecision = 6; [Theory] [MemberData(nameof(OBBfData))] public void ConstructorSingle_MinMax(float3[] vertices, float3 min, float3 max) { var actual = new OBBf(vertices); for (var i = 0; i < 3; i++) { Assert.Equal(min[i], actual.Min[i], fPrecision); Assert.Equal(max[i], actual.Max[i], fPrecision); } } [Theory] [MemberData(nameof(OBBdData))] public void ConstructorDouble_MinMax(double3[] vertices, double3 min, double3 max) { var actual = new OBBd(vertices); for (var i = 0; i < 3; i++) { Assert.Equal(min[i], actual.Min[i], dPrecision); Assert.Equal(max[i], actual.Max[i], dPrecision); } } public static IEnumerable<object[]> OBBfData() { yield return new object[] { new float3[] { new float3(float.NaN, float.NaN, float.NaN), }, new float3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity), new float3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), }; yield return new object[] { new float3[] { new float3(0, 0, 0), new float3(0.25f, 0.25f, 0.25f), new float3(0.5f, 0.5f, 0.5f), new float3(0.75f, 0.75f, 0.75f), new float3(1.25f, 1.25f, 1.25f), new float3(1.5f, 1.5f, 1.5f), new float3(1.75f, 1.75f, 1.75f), new float3(2, 2, 2), }, new float3(0, 0, 0), new float3(2, 2, 2) }; yield return new object[] { new float3[] { new float3(-5, -5, -5), new float3(-0.25f, -0.25f, -0.25f), new float3(-0.5f, -0.5f, -0.5f), new float3(0.75f, 0.75f, 0.75f), new float3(1.25f, 1.25f, 1.25f), new float3(1.5f, 1.5f, 1.5f), new float3(1.75f, 1.75f, 1.75f), new float3(15, 15, 15), }, new float3(-5, -5, -5), new float3(15, 15, 15) }; yield return new object[] { new float3[] { new float3(0, 0, 0) }, new float3(0, 0, 0), new float3(0, 0, 0) }; yield return new object[] { new float3[] { new float3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity), new float3(0.25f, 0.25f, 0.25f), new float3(0.5f, 0.5f, 0.5f), new float3(0.75f, 0.75f, 0.75f), new float3(1.25f, 1.25f, 1.25f), new float3(1.5f, 1.5f, 1.5f), new float3(1.75f, 1.75f, 1.75f), new float3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), }, new float3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity), new float3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), }; } public static IEnumerable<object[]> OBBdData() { yield return new object[] { new double3[] { new double3(double.NaN, double.NaN, double.NaN), }, new double3(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity), new double3(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity), }; yield return new object[] { new double3[] { new double3(0, 0, 0), new double3(0.25f, 0.25f, 0.25f), new double3(0.5f, 0.5f, 0.5f), new double3(0.75f, 0.75f, 0.75f), new double3(1.25f, 1.25f, 1.25f), new double3(1.5f, 1.5f, 1.5f), new double3(1.75f, 1.75f, 1.75f), new double3(2, 2, 2), }, new double3(0, 0, 0), new double3(2, 2, 2) }; yield return new object[] { new double3[] { new double3(-5, -5, -5), new double3(-0.25f, -0.25f, -0.25f), new double3(-0.5f, -0.5f, -0.5f), new double3(0.75f, 0.75f, 0.75f), new double3(1.25f, 1.25f, 1.25f), new double3(1.5f, 1.5f, 1.5f), new double3(1.75f, 1.75f, 1.75f), new double3(15, 15, 15), }, new double3(-5, -5, -5), new double3(15, 15, 15) }; yield return new object[] { new double3[] { new double3(0, 0, 0) }, new double3(0, 0, 0), new double3(0, 0, 0) }; yield return new object[] { new double3[] { new double3(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity), new double3(0.25f, 0.25f, 0.25f), new double3(0.5f, 0.5f, 0.5f), new double3(0.75f, 0.75f, 0.75f), new double3(1.25f, 1.25f, 1.25f), new double3(1.5f, 1.5f, 1.5f), new double3(1.75f, 1.75f, 1.75f), new double3(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity), }, new double3(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity), new double3(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity), }; } } }
35.470899
107
0.434218
[ "BSD-2-Clause", "MIT" ]
ASPePeX/Fusee
src/Tests/Math/Core/OBBTest.cs
6,706
C#
// using System; // using System.Collections.Generic; // using System.Linq.Expressions; // using System.Threading.Tasks; // using Order.Domain.DomainSpecifications; // // namespace Order.Domain.Repositories // { // public interface IDomainReadModelRepository<T> // { // Task Upsert(T entity); // Task<List<T>> DomainFilter(Specification<T> filter); // Task<List<T>> Filter(Expression<Func<T, bool>> expression); // Task<T> Get(Expression<Func<T, bool>> expression); // } // }
32.5
70
0.653846
[ "MIT" ]
MrBugra/EventSourcing.Order
Order.Domain/Repositories/IDomainReadModelRepository.cs
522
C#
using System; using System.Collections.Generic; using System.Linq; using Massive; namespace Oak.Tests.describe_DynamicModels.Classes { public class Market : DynamicModel { Suppliers suppliers = new Suppliers(); SupplyChains supplyChains = new SupplyChains(); public Market(object dto) : base(dto) { } IEnumerable<dynamic> Associates() { yield return new HasMany(supplyChains); yield return new HasManyThrough(suppliers, supplyChains); } } }
20.666667
69
0.625448
[ "MIT" ]
amirrajan/Oak
Oak.Tests/describe_DynamicModels/Classes/Market.cs
558
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using PnP.Core.Model.SharePoint; namespace PnP.Core.Test.SharePoint { [TestClass] public class ListMetaDataMapperTests { [ClassInitialize] public static void TestFixtureSetup(TestContext context) { // Configure mocking default for all tests in this class, unless override by a specific test //TestCommon.Instance.Mocking = false; } [TestMethod] public void ListTypeTest() { // Library types Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.DocumentLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.WebPageLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.XMLForm)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.PictureLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.DataConnectionLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.HelpLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.HomePageLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.MySiteDocumentLibrary)); Assert.IsTrue(ListMetaDataMapper.IsLibrary(ListTemplateType.SharingLinks)); Assert.IsTrue(ListMetaDataMapper.IsLibrary((ListTemplateType)10102)); Assert.IsTrue(ListMetaDataMapper.IsLibrary((ListTemplateType)3300)); // Catalogs Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.AppDataCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.AppFilesCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.DesignCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.ListTemplateCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.MasterPageCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.MaintenanceLogs)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.SolutionCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.ThemeCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.WebPartCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.WebTemplateCatalog)); Assert.IsTrue(ListMetaDataMapper.IsCatalog(ListTemplateType.NoCodePublic)); // Lists Assert.IsTrue(ListMetaDataMapper.IsList(ListTemplateType.GenericList)); Assert.IsTrue(ListMetaDataMapper.IsList(ListTemplateType.Survey)); Assert.IsTrue(ListMetaDataMapper.IsList(ListTemplateType.Links)); } [TestMethod] public void RestEntityToServerRelativeUrlTest() { Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/lists/Demo", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "DemoList", ListTemplateType.GenericList)); Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/lists/199f4c089b2a87472ebd357031a7c11be9threadtacv2_wiki", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "199f4c089b2a87472ebd357031a7c11be9threadtacv2_x005f_wikiList", ListTemplateType.GenericList)); Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/_catalogs/design", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "OData__x005f_catalogs_x002f_design", ListTemplateType.DesignCatalog)); Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/lists/ContentTypeSyncLog", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "ContentTypeSyncLogList", ListTemplateType.GenericList)); Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/Shared Documents", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "Shared_x0020_Documents", ListTemplateType.DocumentLibrary)); Assert.AreEqual("https://contoso.sharepoint.com/sites/siteA/_catalogs/users", ListMetaDataMapper.RestEntityTypeNameToUrl(new System.Uri("https://contoso.sharepoint.com/sites/siteA"), "UserInfo", ListTemplateType.UserInformation)); } [TestMethod] public void GraphNameToRestEntityTest() { Assert.AreEqual("DemoList", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("Demo", ListTemplateType.GenericList)); Assert.AreEqual("199f4c089b2a87472ebd357031a7c11be9threadtacv2_x005f_wikiList", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("199f4c089b2a87472ebd357031a7c11be9threadtacv2_wiki", ListTemplateType.GenericList)); Assert.AreEqual("OData__x005f_catalogs_x002f_design", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("design", ListTemplateType.DesignCatalog)); Assert.AreEqual("ContentTypeSyncLogList", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("ContentTypeSyncLog", ListTemplateType.GenericList)); Assert.AreEqual("Shared_x0020_Documents", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("Shared Documents", ListTemplateType.DocumentLibrary)); Assert.AreEqual("UserInfo", ListMetaDataMapper.MicrosoftGraphNameToRestEntityTypeName("users", ListTemplateType.UserInformation)); } } }
66.744186
235
0.746341
[ "MIT" ]
PaoloPia/pnpcore
src/sdk/PnP.Core.Test/SharePoint/ListMetaDataMapperTests.cs
5,742
C#
using System.Web.Mvc; using V308CMS.Admin.Attributes; using V308CMS.Admin.Helpers; using V308CMS.Admin.Models; using V308CMS.Common; using V308CMS.Data.Enum; namespace V308CMS.Admin.Controllers { [Authorize] [CheckGroupPermission(true, "Đơn vị tính")] public class ProductUnitController:BaseController { [CheckPermission(0, "Danh sách")] public ActionResult Index() { return View("Index", UnitService.GetAll()); } [CheckPermission(1, "Thêm mới")] public ActionResult Create() { ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Create", new ProductUnitModels()); } [HttpPost] [CheckPermission(1, "Thêm mới")] [ActionName("Create")] [ValidateAntiForgeryToken] public ActionResult OnCreate(ProductUnitModels unit) { if (ModelState.IsValid) { var result = UnitService.Insert ( unit.Name, unit.CreatedAt, unit.UpdatedAt, unit.State ); if (result == Result.Exists) { ModelState.AddModelError("", string.Format("Đơn vị tính '{0}' đã tồn tại trên hệ thống.",unit.Name)); ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Create", unit); } SetFlashMessage( string.Format("Thêm đơn vị tính '{0}' thành công.",unit.Name) ); if (unit.SaveList) { return RedirectToAction("Index"); } ModelState.Clear(); ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Create", unit.ResetValue()); } ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Create", unit); } [CheckPermission(2, "Sửa")] public ActionResult Edit(int id) { var unit = UnitService.Find(id); if (unit == null) { return RedirectToAction("Index"); } ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); var data = new ProductUnitModels { Id = unit.Id, Name = unit.Name, State = unit.State }; return View("Edit", data); } [HttpPost] [CheckPermission(2, "Sửa")] [ActionName("Edit")] [ValidateAntiForgeryToken] public ActionResult OnEdit(ProductUnitModels unit) { if (ModelState.IsValid) { var result = UnitService.Update( unit.Id, unit.Name, unit.CreatedAt, unit.UpdatedAt, unit.State); if (result == Result.NotExists) { ModelState.AddModelError("", "Id không tồn tại trên hệ thống."); ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Edit", unit); } SetFlashMessage(string.Format("Cập nhật Đơn vị tính '{0}' thành công.", unit.Name)); if (unit.SaveList) { return RedirectToAction("Index"); } ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Edit", unit); } ViewBag.ListState = DataHelper.ListEnumType<StateEnum>(); return View("Edit", unit); } [HttpPost] [CheckPermission(3, "Xóa")] [ActionName("Delete")] public ActionResult OnDelete(int id) { var result = UnitService.Delete(id); SetFlashMessage(result == Result.Ok ? "Xóa đơn vị tính thành công." : "Đơn vị tính không tồn tại trên hệ thống."); return RedirectToAction("Index"); } } }
34.885246
121
0.492246
[ "Unlicense" ]
giaiphapictcom/mamoo.vn
V308CMS.Admin/Controllers/ProductUnitController.cs
4,343
C#
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ using System.Net; using com.facebook.witai.lib; using TMPro; using UnityEngine; namespace com.facebook.witai.samples.responsedebugger { public class WitUIInteractionHandler : MonoBehaviour { [Header("Wit")] [SerializeField] private Wit wit; [Header("UI")] [SerializeField] private TMP_InputField inputField; [SerializeField] private TextMeshProUGUI textArea; [Header("Configuration")] [SerializeField] private bool showJson; private string pendingText; private void OnValidate() { if (!wit) wit = FindObjectOfType<Wit>(); } private void Update() { if (null != pendingText) { textArea.text = pendingText; pendingText = null; } } private void OnEnable() { wit.events.OnRequestCreated.AddListener(OnRequestStarted); } private void OnDisable() { wit.events.OnRequestCreated.RemoveListener(OnRequestStarted); } private void OnRequestStarted(WitRequest request) { // The raw response comes back on a different thread. We store the // message received for display on the next frame. if (showJson) request.onRawResponse += (response) => pendingText = response; request.onResponse += (r) => { if (r.StatusCode == (int) HttpStatusCode.OK) { OnResponse(r.ResponseData); } else { OnError($"Error {r.StatusCode}", r.StatusDescription); } }; } public void OnResponse(WitResponseNode response) { if (!showJson) textArea.text = response["text"]; } public void OnError(string error, string message) { textArea.text = $"Error: {error}\n\n{message}"; } public void ToggleActivation() { if (wit.Active) wit.Deactivate(); else { textArea.text = "The mic is active, start speaking now."; wit.Activate(); } } public void Send() { textArea.text = $"Sending \"{inputField.text}\" to Wit.ai for processing..."; wit.Activate(inputField.text); } public void LogResults(string[] parameters) { Debug.Log("Got the following entities back: " + string.Join(", ", parameters)); } } }
27.881188
91
0.537287
[ "BSD-2-Clause" ]
MIShanto/Golpokotha
Assets/Samples/ResponseDebugger/Scripts/WitUIInteractionHandler.cs
2,818
C#
using System; using System.Windows.Forms; using System.IO; using WMPLib; using System.Media; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } CtrlGame ctrg = new CtrlGame(); Pipe pipe = new Pipe(); Coins coins = new Coins(); HighScoreInfo highScore = new HighScoreInfo(); int iChooseBG = 1; int iSpeed = 1; Rocket rocket = new Rocket(); Gift gift = new Gift(); Bird bird = new Bird(); Heart heart = new Heart(); LifeSpan lifeSpan = new LifeSpan(); Timer timer_Bird = new Timer(); Timer timer2 = new Timer(); int speedOfGame; private void Form2_Load(object sender, EventArgs e) { // add coins this.Controls.Add(coins.picBoxCoins); // add heart this.Controls.Add(heart.picBoxHearts); //// add rocket this.Controls.Add(rocket.picBoxEmergency); this.Controls.Add(rocket.picBoxFire); // add gift this.Controls.Add(gift.picBoxGift); this.Controls.Add(gift.picBoxThunder); pipe.DrawPipe(this, pipe); ////items.DrawCoins(); timer_Bird.Interval = 25; timer_Bird.Tick += Timer_Bird_Tick; timer2.Interval = 70; timer2.Tick += Timer2_Tick; } private void Form2_Paint(object sender, PaintEventArgs e) { /////////////////////// NEW VERSION//// // draw pipe if (pipe.pipe_Above1_Appearance) { pipe.Draw_Pipe_Above_1(e.Graphics); } if (pipe.pipe_Bottom1_Appearance) { pipe.Draw_Pipe_Bottom_1(e.Graphics); } if (pipe.pipe_Above2_Appearance) { pipe.Draw_Pipe_Above_2(e.Graphics); } if (pipe.pipe_Bottom2_Appearance) { pipe.Draw_Pipe_Bottom_2(e.Graphics); } // draw rocket if (rocket.rocket_Apearance) { rocket.Draw_Rocket(e.Graphics); } // draw bird if (bird.bird_Appearance) { bird.Draw(e.Graphics); } // life_span if (lifeSpan.life_Span1_Appearance) { lifeSpan.Draw_Heart_1(e.Graphics); } if (lifeSpan.life_Span2_Appearance) { lifeSpan.Draw_Heart_2(e.Graphics); } if (lifeSpan.life_Span3_Appearance) { lifeSpan.Draw_Heart_3(e.Graphics); } // draw shield if (lifeSpan.shield_Apearance) { lifeSpan.Draw_Shield(e.Graphics); } } private void Timer_Bird_Tick(object sender, EventArgs e) { bird.Impact_Bird_pipe(this, pipe, rocket, gift, lifeSpan, timer1, timer2, ctrg, ga); Invalidate(); } private void timer1_Tick(object sender, EventArgs e) { this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); /////////////////////// NEW VERSION//// /// //pipe if (iSpeed == 1) { speedOfGame = 5; pipe.PipeInGame(this, pipe, bird, speedOfGame); rocket.RocketInGame(bird, speedOfGame); gift.GiftInGame(bird,speedOfGame); heart.HeartsInGame(bird, speedOfGame); coins.CoinsInGame(bird, speedOfGame); } else if (iSpeed == 2) { speedOfGame = 7; pipe.PipeInGame(this, pipe, bird, speedOfGame); rocket.RocketInGame(bird, speedOfGame); gift.GiftInGame(bird, speedOfGame); heart.HeartsInGame(bird, speedOfGame); coins.CoinsInGame(bird, speedOfGame); } else if (iSpeed == 3) { speedOfGame = 10; pipe.PipeInGame(this, pipe, bird, speedOfGame); rocket.RocketInGame(bird, speedOfGame); gift.GiftInGame(bird, speedOfGame); heart.HeartsInGame(bird, speedOfGame); coins.CoinsInGame(bird, speedOfGame); } //// coins coins.GetCoins(this, bird, pipe); coins.Impact_Coins_Bird(bird); //// hearts heart.GetHearts(this, bird, pipe); heart.Impact_Hearts_Bird(bird); /// lifespan lifeSpan.DrawLifeSpan(); if (heart.sign_getHearts) { lifeSpan.Increase(heart); //heart.sign_getHearts = false; } // shield character if (lifeSpan.GetCount() == 1) { lifeSpan.shield_Apearance = false; } if (lifeSpan.GetCount() > 1) { lifeSpan.SetVisibleOn(bird); } lifeSpan.Impact_Shield_Rocket(rocket, bird); lifeSpan.Impact_Shield_Pipes(pipe, bird, heart); if (heart.sign_decreaseHearts) { lifeSpan.Decrease(heart); } // rocket rocket.GetRocket(this, bird, pipe); rocket.Impact_Rocket_Bird(bird, gift, lifeSpan, timer_Bird, timer1); rocket.InvisibleEmergency(this); //Gift gift.GetGift(this, pipe); gift.Impact_Gift_Bird(bird, timer1, timer_Bird, timer2); Invalidate(); // bird bird.GetScore(pipe, label1); highScore.HighScore(); } private void Timer2_Tick(object sender, EventArgs e) { gift.count_Flash++; } private void btt_Menu_Click(object sender, EventArgs e) { ctrg.MainScreenOff(btt_Play, btt_Menu, pB_IntroBird); ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); } private void btt_Play_Click(object sender, EventArgs e) { ctrg.MainScreenOff(btt_Play, btt_Menu, pB_IntroBird); bird.bird_Appearance = true; ctrg.SoundStartGame(); timer1.Start(); timer_Bird.Start(); label1.Visible = true; } private void btt_speed_Click(object sender, EventArgs e) { ctrg.MenuOff(btt_scene, btt_speed, btt_item, btt_Back); ctrg.SubMenuOn(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); } private void btt_Back_Click(object sender, EventArgs e) { if (ctrg.Check(btt_item, rebirdPictureBox) == 1) { ctrg.MainScreenOn(btt_Play, btt_Menu); ctrg.SubMenuOff(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); ctrg.MenuOff(btt_scene, btt_speed, btt_item, btt_Back); pl_BgMenu.Visible = false; } else { ctrg.SubMenuOff(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); pl_BgMenu.Visible = true; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); } } private void btt_SpeedHard_Click(object sender, EventArgs e) { iSpeed = 3; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); } private void btt_SpeedEasy_Click(object sender, EventArgs e) { iSpeed = 1; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); } private void btt_SpeedMedium_Click(object sender, EventArgs e) { iSpeed = 2; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_SpeedEasy, btt_SpeedHard, btt_SpeedMedium); } private void Form2_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Space) { if (bird.isAlive) { bird.Move_Bird_Up(); } } if (e.KeyCode == Keys.Space) e.Handled = true; } private void btt_item_Click(object sender, EventArgs e) { ctrg.MenuOff(btt_scene, btt_speed, btt_item, btt_Back); ctrg.SubMenuOn(yebirdPictureBox, blbirdPictureBox, rebirdPictureBox); } private void yebirdPictureBox_Click(object sender, EventArgs e) { bird.index_bird = 1; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(yebirdPictureBox, blbirdPictureBox, rebirdPictureBox); } private void blbirdPictureBox_Click(object sender, EventArgs e) { bird.index_bird = 2; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(yebirdPictureBox, blbirdPictureBox, rebirdPictureBox); } private void rebirdPictureBox_Click(object sender, EventArgs e) { bird.index_bird = 3; ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(yebirdPictureBox, blbirdPictureBox, rebirdPictureBox); } private void btt_scene_Click(object sender, EventArgs e) { ctrg.MenuOff(btt_scene, btt_speed, btt_item, btt_Back); ctrg.SubMenuOn(btt_scenceChrist, btt_scenceHallow, btt_scenceOrigin); } // Form1 F = new Form1(); public bool buttonOriWasClicked = false; private void btt_scenceOrigin_Click(object sender, EventArgs e) { buttonOriWasClicked = true; if (buttonHaloWasClicked == true || buttonChristWasClicked == true) { buttonOriWasClicked = false; } iChooseBG = 1; // Properties.Settings.Default // ctrg.ChooseBgGameForm1(1, F); //Form1.BackgroundImage = Properties.Resources.ori_bg; //F.pictureBox1.BackgroundImage = Properties.Resources.ori_logo; // F.panel1.BackgroundImage = Properties.Resources.ori_fame; Properties.Settings.Default.Bg = iChooseBG.ToString(); Properties.Settings.Default.Save(); ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_scenceOrigin, btt_scenceHallow, btt_scenceChrist); btt_Play.BackgroundImage = Properties.Resources.btt_ori; btt_Play.OnHoverImage = Properties.Resources.btt_ori; btt_Play.Size = new System.Drawing.Size(150, 60); btt_Play.ImageSize = new System.Drawing.Size(151, 63); btt_Play.Location = new System.Drawing.Point(124, 225); btt_scene.OnHoverImage = Properties.Resources.season_ori; btt_scene.BackgroundImage = Properties.Resources.season_ori; btt_speed.OnHoverImage = Properties.Resources.speed_ori; btt_speed.BackgroundImage = Properties.Resources.speed_ori; btt_item.OnHoverImage = Properties.Resources.item_ori; btt_item.BackgroundImage = Properties.Resources.item_ori; btt_Menu.OnHoverImage = Properties.Resources.menu_ori; btt_Menu.BackgroundImage = Properties.Resources.menu_ori; ctrg.ChooseBgGame(iChooseBG, this); } public bool buttonChristWasClicked = false; private void btt_scenceChrist_Click(object sender, EventArgs e) { buttonChristWasClicked = true; // if (buttonHaloWasClicked == true || buttonOriWasClicked == true) // { //buttonChristWasClicked = false; // } iChooseBG = 2; Properties.Settings.Default.Bg = iChooseBG.ToString(); Properties.Settings.Default.Save(); ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_scenceOrigin, btt_scenceHallow, btt_scenceChrist); btt_Play.BackgroundImage = Properties.Resources.play_christ; btt_Play.OnHoverImage = Properties.Resources.play_christ; btt_Play.Size = new System.Drawing.Size(135, 60); btt_Play.ImageSize = new System.Drawing.Size(138, 61); btt_Play.Location = new System.Drawing.Point(130, 225); btt_scene.OnHoverImage = Properties.Resources.season_christ; btt_scene.BackgroundImage = Properties.Resources.season_christ; btt_speed.OnHoverImage = Properties.Resources.speed_christ; btt_speed.BackgroundImage = Properties.Resources.speed_christ; btt_item.OnHoverImage = Properties.Resources.item_christ; btt_item.BackgroundImage = Properties.Resources.item_christ; btt_Menu.OnHoverImage = Properties.Resources.menu_christ; btt_Menu.BackgroundImage = Properties.Resources.menu_christ; ctrg.ChooseBgGame(iChooseBG, this); } public bool buttonHaloWasClicked = false; private void btt_scenceHallow_Click(object sender, EventArgs e) { buttonHaloWasClicked = true; // if (buttonOriWasClicked == true || buttonOriWasClicked == true) // { // buttonHaloWasClicked = false; // } iChooseBG = 3; Properties.Settings.Default.Bg = iChooseBG.ToString(); Properties.Settings.Default.Save(); ctrg.MenuOn(pB_IntroBird, btt_scene, btt_speed, btt_item, pl_BgMenu, btt_Back); ctrg.SubMenuOff(btt_scenceOrigin, btt_scenceHallow, btt_scenceChrist); btt_Play.BackgroundImage = Properties.Resources.pl; btt_Play.OnHoverImage = Properties.Resources.pl; btt_Play.Size = new System.Drawing.Size(153, 67); btt_Play.ImageSize = new System.Drawing.Size(158, 69); btt_Play.Location = new System.Drawing.Point(124, 225); btt_scene.OnHoverImage = Properties.Resources.season_hallow; btt_scene.BackgroundImage = Properties.Resources.season_hallow; btt_speed.OnHoverImage = Properties.Resources.speed_hallow; btt_speed.BackgroundImage = Properties.Resources.speed_hallow; btt_item.OnHoverImage = Properties.Resources.item_hallow; btt_item.BackgroundImage = Properties.Resources.item_hallow; btt_Menu.OnHoverImage = Properties.Resources.menu_hallow; btt_Menu.BackgroundImage = Properties.Resources.menu_hallow; ctrg.ChooseBgGame(iChooseBG, this); } private void pictureBox1_Click(object sender, EventArgs e) { } } }
30.287619
96
0.561285
[ "MIT", "Unlicense" ]
LucasTran-tq/FlappyBirdPremium
FLAPPYBIRD_FINAL VERSION 2.0/FBgame-Final Version/FBgame/WindowsFormsApplication1/Form2.cs
15,903
C#
using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace GiftModels.Test { [TestClass] public class ModelTests { private readonly string _content = File.ReadAllText("GiftExample.json"); [TestMethod] public void Deserialize() { var giftdetail = JsonConvert.DeserializeObject<GiftDetails>(_content); Assert.IsNotNull(giftdetail); Assert.AreEqual("123456789", giftdetail.PrimaryDonor.Detail.IdNumber); } [TestMethod] public void Serialize() { var giftdetail = JsonConvert.DeserializeObject<GiftDetails>(_content); var result = JsonConvert.SerializeObject(giftdetail); Assert.IsNotNull(result); Assert.IsTrue(result.Length > 0); } } }
26.878788
83
0.614431
[ "MIT" ]
ucdavis/GiftModels
GiftModels.Test/ModelTests.cs
889
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Windows.Input; namespace Microsoft.Test.Stability.Extensions.Actions { public class KeyboardCombinationPressAction : SimpleDiscoverableAction { #region Public Members public Key RandomKey { get; set; } public bool IsCtrl { get; set; } public bool IsAlt { get; set; } public bool IsShift { get; set; } #endregion #region Override Members public override void Perform() { if (IsKeyCombinationOkay(RandomKey, IsCtrl, IsAlt, IsShift)) { List<Key> allKeys = new List<Key>(); if (IsCtrl) { allKeys.Add(Key.LeftCtrl); } if (IsAlt) { allKeys.Add(Key.LeftAlt); } if (IsShift) { allKeys.Add(Key.LeftShift); } allKeys.Add(RandomKey); HomelessTestHelpers.KeyPress(allKeys); } } #endregion #region Private Data /// <summary> /// Returns false if key is Control, Alt, Shift, Win or Menu key, or /// if combination is CTRL+ALT+DEL, or /// if combination is ALT+TAB, or /// if combination is SHIFT+CTRL+TAB. /// Note: maybe we have to avoid other combinations. /// </summary> private bool IsKeyCombinationOkay(Key randomByte, bool isCtrl, bool isAlt, bool isShift) { return (randomByte != Key.LeftCtrl && randomByte != Key.RightCtrl && randomByte != Key.LeftAlt && randomByte != Key.RightAlt && randomByte != Key.LeftShift && randomByte != Key.RightShift && randomByte != Key.LWin && randomByte != Key.RWin && randomByte != Key.LaunchApplication1 && randomByte != Key.LaunchApplication2 && randomByte != Key.SelectMedia && randomByte != Key.LaunchMail && randomByte != Key.Apps) && !(randomByte == Key.P && isCtrl && !isAlt && !isShift) && //CTRL+P !(randomByte == Key.Delete && isCtrl && isAlt && !isShift) && //CTRL+ALT+DEL !(randomByte == Key.Escape && isCtrl && !isAlt && isShift) && //CTRL+SHIFT+ESC = Launch Task Manager !(randomByte == Key.F4 && !isCtrl && isAlt && !isShift) && //ALT+F4 = Close Window !(randomByte == Key.F3 && !isCtrl && !isAlt && !isShift) && //F3 = Launch Search !(randomByte == Key.M && isCtrl && isAlt && !isShift) && //CTRL+ALT+M = MSN Desktop Search !(randomByte == Key.Escape && isCtrl && !isAlt && !isShift) && //CTRL+ESC = Start Menu !(randomByte == Key.Escape && !isCtrl && isAlt) && //ALT(+SHIFT)+ESC = Send window to bottom/top z-order !(randomByte == Key.Tab && !isCtrl && isAlt) && //ALT+TAB = Shift Windows !(randomByte == Key.F10 && isShift) && //SHIFT+F10 = Show Context Menu !(randomByte == Key.Space && !isCtrl && isAlt && !isShift) && //ALT+SPACE = Open System Menu !(randomByte == Key.Tab && isCtrl && !isAlt && isShift); //CTRL+SHIFT+TAB = Shift Windows } #endregion } }
42.4
124
0.529967
[ "MIT" ]
batzen/wpf-test
src/Test/Common/Code/Microsoft/Test/Stability/Extensions/Actions/KeyboardCombinationPressAction.cs
3,606
C#
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sheng.SIMBE.Core.Entity; using Sheng.SIMBE.Core; using Sheng.SIMBE.Core.Event; using Sheng.SIMBE.IDE.EventDev; namespace Sheng.SailingEase.Components.NavigationComponent { class ToolStripSeparatorEntityDev : ToolStripSeparatorEntity, IFormElementEntityDev { public ToolStripSeparatorEntityDev() { base.EventTypesAdapter = EventDevTypes.Instance; } public System.ComponentModel.IComponent Component { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Type DesignerControlType { get { return typeof(Sheng.SIMBE.IDE.ShellControl.SEToolStripSeparatorDev); } } } }
28.45
89
0.551845
[ "MIT" ]
ckalvin-hub/Sheng.Winform.IDE
SourceCode/Source/Components/Components.Navigation/Entity/ToolStripSeparatorEntityDev.cs
1,186
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.DigitalTwins.Latest { /// <summary> /// The private endpoint connection of a Digital Twin. /// Latest API Version: 2020-12-01. /// </summary> [Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:digitaltwins:PrivateEndpointConnection'.")] [AzureNativeResourceType("azure-native:digitaltwins/latest:PrivateEndpointConnection")] public partial class PrivateEndpointConnection : Pulumi.CustomResource { /// <summary> /// The resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("properties")] public Output<Outputs.PrivateEndpointConnectionResponseProperties> Properties { get; private set; } = null!; /// <summary> /// The resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a PrivateEndpointConnection resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public PrivateEndpointConnection(string name, PrivateEndpointConnectionArgs args, CustomResourceOptions? options = null) : base("azure-native:digitaltwins/latest:PrivateEndpointConnection", name, args ?? new PrivateEndpointConnectionArgs(), MakeResourceOptions(options, "")) { } private PrivateEndpointConnection(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:digitaltwins/latest:PrivateEndpointConnection", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:digitaltwins/latest:PrivateEndpointConnection"}, new Pulumi.Alias { Type = "azure-native:digitaltwins:PrivateEndpointConnection"}, new Pulumi.Alias { Type = "azure-nextgen:digitaltwins:PrivateEndpointConnection"}, new Pulumi.Alias { Type = "azure-native:digitaltwins/v20201201:PrivateEndpointConnection"}, new Pulumi.Alias { Type = "azure-nextgen:digitaltwins/v20201201:PrivateEndpointConnection"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing PrivateEndpointConnection resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static PrivateEndpointConnection Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new PrivateEndpointConnection(name, id, options); } } public sealed class PrivateEndpointConnectionArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the private endpoint connection. /// </summary> [Input("privateEndpointConnectionName")] public Input<string>? PrivateEndpointConnectionName { get; set; } [Input("properties", required: true)] public Input<Inputs.PrivateEndpointConnectionPropertiesArgs> Properties { get; set; } = null!; /// <summary> /// The name of the resource group that contains the DigitalTwinsInstance. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the DigitalTwinsInstance. /// </summary> [Input("resourceName", required: true)] public Input<string> ResourceName { get; set; } = null!; public PrivateEndpointConnectionArgs() { } } }
45.008772
165
0.641006
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DigitalTwins/Latest/PrivateEndpointConnection.cs
5,131
C#
using System; using System.Windows.Input; namespace DelSole.MVVMSpecial.Helpers { /// <summary> /// Generic RelayCommand class. /// </summary> /// <typeparam name="T"></typeparam> public class RelayCommand<T> : ICommand { /// <summary> /// The execute /// </summary> private readonly Action<T> _execute; /// <summary> /// The can execute /// </summary> private readonly Predicate<T> _canExecute; /// <summary> /// Initializes a new instance of the <see cref="RelayCommand{T}" /> class. /// </summary> /// <param name="execute">The execute action.</param> /// <exception cref="System.ArgumentNullException">execute</exception> public RelayCommand(Action<T> execute) : this(execute, null) { } /// <summary> /// Initializes a new instance of the <see cref="RelayCommand{T}" /> class. /// </summary> /// <param name="execute">The execute.</param> /// <param name="canExecute">The can execute predicate.</param> /// <exception cref="System.ArgumentNullException">execute</exception> public RelayCommand(Action<T> execute, Predicate<T> canExecute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); if (canExecute != null) { _canExecute = canExecute; } } /// <summary> /// Occurs when changes occur that affect whether the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Raise <see cref="RelayCommand{T}.CanExecuteChanged" /> event. /// </summary> public void RaiseCanExecuteChanged() { var handler = CanExecuteChanged; handler?.Invoke(this, EventArgs.Empty); } /// <summary> /// Determines whether this instance can execute the specified parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <returns><c>true</c> if this instance can execute the specified parameter; otherwise, <c>false</c>.</returns> public bool CanExecute(object parameter) { return _canExecute == null || _canExecute.Invoke((T)parameter); } /// <summary> /// Executes the specified parameter. /// </summary> /// <param name="parameter">The parameter.</param> public virtual void Execute(object parameter) { if (CanExecute(parameter)) { _execute((T)parameter); } } } }
32.855422
121
0.559956
[ "Apache-2.0" ]
AlessandroDelSole/DelSole.MVVMSpecial
DelSole.MVVMSpecial/Helpers/RelayCommandT.cs
2,729
C#
using Facebook.Yoga; using ReactNative.Bridge; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Text; using System; #if WINDOWS_UWP using Windows.Foundation; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Media; #else using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; #endif namespace ReactNative.Views.TextInput { /// <summary> /// This extension of <see cref="LayoutShadowNode"/> is responsible for /// measuring the layout for Native <see cref="PasswordBox"/>. /// </summary> public class ReactPasswordBoxShadowNode : LayoutShadowNode { private static string s_passwordChar; private const int Unset = -1; private float[] _computedPadding; private int _letterSpacing; private double _fontSize = Unset; private double _lineHeight; private FontStyle? _fontStyle; private FontWeight? _fontWeight; private string _fontFamily; private string _text; /// <summary> /// Instantiates the <see cref="ReactPasswordBoxShadowNode"/>. /// </summary> public ReactPasswordBoxShadowNode() { var computedPadding = GetDefaultPaddings(); SetPadding(EdgeSpacing.Left, computedPadding[0]); SetPadding(EdgeSpacing.Top, computedPadding[1]); SetPadding(EdgeSpacing.Right, computedPadding[2]); SetPadding(EdgeSpacing.Bottom, computedPadding[3]); MeasureFunction = (node, width, widthMode, height, heightMode) => MeasureTextInput(this, node, width, widthMode, height, heightMode); } /// <summary> /// Sets the text for the node. /// </summary> /// <param name="text">The text.</param> [ReactProp("text")] public void SetText(string text) { _text = text ?? ""; MarkUpdated(); } /// <summary> /// Sets the font size for the node. /// </summary> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize, DefaultDouble = Unset)] public void SetFontSize(double fontSize) { if (_fontSize != fontSize) { _fontSize = fontSize; MarkUpdated(); } } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="fontFamily">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(string fontFamily) { if (_fontFamily != fontFamily) { _fontFamily = fontFamily; MarkUpdated(); } } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="fontWeightValue">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(string fontWeightValue) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightValue); if (_fontWeight.HasValue != fontWeight.HasValue || (_fontWeight.HasValue && fontWeight.HasValue && #if WINDOWS_UWP _fontWeight.Value.Weight != fontWeight.Value.Weight)) #else _fontWeight.Value.ToOpenTypeWeight() != fontWeight.Value.ToOpenTypeWeight())) #endif { _fontWeight = fontWeight; MarkUpdated(); } } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="fontStyleSValue">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(string fontStyleSValue) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleSValue); if (_fontStyle != fontStyle) { _fontStyle = fontStyle; MarkUpdated(); } } /// <summary> /// Sets the letter spacing for the node. /// </summary> /// <param name="letterSpacing">The letter spacing.</param> [ReactProp(ViewProps.LetterSpacing)] public void SetLetterSpacing(int letterSpacing) { var spacing = 50*letterSpacing; // TODO: Find exact multiplier (50) to match iOS if (_letterSpacing != spacing) { _letterSpacing = spacing; MarkUpdated(); } } /// <summary> /// Sets the line height. /// </summary> /// <param name="lineHeight">The line height.</param> [ReactProp(ViewProps.LineHeight)] public virtual void SetLineHeight(double lineHeight) { if (_lineHeight != lineHeight) { _lineHeight = lineHeight; MarkUpdated(); } } /// <summary> /// Called to aggregate the current text and event counter. /// </summary> /// <param name="uiViewOperationQueue">The UI operation queue.</param> public override void OnCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) { base.OnCollectExtraUpdates(uiViewOperationQueue); if (_computedPadding != null) { uiViewOperationQueue.EnqueueUpdateExtraData(ReactTag, _computedPadding); _computedPadding = null; } } /// <summary> /// Marks a node as updated. /// </summary> protected override void MarkUpdated() { base.MarkUpdated(); dirty(); } private float[] GetDefaultPaddings() { // TODO: calculate dynamically return new[] { 10f, 3f, 6f, 5f, }; } private float[] GetComputedPadding() { return new float[] { GetPadding(YogaEdge.Left), GetPadding(YogaEdge.Top), GetPadding(YogaEdge.Right), GetPadding(YogaEdge.Bottom), }; } private static YogaSize MeasureTextInput(ReactPasswordBoxShadowNode textInputNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode) { textInputNode._computedPadding = textInputNode.GetComputedPadding(); var borderLeftWidth = textInputNode.GetBorder(YogaEdge.Left); var borderRightWidth = textInputNode.GetBorder(YogaEdge.Right); var normalizedWidth = Math.Max(0, (YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width) - textInputNode._computedPadding[0] - textInputNode._computedPadding[2] - (YogaConstants.IsUndefined(borderLeftWidth) ? 0 : borderLeftWidth) - (YogaConstants.IsUndefined(borderRightWidth) ? 0 : borderRightWidth)); var normalizedHeight = Math.Max(0, YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height); // TODO: Measure text with DirectWrite or other API that does not // require dispatcher access. Currently, we're instantiating a // second CoreApplicationView (that is never activated) and using // its Dispatcher thread to calculate layout. var textBlock = new TextBlock { TextWrapping = TextWrapping.Wrap, }; var passwordChar = GetDefaultPasswordChar(); var normalizedText = !string.IsNullOrEmpty(textInputNode._text) ? new string(passwordChar[0], textInputNode._text.Length) : passwordChar; var inline = new Run { Text = normalizedText }; FormatTextElement(textInputNode, inline); textBlock.Inlines.Add(inline); textBlock.Measure(new Size(normalizedWidth, normalizedHeight)); var borderTopWidth = textInputNode.GetBorder(YogaEdge.Top); var borderBottomWidth = textInputNode.GetBorder(YogaEdge.Bottom); var finalizedHeight = (float)textBlock.DesiredSize.Height; finalizedHeight += textInputNode._computedPadding[1]; finalizedHeight += textInputNode._computedPadding[3]; finalizedHeight += YogaConstants.IsUndefined(borderTopWidth) ? 0 : borderTopWidth; finalizedHeight += YogaConstants.IsUndefined(borderBottomWidth) ? 0 : borderBottomWidth; return MeasureOutput.Make( (float)Math.Ceiling(width), (float)Math.Ceiling(finalizedHeight)); } private static string GetDefaultPasswordChar() { if (s_passwordChar == null) { var passwordBox = new PasswordBox(); s_passwordChar = passwordBox.PasswordChar.ToString(); } return s_passwordChar; } private static void FormatTextElement(ReactPasswordBoxShadowNode textNode, TextElement inline) { if (textNode._fontSize != Unset) { var fontSize = textNode._fontSize; inline.FontSize = fontSize; } if (textNode._fontStyle.HasValue) { var fontStyle = textNode._fontStyle.Value; inline.FontStyle = fontStyle; } if (textNode._fontWeight.HasValue) { var fontWeight = textNode._fontWeight.Value; inline.FontWeight = fontWeight; } if (textNode._fontFamily != null) { var fontFamily = new FontFamily(textNode._fontFamily); inline.FontFamily = fontFamily; } } } }
33.98
187
0.575437
[ "MIT" ]
harunpehlivan/react-native-windows
ReactWindows/ReactNative.Shared/Views/TextInput/ReactPasswordBoxShadowNode.cs
10,196
C#
using LanguageExt; using System; using System.Collections.Generic; using System.Text; namespace Step2 { [Union] public interface ICreationResult<T> { ICreationResult<T> Success(T value); ICreationResult<T> Error(string message); } }
17.8
49
0.689139
[ "MIT" ]
hhko/Books
4.Blogs/DDD/DesigningWithTypes_1/Step2/CreationResult.cs
269
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 Suplanus.Eplan.Database.ProjectManagement { using System; using System.Collections.Generic; public partial class Properties_FLOAT { public int Project_ID { get; set; } public int Property_ID { get; set; } public int Property_Index { get; set; } public double Property_FLOAT_Value { get; set; } } }
34.304348
85
0.539924
[ "MIT" ]
PiotWisn/EPLAN-Suplanus.Eplan.Database
Suplanus.Eplan.Database.ProjectManagement/Properties_FLOAT.cs
789
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Routing; namespace Perfor.Lib.Web.Routes { public class WebRouteHandler : IRouteHandler, IHttpHandler, IDisposable { #region Identity private RouteData routeData = null; private bool m_disposing = false; private HttpContext context = null; /// <summary> /// 析构函数,调用Disposable实现 /// </summary> ~WebRouteHandler() { Dispose(true); } #endregion #region IHttpHandler /// <summary> /// 可以为HttpHandler使用 /// </summary> public bool IsReusable { get { return true; } } /// <summary> /// 处理传入的请求 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { this.context = context; string controller = routeData.Values["controller"].ToString(); string action = routeData.Values["action"].ToString(); List<KeyValuePair<string, object>> args = routeData.Values["args"] as List<KeyValuePair<string, object>>; string text = string.Empty; } #endregion #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (!m_disposing && disposing) { if (context != null) { context.Response.Flush(); context.Response.End(); } } m_disposing = true; } #endregion #region IRouteHandler /// <summary> /// 提供处理HttpHandler类型的对象 /// </summary> /// <param name="requestContext"></param> /// <returns></returns> public IHttpHandler GetHttpHandler(RequestContext requestContext) { routeData = requestContext.RouteData; return this; } #endregion } }
25.643678
117
0.514119
[ "MIT" ]
lianggx/danny.lib
Perfor.Lib/Web/Routes/WebRouteHandler.cs
2,293
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Wodsoft.ComBoost.Data.Entity; namespace DataUnitTest { public class TestB : EntityBase { public virtual string Name { get; set; } public virtual List<TestA> ACollection { get; set; } } }
20.0625
60
0.700935
[ "MIT" ]
Kation/ComBoost
test/DataUnitTest/TestB.cs
323
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.KeyManagementService.Model { /// <summary> /// Container for the parameters to the UpdateAlias operation. /// Associates an existing alias with a different customer master key (CMK). Each CMK /// can have multiple aliases, but the aliases must be unique within the account and region. /// You cannot perform this operation on an alias in a different AWS account. /// /// /// <para> /// This operation works only on existing aliases. To change the alias of a CMK to a new /// value, use <a>CreateAlias</a> to create a new alias and <a>DeleteAlias</a> to delete /// the old alias. /// </para> /// /// <para> /// Because an alias is not a property of a CMK, you can create, update, and delete the /// aliases of a CMK without affecting the CMK. Also, aliases do not appear in the response /// from the <a>DescribeKey</a> operation. To get the aliases of all CMKs in the account, /// use the <a>ListAliases</a> operation. /// </para> /// /// <para> /// An alias name can contain only alphanumeric characters, forward slashes (/), underscores /// (_), and dashes (-). An alias must start with the word <code>alias</code> followed /// by a forward slash (<code>alias/</code>). The alias name can contain only alphanumeric /// characters, forward slashes (/), underscores (_), and dashes (-). Alias names cannot /// begin with <code>aws</code>; that alias name prefix is reserved by Amazon Web Services /// (AWS). /// </para> /// </summary> public partial class UpdateAliasRequest : AmazonKeyManagementServiceRequest { private string _aliasName; private string _targetKeyId; /// <summary> /// Gets and sets the property AliasName. /// <para> /// String that contains the name of the alias to be modified. The name must start with /// the word "alias" followed by a forward slash (alias/). Aliases that begin with "alias/aws" /// are reserved. /// </para> /// </summary> public string AliasName { get { return this._aliasName; } set { this._aliasName = value; } } // Check to see if AliasName property is set internal bool IsSetAliasName() { return this._aliasName != null; } /// <summary> /// Gets and sets the property TargetKeyId. /// <para> /// Unique identifier of the customer master key to be mapped to the alias. /// </para> /// /// <para> /// Specify the key ID or the Amazon Resource Name (ARN) of the CMK. /// </para> /// /// <para> /// For example: /// </para> /// <ul> <li> /// <para> /// Key ID: <code>1234abcd-12ab-34cd-56ef-1234567890ab</code> /// </para> /// </li> <li> /// <para> /// Key ARN: <code>arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab</code> /// /// </para> /// </li> </ul> /// <para> /// To get the key ID and key ARN for a CMK, use <a>ListKeys</a> or <a>DescribeKey</a>. /// </para> /// /// <para> /// To verify that the alias is mapped to the correct CMK, use <a>ListAliases</a>. /// </para> /// </summary> public string TargetKeyId { get { return this._targetKeyId; } set { this._targetKeyId = value; } } // Check to see if TargetKeyId property is set internal bool IsSetTargetKeyId() { return this._targetKeyId != null; } } }
36.210938
109
0.596548
[ "Apache-2.0" ]
HaiNguyenMediaStep/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/UpdateAliasRequest.cs
4,635
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Jint.Native; using Jint.Native.Argument; using Jint.Native.Array; using Jint.Native.Boolean; using Jint.Native.Date; using Jint.Native.Error; using Jint.Native.Function; using Jint.Native.Global; using Jint.Native.Json; using Jint.Native.Math; using Jint.Native.Number; using Jint.Native.Object; using Jint.Native.RegExp; using Jint.Native.String; using Jint.Parser; using Jint.Parser.Ast; using Jint.Runtime; using Jint.Runtime.CallStack; using Jint.Runtime.Debugger; using Jint.Runtime.Descriptors; using Jint.Runtime.Environments; using Jint.Runtime.Interop; using Jint.Runtime.References; namespace Jint { public class Engine { private readonly ExpressionInterpreter _expressions; private readonly StatementInterpreter _statements; private readonly Stack<ExecutionContext> _executionContexts; private JsValue _completionValue = JsValue.Undefined; private int _statementsCount; private long _timeoutTicks; private SyntaxNode _lastSyntaxNode = null; public ITypeConverter ClrTypeConverter; // cache of types used when resolving CLR type names internal Dictionary<string, Type> TypeCache = new Dictionary<string, Type>(); internal static Dictionary<Type, Func<Engine, object, JsValue>> TypeMappers = new Dictionary<Type, Func<Engine, object, JsValue>>() { { typeof(bool), (Engine engine, object v) => new JsValue((bool)v) }, { typeof(byte), (Engine engine, object v) => new JsValue((byte)v) }, { typeof(char), (Engine engine, object v) => new JsValue((char)v) }, { typeof(DateTime), (Engine engine, object v) => engine.Date.Construct((DateTime)v) }, { typeof(DateTimeOffset), (Engine engine, object v) => engine.Date.Construct((DateTimeOffset)v) }, { typeof(decimal), (Engine engine, object v) => new JsValue((double)(decimal)v) }, { typeof(double), (Engine engine, object v) => new JsValue((double)v) }, { typeof(Int16), (Engine engine, object v) => new JsValue((Int16)v) }, { typeof(Int32), (Engine engine, object v) => new JsValue((Int32)v) }, { typeof(Int64), (Engine engine, object v) => new JsValue((Int64)v) }, { typeof(SByte), (Engine engine, object v) => new JsValue((SByte)v) }, { typeof(Single), (Engine engine, object v) => new JsValue((Single)v) }, { typeof(string), (Engine engine, object v) => new JsValue((string)v) }, { typeof(UInt16), (Engine engine, object v) => new JsValue((UInt16)v) }, { typeof(UInt32), (Engine engine, object v) => new JsValue((UInt32)v) }, { typeof(UInt64), (Engine engine, object v) => new JsValue((UInt64)v) }, { typeof(JsValue), (Engine engine, object v) => (JsValue)v }, { typeof(System.Text.RegularExpressions.Regex), (Engine engine, object v) => engine.RegExp.Construct(((System.Text.RegularExpressions.Regex)v).ToString().Trim('/')) } }; internal JintCallStack CallStack = new JintCallStack(); public Engine() : this(null) { } public Engine(Action<Options> options) { _executionContexts = new Stack<ExecutionContext>(); Global = GlobalObject.CreateGlobalObject(this); Object = ObjectConstructor.CreateObjectConstructor(this); Function = FunctionConstructor.CreateFunctionConstructor(this); Array = ArrayConstructor.CreateArrayConstructor(this); String = StringConstructor.CreateStringConstructor(this); RegExp = RegExpConstructor.CreateRegExpConstructor(this); Number = NumberConstructor.CreateNumberConstructor(this); Boolean = BooleanConstructor.CreateBooleanConstructor(this); Date = DateConstructor.CreateDateConstructor(this); Math = MathInstance.CreateMathObject(this); Json = JsonInstance.CreateJsonObject(this); Error = ErrorConstructor.CreateErrorConstructor(this, "Error"); EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError"); RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError"); ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError"); SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError"); TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError"); UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError"); // Because the properties might need some of the built-in object // their configuration is delayed to a later step Global.Configure(); Object.Configure(); Object.PrototypeObject.Configure(); Function.Configure(); Function.PrototypeObject.Configure(); Array.Configure(); Array.PrototypeObject.Configure(); String.Configure(); String.PrototypeObject.Configure(); RegExp.Configure(); RegExp.PrototypeObject.Configure(); Number.Configure(); Number.PrototypeObject.Configure(); Boolean.Configure(); Boolean.PrototypeObject.Configure(); Date.Configure(); Date.PrototypeObject.Configure(); Math.Configure(); Json.Configure(); Error.Configure(); Error.PrototypeObject.Configure(); // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3 GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false); // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1 EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global); Options = new Options(); if (options != null) { options(Options); } Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode); Global.FastAddProperty("eval", Eval, true, false, true); _statements = new StatementInterpreter(this); _expressions = new ExpressionInterpreter(this); if (Options._IsClrAllowed) { Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false); Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) => { return new NamespaceReference(this, TypeConverter.ToString(arguments.At(0))); }), false, false, false); } ClrTypeConverter = new DefaultTypeConverter(this); BreakPoints = new List<BreakPoint>(); DebugHandler = new DebugHandler(this); } public LexicalEnvironment GlobalEnvironment; public GlobalObject Global { get; private set; } public ObjectConstructor Object { get; private set; } public FunctionConstructor Function { get; private set; } public ArrayConstructor Array { get; private set; } public StringConstructor String { get; private set; } public RegExpConstructor RegExp { get; private set; } public BooleanConstructor Boolean { get; private set; } public NumberConstructor Number { get; private set; } public DateConstructor Date { get; private set; } public MathInstance Math { get; private set; } public JsonInstance Json { get; private set; } public EvalFunctionInstance Eval { get; private set; } public ErrorConstructor Error { get; private set; } public ErrorConstructor EvalError { get; private set; } public ErrorConstructor SyntaxError { get; private set; } public ErrorConstructor TypeError { get; private set; } public ErrorConstructor RangeError { get; private set; } public ErrorConstructor ReferenceError { get; private set; } public ErrorConstructor UriError { get; private set; } public ExecutionContext ExecutionContext { get { return _executionContexts.Peek(); } } internal Options Options { get; private set; } #region Debugger public delegate StepMode DebugStepDelegate(object sender, DebugInformation e); public delegate StepMode BreakDelegate(object sender, DebugInformation e); public event DebugStepDelegate Step; public event BreakDelegate Break; internal DebugHandler DebugHandler { get; private set; } public List<BreakPoint> BreakPoints { get; private set; } internal StepMode? InvokeStepEvent(DebugInformation info) { if (Step != null) { return Step(this, info); } return null; } internal StepMode? InvokeBreakEvent(DebugInformation info) { if (Break != null) { return Break(this, info); } return null; } #endregion public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding) { var executionContext = new ExecutionContext { LexicalEnvironment = lexicalEnvironment, VariableEnvironment = variableEnvironment, ThisBinding = thisBinding }; _executionContexts.Push(executionContext); return executionContext; } /// <summary> /// Allows adding a lookup assembly after the engine has started. In AllowClr mode, the lookup assemblies are additionally /// searched through when accessing a type in a registered namespace. Has no effect if AllowClr is false. Types without a /// namespace are not made accessible. Ambigous types are matched in the order added, with the System and currently executing /// assembly always coming first. /// </summary> /// <param name="assembly">An assembly that is loaded in the current app domain</param> public void AddLookupAssembly(Assembly assembly) { if (!Options._LookupAssemblies.Contains(assembly)) Options._LookupAssemblies.Add(assembly); } public Engine SetValue(string name, Delegate value) { Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true); return this; } public Engine SetValue(string name, string value) { return SetValue(name, new JsValue(value)); } public Engine SetValue(string name, double value) { return SetValue(name, new JsValue(value)); } public Engine SetValue(string name, bool value) { return SetValue(name, new JsValue(value)); } public Engine SetValue(string name, JsValue value) { Global.Put(name, value, false); return this; } public Engine SetValue(string name, Object obj) { return SetValue(name, JsValue.FromObject(this, obj)); } public void LeaveExecutionContext() { _executionContexts.Pop(); } /// <summary> /// Initializes the statements count /// </summary> public void ResetStatementsCount() { _statementsCount = 0; } public void ResetTimeoutTicks() { var timeoutIntervalTicks = Options._TimeoutInterval.Ticks; _timeoutTicks = timeoutIntervalTicks > 0 ? DateTime.UtcNow.Ticks + timeoutIntervalTicks : 0; } /// <summary> /// Initializes list of references of called functions /// </summary> public void ResetCallStack() { CallStack.Clear(); } public Engine Execute(string source) { var parser = new JavaScriptParser(); return Execute(parser.Parse(source)); } public Engine Execute(string source, ParserOptions parserOptions) { var parser = new JavaScriptParser(); return Execute(parser.Parse(source, parserOptions)); } public Engine Execute(Program program) { ResetStatementsCount(); ResetTimeoutTicks(); ResetLastStatement(); ResetCallStack(); using (new StrictModeScope(Options._IsStrict || program.Strict)) { DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.FunctionDeclarations, program.VariableDeclarations, null, null); var result = _statements.ExecuteProgram(program); if (result.Type == Completion.Throw) { throw new JavaScriptException(result.GetValueOrDefault(), result.InnerException) .SetCallstack(this, result.Location); } _completionValue = result.GetValueOrDefault(); } return this; } private void ResetLastStatement() { _lastSyntaxNode = null; } /// <summary> /// Gets the last evaluated statement completion value /// </summary> public JsValue GetCompletionValue() { return _completionValue; } public Completion ExecuteStatement(Statement statement) { var maxStatements = Options._MaxStatements; if (maxStatements > 0 && _statementsCount++ > maxStatements) { throw new StatementsCountOverflowException(); } if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks) { throw new TimeoutException(); } _lastSyntaxNode = statement; if (Options._IsDebugMode) { DebugHandler.OnStep(statement); } switch (statement.Type) { case SyntaxNodes.BlockStatement: return _statements.ExecuteBlockStatement(statement.As<BlockStatement>()); case SyntaxNodes.BreakStatement: return _statements.ExecuteBreakStatement(statement.As<BreakStatement>()); case SyntaxNodes.ContinueStatement: return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>()); case SyntaxNodes.DoWhileStatement: return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>()); case SyntaxNodes.DebuggerStatement: return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>()); case SyntaxNodes.EmptyStatement: return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>()); case SyntaxNodes.ExpressionStatement: return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>()); case SyntaxNodes.ForStatement: return _statements.ExecuteForStatement(statement.As<ForStatement>()); case SyntaxNodes.ForInStatement: return _statements.ExecuteForInStatement(statement.As<ForInStatement>()); case SyntaxNodes.FunctionDeclaration: return new Completion(Completion.Normal, null, null); case SyntaxNodes.IfStatement: return _statements.ExecuteIfStatement(statement.As<IfStatement>()); case SyntaxNodes.LabeledStatement: return _statements.ExecuteLabelledStatement(statement.As<LabelledStatement>()); case SyntaxNodes.ReturnStatement: return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>()); case SyntaxNodes.SwitchStatement: return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>()); case SyntaxNodes.ThrowStatement: return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>()); case SyntaxNodes.TryStatement: return _statements.ExecuteTryStatement(statement.As<TryStatement>()); case SyntaxNodes.VariableDeclaration: return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>()); case SyntaxNodes.WhileStatement: return _statements.ExecuteWhileStatement(statement.As<WhileStatement>()); case SyntaxNodes.WithStatement: return _statements.ExecuteWithStatement(statement.As<WithStatement>()); case SyntaxNodes.Program: return _statements.ExecuteProgram(statement.As<Program>()); default: throw new ArgumentOutOfRangeException(); } } public object EvaluateExpression(Expression expression) { _lastSyntaxNode = expression; switch (expression.Type) { case SyntaxNodes.AssignmentExpression: return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>()); case SyntaxNodes.ArrayExpression: return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>()); case SyntaxNodes.BinaryExpression: return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>()); case SyntaxNodes.CallExpression: return _expressions.EvaluateCallExpression(expression.As<CallExpression>()); case SyntaxNodes.ConditionalExpression: return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>()); case SyntaxNodes.FunctionExpression: return _expressions.EvaluateFunctionExpression(expression.As<FunctionExpression>()); case SyntaxNodes.Identifier: return _expressions.EvaluateIdentifier(expression.As<Identifier>()); case SyntaxNodes.Literal: return _expressions.EvaluateLiteral(expression.As<Literal>()); case SyntaxNodes.RegularExpressionLiteral: return _expressions.EvaluateLiteral(expression.As<Literal>()); case SyntaxNodes.LogicalExpression: return _expressions.EvaluateLogicalExpression(expression.As<LogicalExpression>()); case SyntaxNodes.MemberExpression: return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>()); case SyntaxNodes.NewExpression: return _expressions.EvaluateNewExpression(expression.As<NewExpression>()); case SyntaxNodes.ObjectExpression: return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>()); case SyntaxNodes.SequenceExpression: return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>()); case SyntaxNodes.ThisExpression: return _expressions.EvaluateThisExpression(expression.As<ThisExpression>()); case SyntaxNodes.UpdateExpression: return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>()); case SyntaxNodes.UnaryExpression: return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>()); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1 /// </summary> /// <param name="value"></param> /// <returns></returns> public JsValue GetValue(object value) { var reference = value as Reference; if (reference == null) { var completion = value as Completion; if (completion != null) { return GetValue(completion.Value); } return (JsValue)value; } if (reference.IsUnresolvableReference()) { if (Options._ReferenceResolver != null && Options._ReferenceResolver.TryUnresolvableReference(this, reference, out JsValue val)) { return val; } throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined"); } var baseValue = reference.GetBase(); if (reference.IsPropertyReference()) { if (Options._ReferenceResolver != null && Options._ReferenceResolver.TryPropertyReference(this, reference, ref baseValue)) { return baseValue; } if (reference.HasPrimitiveBase() == false) { var o = TypeConverter.ToObject(this, baseValue); return o.Get(reference.GetReferencedName()); } else { var o = TypeConverter.ToObject(this, baseValue); var desc = o.GetProperty(reference.GetReferencedName()); if (desc == PropertyDescriptor.Undefined) { return JsValue.Undefined; } if (desc.IsDataDescriptor()) { return desc.Value; } var getter = desc.Get; if (getter == Undefined.Instance) { return Undefined.Instance; } var callable = (ICallable)getter.AsObject(); return callable.Call(baseValue, Arguments.Empty); } } else { var record = baseValue.As<EnvironmentRecord>(); if (record == null) { throw new ArgumentException(); } return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict()); } } /// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2 /// </summary> /// <param name="reference"></param> /// <param name="value"></param> public void PutValue(Reference reference, JsValue value) { if (reference.IsUnresolvableReference()) { if (reference.IsStrict()) { throw new JavaScriptException(ReferenceError); } Global.Put(reference.GetReferencedName(), value, false); } else if (reference.IsPropertyReference()) { var baseValue = reference.GetBase(); if (!reference.HasPrimitiveBase()) { baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict()); } else { PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict()); } } else { var baseValue = reference.GetBase(); var record = baseValue.As<EnvironmentRecord>(); if (record == null) { throw new ArgumentNullException(); } record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict()); } } /// <summary> /// Used by PutValue when the reference has a primitive base value /// </summary> /// <param name="b"></param> /// <param name="name"></param> /// <param name="value"></param> /// <param name="throwOnError"></param> public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError) { var o = TypeConverter.ToObject(this, b); if (!o.CanPut(name)) { if (throwOnError) { throw new JavaScriptException(TypeError); } return; } var ownDesc = o.GetOwnProperty(name); if (ownDesc.IsDataDescriptor()) { if (throwOnError) { throw new JavaScriptException(TypeError); } return; } var desc = o.GetProperty(name); if (desc.IsAccessorDescriptor()) { var setter = (ICallable)desc.Set.AsObject(); setter.Call(b, new[] { value }); } else { if (throwOnError) { throw new JavaScriptException(TypeError); } } } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="propertyName">The arguments of the function call.</param> /// <param name="arguments"></param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(string propertyName, params object[] arguments) { return Invoke(propertyName, null, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="propertyName">The name of the function to call.</param> /// <param name="thisObj">The this value inside the function call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(string propertyName, object thisObj, object[] arguments) { var value = GetValue(propertyName); return Invoke(value, thisObj, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="value">The function to call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(JsValue value, params object[] arguments) { return Invoke(value, null, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="value">The function to call.</param> /// <param name="thisObj">The this value inside the function call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(JsValue value, object thisObj, object[] arguments) { var callable = value.TryCast<ICallable>(); if (callable == null) { throw new ArgumentException("Can only invoke functions"); } return callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray()); } /// <summary> /// Gets a named value from the Global scope. /// </summary> /// <param name="propertyName">The name of the property to return.</param> public JsValue GetValue(string propertyName) { return GetValue(Global, propertyName); } /// <summary> /// Gets the last evaluated <see cref="SyntaxNode"/>. /// </summary> public SyntaxNode GetLastSyntaxNode() { return _lastSyntaxNode; } /// <summary> /// Gets a named value from the specified scope. /// </summary> /// <param name="scope">The scope to get the property from.</param> /// <param name="propertyName">The name of the property to return.</param> public JsValue GetValue(JsValue scope, string propertyName) { if (System.String.IsNullOrEmpty(propertyName)) { throw new ArgumentException("propertyName"); } var reference = new Reference(scope, propertyName, Options._IsStrict); return GetValue(reference); } // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5 public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IList<FunctionDeclaration> functionDeclarations, IList<VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments) { var env = ExecutionContext.VariableEnvironment.Record; bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode; var strict = StrictModeScope.IsStrictModeCode; if (declarationBindingType == DeclarationBindingType.FunctionCode) { var argCount = arguments.Length; var n = 0; foreach (var argName in functionInstance.FormalParameters) { n++; var v = n > argCount ? Undefined.Instance : arguments[n - 1]; var argAlreadyDeclared = env.HasBinding(argName); if (!argAlreadyDeclared) { env.CreateMutableBinding(argName); } env.SetMutableBinding(argName, v, strict); } } foreach (var f in functionDeclarations) { var fn = f.Id.Name; var fo = Function.CreateFunctionObject(f); var funcAlreadyDeclared = env.HasBinding(fn); if (!funcAlreadyDeclared) { env.CreateMutableBinding(fn, configurableBindings); } else { if (env == GlobalEnvironment.Record) { var go = Global; var existingProp = go.GetProperty(fn); if (existingProp.Configurable.Value) { go.DefineOwnProperty(fn, new PropertyDescriptor( value: Undefined.Instance, writable: true, enumerable: true, configurable: configurableBindings ), true); } else { if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value)) { throw new JavaScriptException(TypeError); } } } } env.SetMutableBinding(fn, fo, strict); } var argumentsAlreadyDeclared = env.HasBinding("arguments"); if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared) { var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict); if (strict) { var declEnv = env as DeclarativeEnvironmentRecord; if (declEnv == null) { throw new ArgumentException(); } declEnv.CreateImmutableBinding("arguments"); declEnv.InitializeImmutableBinding("arguments", argsObj); } else { env.CreateMutableBinding("arguments"); env.SetMutableBinding("arguments", argsObj, false); } } // process all variable declarations in the current parser scope foreach (var d in variableDeclarations.SelectMany(x => x.Declarations)) { var dn = d.Id.Name; var varAlreadyDeclared = env.HasBinding(dn); if (!varAlreadyDeclared) { env.CreateMutableBinding(dn, configurableBindings); env.SetMutableBinding(dn, Undefined.Instance, strict); } } } } }
39.042627
252
0.568798
[ "BSD-2-Clause" ]
djkrose/jint-unity
Jint/Engine.cs
33,891
C#
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace Nest { [JsonConverter(typeof(ReadAsTypeJsonConverter<BoolQuery>))] [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public interface IBoolQuery : IQuery { /// <summary> /// The clause(s) that must appear in matching documents /// </summary> [JsonProperty("must", DefaultValueHandling = DefaultValueHandling.Ignore)] IEnumerable<QueryContainer> Must { get; set; } /// <summary> /// The clause (query) must not appear in the matching documents. Note that it is not possible to search on documents that only consists of a must_not clauses. /// </summary> [JsonProperty("must_not", DefaultValueHandling = DefaultValueHandling.Ignore)] IEnumerable<QueryContainer> MustNot { get; set; } /// <summary> /// The clause (query) should appear in the matching document. A boolean query with no must clauses, one or more should clauses must match a document. /// The minimum number of should clauses to match can be set using minimum_should_match parameter. /// </summary> [JsonProperty("should", DefaultValueHandling = DefaultValueHandling.Ignore)] IEnumerable<QueryContainer> Should { get; set; } /// <summary> /// The clause (query) which is to be used as a filter (in filter context). /// </summary> [JsonProperty("filter", DefaultValueHandling = DefaultValueHandling.Ignore)] IEnumerable<QueryContainer> Filter { get; set; } /// <summary> /// Specifies a minimum number of the optional BooleanClauses which must be satisfied. /// </summary> [JsonProperty("minimum_should_match")] MinimumShouldMatch MinimumShouldMatch { get; set; } /// <summary> /// Specifies if the coordination factor for the query should be disabled. /// The coordination factor is used to reward documents that contain a higher /// percentage of the query terms. The more query terms that appear in the document, /// the greater the chances that the document is a good match for the query. /// </summary> [JsonProperty("disable_coord")] bool? DisableCoord { get; set; } bool Locked { get; } } public class BoolQuery : QueryBase, IBoolQuery { internal static bool Locked(IBoolQuery q) => !q.Name.IsNullOrEmpty() || q.Boost.HasValue || q.DisableCoord.HasValue || q.MinimumShouldMatch != null; bool IBoolQuery.Locked => BoolQuery.Locked(this); /// <summary> /// The clause(s) that must appear in matching documents /// </summary> public IEnumerable<QueryContainer> Must { get; set; } /// <summary> /// The clause (query) must not appear in the matching documents. Note that it is not possible to search on documents that only consists of a must_not clauses. /// </summary> public IEnumerable<QueryContainer> MustNot { get; set; } /// <summary> /// The clause (query) should appear in the matching document. A boolean query with no must clauses, one or more should clauses must match a document. /// The minimum number of should clauses to match can be set using minimum_should_match parameter. /// </summary> public IEnumerable<QueryContainer> Should { get; set; } /// <summary> /// The clause (query) which is to be used as a filter (in filter context). /// </summary> public IEnumerable<QueryContainer> Filter { get; set; } /// <summary> /// Specifies a minimum number of the optional BooleanClauses which must be satisfied. /// </summary> public MinimumShouldMatch MinimumShouldMatch { get; set; } /// <summary> /// Specifies if the coordination factor for the query should be disabled. /// The coordination factor is used to reward documents that contain a higher /// percentage of the query terms. The more query terms that appear in the document, /// the greater the chances that the document is a good match for the query. /// </summary> public bool? DisableCoord { get; set; } internal override void WrapInContainer(IQueryContainer c) => c.Bool = this; protected override bool Conditionless => IsConditionless(this); internal static bool IsConditionless(IBoolQuery q) { if (!q.Must.HasAny() && !q.Should.HasAny() && !q.MustNot.HasAny() && !q.Filter.HasAny()) return true; var mustNots = q.MustNot.HasAny() && q.MustNot.All(qq => qq.IsConditionless()); var shoulds = q.Should.HasAny() && q.Should.All(qq => qq.IsConditionless()); var musts = q.Must.HasAny() && q.Must.All(qq => qq.IsConditionless()); var filters = q.Filter.HasAny() && q.Filter.All(qq => qq.IsConditionless()); return mustNots && shoulds && musts && filters; } } public class BoolQueryDescriptor<T> : QueryDescriptorBase<BoolQueryDescriptor<T>, IBoolQuery> , IBoolQuery where T : class { bool IBoolQuery.Locked => BoolQuery.Locked(this); protected override bool Conditionless => BoolQuery.IsConditionless(this); IEnumerable<QueryContainer> IBoolQuery.Must { get; set; } IEnumerable<QueryContainer> IBoolQuery.MustNot { get; set; } IEnumerable<QueryContainer> IBoolQuery.Should { get; set; } IEnumerable<QueryContainer> IBoolQuery.Filter { get; set; } MinimumShouldMatch IBoolQuery.MinimumShouldMatch { get; set; } bool? IBoolQuery.DisableCoord { get; set; } /// <summary> /// Specifies if the coordination factor for the query should be disabled. /// The coordination factor is used to reward documents that contain a higher /// percentage of the query terms. The more query terms that appear in the document, /// the greater the chances that the document is a good match for the query. /// </summary> /// <returns></returns> public BoolQueryDescriptor<T> DisableCoord() => Assign(a => a.DisableCoord = true); /// <summary> /// Specifies a minimum number of the optional BooleanClauses which must be satisfied. /// </summary> /// <param name="minimumShouldMatches"></param> /// <returns></returns> public BoolQueryDescriptor<T> MinimumShouldMatch(MinimumShouldMatch minimumShouldMatches) => Assign(a => a.MinimumShouldMatch = minimumShouldMatches); /// <summary> /// The clause(s) that must appear in matching documents /// </summary> public BoolQueryDescriptor<T> Must(params Func<QueryContainerDescriptor<T>, QueryContainer>[] queries) => Assign(a => a.Must = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause(s) that must appear in matching documents /// </summary> public BoolQueryDescriptor<T> Must(IEnumerable<Func<QueryContainerDescriptor<T>, QueryContainer>> queries) => Assign(a => a.Must = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause(s) that must appear in matching documents /// </summary> public BoolQueryDescriptor<T> Must(params QueryContainer[] queries) => Assign(a => a.Must = queries.Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) must not appear in the matching documents. Note that it is not possible to search on documents that only consists of a must_not clauses. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> MustNot(params Func<QueryContainerDescriptor<T>, QueryContainer>[] queries) => Assign(a => a.MustNot = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) must not appear in the matching documents. Note that it is not possible to search on documents that only consists of a must_not clauses. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> MustNot(IEnumerable<Func<QueryContainerDescriptor<T>, QueryContainer>> queries) => Assign(a => a.MustNot = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) must not appear in the matching documents. Note that it is not possible to search on documents that only consists of a must_not clauses. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> MustNot(params QueryContainer[] queries) => Assign(a => a.MustNot = queries.Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) should appear in the matching document. A boolean query with no must clauses, one or more should clauses must match a document. /// The minimum number of should clauses to match can be set using minimum_should_match parameter. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Should(params Func<QueryContainerDescriptor<T>, QueryContainer>[] queries) => Assign(a => a.Should = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) should appear in the matching document. A boolean query with no must clauses, one or more should clauses must match a document. /// The minimum number of should clauses to match can be set using minimum_should_match parameter. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Should(IEnumerable<Func<QueryContainerDescriptor<T>, QueryContainer>> queries) => Assign(a => a.Should = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) should appear in the matching document. A boolean query with no must clauses, one or more should clauses must match a document. /// The minimum number of should clauses to match can be set using minimum_should_match parameter. /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Should(params QueryContainer[] queries) => Assign(a => a.Should = queries.Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) which is to be used as a filter (in filter context). /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Filter(params Func<QueryContainerDescriptor<T>, QueryContainer>[] queries) => Assign(a => a.Filter = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) which is to be used as a filter (in filter context). /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Filter(IEnumerable<Func<QueryContainerDescriptor<T>, QueryContainer>> queries) => Assign(a => a.Filter = queries.Select(q => q?.InvokeQuery(new QueryContainerDescriptor<T>())).Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); /// <summary> /// The clause (query) which is to be used as a filter (in filter context). /// </summary> /// <param name="queries"></param> /// <returns></returns> public BoolQueryDescriptor<T> Filter(params QueryContainer[] queries) => Assign(a => a.Filter = queries.Where(q => !q.IsNullOrConditionless()).ToListOrNullIfEmpty()); } }
49.153191
161
0.712925
[ "Apache-2.0" ]
RossLieberman/NEST
src/Nest/QueryDsl/Compound/Bool/BoolQuery.cs
11,553
C#
//------------------------------------------------------------------------- // Copyright © 2020 Province of British Columbia // // 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. //------------------------------------------------------------------------- // <auto-generated /> #pragma warning disable CS1591 using System; using System.Text.Json; using HealthGateway.Database.Context; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace HealthGateway.Database.Migrations { [DbContext(typeof(GatewayDbContext))] [Migration("20200803222317_PushBannerChange")] partial class PushBannerChange { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("gateway") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) .HasAnnotation("ProductVersion", "3.1.6") .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("Relational:Sequence:.gateway.trace_seq", "'gateway.trace_seq', '', '1', '1', '1', '999999', 'Int64', 'True'"); modelBuilder.Entity("HealthGateway.Database.Models.ActiveIngredient", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("ActiveIngredientId") .HasColumnType("uuid"); b.Property<int>("ActiveIngredientCode") .HasColumnType("integer"); b.Property<string>("Base") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("DosageUnit") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("DosageUnitFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("DosageValue") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("Ingredient") .HasColumnType("character varying(240)") .HasMaxLength(240); b.Property<string>("IngredientFrench") .HasColumnType("character varying(400)") .HasMaxLength(400); b.Property<string>("IngredientSuppliedInd") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("Notes") .HasColumnType("character varying(2000)") .HasMaxLength(2000); b.Property<string>("Strength") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<string>("StrengthType") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("StrengthTypeFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("StrengthUnit") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("StrengthUnitFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("ActiveIngredient"); }); modelBuilder.Entity("HealthGateway.Database.Models.ApplicationSetting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("ApplicationSettingsId") .HasColumnType("uuid"); b.Property<string>("Application") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("Component") .IsRequired() .HasColumnType("character varying(50)") .HasMaxLength(50); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Key") .IsRequired() .HasColumnType("character varying(250)") .HasMaxLength(250); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Value") .HasColumnType("text"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("Application", "Component", "Key") .IsUnique(); b.ToTable("ApplicationSetting"); b.HasData( new { Id = new Guid("5f279ba2-8e7b-4b1d-8c69-467d94dcb7fb"), Application = "JOBS", Component = "NotifyUpdatedLegalAgreementsJob", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Key = "ToS-Last-Checked", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Value = "05/01/2019", Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.AuditEvent", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("AuditEventId") .HasColumnType("uuid"); b.Property<string>("ApplicationSubject") .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("ApplicationType") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<DateTime>("AuditEventDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("ClientIP") .IsRequired() .HasColumnType("character varying(15)") .HasMaxLength(15); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Trace") .HasColumnType("character varying(200)") .HasMaxLength(200); b.Property<long?>("TransactionDuration") .HasColumnType("bigint"); b.Property<string>("TransactionName") .IsRequired() .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("TransactionResultCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("TransactionVersion") .HasColumnType("character varying(5)") .HasMaxLength(5); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("ApplicationType"); b.HasIndex("TransactionResultCode"); b.ToTable("AuditEvent"); }); modelBuilder.Entity("HealthGateway.Database.Models.AuditTransactionResultCode", b => { b.Property<string>("ResultCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(30)") .HasMaxLength(30); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("ResultCode"); b.ToTable("AuditTransactionResultCode"); b.HasData( new { ResultCode = "Ok", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Success", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ResultCode = "Fail", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Failure", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ResultCode = "NotAuth", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Unauthorized", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ResultCode = "Err", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "System Error", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.BetaRequest", b => { b.Property<string>("HdId") .HasColumnName("BetaRequestId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("HdId"); b.ToTable("BetaRequest"); }); modelBuilder.Entity("HealthGateway.Database.Models.Comment", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("CommentId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("EntryTypeCode") .IsRequired() .HasColumnType("character varying(3)") .HasMaxLength(3); b.Property<string>("ParentEntryId") .IsRequired() .HasColumnType("character varying(36)") .HasMaxLength(36); b.Property<string>("Text") .HasColumnType("character varying(1344)") .HasMaxLength(1344); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("UserProfileId") .IsRequired() .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("UserProfileId"); b.ToTable("Comment"); }); modelBuilder.Entity("HealthGateway.Database.Models.Communication", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("CommunicationId") .HasColumnType("uuid"); b.Property<string>("CommunicationStatusCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CommunicationTypeCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<DateTime>("EffectiveDateTime") .HasColumnType("timestamp without time zone"); b.Property<DateTime>("ExpiryDateTime") .HasColumnType("timestamp without time zone"); b.Property<int>("Priority") .HasColumnType("integer"); b.Property<DateTime?>("ScheduledDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Subject") .IsRequired() .HasColumnType("character varying(1000)") .HasMaxLength(1000); b.Property<string>("Text") .IsRequired() .HasColumnType("character varying(1000)") .HasMaxLength(1000); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("CommunicationStatusCode"); b.HasIndex("CommunicationTypeCode"); b.ToTable("Communication"); }); modelBuilder.Entity("HealthGateway.Database.Models.CommunicationEmail", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("CommunicationEmailId") .HasColumnType("uuid"); b.Property<Guid>("CommunicationId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("EmailId") .HasColumnType("uuid"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("UserProfileHdId") .IsRequired() .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("CommunicationId"); b.HasIndex("EmailId"); b.HasIndex("UserProfileHdId"); b.ToTable("CommunicationEmail"); }); modelBuilder.Entity("HealthGateway.Database.Models.CommunicationStatusCode", b => { b.Property<string>("StatusCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(50)") .HasMaxLength(50); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("StatusCode"); b.ToTable("CommunicationStatusCode"); b.HasData( new { StatusCode = "New", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "A newly created Communication", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Pending", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "A Communication pending batch pickup", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Processing", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Communication is being processed", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Processed", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "A Communication which has been sent", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Error", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "A Communication that will not be sent", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.CommunicationTypeCode", b => { b.Property<string>("StatusCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(30)") .HasMaxLength(30); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("StatusCode"); b.ToTable("CommunicationTypeCode"); b.HasData( new { StatusCode = "Banner", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Banner communication type", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Email", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Email communication type", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.Company", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("CompanyId") .HasColumnType("uuid"); b.Property<string>("AddressBillingFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("AddressMailingFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("AddressNotificationFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("AddressOther") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("CityName") .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<int>("CompanyCode") .HasColumnType("integer"); b.Property<string>("CompanyName") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("CompanyType") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("Country") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("CountryFrench") .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("ManufacturerCode") .HasColumnType("character varying(5)") .HasMaxLength(5); b.Property<string>("PostOfficeBox") .HasColumnType("character varying(15)") .HasMaxLength(15); b.Property<string>("PostalCode") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<string>("Province") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("ProvinceFrench") .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("StreetName") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("SuiteNumber") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("Company"); }); modelBuilder.Entity("HealthGateway.Database.Models.DrugProduct", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("DrugProductId") .HasColumnType("uuid"); b.Property<string>("AccessionNumber") .HasColumnType("character varying(5)") .HasMaxLength(5); b.Property<string>("AiGroupNumber") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("BrandName") .IsRequired() .HasColumnType("character varying(200)") .HasMaxLength(200); b.Property<string>("BrandNameFrench") .HasColumnType("character varying(300)") .HasMaxLength(300); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Descriptor") .HasColumnType("character varying(150)") .HasMaxLength(150); b.Property<string>("DescriptorFrench") .HasColumnType("character varying(200)") .HasMaxLength(200); b.Property<string>("DrugClass") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("DrugClassFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("DrugCode") .IsRequired() .HasColumnType("character varying(8)") .HasMaxLength(8); b.Property<string>("DrugIdentificationNumber") .IsRequired() .HasColumnType("character varying(29)") .HasMaxLength(29); b.Property<Guid>("FileDownloadId") .HasColumnType("uuid"); b.Property<DateTime>("LastUpdate") .HasColumnType("timestamp without time zone"); b.Property<string>("NumberOfAis") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("PediatricFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("ProductCategorization") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("FileDownloadId"); b.ToTable("DrugProduct"); }); modelBuilder.Entity("HealthGateway.Database.Models.Email", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("EmailId") .HasColumnType("uuid"); b.Property<int>("Attempts") .HasColumnType("integer"); b.Property<string>("Body") .IsRequired() .HasColumnType("text"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("EmailStatusCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("FormatCode") .IsRequired() .HasColumnType("character varying(4)") .HasMaxLength(4); b.Property<string>("From") .IsRequired() .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<DateTime?>("LastRetryDateTime") .HasColumnType("timestamp without time zone"); b.Property<int>("Priority") .HasColumnType("integer"); b.Property<DateTime?>("SentDateTime") .HasColumnType("timestamp without time zone"); b.Property<int>("SmtpStatusCode") .HasColumnType("integer"); b.Property<string>("Subject") .IsRequired() .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("To") .IsRequired() .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("EmailStatusCode"); b.HasIndex("FormatCode"); b.ToTable("Email"); }); modelBuilder.Entity("HealthGateway.Database.Models.EmailFormatCode", b => { b.Property<string>("FormatCode") .HasColumnType("character varying(4)") .HasMaxLength(4); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("FormatCode"); b.ToTable("EmailFormatCode"); b.HasData( new { FormatCode = "Text", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { FormatCode = "HTML", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.EmailStatusCode", b => { b.Property<string>("StatusCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(30)") .HasMaxLength(30); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("StatusCode"); b.ToTable("EmailStatusCode"); b.HasData( new { StatusCode = "New", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "A newly created email", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Pending", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "An email pending batch pickup", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Processed", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "An email that has been sent", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { StatusCode = "Error", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "An Email that will not be sent", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.EmailTemplate", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("EmailTemplateId") .HasColumnType("uuid"); b.Property<string>("Body") .IsRequired() .HasColumnType("text"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<DateTime>("EffectiveDate") .HasColumnType("timestamp without time zone"); b.Property<DateTime?>("ExpiryDate") .HasColumnType("timestamp without time zone"); b.Property<string>("FormatCode") .IsRequired() .HasColumnType("character varying(4)") .HasMaxLength(4); b.Property<string>("From") .IsRequired() .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<string>("Name") .IsRequired() .HasColumnType("character varying(30)") .HasMaxLength(30); b.Property<int>("Priority") .HasColumnType("integer"); b.Property<string>("Subject") .IsRequired() .HasColumnType("character varying(100)") .HasMaxLength(100); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("FormatCode"); b.ToTable("EmailTemplate"); b.HasData( new { Id = new Guid("040c2ec3-d6c0-4199-9e4b-ebe6da48d52a"), Body = @"<!doctype html> <html lang=""en""> <head></head> <body style = ""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style = ""background:#003366;""> <th width=""45"" ></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria - label=""Health Gateway Logo""> <img src=""${ActivationHost}/Logo.png"" alt=""Health Gateway Logo""/> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style = ""font-size:18px;"">Almost there!</h1> <p>We've received a request to register your email address for a Health Gateway account.</p> <p>To activate your account, please verify your email by clicking the link:</p> <a style = ""color:#1292c5;font-weight:600;"" href = ""${ActivationHost}/ValidateEmail/${InviteKey}""> Health Gateway Account Verification </a> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "Registration", Priority = 10, Subject = "Health Gateway Email Verification ${Environment}", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("896f8f2e-3bed-400b-acaf-51dd6082b4bd"), Body = @"<!doctype html> <html lang=""en""> <head></head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo""/> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Good day,</h1> <p>You are receiving this email as a Health Gateway patient partner. We welcome your feedback and suggestions as one of the first users of the application.</p> <p>Please click on the link below which will take you to your registration for the Health Gateway service. This registration link is valid for your one-time use only. We kindly ask that you do not share your link with anyone else.</p> <a style = ""font-weight:600;"" href=""${host}/registrationInfo?inviteKey=${inviteKey}&email=${emailTo}"">Register Now</a> <p>If you have any questions about the registration process, including signing up to use your BC Services Card for authentication, please contact Nino Samson at nino.samson@gov.bc.ca.</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "Invite", Priority = 1, Subject = "Health Gateway Private Invitation", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("2ab5d4aa-c4c9-4324-a753-cde4e21e7612"), Body = @"<!doctype html> <html lang=""en""> <head></head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo""/> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Good day,</h1> <p>Thank you for joining the wait list to be an early user of the Health Gateway.</p> <p>You will receive an email in the near future with a registration link.</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "BetaConfirmation", Priority = 1, Subject = "Health Gateway Waitlist Confirmation", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("eb695050-e2fb-4933-8815-3d4656e4541d"), Body = @"<!doctype html> <html lang=""en""> <head> </head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo"" /> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Hi,</h1> <p> You are receiving this email as a user of the Health Gateway. We have updated our Terms of Service, effective ${effectivedate}. </p> <p>For more information, we encourage you to review the full <a href=""${host}/${path}"">Terms of Service</a> and check out the <a href=""https://github.com/bcgov/healthgateway/wiki"">release notes</a> for a summary of new features.</p> <p>If you have any questions or wish to provide any feedback, please contact <a href=""mailto:${contactemail}"">${contactemail}</a>.</p> <p>Regards,</p> <p>Health Gateway Team</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "TermsOfService", Priority = 1, Subject = "Health Gateway Updated Terms of Service ", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("79503a38-c14a-4992-b2fe-5586629f552e"), Body = @"<!doctype html> <html lang=""en""> <head> </head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo"" /> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Hi,</h1> <p> You have closed your Health Gateway account. If you would like to recover your account, please login to Health Gateway within the next 30 days and click “Recover Account”. No further action is required if you want your account and personally entered information to be removed from the Health Gateway after this time period. </p> <p>Thanks,</p> <p>Health Gateway Team</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "AccountClosed", Priority = 1, Subject = "Health Gateway Account Closed ", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("2fe8c825-d4de-4884-be6a-01a97b466425"), Body = @"<!doctype html> <html lang=""en""> <head> </head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo"" /> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Hi,</h1> <p> You have successfully recovered your Health Gateway account. You may continue to use the service as you did before. </p> <p>Thanks,</p> <p>Health Gateway Team</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "AccountRecovered", Priority = 1, Subject = "Health Gateway Account Recovered", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("d9898318-4e53-4074-9979-5d24bd370055"), Body = @"<!doctype html> <html lang=""en""> <head> </head> <body style=""margin:0""> <table cellspacing=""0"" align=""left"" width=""100%"" style=""margin:0;color:#707070;font-family:Helvetica;font-size:12px;""> <tr style=""background:#036;""> <th width=""45""></th> <th width=""350"" align=""left"" style=""text-align:left;""> <div role=""img"" aria-label=""Health Gateway Logo""> <img src=""${host}/Logo.png"" alt=""Health Gateway Logo"" /> </div> </th> <th width=""""></th> </tr> <tr> <td colspan=""3"" height=""20""></td> </tr> <tr> <td></td> <td> <h1 style=""font-size:18px;"">Hi,</h1> <p> Your Health Gateway account closure has been completed. Your account and personally entered information have been removed from the application. You are welcome to register again for the Health Gateway in the future. </p> <p>Thanks,</p> <p>Health Gateway Team</p> </td> <td></td> </tr> </table> </body> </html>", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), FormatCode = "HTML", From = "HG_Donotreply@gov.bc.ca", Name = "AccountRemoved", Priority = 1, Subject = "Health Gateway Account Closure Complete", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.FileDownload", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("FileDownloadId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Hash") .IsRequired() .HasColumnType("character varying(44)") .HasMaxLength(44); b.Property<string>("Name") .IsRequired() .HasColumnType("character varying(35)") .HasMaxLength(35); b.Property<string>("ProgramCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("Hash") .IsUnique(); b.HasIndex("ProgramCode") .IsUnique(); b.ToTable("FileDownload"); }); modelBuilder.Entity("HealthGateway.Database.Models.Form", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("FormId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("PharmaceuticalForm") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<int>("PharmaceuticalFormCode") .HasColumnType("integer"); b.Property<string>("PharmaceuticalFormFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("Form"); }); modelBuilder.Entity("HealthGateway.Database.Models.GenericCache", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("GenericCacheId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Domain") .IsRequired() .HasColumnType("character varying(250)") .HasMaxLength(250); b.Property<DateTime?>("ExpiryDateTime") .IsRequired() .HasColumnType("timestamp without time zone"); b.Property<string>("HdId") .IsRequired() .HasColumnType("character varying(54)") .HasMaxLength(54); b.Property<JsonDocument>("JSON") .IsRequired() .HasColumnType("jsonb"); b.Property<string>("JSONType") .IsRequired() .HasColumnType("text"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.ToTable("GenericCache"); }); modelBuilder.Entity("HealthGateway.Database.Models.LegalAgreement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("LegalAgreementsId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<DateTime?>("EffectiveDate") .IsRequired() .HasColumnType("timestamp without time zone"); b.Property<string>("LegalAgreementCode") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("LegalText") .IsRequired() .HasColumnType("text"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("LegalAgreementCode"); b.ToTable("LegalAgreement"); b.HasData( new { Id = new Guid("f5acf1de-2f5f-431e-955d-a837d5854182"), CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), LegalAgreementCode = "ToS", LegalText = @"<p><strong>HealthGateway Terms of Service</strong></p> <p> Use of this service is governed by the following terms and conditions. Please read these terms and conditions carefully, as by using this website you will be deemed to have agreed to them. If you do not agree with these terms and conditions, do not use this service. </p> <p> The Health Gateway provides BC residents with access to their health information empowering patients and their families to manage their health care. In accessing your health information through this service, you acknowledge that the information within does not represent a comprehensive record of your health care in BC. No personal health information will be stored within the Health Gateway application. Each time you login, your health information will be fetched from information systems within BC and purged upon logout. If you choose to share your health information accessed through the website with a family member or caregiver, you are responsible for all the actions they take with respect to the use of your information. </p> <p> This service is not intended to provide you with medical advice nor replace the care provided by qualified health care professionals. If you have questions or concerns about your health, please contact your care provider. </p> <p> The personal information you provide (Name and Email) will be used for the purpose of connecting your Health Gateway account to your BC Services Card account under the authority of section 33(a) of the Freedom of Information and Protection of Privacy Act. This will be done through the BC Services Identity Assurance Service. Once your identity is verified using your BC Services Card, you will be able to view your health records from various health information systems in one place. Health Gateway’s collection of your personal information is under the authority of section 26(c) of the Freedom of Information and Protection of Privacy Act. </p> <p> If you have any questions about our collection or use of personal information, please direct your inquiries to the Health Gateway team: </p> <p> <i ><div>Nino Samson</div> <div>Product Owner, Health Gateway</div> <div>Telephone: 778-974-2712</div> <div>Email: nino.samson@gov.bc.ca</div> </i> </p> <p><strong>Limitation of Liabilities</strong></p> <p> Under no circumstances will the Government of British Columbia be liable to any person or business entity for any direct, indirect, special, incidental, consequential, or other damages based on any use of this website or any other website to which this site is linked, including, without limitation, any lost profits, business interruption, or loss of programs or information, even if the Government of British Columbia has been specifically advised of the possibility of such damages. </p>", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("ec438d12-f8e2-4719-8444-28e35d34674c"), CreatedBy = "System", CreatedDateTime = new DateTime(2020, 3, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2020, 3, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), LegalAgreementCode = "ToS", LegalText = @"<p><strong>HealthGateway Terms of Service</strong></p> <p> Use of the Health Gateway service (the “Service”) is governed by the following terms and conditions. Please read these terms and conditions carefully, as by using the Service you will be deemed to have agreed to them. If you do not agree with these terms and conditions, please do not use the Service. </p> <p> <p><strong>1. The Health Gateway Service</strong></p> The Service provides residents of British Columbia with access to their health information (<strong>""Health Information""</strong>). It allows users to, in one place, view their Health Information from various Provincial health information systems, empowering patients and their families to manage their health care. </p> <p><strong>2. Your use of the Service </strong></p> <p> You may only access your own Health Information using the Service. </p> <p> If you choose to share the Health Information accessed through this Service with others (e.g. with a family member or caregiver), you are responsible for all the actions they take with respect to the use of your Health Information. </p> <p> You must follow any additional terms and conditions made available to you in relation to the Service. </p> <p> Do not misuse the Service, for example by trying to access or use it using a method other than the interface and instructions we provide. You may use the Service only as permitted by law. We may suspend or stop providing the Service to you if you do not comply with these terms and conditions, or if we are investigating a suspected misuse of the Service. </p> <p> Using the Service does not give you ownership of any intellectual property rights in the Service or the content you access. Don’t remove, obscure, or alter any legal notices displayed in connection with the Service. </p> <p> We may stop providing the Service to you, or may add or create new limits on the Service, for any reason and at any time. </p> <p><strong>3. Service is not a comprehensive health record or medical advice</strong></p> <p> The Health Information accessed through this Service is not a comprehensive record of your health care in BC. </p> <p> This Service is not intended to provide you with medical advice or replace the care provided by qualified health care professionals. If you have questions or concerns about your health, please contact your care provider. </p> <p><strong>4. Privacy Notice</strong></p> <p> The personal information you provide the Service (Name and Email) will be used for the purpose of connecting your Health Gateway account to your BC Services Card account under the authority of section 26(c) of the Freedom of Information and Protection of Privacy Act. Once your BC Services Card is verified by the Service, you will be able to view your Health Information using the Service. The Service’s collection of your personal information is under the authority of section 26(c) of the Freedom of Information and Protection of Privacy Act. </p> <p> The Service’s notes feature allows you to enter your own notes to provide more information related to your health care. Use of this feature is entirely voluntary. Any notes will be stored in the Health Gateway in perpetuity, or until you choose to delete your account or remove specific notes. Any notes that you create can only be accessed by you securely using your BC Services Card. </p> <p> If you have any questions about our collection or use of personal information, please direct your inquiries to the Health Gateway team: </p> <p> <i> <div>Nino Samson</div> <div>Product Owner, Health Gateway</div> <div>Telephone: <a href=""tel:778-974-2712"">778-974-2712</a></div> <div>Email: <a href=""mailto:nino.samson@gov.bc.ca"">nino.samson@gov.bc.ca</a></div> </i> </p> <p><strong>5. Warranty Disclaimer</strong></p> <p> The Service and all of the information it contains are provided "" as is"" without warranty of any kind, whether express or implied. All implied warranties, including, without limitation, implied warranties of merchantability, fitness for a particular purpose, and non-infringement, are hereby expressly disclaimed. </p> <p><strong>6. Limitation of Liabilities</strong></p> <p> Under no circumstances will the Government of British Columbia be liable to any person or business entity for any direct, indirect, special, incidental, consequential, or other damages based on any use of the Service or any website or system to which this Service may be linked, including, without limitation, any lost profits, business interruption, or loss of programs or information, even if the Government of British Columbia has been specifically advised of the possibility of such damages. </p> <p><strong>7. About these Terms and Conditions</strong></p> <p> We may modify these terms and conditions, or any additional terms and conditions that apply to the Service, at any time, for example to reflect changes to the law or changes to the Service. You should review these terms and conditions regularly. Changes to these terms and conditions will be effective immediately after they are posted. If you do not agree to any changes to these terms, you should discontinue your use of the Service immediately. If there is any conflict between these terms and conditions and any additional terms and conditions, the additional terms and conditions will prevail. These terms and conditions are governed by and to be construed in accordance with the laws of British Columbia and the federal laws of Canada applicable therein. </p>", UpdatedBy = "System", UpdatedDateTime = new DateTime(2020, 3, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { Id = new Guid("1d94c170-5118-4aa6-ba31-e3e07274ccbd"), CreatedBy = "System", CreatedDateTime = new DateTime(2020, 6, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), EffectiveDate = new DateTime(2020, 7, 31, 0, 0, 0, 0, DateTimeKind.Unspecified), LegalAgreementCode = "ToS", LegalText = @"<p><strong>HealthGateway Terms of Service</strong></p> <p> Use of the Health Gateway service (the <strong>""Service""</strong>) is governed by the following terms and conditions. Please read these terms and conditions carefully, as by using the Service you will be deemed to have agreed to them. If you do not agree with these terms and conditions, please do not use the Service. </p> <p> <p><strong>1. The Health Gateway Service</strong></p> <p> The Service provides residents of British Columbia with access to their health information (<strong>""Health Information""</strong>). It allows users to, in one place, view their Health Information from various Provincial health information systems, empowering patients and their families to manage their health care. </p> <p><strong>2. Your use of the Service</strong></p> <p> You may only access your own Health Information using the Service. </p> <p> If you choose to share the Health Information accessed through this Service with others (e.g. with a family member or caregiver), you are responsible for all the actions they take with respect to the use of your Health Information. </p> <p> You must follow any additional terms and conditions made available to you in relation to the Service. </p> <p> Do not misuse the Service, for example by trying to access or use it using a method other than the interface and instructions we provide. You may use the Service only as permitted by law. We may suspend or stop providing the Service to you if you do not comply with these terms and conditions, or if we are investigating a suspected misuse of the Service. </p> <p> Using the Service does not give you ownership of any intellectual property rights in the Service or the content you access. Don’t remove, obscure, or alter any legal notices displayed in connection with the Service. </p> <p> We may stop providing the Service to you, or may add or create new limits on the Service, for any reason and at any time. </p> <p><strong>3. Service is not a comprehensive health record or medical advice</strong></p> <p> The Health Information accessed through this Service is not a comprehensive record of your health care in BC. </p> <p> This Service is not intended to provide you with medical advice or replace the care provided by qualified health care professionals. If you have questions or concerns about your health, please contact your care provider. </p> <p><strong>4. Privacy Notice</strong></p> <p> Your personal information will be collected by the Health Gateway (Ministry of Health) and Service BC under the authority of section 26(c) of the Freedom of Information and Protection of Privacy Act for the purpose of providing access to your health records. Your personal information such as name, email and cell phone number will be shared with other public health service agencies to query your health information and notify you of updates. Your personal information will not be used or disclosed for any other purposes. </p> <p> The Service’s notes and comments features allow you to enter your own notes to provide more information related to your health care. Use of these features is entirely voluntary. Any notes will be stored in the Health Gateway until you choose to delete your account or remove specific notes. Any notes that you create can only be accessed by you securely using your BC Services Card. </p> <p> If you have any questions about our collection or use of personal information, please direct your inquiries to the Health Gateway team: </p> <p> <i> Nino Samson<br /> Product Owner, Health Gateway<br /> Telephone: <a href=""tel:778-974-2712"">778-974-2712</a><br /> Email: <a href=""mailto:nino.samson@gov.bc.ca"">nino.samson@gov.bc.ca</a><br /> Address: 1483 Douglas Street; PO BOX 9635 STN PROV GOVT, Victoria BC<br /> </i> </p> <p><strong>5. Warranty Disclaimer</strong></p> <p> The Service and all of the information it contains are provided ""as is"" without warranty of any kind, whether express or implied. All implied warranties, including, without limitation, implied warranties of merchantability, fitness for a particular purpose, and non-infringement, are hereby expressly disclaimed. </p> <p><strong>6. Limitation of Liabilities</strong></p> <p> Under no circumstances will the Government of British Columbia be liable to any person or business entity for any direct, indirect, special, incidental, consequential, or other damages based on any use of the Service or any website or system to which this Service may be linked, including, without limitation, any lost profits, business interruption, or loss of programs or information, even if the Government of British Columbia has been specifically advised of the possibility of such damages. </p> <p><strong>7. About these Terms and Conditions</strong></p> <p> We may modify these terms of service, or any additional terms that apply to the Service, at any time, for example to reflect changes to the law or changes to the Service. You should review these terms of service regularly. Changes to these terms of service will be effective immediately after they are posted. If you do not agree to any changes to these terms, you should discontinue your use of the Service immediately. </p> <p> If there is any conflict between these terms of service and any additional terms of service, the additional terms of service will prevail. </p> <p> These terms of service are governed by and to be construed in accordance with the laws of British Columbia and the federal laws of Canada applicable therein. </p>", UpdatedBy = "System", UpdatedDateTime = new DateTime(2020, 6, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.LegalAgreementTypeCode", b => { b.Property<string>("LegalAgreementCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(50)") .HasMaxLength(50); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("LegalAgreementCode"); b.ToTable("LegalAgreementTypeCode"); b.HasData( new { LegalAgreementCode = "ToS", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Terms of Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.MessagingVerification", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("MessagingVerificationId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<bool>("Deleted") .HasColumnType("boolean"); b.Property<Guid?>("EmailId") .HasColumnType("uuid"); b.Property<DateTime>("ExpireDate") .HasColumnType("timestamp without time zone"); b.Property<string>("HdId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<Guid>("InviteKey") .HasColumnType("uuid"); b.Property<string>("SMSNumber") .HasColumnType("text"); b.Property<string>("SMSValidationCode") .HasColumnType("character varying(6)") .HasMaxLength(6); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<bool>("Validated") .HasColumnType("boolean"); b.Property<int>("VerificationAttempts") .HasColumnType("integer"); b.Property<string>("VerificationType") .IsRequired() .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("EmailId"); b.HasIndex("VerificationType"); b.ToTable("MessagingVerification"); }); modelBuilder.Entity("HealthGateway.Database.Models.MessagingVerificationTypeCode", b => { b.Property<string>("MessagingVerificationCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(50)") .HasMaxLength(50); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("MessagingVerificationCode"); b.ToTable("MessagingVerificationTypeCode"); b.HasData( new { MessagingVerificationCode = "Email", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Email Verification Type Code", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { MessagingVerificationCode = "SMS", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "SMS Verification Type Code", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.Note", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("NoteId") .HasColumnType("uuid"); b.Property<string>("HdId") .HasColumnName("UserProfileId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<DateTime>("JournalDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Text") .HasColumnType("character varying(1344)") .HasMaxLength(1344); b.Property<string>("Title") .HasColumnType("character varying(152)") .HasMaxLength(152); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id", "HdId"); b.HasIndex("HdId"); b.ToTable("Note"); }); modelBuilder.Entity("HealthGateway.Database.Models.Packaging", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("PackagingId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("PackageSize") .HasColumnType("character varying(5)") .HasMaxLength(5); b.Property<string>("PackageSizeUnit") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("PackageSizeUnitFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("PackageType") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("PackageTypeFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("ProductInformation") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UPC") .HasColumnType("character varying(12)") .HasMaxLength(12); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("Packaging"); }); modelBuilder.Entity("HealthGateway.Database.Models.PharmaCareDrug", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("PharmaCareDrugId") .HasColumnType("uuid"); b.Property<string>("BenefitGroupList") .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<string>("BrandName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("CFRCode") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("DINPIN") .IsRequired() .HasColumnType("character varying(8)") .HasMaxLength(8); b.Property<string>("DosageForm") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<DateTime>("EffectiveDate") .HasColumnType("Date"); b.Property<DateTime>("EndDate") .HasColumnType("Date"); b.Property<Guid>("FileDownloadId") .HasColumnType("uuid"); b.Property<DateTime>("FormularyListDate") .HasColumnType("Date"); b.Property<string>("GenericName") .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<string>("LCAIndicator") .HasColumnType("character varying(2)") .HasMaxLength(2); b.Property<decimal?>("LCAPrice") .HasColumnType("decimal(8,4)"); b.Property<string>("LimitedUseFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("Manufacturer") .HasColumnType("character varying(6)") .HasMaxLength(6); b.Property<int?>("MaximumDaysSupply") .HasColumnType("integer"); b.Property<decimal?>("MaximumPrice") .HasColumnType("decimal(8,4)"); b.Property<string>("PayGenericIndicator") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("PharmaCarePlanDescription") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("Plan") .HasColumnType("character varying(2)") .HasMaxLength(2); b.Property<int?>("QuantityLimit") .HasColumnType("integer"); b.Property<string>("RDPCategory") .HasColumnType("character varying(4)") .HasMaxLength(4); b.Property<string>("RDPExcludedPlans") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<decimal?>("RDPPrice") .HasColumnType("decimal(8,4)"); b.Property<string>("RDPSubCategory") .HasColumnType("character varying(4)") .HasMaxLength(4); b.Property<string>("TrialFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("FileDownloadId"); b.ToTable("PharmaCareDrug"); }); modelBuilder.Entity("HealthGateway.Database.Models.PharmaceuticalStd", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("PharmaceuticalStdId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("PharmaceuticalStdDesc") .HasColumnType("text"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("PharmaceuticalStd"); }); modelBuilder.Entity("HealthGateway.Database.Models.ProgramTypeCode", b => { b.Property<string>("ProgramCode") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .IsRequired() .HasColumnType("character varying(50)") .HasMaxLength(50); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("ProgramCode"); b.ToTable("ProgramTypeCode"); b.HasData( new { ProgramCode = "FED-DRUG-A", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Federal Approved Drug Load", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "FED-DRUG-M", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Federal Marketed Drug Load", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "FED-DRUG-C", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Federal Cancelled Drug Load", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "FED-DRUG-D", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Federal Dormant Drug Load", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "PROV-DRUG", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Provincial Pharmacare Drug Load", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "CFG", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Configuration Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "WEB", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Web Client", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "IMM", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Immunization Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "PAT", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Patient Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "MED", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Medication Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "LAB", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Laboratory Service", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "ADMIN", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Admin Client", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }, new { ProgramCode = "JOBS", CreatedBy = "System", CreatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Description = "Job Scheduler", UpdatedBy = "System", UpdatedDateTime = new DateTime(2019, 5, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Version = 0u }); }); modelBuilder.Entity("HealthGateway.Database.Models.Route", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("RouteId") .HasColumnType("uuid"); b.Property<string>("Administration") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<int>("AdministrationCode") .HasColumnType("integer"); b.Property<string>("AdministrationFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("Route"); }); modelBuilder.Entity("HealthGateway.Database.Models.Schedule", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("ScheduleId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("ScheduleDesc") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("ScheduleDescFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.ToTable("Schedule"); }); modelBuilder.Entity("HealthGateway.Database.Models.Status", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("StatusId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("CurrentStatusFlag") .HasColumnType("character varying(1)") .HasMaxLength(1); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp without time zone"); b.Property<DateTime?>("HistoryDate") .HasColumnType("timestamp without time zone"); b.Property<string>("LotNumber") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("StatusDesc") .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("StatusDescFrench") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId"); b.ToTable("Status"); }); modelBuilder.Entity("HealthGateway.Database.Models.TherapeuticClass", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("TherapeuticClassId") .HasColumnType("uuid"); b.Property<string>("Ahfs") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("AhfsFrench") .HasColumnType("character varying(160)") .HasMaxLength(160); b.Property<string>("AhfsNumber") .HasColumnType("character varying(20)") .HasMaxLength(20); b.Property<string>("Atc") .HasColumnType("character varying(120)") .HasMaxLength(120); b.Property<string>("AtcFrench") .HasColumnType("character varying(240)") .HasMaxLength(240); b.Property<string>("AtcNumber") .HasColumnType("character varying(8)") .HasMaxLength(8); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("TherapeuticClass"); }); modelBuilder.Entity("HealthGateway.Database.Models.UserFeedback", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("UserFeedbackId") .HasColumnType("uuid"); b.Property<string>("Comment") .HasColumnType("character varying(500)") .HasMaxLength(500); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<bool>("IsReviewed") .HasColumnType("boolean"); b.Property<bool>("IsSatisfied") .HasColumnType("boolean"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("UserProfileId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("UserProfileId"); b.ToTable("UserFeedback"); }); modelBuilder.Entity("HealthGateway.Database.Models.UserPreference", b => { b.Property<string>("HdId") .HasColumnName("UserProfileId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<string>("Preference") .HasColumnType("text"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Value") .IsRequired() .HasColumnType("text"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("HdId", "Preference"); b.ToTable("UserPreference"); }); modelBuilder.Entity("HealthGateway.Database.Models.UserProfile", b => { b.Property<string>("HdId") .HasColumnName("UserProfileId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<bool>("AcceptedTermsOfService") .HasColumnType("boolean"); b.Property<DateTime?>("ClosedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Email") .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<string>("EncryptionKey") .HasColumnType("character varying(44)") .HasMaxLength(44); b.Property<Guid?>("IdentityManagementId") .HasColumnType("uuid"); b.Property<DateTime?>("LastLoginDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("SMSNumber") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("HdId"); b.ToTable("UserProfile"); }); modelBuilder.Entity("HealthGateway.Database.Models.UserProfileHistory", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("UserProfileHistoryId") .HasColumnType("uuid"); b.Property<bool>("AcceptedTermsOfService") .HasColumnType("boolean"); b.Property<DateTime?>("ClosedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Email") .HasColumnType("character varying(254)") .HasMaxLength(254); b.Property<string>("EncryptionKey") .HasColumnType("character varying(44)") .HasMaxLength(44); b.Property<string>("HdId") .IsRequired() .HasColumnName("UserProfileId") .HasColumnType("character varying(52)") .HasMaxLength(52); b.Property<Guid?>("IdentityManagementId") .HasColumnType("uuid"); b.Property<DateTime?>("LastLoginDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("Operation") .IsRequired() .HasColumnType("text"); b.Property<DateTime>("OperationDateTime") .HasColumnType("timestamp without time zone"); b.Property<string>("SMSNumber") .HasColumnType("character varying(10)") .HasMaxLength(10); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.ToTable("UserProfileHistory"); }); modelBuilder.Entity("HealthGateway.Database.Models.VeterinarySpecies", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("VeterinarySpeciesId") .HasColumnType("uuid"); b.Property<string>("CreatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("CreatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<Guid>("DrugProductId") .HasColumnType("uuid"); b.Property<string>("Species") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("SpeciesFrench") .HasColumnType("character varying(160)") .HasMaxLength(160); b.Property<string>("SubSpecies") .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("UpdatedBy") .IsRequired() .HasColumnType("character varying(60)") .HasMaxLength(60); b.Property<DateTime>("UpdatedDateTime") .HasColumnType("timestamp without time zone"); b.Property<uint>("Version") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnName("xmin") .HasColumnType("xid"); b.HasKey("Id"); b.HasIndex("DrugProductId") .IsUnique(); b.ToTable("VeterinarySpecies"); }); modelBuilder.Entity("HealthGateway.Database.Models.ActiveIngredient", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("ActiveIngredient") .HasForeignKey("HealthGateway.Database.Models.ActiveIngredient", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.ApplicationSetting", b => { b.HasOne("HealthGateway.Database.Models.ProgramTypeCode", null) .WithMany() .HasForeignKey("Application") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.AuditEvent", b => { b.HasOne("HealthGateway.Database.Models.ProgramTypeCode", null) .WithMany() .HasForeignKey("ApplicationType") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthGateway.Database.Models.AuditTransactionResultCode", null) .WithMany() .HasForeignKey("TransactionResultCode") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Comment", b => { b.HasOne("HealthGateway.Database.Models.UserProfile", "UserProfile") .WithMany() .HasForeignKey("UserProfileId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Communication", b => { b.HasOne("HealthGateway.Database.Models.CommunicationStatusCode", null) .WithMany() .HasForeignKey("CommunicationStatusCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthGateway.Database.Models.CommunicationTypeCode", null) .WithMany() .HasForeignKey("CommunicationTypeCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.CommunicationEmail", b => { b.HasOne("HealthGateway.Database.Models.Communication", "Communication") .WithMany() .HasForeignKey("CommunicationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthGateway.Database.Models.Email", "Email") .WithMany() .HasForeignKey("EmailId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthGateway.Database.Models.UserProfile", "UserProfile") .WithMany() .HasForeignKey("UserProfileHdId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Company", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("Company") .HasForeignKey("HealthGateway.Database.Models.Company", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.DrugProduct", b => { b.HasOne("HealthGateway.Database.Models.FileDownload", "FileDownload") .WithMany() .HasForeignKey("FileDownloadId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Email", b => { b.HasOne("HealthGateway.Database.Models.EmailStatusCode", null) .WithMany() .HasForeignKey("EmailStatusCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthGateway.Database.Models.EmailFormatCode", null) .WithMany() .HasForeignKey("FormatCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.EmailTemplate", b => { b.HasOne("HealthGateway.Database.Models.EmailFormatCode", null) .WithMany() .HasForeignKey("FormatCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.FileDownload", b => { b.HasOne("HealthGateway.Database.Models.ProgramTypeCode", null) .WithMany() .HasForeignKey("ProgramCode") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Form", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("Form") .HasForeignKey("HealthGateway.Database.Models.Form", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.LegalAgreement", b => { b.HasOne("HealthGateway.Database.Models.LegalAgreementTypeCode", null) .WithMany() .HasForeignKey("LegalAgreementCode") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.MessagingVerification", b => { b.HasOne("HealthGateway.Database.Models.Email", "Email") .WithMany() .HasForeignKey("EmailId"); b.HasOne("HealthGateway.Database.Models.MessagingVerificationTypeCode", null) .WithMany() .HasForeignKey("VerificationType") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Note", b => { b.HasOne("HealthGateway.Database.Models.UserProfile", null) .WithMany() .HasForeignKey("HdId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Packaging", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("Packaging") .HasForeignKey("HealthGateway.Database.Models.Packaging", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.PharmaCareDrug", b => { b.HasOne("HealthGateway.Database.Models.FileDownload", "FileDownload") .WithMany() .HasForeignKey("FileDownloadId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.PharmaceuticalStd", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", "DrugProduct") .WithOne("PharmaceuticalStd") .HasForeignKey("HealthGateway.Database.Models.PharmaceuticalStd", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Route", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("Route") .HasForeignKey("HealthGateway.Database.Models.Route", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.Status", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithMany("Statuses") .HasForeignKey("DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.TherapeuticClass", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("TherapeuticClass") .HasForeignKey("HealthGateway.Database.Models.TherapeuticClass", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthGateway.Database.Models.UserFeedback", b => { b.HasOne("HealthGateway.Database.Models.UserProfile", "UserProfile") .WithMany() .HasForeignKey("UserProfileId"); }); modelBuilder.Entity("HealthGateway.Database.Models.VeterinarySpecies", b => { b.HasOne("HealthGateway.Database.Models.DrugProduct", null) .WithOne("VeterinarySpecies") .HasForeignKey("HealthGateway.Database.Models.VeterinarySpecies", "DrugProductId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
43.398075
343
0.462234
[ "Apache-2.0" ]
WadeBarnes/healthgateway
Apps/Database/src/Migrations/20200803222317_PushBannerChange.Designer.cs
148,835
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dolittle.Execution.for_WeakDelegate { public class ClassWithMethod { public const int ReturnValue = 42; public int SomeMethod(string stringParameter, double intParameter) { return ReturnValue; } public int SomeOtherMethod(IInterface input) { return ReturnValue; } } }
24.952381
101
0.652672
[ "MIT" ]
dolittle-fundamentals/DotNET.Fundamentals
Specifications/Execution/for_WeakDelegate/ClassWithMethod.cs
526
C#
#if HE_SYSCORE && STEAMWORKS_NET && HE_STEAMCOMPLETE && !HE_STEAMFOUNDATION && !DISABLESTEAMWORKS using UnityEngine; namespace HeathenEngineering.SteamworksIntegration { public class InputActionSet : ScriptableObject { public string setName; public Steamworks.InputActionSetHandle_t Handle => handle; private Steamworks.InputActionSetHandle_t handle; public bool IsActive(Steamworks.InputHandle_t controller) { if (handle.m_InputActionSetHandle == 0) handle = API.Input.Client.GetActionSetHandle(setName); if (handle.m_InputActionSetHandle != 0) { var layers = API.Input.Client.GetCurrentActionSet(controller); if (layers.m_InputActionSetHandle == handle.m_InputActionSetHandle) return true; else return false; } else return false; } public void Activate(Steamworks.InputHandle_t controller) { if (handle.m_InputActionSetHandle == 0) handle = API.Input.Client.GetActionSetHandle(setName); if (handle.m_InputActionSetHandle != 0) { API.Input.Client.ActivateActionSet(controller, handle); } } } #if UNITY_EDITOR [UnityEditor.CustomEditor(typeof(InputActionSet))] public class InputActionSetEditor : UnityEditor.Editor { public override void OnInspectorGUI() { } } #endif } #endif
30.627451
99
0.612036
[ "MIT" ]
KD-Kevin/Age-of-War---Like-Game
Age Of War Game/Assets/Imported Assets/_Heathen Engineering/Assets/com.heathen.steamworkscomplete/Runtime/InputActionSet.cs
1,564
C#
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.Extensions.Logging; using Microsoft.Owin; using Steeltoe.Common; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Endpoint.CloudFoundry; using Steeltoe.Management.Endpoint.Security; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Steeltoe.Management.EndpointOwin.CloudFoundry { public class CloudFoundrySecurityOwinMiddleware : OwinMiddleware { private ILogger<CloudFoundrySecurityOwinMiddleware> _logger; private ICloudFoundryOptions _options; private SecurityBase _base; private IManagementOptions _mgmtOptions; public CloudFoundrySecurityOwinMiddleware(OwinMiddleware next, ICloudFoundryOptions options, IEnumerable<IManagementOptions> mgmtOptions, ILogger<CloudFoundrySecurityOwinMiddleware> logger = null) : base(next) { _options = options; _logger = logger; _mgmtOptions = mgmtOptions.OfType<CloudFoundryManagementOptions>().Single(); _base = new SecurityBase(options, _mgmtOptions, logger); } [Obsolete] public CloudFoundrySecurityOwinMiddleware(OwinMiddleware next, ICloudFoundryOptions options, ILogger<CloudFoundrySecurityOwinMiddleware> logger = null) : base(next) { _options = options; _logger = logger; _base = new SecurityBase(options, logger); } public override async Task Invoke(IOwinContext context) { #pragma warning disable CS0612 // Type or member is obsolete bool isEnabled = _mgmtOptions == null ? _options.IsEnabled : _options.IsEnabled(_mgmtOptions); #pragma warning restore CS0612 // Type or member is obsolete // if running on Cloud Foundry, security is enabled, the path starts with /cloudfoundryapplication... if (Platform.IsCloudFoundry && isEnabled && _base.IsCloudFoundryRequest(context.Request.Path.ToString())) { context.Response.Headers.Set("Access-Control-Allow-Credentials", "true"); context.Response.Headers.Set("Access-Control-Allow-Origin", context.Request.Headers.Get("origin")); context.Response.Headers.Set("Access-Control-Allow-Headers", "Authorization,X-Cf-App-Instance,Content-Type"); // don't run security for a CORS request, do return 204 if (context.Request.Method == "OPTIONS") { context.Response.StatusCode = (int)HttpStatusCode.NoContent; return; } _logger?.LogTrace("Beginning Cloud Foundry Security Processing"); // identify the application so we can confirm the user making the request has permission if (string.IsNullOrEmpty(_options.ApplicationId)) { await ReturnError(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, _base.APPLICATION_ID_MISSING_MESSAGE)); return; } // make sure we know where to get user permissions if (string.IsNullOrEmpty(_options.CloudFoundryApi)) { await ReturnError(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, _base.CLOUDFOUNDRY_API_MISSING_MESSAGE)); return; } _logger?.LogTrace("Identifying which endpoint the request at {EndpointRequestPath} is for", context.Request.Path); IEndpointOptions target = FindTargetEndpoint(context.Request.Path); if (target == null) { await ReturnError(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, _base.ENDPOINT_NOT_CONFIGURED_MESSAGE)); return; } _logger?.LogTrace("Getting user permissions"); var sr = await GetPermissions(context); if (sr.Code != HttpStatusCode.OK) { await ReturnError(context, sr); return; } _logger?.LogTrace("Applying user permissions to request"); var permissions = sr.Permissions; if (!target.IsAccessAllowed(permissions)) { await ReturnError(context, new SecurityResult(HttpStatusCode.Forbidden, _base.ACCESS_DENIED_MESSAGE)); return; } _logger?.LogTrace("Access granted!"); } await Next.Invoke(context); } internal async Task<SecurityResult> GetPermissions(IOwinContext context) { string token = GetAccessToken(context.Request); return await _base.GetPermissionsAsync(token); } internal string GetAccessToken(IOwinRequest request) { if (request.Headers.TryGetValue(_base.AUTHORIZATION_HEADER, out string[] headerVal)) { string header = headerVal[0]; if (header?.StartsWith(_base.BEARER, StringComparison.OrdinalIgnoreCase) == true) { return header.Substring(_base.BEARER.Length + 1); } } return null; } private IEndpointOptions FindTargetEndpoint(PathString path) { List<IEndpointOptions> configEndpoints; // Remove in 3.0 if (_mgmtOptions == null) { #pragma warning disable CS0612 // Type or member is obsolete configEndpoints = _options.Global.EndpointOptions; #pragma warning restore CS0612 // Type or member is obsolete foreach (var ep in configEndpoints) { PathString epPath = new PathString(ep.Path); if (path.StartsWithSegments(epPath)) { return ep; } } return null; } configEndpoints = _mgmtOptions.EndpointOptions; foreach (var ep in configEndpoints) { var contextPath = _mgmtOptions.Path; if (!contextPath.EndsWith("/") && !string.IsNullOrEmpty(ep.Path)) { contextPath += "/"; } var fullPath = contextPath + ep.Path; if (path.StartsWithSegments(new PathString(fullPath))) { return ep; } } return null; } private async Task ReturnError(IOwinContext context, SecurityResult error) { LogError(context, error); context.Response.Headers.SetValues("Content-Type", new string[] { "application/json;charset=UTF-8" }); context.Response.StatusCode = (int)error.Code; await context.Response.WriteAsync(_base.Serialize(error)); } private void LogError(IOwinContext context, SecurityResult error) { _logger?.LogError("Actuator Security Error: {ErrorCode} - {ErrorMessage}", error.Code, error.Message); if (_logger?.IsEnabled(LogLevel.Trace) == true) { foreach (var header in context.Request.Headers) { _logger?.LogTrace("Header: {HeaderKey} - {HeaderValue}", header.Key, header.Value); } } } } }
40.544554
204
0.601587
[ "ECL-2.0", "Apache-2.0" ]
spring-operator/Management
src/Steeltoe.Management.EndpointOwin/CloudFoundry/CloudFoundrySecurityOwinMiddleware.cs
8,192
C#
using System; namespace Jal.Monads { public delegate Exceptional<T> Try<T>(); public static class TryCoreExtensions { public static Try<T> AsTry<T>(this Func<T> func) { return () => Exceptional<T>.Return(func()); } public static Exceptional<T> Run<T>(this Try<T> @try) { try { return @try(); } catch (Exception e) { return Exceptional<T>.Return(e); } } public static Try<O> Bind<T, O>(this Try<T> @try, Func<T, Try<O>> func) { if (func == null) { throw new ArgumentNullException(nameof(func)); } Try<O> f = () => @try.Run().Match(t => func(t).Run(), exception => Exceptional<O>.Return(exception)); return f; } public static Try<O> Map<T, O>(this Try<T> @try, Func<T, O> func) { if (func == null) { throw new ArgumentNullException(nameof(func)); } Try<O> f = () => @try.Run().Match(t => Exceptional<O>.Return(func(t)), exception => Exceptional<O>.Return(exception)); return f; } public static R Match<T, R>(this Try<T> @try, Func<T, R> success, Func<Exception, R> failure) { if (success == null) throw new ArgumentNullException(nameof(success)); if (failure == null) throw new ArgumentNullException(nameof(failure)); var res = @try.Run(); return res.HasException ? failure(res.Exception) : success(res.Value); } } }
26.953125
130
0.478841
[ "Apache-2.0" ]
raulnq/Jal.Monads
Jal.Monads/Extensions/TryCoreExtensions.cs
1,727
C#
using System.ComponentModel.DataAnnotations; namespace SmartHome.DomainCore.Data.Models { public class CreateUserModel { [Required] public string? UserName { get; set; } [Required] public string? Email { get; set; } [Required] public string? Password { get; set; } } }
21.6875
45
0.585014
[ "MIT" ]
JanPalasek/smart-home-server
SmartHome.DomainCore/Data/Models/CreateUserModel.cs
347
C#
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.AI; using UnityEngine.SceneManagement; namespace Enemy { [RequireComponent(typeof(NavMeshAgent))] public class BossMovement : MonoBehaviour { Transform player; GameObject playerObject; NavMeshAgent agent; Animator anim; SceneData InfoSaver; private VelocityReporter playerVelocityReporter; public GameObject leftLegCollider; public GameObject rightLegCollider; public GameObject leftArmCollider; public GameObject rightArmCollider; public GameObject forceAttackCollider; public bool isInvincible; public bool canMove; public bool isDead; public float attackDistance = 2.0f; public float dot; public PlayerHealth playerHealth; public float health; public event Action<float> OnHealthPctChanged = delegate { }; private float maxHealth = 1200; public bool ableToDealDamage = true; public AudioClip hitClip; public AudioClip deathClip; public AudioClip powerUp; public AudioClip powerDown; public AudioClip stomp; public AudioClip explosion; public AudioClip fireballClip; AudioSource enemyAudio; private Quaternion previousRotation; public EndGameManager endMenu; public float delta; private bool strongAttack = false; public int numAttacks; private int randomAnimSelector = 0; public GameObject[] floorArray; private int floorPointer = 0; public GameObject forceAttackRenderer; ParticleSystem hitParticles; private bool forceDamagePossible = false; public GameObject projectile; public float dist_2; public float radius; private TransitionController transitionController; //private int num_moves_start = 1; //private int num_moves_end = 2; //private bool phase_two = false; public enum AIState { chasePlayer, attack, idle, throwProjectile }; public AIState aiState; public float dist; private void Awake() { leftLegCollider.SetActive(false); rightLegCollider.SetActive(false); leftArmCollider.SetActive(false); rightArmCollider.SetActive(false); forceAttackCollider.SetActive(false); player = GameObject.FindGameObjectWithTag("Player").transform; playerObject = GameObject.FindGameObjectWithTag("Player"); InfoSaver = GameObject.FindGameObjectWithTag("InfoSaver").GetComponent<SceneData>(); health = this.maxHealth; agent = GetComponent<NavMeshAgent>(); anim = GetComponentInChildren<Animator>(); playerVelocityReporter = player.GetComponent<VelocityReporter>(); aiState = AIState.chasePlayer; dist = Vector3.Distance(player.position, transform.position); playerHealth = player.GetComponent<PlayerHealth>(); enemyAudio = GetComponent<AudioSource>(); agent.speed = InfoSaver.getAgentSpeed(); hitParticles = GetComponentInChildren<ParticleSystem>(); transitionController = GameObject.FindGameObjectWithTag("TransitionController").GetComponent<TransitionController>(); } // Update is called once per frame void Update() { delta = Time.deltaTime; if (isInvincible) { isInvincible = !canMove; } canMove = anim.GetBool("can_move"); if (health <= 0.75*this.maxHealth && canMove && !InfoSaver.getPhase_two()) { anim.SetBool("IsIdle", true); anim.SetBool("can_move", false); anim.Play("Luigi_PhaseTwo"); agent.isStopped = true; anim.applyRootMotion = true; aiState = AIState.idle; idle(); } if (!canMove && !isDead && randomAnimSelector != 2) { Quaternion rotationAngle = Quaternion.LookRotation(player.position - transform.position); if (randomAnimSelector == 4) { transform.rotation = Quaternion.Slerp(transform.rotation, rotationAngle, delta); } else { transform.rotation = Quaternion.Slerp(transform.rotation, rotationAngle, delta / InfoSaver.getSlepSpeed()); } } if (canMove && !isDead) { agent.enabled = true; agent.isStopped = false; anim.applyRootMotion = false; dist = Vector3.Distance(player.position, transform.position); dot = Vector3.Dot((player.position - transform.position).normalized, transform.forward.normalized); Quaternion rotationAngle = Quaternion.LookRotation(player.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotationAngle, delta); if (dist <= attackDistance && dot >= 0.75) { anim.applyRootMotion = false; aiState = AIState.attack; attack(); } if (dist > attackDistance) { anim.applyRootMotion = false; aiState = AIState.chasePlayer; chasePlayer(); } } dist_2 = Vector3.Distance(player.position, transform.position); if (forceDamagePossible && ableToDealDamage && (dist_2 <= 4.7)) { playerHealth.TakeDamage(25, player.position); ableToDealDamage = false; } } void idle() { anim.SetBool("IsIdle", true); chasePlayer(); } void chasePlayer() { anim.SetBool("IsIdle", false); agent.destination = player.position; } /* void chasePlayer() { anim.SetBool("IsIdle", false); dot = Vector3.Dot((transform.position- player.position).normalized, (playerVelocityReporter.velocity).normalized); if (dot >= 0.7f) { agent.destination = player.position; } else { SetDestinationMoving(); } } */ void attack() { anim.SetBool("IsIdle", true); anim.SetBool("can_move", false); randomAnimSelector = (int) UnityEngine.Random.Range(1, InfoSaver.getNumBossMovesEnd() + 1); anim.Play("Luigi_Attack" + randomAnimSelector); agent.isStopped = true; anim.applyRootMotion = true; aiState = AIState.idle; idle(); } public void TakeDamage(float v, Vector3 hitPoint) { if (isInvincible || isDead) return; health -= v; float currentHealthPct = this.health / this.maxHealth; OnHealthPctChanged(currentHealthPct); hitParticles.transform.position = hitPoint; hitParticles.Play(); isInvincible = true; // Play damage animation enemyAudio.clip = hitClip; enemyAudio.Play(); anim.applyRootMotion = true; anim.SetBool("can_move", false); aiState = AIState.idle; agent.isStopped = true; if (health <= 0) { death(); } else { idle(); } } void death() { anim.SetBool("IsIdle", true); anim.SetTrigger("IsDead"); isDead = true; enemyAudio.clip = deathClip; enemyAudio.Play(); endMenu.EndScreen(true); } public void OpenBossLeftLegDamageCollider() { leftLegCollider.SetActive(true); ableToDealDamage = true; } public void OpenBossRightLegDamageCollider() { rightLegCollider.SetActive(true); ableToDealDamage = true; } public void OpenBossForceAttackCollider() { forceDamagePossible = true; ableToDealDamage = true; } public void CloseBossLeftLegDamageCollider() { leftLegCollider.SetActive(false); } public void CloseBossForceAttackCollider() { forceDamagePossible = false; } public void CloseBossRightLegDamageCollider() { rightLegCollider.SetActive(false); } public void GrowOneSize() { transform.localScale += new Vector3(0.65f, 0.65f, 0.65f); } public void playPowerUp() { enemyAudio.clip = powerUp; enemyAudio.Play(); } public void playExplosion() { enemyAudio.clip = explosion; enemyAudio.Play(); } public void ShrinkOneSize() { transform.localScale -= new Vector3(0.65f, 0.65f, 0.65f); } public void playPowerDown() { enemyAudio.clip = powerDown; enemyAudio.Play(); } public void playStomp() { enemyAudio.clip = stomp; enemyAudio.Play(); } public void begin_phase_two() { InfoSaver.SavePlayer(); InfoSaver.setPhase_two(true); playerObject.GetComponent<CapsuleCollider>().enabled = false; playerObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.up * 50, ForceMode.Impulse); transitionController.fadeOut(); InfoSaver.setNumBossMovesEnd(4); InfoSaver.setAgentSpeed(4.0f); InfoSaver.setSlepSpeed(1.5f); // commented out knockbacking //InfoSaver.setBossKnockbackBool(true); InfoSaver.setEnemyBossDamage(20); agent.speed = InfoSaver.getAgentSpeed(); Invoke("load_final_battle", 2.5f); } public void load_final_battle() { SceneManager.LoadScene("Final_Battle"); } public void destroyFloor() { if (floorPointer < floorArray.Length && floorArray[floorPointer] != null) { int i = 0; GameObject destructibleFloor = floorArray[floorPointer]; //GameObject[] childrenObjects = new GameObject[4]; foreach (Transform child in destructibleFloor.transform) { //childrenObjects[i] = child.gameObject; child.gameObject.GetComponent<FloorDestruction>().flashing = true; ++i; } //StartCoroutine(flashCoroutine(childrenObjects, 0.2f)); ++floorPointer; } } /* // should not be used anymore IEnumerator flashCoroutine(GameObject[] childrenObjects, float intervalTime) { float duration = 0.35f; bool stop = false; int index = 0; Color startColor = childrenObjects[0].GetComponent<MeshRenderer>().material.color; Color[] colorArray = { startColor, Color.red }; while (!stop) { for (int i = 0; i < childrenObjects.Length; ++i) { childrenObjects[i].GetComponent<MeshRenderer>().material.color = colorArray[index % 2]; } duration -= Time.deltaTime; if (duration < 0) { stop = true; for (int i = 0; i < childrenObjects.Length; ++i) { childrenObjects[i].GetComponent<FloorDestruction>().destroy = true; } yield break; } ++index; yield return new WaitForSeconds(intervalTime); } } */ /* IEnumerator flashCollider(float intervalTime) { float duration = 0.3f; bool stop = false; int index = 0; forceAttackCollider.SetActive(true); forceAttackCollider.GetComponent<SphereCollider>().enabled = false; while (!stop) { if (index % 5 == 0) { forceAttackRenderer.GetComponent<MeshRenderer>().enabled = true; } else { forceAttackRenderer.GetComponent<MeshRenderer>().enabled = false; } duration -= Time.deltaTime; if (duration < 0) { stop = true; forceAttackCollider.GetComponent<SphereCollider>().enabled = true; forceAttackRenderer.GetComponent<MeshRenderer>().enabled = false; forceAttackCollider.SetActive(false); yield break; } ++index; yield return new WaitForSeconds(intervalTime); } } */ public void playFireball() { enemyAudio.clip = fireballClip; enemyAudio.Play(); } public void generateFireball() { //transform.LookAt(player.position); GameObject fireBall = Instantiate(projectile, transform.position + new Vector3(0, 1.25f, 0), Quaternion.LookRotation(player.position - transform.position)); //fireBall.GetComponent<Rigidbody>().AddRelativeForce(fireBall.transform.forward * 1000); } /* private void SetDestinationMoving() { float dist = (player.position - agent.transform.position).magnitude; float lookAheadT = dist / agent.speed; Vector3 targetVelocity = playerVelocityReporter.velocity; NavMeshHit hit; Vector3 targetPoint = player.position + lookAheadT * targetVelocity; NavMesh.SamplePosition(targetPoint, out hit, 8.0f, -1); agent.destination = hit.position; } */ } }
33.949425
168
0.537175
[ "MIT" ]
egonzalez49/Toy-Souls
Assets/Scripts/Survival_Shooter/BossMovement.cs
14,770
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Domain { /// <summary> /// AlipayOpenAppMessagetemplateSubscribeQueryModel Data Structure. /// </summary> [Serializable] public class AlipayOpenAppMessagetemplateSubscribeQueryModel : AopObject { /// <summary> /// 消息模板id,可以填写多个,最多不超过3个。模板id需要保持同一个应用主体,并且展示在同一个订阅组件中的模板id。 模板id获取详情参见<a href="https://opendocs.alipay.com/mini/01rnqx">模板消息</a>。 /// </summary> [XmlArray("template_id_list")] [XmlArrayItem("string")] public List<string> TemplateIdList { get; set; } /// <summary> /// 订阅消息模板用户的支付宝唯一标识,2088开头。 /// </summary> [XmlElement("user_id")] public string UserId { get; set; } } }
30.592593
140
0.622276
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/AlipayOpenAppMessagetemplateSubscribeQueryModel.cs
992
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SiteInvoicer.Account { public partial class OpenAuthProviders { /// <summary> /// providerDetails control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ListView providerDetails; } }
31.56
84
0.48289
[ "Apache-2.0" ]
yhau1989/InvoiceSite
SiteInvoicer/SiteInvoicer/Account/OpenAuthProviders.ascx.designer.cs
791
C#
using System; namespace svelde.nmea.parser { public class GlgsvMessage : GsvMessage { public GlgsvMessage() { Type = "GLGSV"; } public override void Parse(string nmeaLine) { base.Parse(nmeaLine); } } }
15.684211
51
0.503356
[ "MIT" ]
sandervandevelde/nmeaparser
src/svelde.nmea.parser/GlgsvMessage.cs
300
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SAS.Provider.Core; using SAS_Provider.Models; namespace SAS_Provider.Controllers { [Authorize] public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public string Token() { var storageSasProvider = new StorageSasProvider("fxprgconfit", "0JlbNBt6/5d2yEWU2o35oPXpFncaYNHY8mz5eF4HiSKe1IbKgKKC57Bh8+NznwYJYbm3be+w1t44E8wraS4FNQ=="); var result = storageSasProvider.CreateSasForContainer("auroratest", 0.5).Result; return result; } public IActionResult Privacy() { return View(); } [AllowAnonymous] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
27.092593
167
0.624744
[ "MIT" ]
patrickCode/cloud-9
Storage-Sas-Utility/SAS_Provider/SAS_Provider/Controllers/HomeController.cs
1,465
C#
using Innovator.Client; using InnovatorAdmin.Connections; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace InnovatorAdmin.Scripts { public partial class ScriptWindow : Form { private IAsyncScript _script; private ConnectionData _connData; private IPromise<IAsyncConnection> _conn; private IPromise _currentRun; public ScriptWindow() { InitializeComponent(); this.Icon = (this.Owner ?? Application.OpenForms[0]).Icon; menuStrip.Renderer = new SimpleToolstripRenderer(); } public void SetConnection(ConnectionData connData) { _conn = null; _connData = null; btnEditConnection.Text = "No Connection ▼"; lblConnColor.BackColor = Color.Transparent; if (connData.Type != ConnectionType.Innovator) { Dialog.MessageDialog.Show("Only Innovator connections are supported"); return; } _connData = connData; btnEditConnection.Text = "Connecting... ▼"; _conn = connData.ArasLogin(true) .UiPromise(this) .Done(c => { btnEditConnection.Text = connData.ConnectionName + " ▼"; lblConnColor.BackColor = connData.Color; }); } public ScriptWindow WithScript(IAsyncScript script) { _script = script; lblScriptName.Text = ScriptManager.Instance.GetName(script); propGrid.SelectedObject = _script; return this; } private void mniClose_Click(object sender, EventArgs e) { this.Close(); } private void mniOtherScripts_Click(object sender, EventArgs e) { try { var script = Scripts.ScriptManager.Instance.PromptForScript(this , this.RectangleToScreen(menuStrip.Bounds)); if (script != null) new Scripts.ScriptWindow().WithScript(script).Show(); } catch (Exception ex) { Utils.HandleError(ex); } } private void btnSubmit_Click(object sender, EventArgs e) { try { if (_currentRun == null) { if (_conn == null) { outputEditor.Text = "Please select a connection first"; return; } btnSubmit.Text = "► Cancel"; outputEditor.Text = "Processing..."; _currentRun = _conn .Continue(c => _script.Execute(c)) .UiPromise(this) .Done(s => { outputEditor.Text = s; _currentRun = null; }) .Fail(ex => outputEditor.Text = ex.ToString()); } else { btnSubmit.Text = "► Run"; _currentRun.Cancel(); _currentRun = null; } } catch (Exception ex) { outputEditor.Text = ex.ToString(); } } private void btnEditConnection_Click(object sender, EventArgs e) { using (var dialog = new ConnectionEditorForm()) { dialog.Multiselect = false; if (_connData != null) dialog.SetSelected(_connData); if (dialog.ShowDialog(this, menuStrip.RectangleToScreen(btnEditConnection.Bounds)) == System.Windows.Forms.DialogResult.OK) { SetConnection(dialog.SelectedConnections.First()); } } } } }
25.328467
93
0.597118
[ "MIT" ]
GCAE/InnovatorAdmin
InnovatorAdmin/Scripts/ScriptWindow.cs
3,482
C#
using System; using System.Collections.Generic; using System.Text; namespace Cms.NetCore.ViewModels.param.Role { public class RoleMenuPara { public Guid RoleId { get; set; } public List<MenuButtonAttributes> MenuButtonIds { get; set; } } }
20.769231
69
0.692593
[ "MIT" ]
zznzuoning/Cms.NetCore
Cms.NetCore/Cms.NetCore.ViewModels/param/Role/RoleMenuPara.cs
272
C#
/* * HelloWebApi * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; namespace HelloWebApi.Service.Client { /// <summary> /// API Response /// </summary> public class ApiResponse<T> { /// <summary> /// Gets or sets the status code (HTTP status code) /// </summary> /// <value>The status code.</value> public int StatusCode { get; private set; } /// <summary> /// Gets or sets the HTTP headers /// </summary> /// <value>HTTP headers</value> public IDictionary<string, string> Headers { get; private set; } /// <summary> /// Gets or sets the data (parsed HTTP body) /// </summary> /// <value>The data.</value> public T Data { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ApiResponse&lt;T&gt;" /> class. /// </summary> /// <param name="statusCode">HTTP status code.</param> /// <param name="headers">HTTP headers.</param> /// <param name="data">Data (parsed HTTP body)</param> public ApiResponse(int statusCode, IDictionary<string, string> headers, T data) { this.StatusCode= statusCode; this.Headers = headers; this.Data = data; } } }
28.054545
104
0.572262
[ "MIT" ]
nuitsjp/WebApiStudy
HelloWebApi.Service/src/HelloWebApi.Service/Client/ApiResponse.cs
1,543
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. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeActions.WorkspaceServices { internal interface ISymbolRenamedCodeActionOperationFactoryWorkspaceService : IWorkspaceService { CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution); } }
36.375
142
0.805842
[ "MIT" ]
333fred/roslyn
src/Features/Core/Portable/CodeRefactorings/WorkspaceServices/ISymbolRenamedCodeActionOperationFactoryWorkspaceService.cs
584
C#
using System; using Ayehu.Sdk.ActivityCreation.Interfaces; using Ayehu.Sdk.ActivityCreation.Extension; using Ayehu.Sdk.ActivityCreation.Helpers; using System.Net; using System.Net.Http; using System.Text; using System.Collections.Generic; namespace Ayehu.Thycotic { public class TY_Toggle_Current_State : IActivityAsync { public string endPoint = "https://{hostname}"; public string Jsonkeypath = "enabled"; public string password1 = ""; private bool omitJsonEmptyorNull = true; private string contentType = "application/json"; private string httpMethod = "POST"; private string _uriBuilderPath; private string _postData; private System.Collections.Generic.Dictionary<string, string> _headers; private System.Collections.Generic.Dictionary<string, string> _queryStringArray; private string uriBuilderPath { get { if (string.IsNullOrEmpty(_uriBuilderPath)) { _uriBuilderPath = "SecretServer/api/v1/sdk-client-accounts/enabled"; } return _uriBuilderPath; } set { this._uriBuilderPath = value; } } private string postData { get { if (string.IsNullOrEmpty(_postData)) { _postData = ""; } return _postData; } set { this._postData = value; } } private System.Collections.Generic.Dictionary<string, string> headers { get { if (_headers == null) { _headers = new Dictionary<string, string>() { {"Authorization","Bearer " + password1} }; } return _headers; } set { this._headers = value; } } private System.Collections.Generic.Dictionary<string, string> queryStringArray { get { if (_queryStringArray == null) { _queryStringArray = new Dictionary<string, string>() { }; } return _queryStringArray; } set { this._queryStringArray = value; } } public TY_Toggle_Current_State() { } public TY_Toggle_Current_State(string endPoint, string Jsonkeypath, string password1) { this.endPoint = endPoint; this.Jsonkeypath = Jsonkeypath; this.password1 = password1; } public async System.Threading.Tasks.Task<ICustomActivityResult> Execute() { HttpClient client = new HttpClient(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); UriBuilder UriBuilder = new UriBuilder(endPoint); UriBuilder.Path = uriBuilderPath; UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray); HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString()); if (contentType == "application/x-www-form-urlencoded") myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData); else if (string.IsNullOrEmpty(postData) == false) if (omitJsonEmptyorNull) myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json"); else myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType); foreach (KeyValuePair<string, string> headeritem in headers) client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value); HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result; switch (response.StatusCode) { case HttpStatusCode.NoContent: case HttpStatusCode.Created: case HttpStatusCode.Accepted: case HttpStatusCode.OK: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath); else return this.GenerateActivityResult("Success"); } default: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) throw new Exception(response.Content.ReadAsStringAsync().Result); else if (string.IsNullOrEmpty(response.ReasonPhrase) == false) throw new Exception(response.ReasonPhrase); else throw new Exception(response.StatusCode.ToString()); } } } public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } } }
35.549669
251
0.618107
[ "MIT" ]
Ayehu/custom-activities
Thycotic/SdkClientAccounts/TY Toggle Current State/TY Toggle Current State.cs
5,368
C#
// <auto-generated /> namespace Getting_Started_with_ASP.NET_MVC_5.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class DataAnnotations : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(DataAnnotations)); string IMigrationMetadata.Id { get { return "201711091637494_DataAnnotations"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.366667
98
0.634548
[ "MIT" ]
GSoster/aspnet-lab
mvc/Getting Started with ASP.NET MVC 5/Getting Started with ASP.NET MVC 5/Migrations/201711091637494_DataAnnotations.Designer.cs
851
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information namespace Microsoft.Azure.Management.Compute.Fluent { using Models; using ResourceManager.Fluent.Core; /// <summary> /// The implementation for VirtualMachineExtensionImageType. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVFeHRlbnNpb25JbWFnZVR5cGVJbXBs internal partial class VirtualMachineExtensionImageTypeImpl : Wrapper<VirtualMachineExtensionImageInner>, IVirtualMachineExtensionImageType { private IVirtualMachineExtensionImagesOperations client; private IVirtualMachinePublisher publisher; ///GENMHASH:8175A2B55D06EDD2889B5CCA8AAB9443:B3CBCEB2E89FF4D7DBD086799C1C3A5B internal VirtualMachineExtensionImageTypeImpl(IVirtualMachineExtensionImagesOperations client, IVirtualMachinePublisher publisher, VirtualMachineExtensionImageInner inner) : base(inner) { this.client = client; this.publisher = publisher; } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC public string Id() { return Inner.Id; } ///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070 public string Name() { return Inner.Name; } ///GENMHASH:F340B9C68B7C557DDB54F615FEF67E89:3054A3D10ED7865B89395E7C007419C9 public string RegionName() { return Inner.Location; } ///GENMHASH:8E3FF63FC02A3540865E75052785D668:614A841E9596603BBD981A7D09F66158 public IVirtualMachinePublisher Publisher() { return this.publisher; } ///GENMHASH:94793EAE475C6B7C746F92BF13EFF2CA:8A3CBABE304A052103727B1255FD5A63 public IVirtualMachineExtensionImageVersions Versions() { return new VirtualMachineExtensionImageVersionsImpl(this.client, this); } } }
37.350877
193
0.721935
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/Compute/VirtualMachineExtensionImageTypeImpl.cs
2,129
C#
// // Copyright 2015 Blu Age Corporation - Plano, Texas // // 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; using Summer.Batch.Extra.Copybook; namespace Summer.Batch.Extra.Ebcdic { /// <summary> /// An EbcdicReaderMapper maps a list of fields, corresponding to an EBCDIC /// record, to a business object. /// </summary> /// <typeparam name="TT">&nbsp;</typeparam> public interface IEbcdicReaderMapper<out TT> { /// <summary> /// Converts the content of a list of values into a business object. /// </summary> /// <param name="values">the list of values to map</param> /// <param name="itemCount">the record line number, starting at 0.</param> /// <returns>The mapped object</returns> TT Map(IList<object> values, int itemCount); /// <summary> /// Sets the record format map to use for mapping /// </summary> RecordFormatMap RecordFormatMap { set; } /// <summary> /// Sets the date parser /// </summary> IDateParser DateParser { set; } /// <summary> /// The getter for the distinguished pattern. /// </summary> string DistinguishedPattern { get; } } }
35.313725
82
0.637424
[ "Apache-2.0" ]
SummerBatch/SummerBatchCore
Summer.Batch.Extra/Ebcdic/IEbcdicReaderMapper.cs
1,803
C#
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Microsoft.VisualStudio.CodeCoverage; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Coverage.Analysis; using System.IO; using System.Xml.Linq; using System.Linq; namespace CodeCoverageCS { class CoverProgram { public CoverProgram() { //set system path string performance_tools_x86_path = @";C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Performance Tools"; string performance_tools_x64_path = @";C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Performance Tools\x64"; var name = "PATH"; string pathvar = System.Environment.GetEnvironmentVariable(name); var value = pathvar + performance_tools_x64_path; var target = EnvironmentVariableTarget.Machine; System.Environment.SetEnvironmentVariable(name, value, target); } public void getCoverage() { //define exe path to test //string programPathWithArgs = @"D:\afl\mupdf\platform\win32\Release\mutool.exe clean -difa ./_pdfs/1.pdf"; //string programPath = @"D:\afl\mupdf\platform\win32\Release\mutool.exe"; string programPath = @"C:\Users\Morteza\Documents\Visual Studio 2015\Projects\CodeCoverageTest\Debug\CodeCoverageTest.exe"; //set system path var name = "PATH"; string pathvar = System.Environment.GetEnvironmentVariable(name); var value = pathvar + @";C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Performance Tools\"; var target = EnvironmentVariableTarget.Machine; System.Environment.SetEnvironmentVariable(name, value, target); // TODO: Write code to call vsinstr.exe //Process p = new Process(); //StringBuilder sb = new StringBuilder("/COVERAGE "); // sb.Append(programPath); //p.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Performance Tools\vsinstr.exe"; //p.StartInfo.Arguments = sb.ToString(); //p.Start(); //p.WaitForExit(); // TODO: Look at the return code – 0 for success // A guid is used to keep track of the run Guid myrunguid = Guid.NewGuid(); Monitor m = new Monitor(); m.StartRunCoverage(myrunguid, @"./_coverage/cov01"); // TODO: Launch tests that can // exercise myassembly.exe Process p2 = new Process(); p2.StartInfo.FileName = programPath; //p2.StartInfo.Arguments = "clean -difa ./_pdfs/3.pdf"; p2.Start(); //string strCmdText; //strCmdText = "/C" + programPath + " clean -difa ./_pdfs/3.pdf"; //strCmdText = "/C" + programPath; //Process.Start("CMD.exe", strCmdText); // Complete the run m.FinishRunCoverage(myrunguid); } public void convertCoverageFileToXmlFile(string fileName) { string coverage_file_path = @"D:\afl\mupdf\platform\win32\Release\coverage_ift\"; string mupdf_x86_path = @"D:\afl\mupdf\platform\win32\Release\mupdf.exe"; string mupdf_x64_path = @"D:\afl\mupdf\platform\win32\x64\Release\mupdf.exe"; string coverage_xml_path = @"D:\afl\mupdf\platform\win32\Release\coverage_ift\temp1.coverage.coveragexml"; using (CoverageInfo info = CoverageInfo.CreateFromFile(coverage_file_path + fileName, new string[] { mupdf_x64_path }, new string[] { })) { CoverageDS data = info.BuildDataSet(); data.WriteXml(coverage_xml_path); } Console.WriteLine("Start2"); readCodeCoverage(fileName); } public void readCodeCoverage(string fileName) { string coverage_file_path = @"D:\afl\mupdf\platform\win32\Release\coverage_ift\"; string coverage_xml_path = @"D:\afl\mupdf\platform\win32\Release\coverage_ift\temp1.coverage.coveragexml"; string coverage_template_path = @"D:\afl\mupdf\platform\win32\Release\coverage_ift\temp.xml"; var xmlOrigin = XDocument.Load(coverage_xml_path); var xmlTemp = XDocument.Load(coverage_template_path); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("ModuleName").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("ModuleName").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("ImageSize").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("ImageSize").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("ImageLinkTime").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("ImageLinkTime").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("LinesCovered").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("LinesCovered").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("LinesPartiallyCovered").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("LinesPartiallyCovered").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("LinesNotCovered").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("LinesNotCovered").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("BlocksCovered").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("BlocksCovered").Value.ToString(); xmlTemp.Element("CoverageDSPriv").Element("Module").Element("BlocksNotCovered").Value = xmlOrigin.Element("CoverageDSPriv").Element("Module").Element("BlocksNotCovered").Value.ToString(); xmlTemp.Save(coverage_file_path + fileName + ".xml"); } static void Main(string[] args) { var cp = new CoverProgram(); //cp.getCoverage(); Console.WriteLine("Start"); /* for (int i=1; i<=1; i++) { cp.convertCoverageFileToXmlFile(i + ".coverage"); } */ //cp.convertCoverageFileToXmlFile(@"host1_max_model7_div_1.0_mou_date_2019-03-16_13-53-57.coverage"); cp.convertCoverageFileToXmlFile(@"1.coverage"); Console.WriteLine("Finished"); } } }
47.635714
209
0.638776
[ "MIT" ]
GordonShinozaki/iust_deep_fuzz
seed/convert_coverage_to_xml/CodeCoverageCS/CodeCoverageCS/Program.cs
6,673
C#
// <auto-generated /> using System; using BookingSystem.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BookingSystem.Data.Migrations { [DbContext(typeof(BookingContext))] partial class BookingContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BookingSystem.Models.Entities.AppUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Booking", b => { b.Property<int>("BookingId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("End"); b.Property<int>("SiteId"); b.Property<DateTime>("Start"); b.Property<string>("TenantId"); b.HasKey("BookingId"); b.HasIndex("SiteId"); b.HasIndex("TenantId"); b.ToTable("Bookings"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Country", b => { b.Property<int>("CountryId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name"); b.HasKey("CountryId"); b.ToTable("Countries"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Currency", b => { b.Property<int>("CurrencyId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code"); b.Property<string>("Name"); b.Property<string>("Symbol"); b.HasKey("CurrencyId"); b.ToTable("Currencies"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Location", b => { b.Property<int>("LocationId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address"); b.Property<int>("CountryId"); b.Property<string>("PostalCode"); b.Property<string>("Region"); b.Property<int>("SiteId"); b.Property<string>("TownCity"); b.HasKey("LocationId"); b.HasIndex("CountryId"); b.HasIndex("SiteId") .IsUnique(); b.ToTable("Locations"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Photo", b => { b.Property<int>("PhotoId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<byte[]>("Image"); b.Property<int>("SiteId"); b.Property<string>("Title"); b.HasKey("PhotoId"); b.HasIndex("SiteId"); b.ToTable("Photos"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Price", b => { b.Property<int>("PriceId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("Amount") .HasColumnType("decimal(18, 2)"); b.Property<int>("CurrencyId"); b.Property<DateTime>("End"); b.Property<int>("SiteId"); b.Property<DateTime>("Start"); b.HasKey("PriceId"); b.HasIndex("CurrencyId"); b.HasIndex("SiteId"); b.ToTable("Prices"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Site", b => { b.Property<int>("SiteId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("OwnerId"); b.HasKey("SiteId"); b.HasIndex("OwnerId"); b.ToTable("Sites"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Booking", b => { b.HasOne("BookingSystem.Models.Entities.Site", "Site") .WithMany("Bookings") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BookingSystem.Models.Entities.AppUser", "Tenant") .WithMany("Bookings") .HasForeignKey("TenantId"); }); modelBuilder.Entity("BookingSystem.Models.Entities.Location", b => { b.HasOne("BookingSystem.Models.Entities.Country", "Country") .WithMany() .HasForeignKey("CountryId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BookingSystem.Models.Entities.Site", "Site") .WithOne("Location") .HasForeignKey("BookingSystem.Models.Entities.Location", "SiteId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("BookingSystem.Models.Entities.Photo", b => { b.HasOne("BookingSystem.Models.Entities.Site", "Site") .WithMany("Photos") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("BookingSystem.Models.Entities.Price", b => { b.HasOne("BookingSystem.Models.Entities.Currency", "Currency") .WithMany() .HasForeignKey("CurrencyId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BookingSystem.Models.Entities.Site", "Site") .WithMany("Prices") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("BookingSystem.Models.Entities.Site", b => { b.HasOne("BookingSystem.Models.Entities.AppUser", "Owner") .WithMany("Sites") .HasForeignKey("OwnerId"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BookingSystem.Models.Entities.AppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BookingSystem.Models.Entities.AppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BookingSystem.Models.Entities.AppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("BookingSystem.Models.Entities.AppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.188235
125
0.476229
[ "MIT" ]
kalinalazarova1/BookingSystem
BookingSystem.Data/Migrations/BookingContextModelSnapshot.cs
14,957
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; namespace Fun2RepairMVC.Common.PublicCode { [AutoMap(typeof(CityTranslation))] public class CityTranslationDto:EntityDto { public virtual string Name { get; set; } public string Language { get; set; } } }
22.846154
48
0.69697
[ "MIT" ]
JsnowyXu/Abp5.2IssueFeedback
Fun2RepairMVC.Application/Common/PublicCode/CityTranslationDto.cs
299
C#
using System.Collections; using DCL; using DCL.Components; using DCL.Helpers; using DCL.Models; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; public class PBRMaterialVisualTests : VisualTestsBase { [UnityTest] [VisualTest] [Explicit] [Category("Explicit")] public IEnumerator AlphaTextureShouldWork_Generate() { yield return VisualTestHelpers.GenerateBaselineForTest(AlphaTextureShouldWork()); } [UnityTest] [VisualTest] [Category("Explicit")] [Explicit] public IEnumerator AlphaTextureShouldWork() { yield return InitVisualTestsScene("PBRMaterialVisualTests_AlphaTextureShouldWork"); DCLTexture texture = TestHelpers.CreateDCLTexture(scene, TestAssetsUtils.GetPath() + "/Images/alphaTexture.png"); yield return texture.routine; Vector3 camTarget = new Vector3(5, 2, 5); VisualTestHelpers.RepositionVisualTestsCamera(VisualTestController.i.camera, camTarget - new Vector3(2, -1, 2), camTarget); PBRMaterial matPBR = TestHelpers.CreateEntityWithPBRMaterial(scene, new PBRMaterial.Model { albedoTexture = texture.id, transparencyMode = 2, albedoColor = Color.blue }, camTarget, out IDCLEntity entity); yield return matPBR.routine; yield return new WaitForAllMessagesProcessed(); yield return VisualTestHelpers.TakeSnapshot(); } }
33.27907
142
0.716981
[ "Apache-2.0" ]
0xBlockchainx0/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Components/Materials/Tests/PBRMaterialVisualTests.cs
1,433
C#
using System; using System.Collections.Generic; namespace Knet.Kudu.Client.Connection; public class ServerInfoCache { // This random integer is used when making any random choice for replica // selection. It is static to provide a deterministic selection for any given // process and therefore also better cache affinity while ensuring that we can // still benefit from spreading the load across replicas for other processes // and applications. private static readonly int _randomInt = new Random().Next(int.MaxValue); private readonly List<ServerInfo> _servers; private readonly List<KuduReplica> _replicas; private readonly int _leaderIndex; private readonly int _randomIndex; public ServerInfoCache( List<ServerInfo> servers, List<KuduReplica> replicas, int leaderIndex) { _servers = servers; _replicas = replicas; _leaderIndex = leaderIndex; var numServers = servers.Count; if (numServers > 0) _randomIndex = _randomInt % numServers; } /// <summary> /// Get replicas of this tablet. /// </summary> public IReadOnlyList<ServerInfo> Servers => _servers; /// <summary> /// Get replicas of this tablet. /// </summary> public IReadOnlyList<KuduReplica> Replicas => _replicas; /// <summary> /// Get the information on the tablet server that we think holds the /// leader replica for this tablet. Returns null if we don't know who /// the leader is. /// </summary> public ServerInfo? GetLeaderServerInfo() { // Check if we have a leader. if (_leaderIndex == -1) return null; return _servers[_leaderIndex]; } /// <summary> /// Select the closest replica to the client. Replicas are classified /// from closest to furthest as follows: /// <list type="number"> /// <item><description>Local replicas</description></item> /// <item><description> /// Replicas whose tablet server has the same location as the client /// </description></item> /// <item><description>All other replicas</description></item> /// </list> /// </summary> /// <param name="location">The location of the client.</param> public ServerInfo? GetClosestServerInfo(string? location = null) { // This method returns // 1. a randomly picked server among local servers, if there is one based // on IP and assigned location, or // 2. a randomly picked server in the same assigned location, if there is a // server in the same location, or, finally, // 3. a randomly picked server among all tablet servers. var servers = _servers; int numServers = servers.Count; ServerInfo? result = null; Span<byte> localServers = stackalloc byte[numServers]; Span<byte> serversInSameLocation = stackalloc byte[numServers]; int randomIndex = _randomIndex; byte index = 0; byte localIndex = 0; byte sameLocationIndex = 0; bool missingLocation = string.IsNullOrEmpty(location); foreach (var serverInfo in servers) { bool serverInSameLocation = serverInfo.InSameLocation(location); // Only consider a server "local" if we're in the same location, or if // there is missing location info. if (missingLocation || !serverInfo.HasLocation || serverInSameLocation) { if (serverInfo.IsLocal) localServers[localIndex++] = index; } if (serverInSameLocation) serversInSameLocation[sameLocationIndex++] = index; if (index == randomIndex) result = serverInfo; index++; } if (localIndex > 0) { randomIndex = _randomInt % localIndex; return servers[localServers[randomIndex]]; } if (sameLocationIndex > 0) { randomIndex = _randomInt % sameLocationIndex; return servers[serversInSameLocation[randomIndex]]; } return result; } /// <summary> /// Helper function to centralize the calling of methods based on the /// passed replica selection mechanism. /// </summary> /// <param name="replicaSelection">Replica selection mechanism to use.</param> /// <param name="location">The location of the client.</param> public ServerInfo? GetServerInfo(ReplicaSelection replicaSelection, string? location = null) { if (replicaSelection == ReplicaSelection.LeaderOnly) return GetLeaderServerInfo(); return GetClosestServerInfo(location); } /// <summary> /// Get the information on the tablet server that we think holds the /// leader replica for this tablet. Returns null if we don't know who /// the leader is. /// </summary> public KuduReplica? GetLeaderReplica() { // Check if we have a leader. if (_leaderIndex == -1) return null; return _replicas[_leaderIndex]; } /// <summary> /// Clears the leader UUID if the passed tablet server is the current leader. /// If it is the current leader, then the next call to this tablet will have /// to query the master to find the new leader. /// </summary> /// <param name="uuid"> /// A tablet server that gave a sign that it isn't this tablet's leader. /// </param> public ServerInfoCache DemoteLeader(string uuid) { var leaderIndex = _leaderIndex; if (leaderIndex != -1) { var serverInfo = _servers[leaderIndex]; if (serverInfo.Uuid == uuid) { var replicas = _replicas; var newReplicas = new List<KuduReplica>(replicas); var priorLeaderReplica = replicas[leaderIndex]; var newLeaderReplica = new KuduReplica( priorLeaderReplica.HostPort, ReplicaRole.Follower, priorLeaderReplica.DimensionLabel); newReplicas[leaderIndex] = newLeaderReplica; return new ServerInfoCache(_servers, newReplicas, -1); } } return this; } /// <summary> /// Removes the passed tablet server from this tablet's list of tablet servers. /// </summary> /// <param name="uuid">A tablet server to remove from this cache.</param> public ServerInfoCache RemoveTabletServer(string uuid) { var servers = _servers; var replicas = _replicas; var numServers = servers.Count; var newServers = new List<ServerInfo>(numServers); var newReplicas = new List<KuduReplica>(numServers); var leaderIndex = _leaderIndex; for (int i = 0; i < numServers; i++) { var server = servers[i]; var replica = replicas[i]; if (server.Uuid == uuid) { if (leaderIndex > i) { leaderIndex--; } else if (leaderIndex == i) { leaderIndex = -1; } continue; } newServers.Add(server); newReplicas.Add(replica); } return new ServerInfoCache(newServers, newReplicas, leaderIndex); } }
33.302222
96
0.599893
[ "Apache-2.0" ]
xqrzd/kudu
src/Knet.Kudu.Client/Connection/ServerInfoCache.cs
7,493
C#
using FluentAssertions; using NSubstitute; using NUnit.Framework; using Slack.NetStandard; using Slack.NetStandard.Objects; using Slack.NetStandard.WebApi; using Slack.NetStandard.WebApi.Chat; using System; using System.Threading; using System.Threading.Tasks; using Zkrd.Slack.WebApiDemo.Services; namespace Zkrd.Slack.WebApiDemo.Tests.Services; [TestFixture] public class SlackServiceTests { [Test] public async Task PostMessage_Should_ReturnNotFound_If_ChannelWasNotFound() { var apiClient = Substitute.For<ISlackApiClient>(); apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = Array.Empty<Channel>() }); var sut = new SlackService(apiClient); (ApiResults success, string _) = await sut.PostMessage("foo", "bar"); success.Should().Be(ApiResults.NotFound); } [Test] public async Task PostMessage_Should_ReturnCorrectMessage_If_ChannelWasNotFound() { var apiClient = Substitute.For<ISlackApiClient>(); apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = Array.Empty<Channel>() }); var sut = new SlackService(apiClient); (ApiResults _, string errorMessage) = await sut.PostMessage("foo", "bar"); errorMessage.Should().Be("Channel not found"); } [Test] public async Task PostMessage_Should_ReturnError_If_PostingMessageWasNotOk() { var apiClient = Substitute.For<ISlackApiClient>(); const string channelName = "bar"; apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = new []{new Channel{Name = channelName}} }); apiClient.Chat.Post(null).ReturnsForAnyArgs( new PostMessageResponse { OK = false, Error = "There was an error", } ); var sut = new SlackService(apiClient); (ApiResults success, string _) = await sut.PostMessage("foo", channelName); success.Should().Be(ApiResults.Error); } [Test] public async Task PostMessage_Should_ReturnCorrectMessage_If_PostingMessageWasNotOk() { var apiClient = Substitute.For<ISlackApiClient>(); const string channelName = "bar"; apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = new []{new Channel{Name = channelName}} }); apiClient.Chat.Post(null).ReturnsForAnyArgs( new PostMessageResponse { OK = false, Error = "There was an error", } ); var sut = new SlackService(apiClient); (ApiResults _, string errorMessage) = await sut.PostMessage("foo", channelName); errorMessage.Should().Be("There was an error"); } [Test] public async Task PostMessage_Should_ReturnOk_If_PostingMessageWasOk() { var apiClient = Substitute.For<ISlackApiClient>(); const string channelName = "bar"; apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = new []{new Channel{Name = channelName}} }); apiClient.Chat.Post(null).ReturnsForAnyArgs( new PostMessageResponse { OK = true, } ); var sut = new SlackService(apiClient); (ApiResults success, string _) = await sut.PostMessage("foo", channelName); success.Should().Be(ApiResults.Ok); } [Test] public async Task PostMessage_Should_ReturnNoMessage_If_PostingMessageWasOk() { var apiClient = Substitute.For<ISlackApiClient>(); const string channelName = "bar"; apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = new []{new Channel{Name = channelName}} }); apiClient.Chat.Post(null).ReturnsForAnyArgs( new PostMessageResponse { OK = true, } ); var sut = new SlackService(apiClient); (ApiResults _, string errorMessage) = await sut.PostMessage("foo", channelName); errorMessage.Should().BeEmpty(); } [Test] public async Task PostMessage_Should_ThrowOperationAbortedException_If_CancellationTokenWasSetToCancelled() { var apiClient = Substitute.For<ISlackApiClient>(); const string channelName = "bar"; apiClient.Conversations.List(null).ReturnsForAnyArgs( new ChannelListResponse { Channels = new []{new Channel{Name = channelName}} }); apiClient.Chat.Post(null).ReturnsForAnyArgs( new PostMessageResponse { OK = true, } ); var cts = new CancellationTokenSource(); cts.Cancel(); var sut = new SlackService(apiClient); Func<Task> throwingAction = async () => await sut.PostMessage("foo", channelName, cts.Token); await throwingAction.Should().ThrowAsync<OperationCanceledException>(); } }
29.80117
110
0.645801
[ "MIT" ]
fscheel/ZKRD.Slack.Runner
Zkrd.Slack.WebApiDemo.Tests/Services/SlackServiceTests.cs
5,096
C#
namespace Mobile.Common.Util { public class DataFormats { public const string MonetaryAmountFormat = "#,##0.##"; public const string DateFormat = "yyyy-MM-dd"; public const string PeriodicDateFormat = "dd-MM-yyyy"; public const string PeriodicDatePrintFormat = "ddMMyy"; public const string DateTimeFormat = "yyyy-MM-dd mm:HH:ss"; public static string FiscalPrinterAmountFormat = "#0.###"; public static string QuantityFormat = "#,##0.##"; } }
36.571429
67
0.646484
[ "MIT" ]
Georgekibet/VoteTalyingSystem
Mobile/Mobile.Common/Util/DataFormats.cs
512
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 #if !(NETSTANDARD1_0 || NETSTANDARD1_3) #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using System.Collections.Generic; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; namespace Newtonsoft.Json.Tests.Issues { [TestFixture] public class Issue2444 { [Test] public void Test() { var namingStrategy = new SnakeCaseNamingStrategy(); var settings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = namingStrategy } }; string json = @"{""dict"":{""value1"":""a"",""text_value"":""b""}}"; DataClass c = JsonConvert.DeserializeObject<DataClass>(json, settings); Assert.AreEqual(2, c.Dict.Count); Assert.AreEqual("a", c.Dict[MyEnum.Value1]); Assert.AreEqual("b", c.Dict[MyEnum.TextValue]); string json1 = @"{""dict"":{""Value1"":""a"",""TextValue"":""b""}}"; DataClass c1 = JsonConvert.DeserializeObject<DataClass>(json1, settings); Assert.AreEqual(2, c1.Dict.Count); Assert.AreEqual("a", c1.Dict[MyEnum.Value1]); Assert.AreEqual("b", c1.Dict[MyEnum.TextValue]); // Non-dictionary values should still error ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<List<MyEnum>>(@"[""text_value""]", settings); }, @"Error converting value ""text_value"" to type 'Newtonsoft.Json.Tests.Issues.Issue2444+MyEnum'. Path '[0]', line 1, position 13."); } public enum MyEnum { Value1, TextValue } public class DataClass { public Dictionary<MyEnum, string> Dict { get; set; } } } } #endif
35.954545
147
0.646334
[ "MIT" ]
AntiTenzor/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Issues/Issue2444.cs
3,166
C#
namespace Melanchall.DryWetMidi.Standards { /// <summary> /// General MIDI Level 2 'SFX' percussion. /// </summary> public enum GeneralMidi2SfxPercussion : byte { /// <summary> /// 'High Q' General MIDI 2 percussion note. /// </summary> HighQ = 39, /// <summary> /// 'Slap' General MIDI 2 percussion note. /// </summary> Slap = 40, /// <summary> /// 'Scratch Push' General MIDI 2 percussion note. /// </summary> ScratchPush = 41, /// <summary> /// 'Scratch Pull' General MIDI 2 percussion note. /// </summary> ScratchPull = 42, /// <summary> /// 'Sticks' General MIDI 2 percussion note. /// </summary> Sticks = 43, /// <summary> /// 'Square Click' General MIDI 2 percussion note. /// </summary> SquareClick = 44, /// <summary> /// 'Metronome Click' General MIDI 2 percussion note. /// </summary> MetronomeClick = 45, /// <summary> /// 'Metronome Bell' General MIDI 2 percussion note. /// </summary> MetronomeBell = 46, /// <summary> /// 'Guitar Fret Noise' General MIDI 2 percussion note. /// </summary> GuitarFretNoise = 47, /// <summary> /// 'Guitar Cutting Noise Up' General MIDI 2 percussion note. /// </summary> GuitarCuttingNoiseUp = 48, /// <summary> /// 'Guitar Cutting Noise Down' General MIDI 2 percussion note. /// </summary> GuitarCuttingNoiseDown = 49, /// <summary> /// 'String Slap Of Double Bass' General MIDI 2 percussion note. /// </summary> StringSlapOfDoubleBass = 50, /// <summary> /// 'Fl Key Click' General MIDI 2 percussion note. /// </summary> FlKeyClick = 51, /// <summary> /// 'Laughing' General MIDI 2 percussion note. /// </summary> Laughing = 52, /// <summary> /// 'Scream' General MIDI 2 percussion note. /// </summary> Scream = 53, /// <summary> /// 'Punch' General MIDI 2 percussion note. /// </summary> Punch = 54, /// <summary> /// 'Heart Beat' General MIDI 2 percussion note. /// </summary> HeartBeat = 55, /// <summary> /// 'Footsteps 1' General MIDI 2 percussion note. /// </summary> Footsteps1 = 56, /// <summary> /// 'Footsteps 2' General MIDI 2 percussion note. /// </summary> Footsteps2 = 57, /// <summary> /// 'Applause' General MIDI 2 percussion note. /// </summary> Applause = 58, /// <summary> /// 'Door Creaking' General MIDI 2 percussion note. /// </summary> DoorCreaking = 59, /// <summary> /// 'Door' General MIDI 2 percussion note. /// </summary> Door = 60, /// <summary> /// 'Scratch' General MIDI 2 percussion note. /// </summary> Scratch = 61, /// <summary> /// 'Wind Chimes' General MIDI 2 percussion note. /// </summary> WindChimes = 62, /// <summary> /// 'Car-Engine' General MIDI 2 percussion note. /// </summary> CarEngine = 63, /// <summary> /// 'Car-Stop' General MIDI 2 percussion note. /// </summary> CarStop = 64, /// <summary> /// 'Car-Pass' General MIDI 2 percussion note. /// </summary> CarPass = 65, /// <summary> /// 'Car-Crash' General MIDI 2 percussion note. /// </summary> CarCrash = 66, /// <summary> /// 'Siren' General MIDI 2 percussion note. /// </summary> Siren = 67, /// <summary> /// 'Train' General MIDI 2 percussion note. /// </summary> Train = 68, /// <summary> /// 'Jetplane' General MIDI 2 percussion note. /// </summary> Jetplane = 69, /// <summary> /// 'Helicopter' General MIDI 2 percussion note. /// </summary> Helicopter = 70, /// <summary> /// 'Starship' General MIDI 2 percussion note. /// </summary> Starship = 71, /// <summary> /// 'Gun Shot' General MIDI 2 percussion note. /// </summary> GunShot = 72, /// <summary> /// 'Machine Gun' General MIDI 2 percussion note. /// </summary> MachineGun = 73, /// <summary> /// 'Lasergun' General MIDI 2 percussion note. /// </summary> Lasergun = 74, /// <summary> /// 'Explosion' General MIDI 2 percussion note. /// </summary> Explosion = 75, /// <summary> /// 'Dog' General MIDI 2 percussion note. /// </summary> Dog = 76, /// <summary> /// 'Horse Gallop' General MIDI 2 percussion note. /// </summary> HorseGallop = 77, /// <summary> /// 'Birds' General MIDI 2 percussion note. /// </summary> Birds = 78, /// <summary> /// 'Rain' General MIDI 2 percussion note. /// </summary> Rain = 79, /// <summary> /// 'Thunder' General MIDI 2 percussion note. /// </summary> Thunder = 80, /// <summary> /// 'Wind' General MIDI 2 percussion note. /// </summary> Wind = 81, /// <summary> /// 'Seashore' General MIDI 2 percussion note. /// </summary> Seashore = 82, /// <summary> /// 'Stream' General MIDI 2 percussion note. /// </summary> Stream = 83, /// <summary> /// 'Bubble' General MIDI 2 percussion note. /// </summary> Bubble = 84 } }
25.129707
72
0.477689
[ "MIT" ]
EnableIrelandAT/Coimbra
ProjectCoimbra.UWP/Melanchall.DryWetMidi.UWP/Standards/GeneralMidi2/Percussion/GeneralMidi2SfxPercussion.cs
6,008
C#
using System; using moment.net.Enums; using NUnit.Framework; using Shouldly; namespace moment.net.Tests { public class EndOfTests { string dateString = "5/1/2008 8:30:52Z AM"; [Test] public void EndOfMinuteTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Minute).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("01/05/2008 08:30:59"); date.EndOf(DateTimeAnchor.Minute).Kind.ShouldBe(DateTimeKind.Utc); } [Test] public void EndOfHourTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Hour).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("01/05/2008 08:59:59"); date.EndOf(DateTimeAnchor.Hour).Kind.ShouldBe(DateTimeKind.Utc); } [Test] public void EndOfDayTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Day).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("01/05/2008 23:59:59"); date.EndOf(DateTimeAnchor.Day).Kind.ShouldBe(DateTimeKind.Utc); } [Test] public void EndOfWeekTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Week).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("03/05/2008 23:59:59"); date.EndOf(DateTimeAnchor.Week).Kind.ShouldBe(DateTimeKind.Utc); } [Test] public void EndOfMonthTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Month).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("31/05/2008 23:59:59"); date.EndOf(DateTimeAnchor.Month).Kind.ShouldBe(DateTimeKind.Utc); } [Test] public void EndOfYearTest() { var date = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); date.EndOf(DateTimeAnchor.Year).ToString("dd/MM/yyyy HH:mm:ss").ShouldBe("31/12/2008 23:59:59"); date.EndOf(DateTimeAnchor.Year).Kind.ShouldBe(DateTimeKind.Utc); } } }
44.933333
156
0.671365
[ "MIT" ]
bolorundurowb/moment.net
tests/EndOf.Tests.cs
2,696
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.AccessControl; namespace Pathy { /// <summary> /// Represents an absolute or relative path to a directory. /// </summary> public class AnyDirectoryPath : AnyPath { [Conditional(BuildType.Debug)] private void Invariant() { // no extra invariants, yet Debug.Assert(this != null); } internal AnyDirectoryPath(string directoryPath) : base(directoryPath) { Invariant(); } /// <summary> /// Creates a <see cref="AnyDirectoryPath"/> from a base directory path and a relative directory path. /// </summary> /// <param name="basePath">The base directory path.</param> /// <param name="relativePath">The relative directory path.</param> public AnyDirectoryPath(AnyDirectoryPath basePath, RelativeDirectoryPath relativePath) : base(Combined(basePath, relativePath)) { Invariant(); } /// <summary> /// Creates a <see cref="AnyDirectoryPath"/> from the given raw path. /// </summary> /// <param name="directoryPath">The path.</param> /// <exception cref="ArgumentNullException">The <paramref name="directoryPath"/> was <c>null</c>.</exception> /// <exception cref="ArgumentException">There was a problem with the given path.</exception> /// <returns>A new <see cref="AnyDirectoryPath"/> instance.</returns> public static new AnyDirectoryPath From(string directoryPath) { Validation.CheckPath(directoryPath, nameof(directoryPath), Validations.Default); return new AnyDirectoryPath(directoryPath); } private static string Combined(AnyDirectoryPath basePath, RelativeDirectoryPath relativePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } var result = Path.Combine(basePath.RawPath, relativePath.RawPath); // if we have an absolute path we normalize it, // so we can have consistent comparison return basePath.IsAbsolute ? Path.GetFullPath(result) : result; } /// <summary> /// Creates a <see cref="AnyFilePath"/> from a base directory path and a relative file path. /// </summary> /// <param name="basePath">The base directory path.</param> /// <param name="relativePath">The relative file path.</param> /// <returns></returns> [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Alternate is provided as constructor")] public static AnyFilePath operator/(AnyDirectoryPath basePath, RelativeFilePath relativePath) => new AnyFilePath(basePath, relativePath); /// <summary> /// Creates a <see cref="AnyDirectoryPath"/> from a base directory path and a relative directory path. /// </summary> /// <param name="basePath">The base directory path.</param> /// <param name="relativePath">The relative file path.</param> [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Alternate is provided as constructor")] public static AnyDirectoryPath operator/(AnyDirectoryPath basePath, RelativeDirectoryPath relativePath) => new AnyDirectoryPath(basePath, relativePath); /// <summary> /// Creates the directory (including any parent directories), /// unless it already exists. /// </summary> public void Create() => Directory.CreateDirectory(RawPath); /// <summary> /// Deletes the directory and its contents. /// </summary> public void Delete() => Directory.Delete(RawPath, true); /// <summary> /// Deletes the directory, and optionally its contents. /// </summary> /// <param name="recursive">If <c>true</c>, delete the directory contents.</param> public void Delete(bool recursive) => Directory.Delete(RawPath, recursive); /// <summary> /// Creates the directory (including any parent directories), /// unless it already exists. /// </summary> /// <param name="directorySecurity">The Windows security to apply.</param> public void Create(DirectorySecurity directorySecurity) => Directory.CreateDirectory(RawPath, directorySecurity); /// <summary> /// Gets the directory name as a relative path. /// </summary> public RelativeDirectoryPath DirectoryName => new RelativeDirectoryPath(Path.GetFileName(RawPath)); /// <summary> /// Enumerates the files that exist in this directory. /// </summary> /// <returns>A lazily-enumerated list of files in the directory.</returns> public IEnumerable<AnyFilePath> EnumerateFiles() { foreach (var file in Directory.EnumerateFiles(RawPath)) { yield return new AnyFilePath(file); } } /// <summary> /// Enumerates the directories that exist in this directory. /// </summary> /// <returns>A lazily-enumerated list of directories in the directory.</returns> public IEnumerable<AnyDirectoryPath> EnumerateDirectories() { foreach (var dir in Directory.EnumerateDirectories(RawPath)) { yield return new AnyDirectoryPath(dir); } } } }
40.156463
147
0.616636
[ "MIT" ]
Porges/Pathy
Pathy/AnyDirectoryPath.cs
5,905
C#
using Dawnx.AspNetCore.LiveAccount; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Linq; namespace Dawnx.AspNetCore.LiveAccountUtility.Pages.Users { [AllowAnonymous] public class EditModel : PageModel { private readonly ILiveManager _liveAccountManager = DIUtility.GetEntryService<ILiveManager>(LiveManagerService.ServiceType); private readonly ILogger<EditModel> _logger; public EditModel(ILogger<EditModel> logger) { _logger = logger; } [BindProperty] public IdentityUser<string> Input { get; set; } public IActionResult OnGet() { if (!LiveAccountUtility.Authority?.User?.IsUserAllowed(User) ?? false) throw Authority.New_UnauthorizedAccessException; var user = ((dynamic)_liveAccountManager).Users.Find(Request.Query["Id"]); Input = user as IdentityUser<string>; ViewData["LiveRoles"] = _liveAccountManager.LiveRoles .Include(x => x.RoleOperations).ThenInclude(x => x.OperationLink) .ToArray(); ViewData["UserLiveRoles"] = _liveAccountManager.GetUserRoles(Input.UserName); return Page(); } public IActionResult OnPost() { if (!LiveAccountUtility.Authority?.User?.IsUserAllowed(User) ?? false) throw Authority.New_UnauthorizedAccessException; ViewData["LiveRoles"] = _liveAccountManager.LiveRoles .Include(x => x.RoleOperations).ThenInclude(x => x.OperationLink) .ToArray(); ViewData["UserLiveRoles"] = _liveAccountManager.GetUserRoles(Input.UserName); if (ModelState.IsValid) { using (_liveAccountManager.FastProcessing) { _liveAccountManager.SetUserRoles(Input.UserName, Request.Form["LiveRoles"].Select(x => Guid.Parse(x)).ToArray()); } return Redirect("Index"); } return Page(); } } }
34.231884
89
0.629975
[ "MIT" ]
zmjack/Dawnx
~Library/Dawnx.AspNetCore.LiveAccountUtility/Areas/LiveAccountUtility/Pages/Users/Edit.cshtml.cs
2,364
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Graphics3D.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Graphics3D.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
36.958333
171
0.629087
[ "MIT" ]
ClumsyTiger/Graphics3D
Graphics3D/Properties/Resources.Designer.cs
2,663
C#
using LedStrip; using System.Drawing; namespace LedStripGui { [System.Obsolete("Old form settings")] public class Settings { public readonly int ledCount; private int _brightness = 4; private int _updatesPerSecond = 10; private int _paletteChangeDivider = 1000; private bool _rgbControlMode = false; public Color color = Color.White; public Codes.Mode mode = Codes.Mode.Manual; public Codes.Palette palette = Codes.Palette.RainbowColors; public Settings(int ledCount) { this.ledCount = ledCount; } public int Brightness { get { return this._brightness; } set { if (value > Codes.MAX_BRIGHTNESS) { this._brightness = Codes.MAX_BRIGHTNESS; } else if (value < Codes.MIN_BRIGHTNESS) { this._brightness = Codes.MIN_BRIGHTNESS; } else { this._brightness = value; } } } public int UpdatesPerSecond { get { return this._updatesPerSecond; } set { if (value > Codes.MAX_UPDATES_PER_SECOND) { this._updatesPerSecond = Codes.MAX_UPDATES_PER_SECOND; } else if (value < Codes.MIN_UPDATES_PER_SECOND) { this._updatesPerSecond = Codes.MIN_UPDATES_PER_SECOND; } else { this._updatesPerSecond = value; } } } public int PaletteChangeDivider { get { return this._paletteChangeDivider; } set { if (value > Codes.MAX_PALETTE_CHANGE_DIVIDER) { this._paletteChangeDivider = Codes.MAX_PALETTE_CHANGE_DIVIDER; } else if (value < Codes.MIN_PALETTE_CHANGE_DIVIDER) { this._paletteChangeDivider = Codes.MIN_PALETTE_CHANGE_DIVIDER; } else { this._paletteChangeDivider = value; } } } public bool RgbControlMode { get { return this._rgbControlMode; } set { this._rgbControlMode = value; } } } }
28.02439
133
0.529591
[ "MIT" ]
James-Frowen/led-strip-gui
led-strip-gui/Settings.cs
2,300
C#
using System; using System.Web.UI; namespace Cogito.Web.UI.Razor { /// <summary> /// ASP.Net server control that accepts and renders a <see cref="Action{Object}"/>. /// </summary> class HtmlHelperControl : Control { Action<object> action; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="action"></param> public HtmlHelperControl(Action<object> action) { this.action = action; } protected override void Render(HtmlTextWriter writer) { } } }
18.909091
87
0.535256
[ "MIT" ]
alethic/Cogito
Cogito.Web.UI.Razor/HtmlHelperControl.cs
626
C#