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 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 sesv2-2019-09-27.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.SimpleEmailV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetCustomVerificationEmailTemplate Request Marshaller
/// </summary>
public class GetCustomVerificationEmailTemplateRequestMarshaller : IMarshaller<IRequest, GetCustomVerificationEmailTemplateRequest> , 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((GetCustomVerificationEmailTemplateRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetCustomVerificationEmailTemplateRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleEmailV2");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-09-27";
request.HttpMethod = "GET";
if (!publicRequest.IsSetTemplateName())
throw new AmazonSimpleEmailServiceV2Exception("Request object does not have required field TemplateName set");
request.AddPathResource("{TemplateName}", StringUtils.FromString(publicRequest.TemplateName));
request.ResourcePath = "/v2/email/custom-verification-email-templates/{TemplateName}";
return request;
}
private static GetCustomVerificationEmailTemplateRequestMarshaller _instance = new GetCustomVerificationEmailTemplateRequestMarshaller();
internal static GetCustomVerificationEmailTemplateRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetCustomVerificationEmailTemplateRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.287356 | 183 | 0.68434 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/GetCustomVerificationEmailTemplateRequestMarshaller.cs | 3,244 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using DataEventProcessor.EventProcessor;
namespace DataEventProcessor.ServiceClients
{
public class InMemoryProcessorConfigServiceClient : IProcessorConfigServiceClient
{
public Task<ProcessorConfiguration> GetConfigAsync(int processorConfigId)
{
throw new NotImplementedException();
}
}
}
| 25.705882 | 85 | 0.757437 | [
"MIT"
] | cdanhowell/CQRS-Example | DataEventProcessor/ServiceClients/InMemoryProcessorConfigServiceClient.cs | 439 | C# |
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace Nett.AspNet
{
public static class ConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, string path)
=> AddTomlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false);
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, string path, bool optional)
=> AddTomlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false);
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
=> AddTomlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange);
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
=> AddTomlFile(builder, provider, path, s => { s.Optional = optional; s.ReloadOnChange = reloadOnChange; });
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, string path, Action<TomlConfigurationSource> configureSource)
=> AddTomlFile(builder, provider: null, path: path, configureSource: configureSource);
public static IConfigurationBuilder AddTomlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, Action<TomlConfigurationSource> configureSource)
{
var source = new TomlConfigurationSource()
{
FileProvider = provider,
Path = path
};
configureSource?.Invoke(source);
source.ResolveFileProvider();
return builder.Add(source);
}
}
}
| 47.85 | 177 | 0.718913 | [
"MIT"
] | bash/Nett | Source/Nett.AspNet/ConfigurationBuilderExtensions.cs | 1,916 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace Starglade.Mobile.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 23.238095 | 91 | 0.635246 | [
"MIT"
] | saokatali/Starglade | Starglade.Mobile/Starglade.Mobile/Starglade.Mobile.iOS/Main.cs | 490 | C# |
using System;
using NUnit.Framework;
using YiSha.Util;
namespace YiSha.UtilTest
{
public class SecurityHelperTest
{
private string input = "我是谁 ABCD 1234 *=/.";
[Test]
public void TestMD5()
{
string result = SecurityHelper.MD5ToHex(input);
Assert.AreEqual("a7783d564da97a3846f5bf0f6b923d7f", result.ToLower());
}
[Test]
public void TestDES()
{
string ciperText = SecurityHelper.DESEncryptToBase64(input);
string result = SecurityHelper.DESDecryptFromBase64(ciperText);
Assert.AreEqual(input, result);
ciperText = SecurityHelper.DESEncryptToHex(input);
result = SecurityHelper.DESDecryptFromHex(ciperText);
Assert.AreEqual(input, result);
}
[Test]
public void TestAES()
{
string ciperText = SecurityHelper.AESEncryptToBase64(input);
string result = SecurityHelper.AESDecryptFromBase64(ciperText);
Assert.AreEqual(input, result);
ciperText = SecurityHelper.AESEncryptToHex(input);
result = SecurityHelper.AESDecryptFromHex(ciperText);
Assert.AreEqual(input, result);
}
}
}
| 28.704545 | 82 | 0.615202 | [
"MIT"
] | 1051324354/YiShaAdmin | YiSha.Test/YiSha.UtilTest/SecurityHelperTest.cs | 1,271 | C# |
using System;
namespace UnityAnalytics360VideoHeatmap
{
public enum AggregationMethod
{
Increment,
Cumulative,
Average,
Max,
Min,
First,
Last,
Percentile
}
}
| 13.166667 | 39 | 0.535865 | [
"MIT"
] | ProGamerCode/360-Video-Heatmaps | Assets/AssetStorePackage/Plugins/Heatmaps/Internal/Renderer/AggregationMethod.cs | 239 | 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("MvxPluginNugetTest.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Zuehlke Engineering")]
[assembly: AssemblyProduct("MvxPluginNugetTest.iOS")]
[assembly: AssemblyCopyright("Copyright � Zuehlke Engineering 2016")]
[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("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")]
// 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("2.2.0-pre4")]
[assembly: AssemblyVersion("2.2.0-pre4")]
[assembly: AssemblyFileVersion("2.0.0")]
| 39.324324 | 84 | 0.757388 | [
"Apache-2.0"
] | cmhofmeister/xamarin-bluetooth-le | .build/PluginNugetTest/MvxPluginNugetTest.iOS/Properties/AssemblyInfo.cs | 1,457 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.ElasticSearch.Inputs
{
public sealed class DomainAutoTuneOptionsMaintenanceScheduleDurationGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The unit of time specifying the duration of an Auto-Tune maintenance window. Valid values: `HOURS`.
/// </summary>
[Input("unit", required: true)]
public Input<string> Unit { get; set; } = null!;
/// <summary>
/// An integer specifying the value of the duration of an Auto-Tune maintenance window.
/// </summary>
[Input("value", required: true)]
public Input<int> Value { get; set; } = null!;
public DomainAutoTuneOptionsMaintenanceScheduleDurationGetArgs()
{
}
}
}
| 33.1875 | 111 | 0.6629 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/ElasticSearch/Inputs/DomainAutoTuneOptionsMaintenanceScheduleDurationGetArgs.cs | 1,062 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Valigator
{
public class ValueTypesNotSupportException : Exception
{
public ValueTypesNotSupportException(string message)
: base(message)
{
}
}
}
| 15.866667 | 55 | 0.760504 | [
"MIT"
] | JohannesMoersch/Newtonsoft.FluentValidation | Valigator.Core/ValueTypesNotSupportException.cs | 240 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ContainerService.Fluent;
using Microsoft.Azure.Management.ContainerService.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.IO;
namespace ManageContainerServiceWithKubernetesOrchestrator
{
public class Program
{
/**
* An Azure Container Services sample for managing a container service with Kubernetes orchestration.
* - Create an Azure Container Service with Kubernetes orchestrator
* - Update the number of agent virtual machines in an Azure Container Service
*/
public static void RunSample(IAzure azure, string clientId, string secret)
{
string rgName = SdkContext.RandomResourceName("rgacs", 15);
string acsName = SdkContext.RandomResourceName("acssample", 30);
Region region = Region.USWestCentral;
string rootUserName = "acsuser";
string sshPublicKey = // replace with a real SSH public key
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyhPdNuJUmTeLsaZL83vARuSVlN5qbKs7j"
+ "Cm723fqH85rIRQHgwEUXJbENEgZT0cXEgz4h36bQLMYT3/30fRnxYl8U6gRn27zFiMwaDstOjc9EofStODbiHx9A"
+ "Y1XYStjegdf+LNa5tmRv8dZEdj47XDxosSG3JKHpSuf0fXr4u7NjgAxdYOxyMSPAEcfXQctA+ybHkGDLdjLHT7q5C"
+ "4RXlQT7S9v5z532C3KuUSQW7n3QBP3xw/bC8aKcJafwZUYjYnw7owkBnv4TsZVva2le7maYkrtLH6w+XbhfHY4WwK"
+ "Y2Xxl1TxSGkb8tDsa6XgTmGfAKcDpnIe0DASJD8wFF dotnet.sample@azure.com";
string servicePrincipalClientId = clientId; // replace with a real service principal client id
string servicePrincipalSecret = secret; // and corresponding secret
try
{
//=============================================================
// ...
//=============================================================
// If service principal client id and secret are not set via the local variables, attempt to read the service
// principal client id and secret from a secondary ".azureauth" file set through an environment variable.
//
// If the environment variable was not set then reuse the main service principal set for running this sample.
if (String.IsNullOrWhiteSpace(servicePrincipalClientId) || String.IsNullOrWhiteSpace(servicePrincipalSecret))
{
string envSecondaryServicePrincipal = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION_2");
if (String.IsNullOrWhiteSpace(envSecondaryServicePrincipal) || !File.Exists(envSecondaryServicePrincipal))
{
envSecondaryServicePrincipal = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");
}
servicePrincipalClientId = Utilities.GetSecondaryServicePrincipalClientID(envSecondaryServicePrincipal);
servicePrincipalSecret = Utilities.GetSecondaryServicePrincipalSecret(envSecondaryServicePrincipal);
}
//=============================================================
// Creates an Azure Container Service with Kubernetes orchestration
Utilities.Log("Creating an Azure Container Service with Kubernetes ochestration with one agent and one virtual machine");
IContainerService azureContainerService = azure.ContainerServices.Define(acsName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithKubernetesOrchestration()
.WithServicePrincipal(servicePrincipalClientId, servicePrincipalSecret)
.WithLinux()
.WithRootUsername(rootUserName)
.WithSshKey(sshPublicKey)
.WithMasterNodeCount(ContainerServiceMasterProfileCount.MIN)
.DefineAgentPool("agentpool")
.WithVirtualMachineCount(1)
.WithVirtualMachineSize(ContainerServiceVMSizeTypes.StandardD1V2)
.WithDnsPrefix("dns-ap-" + acsName)
.Attach()
.WithMasterDnsPrefix("dns-" + acsName)
.Create();
Utilities.Log("Created Azure Container Service: " + azureContainerService.Id);
Utilities.Print(azureContainerService);
//=============================================================
// Updates a Kubernetes orchestrator Azure Container Service agent with two virtual machines
Utilities.Log("Updating the Kubernetes Azure Container Service agent with two virtual machines");
azureContainerService.Update()
.WithAgentVirtualMachineCount(2)
.Apply();
Utilities.Log("Updated Azure Container Service: " + azureContainerService.Id);
Utilities.Print(azureContainerService);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=============================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure, "", "");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
} | 50.120567 | 138 | 0.568841 | [
"MIT"
] | Azure-Samples/acs-dotnet-manage-azure-container-service-with-kubernetes-orchestrator | Program.cs | 7,067 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class ManagedObjectReference
{
protected string _type;
protected string _value;
public string Type
{
get
{
return this._type;
}
set
{
this._type = value;
}
}
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
public override string ToString()
{
return string.Format("{0}-{1}", this._type, this._value);
}
public override bool Equals(object obj)
{
return obj != null && obj is ManagedObjectReference && ((ManagedObjectReference)obj).Type == this._type && ((ManagedObjectReference)obj).Value == this._value;
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
public ManagedObjectReference(string id)
{
if (id.StartsWith("/"))
{
id = id.Trim("/".ToCharArray());
int num = id.LastIndexOf("=");
if (num > 0)
{
id = id.Substring(num + 1);
}
}
if (string.IsNullOrEmpty(id))
{
this._type = null;
this._value = null;
return;
}
int num2 = id.IndexOf('-');
if (num2 != -1)
{
this._type = id.Substring(0, num2);
this._value = id.Substring(num2 + 1);
return;
}
this._type = null;
this._value = id;
}
public ManagedObjectReference()
{
}
}
}
| 18.273973 | 161 | 0.596702 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/M/ManagedObjectReference.cs | 1,334 | C# |
using System.Threading.Tasks;
using Vecc.AutoDocker.Client.Docker;
namespace Vecc.AutoDocker.Client
{
public interface IDockerImagesClient : IDockerClient
{
Task<ImageInspect> GetImageAsync(string name);
}
}
| 21.818182 | 57 | 0.7125 | [
"MIT"
] | veccsolutions/Vecc.AutoDocker | src/Vecc.AutoDocker.Client/IDockerImagesClient.cs | 242 | 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CommunityToolkit.Mvvm.UnitTests;
[TestClass]
public partial class Test_ICommandAttribute
{
[TestMethod]
public async Task Test_ICommandAttribute_RelayCommand()
{
MyViewModel model = new();
model.IncrementCounterCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
model.IncrementCounterWithValueCommand.Execute(5);
Assert.AreEqual(model.Counter, 6);
await model.DelayAndIncrementCounterCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 7);
await model.DelayAndIncrementCounterWithTokenCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 8);
await model.DelayAndIncrementCounterWithValueCommand.ExecuteAsync(5);
Assert.AreEqual(model.Counter, 13);
await model.DelayAndIncrementCounterWithValueAndTokenCommand.ExecuteAsync(5);
Assert.AreEqual(model.Counter, 18);
List<Task> tasks = new();
for (int i = 0; i < 10; i++)
{
tasks.Add(model.AddValueToListAndDelayCommand.ExecuteAsync(i));
}
// All values should already be in the list, as commands are executed
// concurrently. Each invocation should still be pending here, but the
// values are added to the list before starting the delay.
CollectionAssert.AreEqual(model.Values, Enumerable.Range(0, 10).ToArray());
await Task.WhenAll(tasks);
}
[TestMethod]
public void Test_ICommandAttribute_CanExecute_NoParameters_Property()
{
CanExecuteViewModel model = new();
model.Flag = true;
model.IncrementCounter_NoParameters_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
model.IncrementCounter_NoParameters_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public void Test_ICommandAttribute_CanExecute_WithParameter_Property()
{
CanExecuteViewModel model = new();
model.Flag = true;
model.IncrementCounter_WithParameter_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
model.IncrementCounter_WithParameter_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public void Test_ICommandAttribute_CanExecute_NoParameters_MethodWithNoParameters()
{
CanExecuteViewModel model = new();
model.Flag = true;
model.IncrementCounter_NoParameters_MethodWithNoParametersCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
model.IncrementCounter_WithParameter_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public void Test_ICommandAttribute_CanExecute_WithParameters_MethodWithNoParameters()
{
CanExecuteViewModel model = new();
model.Flag = true;
model.IncrementCounter_WithParameters_MethodWithNoParametersCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
model.IncrementCounter_WithParameter_PropertyCommand.Execute(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public void Test_ICommandAttribute_CanExecute_WithParameters_MethodWithMatchingParameter()
{
CanExecuteViewModel model = new();
model.IncrementCounter_WithParameters_MethodWithMatchingParameterCommand.Execute(new User { Name = nameof(CanExecuteViewModel) });
Assert.AreEqual(model.Counter, 1);
model.IncrementCounter_WithParameter_PropertyCommand.Execute(new User());
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_CanExecute_Async_NoParameters_Property()
{
CanExecuteViewModel model = new();
model.Flag = true;
await model.IncrementCounter_Async_NoParameters_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
await model.IncrementCounter_Async_NoParameters_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_CanExecute_Async_WithParameter_Property()
{
CanExecuteViewModel model = new();
model.Flag = true;
await model.IncrementCounter_Async_WithParameter_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
await model.IncrementCounter_Async_WithParameter_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_CanExecute_Async_NoParameters_MethodWithNoParameters()
{
CanExecuteViewModel model = new();
model.Flag = true;
await model.IncrementCounter_Async_NoParameters_MethodWithNoParametersCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
await model.IncrementCounter_Async_WithParameter_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_CanExecute_Async_WithParameters_MethodWithNoParameters()
{
CanExecuteViewModel model = new();
model.Flag = true;
await model.IncrementCounter_Async_WithParameters_MethodWithNoParametersCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
model.Flag = false;
await model.IncrementCounter_Async_WithParameter_PropertyCommand.ExecuteAsync(null);
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_CanExecute_Async_WithParameters_MethodWithMatchingParameter()
{
CanExecuteViewModel model = new();
await model.IncrementCounter_Async_WithParameters_MethodWithMatchingParameterCommand.ExecuteAsync(new User { Name = nameof(CanExecuteViewModel) });
Assert.AreEqual(model.Counter, 1);
await model.IncrementCounter_Async_WithParameter_PropertyCommand.ExecuteAsync(new User());
Assert.AreEqual(model.Counter, 1);
}
[TestMethod]
public async Task Test_ICommandAttribute_ConcurrencyControl_AsyncRelayCommand()
{
TaskCompletionSource<object?> tcs = new();
MyViewModel model = new() { ExternalTask = tcs.Task };
Task task = model.AwaitForExternalTaskCommand.ExecuteAsync(null);
Assert.IsTrue(model.AwaitForExternalTaskCommand.IsRunning);
Assert.IsFalse(model.AwaitForExternalTaskCommand.CanExecute(null));
tcs.SetResult(null);
await task;
Assert.IsFalse(model.AwaitForExternalTaskCommand.IsRunning);
Assert.IsTrue(model.AwaitForExternalTaskCommand.CanExecute(null));
}
[TestMethod]
public async Task Test_ICommandAttribute_ConcurrencyControl_AsyncRelayCommandOfT()
{
MyViewModel model = new();
TaskCompletionSource<object?> tcs = new();
Task task = model.AwaitForInputTaskCommand.ExecuteAsync(tcs.Task);
Assert.IsTrue(model.AwaitForInputTaskCommand.IsRunning);
Assert.IsFalse(model.AwaitForInputTaskCommand.CanExecute(null));
tcs.SetResult(null);
await task;
Assert.IsFalse(model.AwaitForInputTaskCommand.IsRunning);
Assert.IsTrue(model.AwaitForInputTaskCommand.CanExecute(null));
}
// See https://github.com/CommunityToolkit/dotnet/issues/13
[TestMethod]
public void Test_ICommandAttribute_ViewModelRightAfterRegion()
{
ViewModelForIssue13 model = new();
Assert.IsNotNull(model.GreetCommand);
Assert.IsInstanceOfType(model.GreetCommand, typeof(RelayCommand));
}
#region Region
public class Region
{
}
#endregion
public partial class ViewModelForIssue13
{
[ICommand]
private void Greet()
{
}
}
public sealed partial class MyViewModel
{
public Task? ExternalTask { get; set; }
public int Counter { get; private set; }
public List<int> Values { get; } = new();
/// <summary>This is a single line summary.</summary>
[ICommand]
private void IncrementCounter()
{
Counter++;
}
/// <summary>
/// This is a multiline summary
/// </summary>
[ICommand]
private void IncrementCounterWithValue(int count)
{
Counter += count;
}
/// <summary>This is single line with also other stuff below</summary>
/// <returns>Foo bar baz</returns>
/// <returns>A task</returns>
[ICommand]
private async Task DelayAndIncrementCounterAsync()
{
await Task.Delay(50);
Counter += 1;
}
[ICommand]
private async Task AddValueToListAndDelayAsync(int value)
{
Values.Add(value);
await Task.Delay(100);
}
#region Test region
/// <summary>
/// This is multi line with also other stuff below
/// </summary>
/// <returns>Foo bar baz</returns>
/// <returns>A task</returns>
[ICommand]
private async Task DelayAndIncrementCounterWithTokenAsync(CancellationToken token)
{
await Task.Delay(50);
Counter += 1;
}
// This should not be ported over
[ICommand]
private async Task DelayAndIncrementCounterWithValueAsync(int count)
{
await Task.Delay(50);
Counter += count;
}
#endregion
[ICommand]
private async Task DelayAndIncrementCounterWithValueAndTokenAsync(int count, CancellationToken token)
{
await Task.Delay(50);
Counter += count;
}
[ICommand(AllowConcurrentExecutions = false)]
private async Task AwaitForExternalTaskAsync()
{
await ExternalTask!;
}
[ICommand(AllowConcurrentExecutions = false)]
private async Task AwaitForInputTaskAsync(Task task)
{
await task;
}
}
public sealed partial class CanExecuteViewModel
{
public int Counter { get; private set; }
public bool Flag { get; set; }
private bool GetFlag1() => Flag;
private bool GetFlag2(User user) => user.Name == nameof(CanExecuteViewModel);
[ICommand(CanExecute = nameof(Flag))]
private void IncrementCounter_NoParameters_Property()
{
Counter++;
}
[ICommand(CanExecute = nameof(Flag))]
private void IncrementCounter_WithParameter_Property(User user)
{
Counter++;
}
[ICommand(CanExecute = nameof(GetFlag1))]
private void IncrementCounter_NoParameters_MethodWithNoParameters()
{
Counter++;
}
[ICommand(CanExecute = nameof(GetFlag1))]
private void IncrementCounter_WithParameters_MethodWithNoParameters(User user)
{
Counter++;
}
[ICommand(CanExecute = nameof(GetFlag2))]
private void IncrementCounter_WithParameters_MethodWithMatchingParameter(User user)
{
Counter++;
}
[ICommand(CanExecute = nameof(Flag))]
private async Task IncrementCounter_Async_NoParameters_Property()
{
Counter++;
await Task.Delay(100);
}
[ICommand(CanExecute = nameof(Flag))]
private async Task IncrementCounter_Async_WithParameter_Property(User user)
{
Counter++;
await Task.Delay(100);
}
[ICommand(CanExecute = nameof(GetFlag1))]
private async Task IncrementCounter_Async_NoParameters_MethodWithNoParameters()
{
Counter++;
await Task.Delay(100);
}
[ICommand(CanExecute = nameof(GetFlag1))]
private async Task IncrementCounter_Async_WithParameters_MethodWithNoParameters(User user)
{
Counter++;
await Task.Delay(100);
}
[ICommand(CanExecute = nameof(GetFlag2))]
private async Task IncrementCounter_Async_WithParameters_MethodWithMatchingParameter(User user)
{
Counter++;
await Task.Delay(100);
}
}
public sealed class User
{
public string? Name { get; set; }
}
}
| 27.625793 | 155 | 0.660366 | [
"MIT"
] | jmarolf/dotnet | tests/CommunityToolkit.Mvvm.UnitTests/Test_ICommandAttribute.cs | 13,067 | 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("Riff.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Riff.UWP")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.62069 | 84 | 0.737657 | [
"MIT"
] | viswanathr88/Riff-Music-Xamarin | Riff.UWP/Properties/AssemblyInfo.cs | 1,036 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CSGenerator.
// </auto-generated>
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using jsval = JSApi.jsval;
public class JSB_UnityEngine_Motion
{
////////////////////// Motion ///////////////////////////////////////
// constructors
static bool Motion_Motion1(JSVCall vc, int argc)
{
int _this = JSApi.getObject((int)JSApi.GetType.Arg);
JSApi.attachFinalizerObject(_this);
--argc;
int len = argc;
if (len == 0)
{
JSMgr.addJSCSRel(_this, new UnityEngine.Motion());
}
return true;
}
// fields
// properties
// methods
//register
public static void __Register()
{
JSMgr.CallbackInfo ci = new JSMgr.CallbackInfo();
ci.type = typeof(UnityEngine.Motion);
ci.fields = new JSMgr.CSCallbackField[]
{
};
ci.properties = new JSMgr.CSCallbackProperty[]
{
};
ci.constructors = new JSMgr.MethodCallBackInfo[]
{
new JSMgr.MethodCallBackInfo(Motion_Motion1, ".ctor"),
};
ci.methods = new JSMgr.MethodCallBackInfo[]
{
};
JSMgr.allCallbackInfo.Add(ci);
}
}
| 19 | 80 | 0.554485 | [
"MIT"
] | linkabox/PureJSB | Assets/Standard Assets/JSBinding/Generated/JSB_UnityEngine_Motion.cs | 1,351 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
// ----------------------------------------------------------------------
// Gold Parser engine.
// See more details on http://www.devincook.com/goldparser/
//
// Original code is written in VB by Devin Cook (GOLDParser@DevinCook.com)
//
// This translation is done by Vladimir Morozov (vmoroz@hotmail.com)
//
// The translation is based on the other engine translations:
// Delphi engine by Alexandre Rai (riccio@gmx.at)
// C# engine by Marcus Klimstra (klimstra@home.nl)
// ----------------------------------------------------------------------
using System;
namespace GoldParser
{
public class GoldParserException : Exception
{
public GoldParserException(string message) : base(message)
{
}
}
}
| 35.566667 | 81 | 0.612933 | [
"MIT"
] | Ethereal77/stride | sources/shaders/Stride.Core.Shaders/GoldParser/GoldParserException.cs | 1,067 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace SelectionSort
{
/// <summary>
/// Tests for SelectionSorter class.
/// </summary>
[TestFixture]
class SelectionSorterTests
{
/// <summary>
/// Setup for each test.
/// </summary>
[SetUp]
public void SetUp()
{
sorter = new SelectionSorter();
}
/// <summary>
/// Checks that null is handled correctly as an input.
/// </summary>
[Test]
public void Null()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => sorter.Sort(null));
StringAssert.Contains("numbers cannot be null", ex.Message);
}
/// <summary>
/// Checks that sequence of numbers can be sorted correctly.
/// </summary>
/// <param name="expected">Expected array of integers.</param>
/// <param name="input">Array of integers to sort.</param>
[TestCase(new int[] { }, new int[] { })]
[TestCase(new int[] { -1 }, new int[] { -1 })]
[TestCase(new int[] { 1, 2, 3 }, new int[] { 3, 2, 1 })]
[TestCase(new int[] { -124, -40, 0, 7, 21, 100, 500 }, new int[] { 100, -40, 500, -124, 0, 21, 7 })]
public void Sort(int[] expected, int[] input)
{
CollectionAssert.AreEqual(expected, sorter.Sort(input));
}
/// <summary>
/// Selection sorter.
/// </summary>
private SelectionSorter sorter;
}
}
| 29.125 | 108 | 0.539546 | [
"MIT"
] | brianjosephegan/coding-questions | SelectionSort/SelectionSorterTests.cs | 1,633 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Cursor controller.
/// </summary>
// TODO @Movement Does not account for other planes than the XY Axis.
public class OverworldCursorMovement : MonoBehaviour
{
private Overworld overworld;
private OverworldManager oManager;
// For Keyboard Input
private Rigidbody2D m_MyRigidbody2D;
private float m_NextMovementTime;
private const float m_SlowMovementPauseTime = 0.2f;
// Figure out how to do extra input to speed up the movement rate.
private const float m_FastMovementPauseTime = 0.1f;
// Events
public delegate void InputAction(Vector3Int localPoint);
public static event InputAction OnCursorMove;
public void Awake()
{
}
public void Start()
{
// Cannot be initialized during Awake!!
overworld = Overworld.GetInstance();
oManager = OverworldManager.GetInstance();
m_MyRigidbody2D = GetComponent<Rigidbody2D>();
m_NextMovementTime = Time.time;
var localPoint = new Vector3Int(Mathf.FloorToInt(transform.position.x),
Mathf.FloorToInt(transform.position.y), 0);
// Start off position
if (OnCursorMove != null)
{
OnCursorMove(localPoint);
}
}
public void Update()
{
DirectionalMove();
MouseMove();
Select();
}
private void MouseMove()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var localPoint = new Vector3Int(Mathf.FloorToInt(point.x),
Mathf.FloorToInt(point.y), 0);
// Can we move to a tile?
if (overworld.IsMovable(localPoint))
{
var worldPoint = oManager.IncludeTilemapAnchor(localPoint);
transform.position = worldPoint;
// Fire Event
if (OnCursorMove != null)
{
OnCursorMove(localPoint);
}
}
}
}
// TODO: @KeyMapping Figure out key mapping for fast and slow movement with keyboard / gamepad.
private void DirectionalMove()
{
// Do I have any input?
if (Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0 ||
Mathf.Abs(Input.GetAxisRaw("Vertical")) > 0)
{
// Am I allowed to move again, yet?
if (Time.time > m_NextMovementTime)
{
m_NextMovementTime = Time.time + m_FastMovementPauseTime;
// Getting movement input for keys, mouse, and joystick.
var input = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
var localPoint = new Vector3Int(Mathf.FloorToInt(transform.position.x + Mathf.Ceil(input.x)),
Mathf.FloorToInt(transform.position.y + Mathf.Ceil(input.y)), 0);
// Can we move to a tile?
if (overworld.IsMovable(localPoint))
{
var worldPoint = oManager.IncludeTilemapAnchor(localPoint);
print("After cursor: " + worldPoint);
transform.position = worldPoint;
// Fire Event for successful move.
if (OnCursorMove != null)
{
OnCursorMove(localPoint);
}
}
}
}
}
private void Select()
{
}
} | 31.534483 | 109 | 0.554948 | [
"MIT"
] | ScotteRoberts/Personal-Projects | games/Fire Emblem/Assets/Sandbox/SRoberts/Scripts/Overworld/Implementations/OverworldCursorMovement.cs | 3,660 | C# |
namespace Battleship.Core.Tests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Battleship.Core.Components;
using Battleship.Core.Components.Board;
using Battleship.Core.Components.Ships;
using Battleship.Core.Enums;
using Battleship.Core.Models;
using Battleship.Core.Utilities;
using NUnit.Framework;
[TestFixture]
public class SegmentationTests : ComponentBase
{
private readonly IShipRandomiser shipRandomiser;
private readonly ISegmentation segmentation;
public SegmentationTests()
{
shipRandomiser = ShipRandomiser.Instance();
segmentation = Segmentation.Instance();
}
[Test]
public void Add_AddSegmentYAxisNotInGridDimension_ThrowIndexOutOfRangeException()
{
// Arrange
int x = XInitialPoint;
int y = GridDimension + Index;
Coordinate coordinate = new Coordinate(x, y);
Segment segment = new Segment(Water);
// Act and Assert
try
{
segmentation.AddSegment(coordinate, segment);
Assert.Fail();
}
catch (IndexOutOfRangeException)
{
Assert.Pass();
}
}
[Test]
public void UpdateSegment_SegmentOutOfRange_ThrowIndexOutOfRangeException()
{
// Arrange
int x = XInitialPoint;
int y = GridDimension + Index;
Coordinate coordinate = new Coordinate(x, y);
var segment = new Segment(ShipDirection.Vertical, new Destroyer(1));
// Act and Assert
try
{
segmentation.UpdateSegment(coordinate, segment);
Assert.Fail();
}
catch (IndexOutOfRangeException)
{
Assert.Pass();
}
}
[Test]
public void UpdateSegmentRange_CantUpdateAEmptySegmentWithAnotherEmptySegment_TrowArgumentException()
{
// Arrange
int x = XInitialPoint;
int y = GridDimension;
Coordinate coordinate = new Coordinate(x, y);
// Act and Assert
try
{
segmentation.AddSegment(coordinate, new Segment(Water));
SortedDictionary<Coordinate, Segment> range = new SortedDictionary<Coordinate, Segment>(new CoordinateComparer())
{
{ coordinate, new Segment(Water) }
};
segmentation.UpdateSegmentRange(range);
Assert.Fail();
}
catch (ArgumentException)
{
Assert.Pass();
}
}
[Test]
public void UpdateSegmentRange_CantUpdateFilledSegmentWithEmptySegment_TrowArgumentException()
{
// Arrange
int x = XInitialPoint;
int y = GridDimension;
Coordinate coordinate = new Coordinate(x, y);
// Act and Assert
try
{
segmentation.AddSegment(coordinate, new Segment(ShipDirection.Horizontal, new BattleShip(1)));
SortedDictionary<Coordinate, Segment> range = new SortedDictionary<Coordinate, Segment>()
{
{ coordinate, new Segment(Water) }
};
segmentation.UpdateSegmentRange(range);
Assert.Fail();
}
catch (ArgumentException)
{
Assert.Pass();
}
}
[Test]
public void UpdateSegmentRange_CanUpdateSegmentWithFilledSegment_ReturnsVoid()
{
// Arrange
int x = XInitialPoint;
int y = GridDimension;
Coordinate coordinate = new Coordinate(x, y);
// Act and Assert
try
{
segmentation.AddSegment(coordinate, new Segment(Water));
SortedDictionary<Coordinate, Segment> range = new SortedDictionary<Coordinate, Segment>(new CoordinateComparer())
{
{ coordinate, new Segment(ShipDirection.Horizontal, new BattleShip(1)) }
};
segmentation.UpdateSegmentRange(range);
Assert.IsTrue(true);
}
catch (ArgumentException)
{
Assert.Fail();
}
}
}
} | 32.013699 | 129 | 0.526744 | [
"MIT"
] | VisualSanity/Battleship | Source/Battleship.Core.Tests/SegmentationTests.cs | 4,676 | 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;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.Collections.Concurrent
{
// Abstract base for a thread-safe dictionary mapping a set of keys (K) to values (V).
//
// This flavor of ConcurrentUnifier holds values using weak references. It does not store the keys directly. Instead, values are
// required to contain the key and expose it via IKeyedItem<K>. This flavor should be used in situations where the keys themselves
// could store direct or indirect references to the value (thus, preventing the value's from being GC'd if the table were to
// store the keys directly.)
//
// Value immortality is guaranteed. Once entered into the dictionary, the value never expires
// in an observable way as long as values don't have finalizers.
//
// To create an actual dictionary, subclass this type and override the protected Factory method
// to instantiate values (V) for the "Add" case.
//
// The key must be of a type that implements IEquatable<K>. The unifier calls IEquality<K>.Equals()
// and Object.GetHashCode() on the keys.
//
// The value must be a reference type that implements IKeyedItem<K>. The unifier invokes the
// IKeyedItem<K>.PrepareKey() method (outside the lock) on any value returned by the factory. This gives the value
// a chance to do any lazy evaluation of the keys while it's safe to do so.
//
// Deadlock risks:
// - Keys may be tested for equality and asked to compute their hashcode while the unifier
// holds its lock. Thus these operations must be written carefully to avoid deadlocks and
// reentrancy in to the table.
//
// - Values may get their IKeyedItem<K>.Key property called while the unifier holds its lock.
// Values that need to do lazy evaluation to compute their keys should do that in the PrepareKey()
// method which the unifier promises to call outside the lock prior to entering the value into the table.
//
// - The Factory method will never be called inside the unifier lock. If two threads race to
// enter a value for the same key, the Factory() may get invoked twice for the same key - one
// of them will "win" the race and its result entered into the dictionary - other gets thrown away.
//
// Notes:
// - This class is used to look up types when GetType() or typeof() is invoked.
// That means that this class itself cannot do or call anything that does these
// things.
//
// - For this reason, it chooses not to mimic the official ConcurrentDictionary class
// (I don't even want to risk using delegates.) Even the LowLevel versions of these
// general utility classes may not be low-level enough for this class's purpose.
//
// Thread safety guarantees:
//
// ConcurrentUnifier is fully thread-safe and requires no
// additional locking to be done by callers.
//
// Performance characteristics:
//
// ConcurrentUnifier will not block a reader, even while
// the table is being written. Only one writer is allowed at a time;
// ConcurrentUnifier handles the synchronization that ensures this.
//
// Safety for concurrent readers is ensured as follows:
//
// Each hash bucket is maintained as a stack. Inserts are done under
// a lock in one of two ways:
//
// - The entry is filled out completely, then "published" by a
// single write to the top of the bucket. This ensures that a reader
// will see a valid snapshot of the bucket, once it has read the head.
//
// - An expired WeakReference inside an existing entry is replaced atomically
// by a new WeakReference. A reader will either see the old expired WeakReference
// (if so, he'll wait for the current lock to be released then do the locked retry)
// or the new WeakReference (which is fine for him to see.))
//
// On resize, we allocate an entirely new table, rather than resizing
// in place. We fill in the new table completely, under the lock,
// then "publish" it with a single write. Any reader that races with
// this will either see the old table or the new one; each will contain
// the same data.
//
internal abstract class ConcurrentUnifierWKeyed<K, V>
where K : IEquatable<K>
where V : class, IKeyedItem<K>
{
protected ConcurrentUnifierWKeyed()
{
_lock = new Lock();
_container = new Container(this);
}
//
// Retrieve the *unique* value for a given key. If the key was previously not entered into the dictionary,
// this method invokes the overridable Factory() method to create the new value. The Factory() method is
// invoked outside of any locks. If two threads race to enter a value for the same key, the Factory()
// may get invoked twice for the same key - one of them will "win" the race and its result entered into the
// dictionary - other gets thrown away.
//
public V GetOrAdd(K key)
{
Debug.Assert(key != null);
Debug.Assert(!_lock.IsAcquired, "GetOrAdd called while lock already acquired. A possible cause of this is an Equals or GetHashCode method that causes reentrancy in the table.");
int hashCode = key.GetHashCode();
V value;
bool found = _container.TryGetValue(key, hashCode, out value);
#if DEBUG
{
V checkedValue;
bool checkedFound;
// In debug builds, always exercise a locked TryGet (this is a good way to detect deadlock/reentrancy through Equals/GetHashCode()).
using (LockHolder.Hold(_lock))
{
_container.VerifyUnifierConsistency();
int h = key.GetHashCode();
checkedFound = _container.TryGetValue(key, h, out checkedValue);
}
if (found)
{
// Since this DEBUG code is holding a strong reference to "value", state of a key must never go from found to not found,
// and only one value may exist per key.
Debug.Assert(checkedFound);
Debug.Assert(object.ReferenceEquals(checkedValue, value));
GC.KeepAlive(value);
}
}
#endif //DEBUG
if (found)
return value;
value = this.Factory(key);
// This doesn't catch every object that has a finalizer, but the old saying about half a loaf...
Debug.Assert(!(value is IDisposable),
"Values placed in this table should not have finalizers. ConcurrentUnifiers guarantee observational immortality only " +
"in the absence of finalizers. Or to speak more plainly, we can use WeakReferences to guarantee observational immortality " +
"without paying the cost of storage immortality.");
if (value == null)
{
// There's no point in caching null's in the dictionary as a WeakReference of null will always show up as expired
// and force a re-add every time. Just return the null value without storing it. This does mean that repeated look ups
// for this case will be very slow - this generally corresponds to scenarios like looking for a type member that doesn't
// exist so hopefully, it's better to have awful throughput for such cases rather than polluting the dictionary with
// "null entries" that have to be special-cased for everyone.
return null;
}
// While still outside the lock, invoke the value's PrepareKey method to give the chance to do any lazy evaluation
// it needs to produce the key quickly and in a deadlock-free manner once we're inside the lock.
value.PrepareKey();
using (LockHolder.Hold(_lock))
{
V heyIWasHereFirst;
if (_container.TryGetValue(key, hashCode, out heyIWasHereFirst))
return heyIWasHereFirst;
if (!_container.HasCapacity)
_container.Resize(); // This overwrites the _container field.
_container.Add(key, hashCode, value);
return value;
}
}
protected abstract V Factory(K key);
private volatile Container _container;
private readonly Lock _lock;
private sealed class Container
{
public Container(ConcurrentUnifierWKeyed<K, V> owner)
{
// Note: This could be done by calling Resize()'s logic but we cannot safely do that as this code path is reached
// during class construction time and Resize() pulls in enough stuff that we get cyclic cctor warnings from the build.
_buckets = new int[_initialCapacity];
for (int i = 0; i < _initialCapacity; i++)
_buckets[i] = -1;
_entries = new Entry[_initialCapacity];
_nextFreeEntry = 0;
_owner = owner;
}
private Container(ConcurrentUnifierWKeyed<K, V> owner, int[] buckets, Entry[] entries, int nextFreeEntry)
{
_buckets = buckets;
_entries = entries;
_nextFreeEntry = nextFreeEntry;
_owner = owner;
}
public bool TryGetValue(K key, int hashCode, out V value)
{
// Lock acquistion NOT required.
int bucket = ComputeBucket(hashCode, _buckets.Length);
int i = Volatile.Read(ref _buckets[bucket]);
while (i != -1)
{
V? actualValue;
if (hashCode == _entries[i]._hashCode && _entries[i]._weakValue.TryGetTarget(out actualValue))
{
K actualKey = actualValue.Key;
if (key.Equals(actualKey))
{
value = actualValue;
return true;
}
}
i = _entries[i]._next;
}
value = default(V);
return false;
}
public void Add(K key, int hashCode, V value)
{
Debug.Assert(_owner._lock.IsAcquired);
int bucket = ComputeBucket(hashCode, _buckets.Length);
int newEntryIdx = _nextFreeEntry;
_entries[newEntryIdx]._weakValue = new WeakReference<V>(value, trackResurrection: false);
_entries[newEntryIdx]._hashCode = hashCode;
_entries[newEntryIdx]._next = _buckets[bucket];
_nextFreeEntry++;
// The line that atomically adds the new key/value pair. If the thread is killed before this line executes but after
// we've incremented _nextFreeEntry, this entry is harmlessly leaked until the next resize.
Volatile.Write(ref _buckets[bucket], newEntryIdx);
VerifyUnifierConsistency();
}
public bool HasCapacity
{
get
{
Debug.Assert(_owner._lock.IsAcquired);
return _nextFreeEntry != _entries.Length;
}
}
public void Resize()
{
Debug.Assert(_owner._lock.IsAcquired);
// Before we actually grow the size of the table, figure out how much we can recover just by dropping entries with
// expired weak references.
int estimatedNumLiveEntries = 0;
for (int bucket = 0; bucket < _buckets.Length; bucket++)
{
for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next)
{
// Check if the weakreference has expired.
V? value;
if (_entries[entry]._weakValue.TryGetTarget(out value))
estimatedNumLiveEntries++;
}
}
double estimatedLivePercentage = ((double)estimatedNumLiveEntries) / ((double)(_entries.Length));
int newSize;
if (estimatedLivePercentage < _growThreshold && (_entries.Length - estimatedNumLiveEntries) > _initialCapacity)
{
newSize = _buckets.Length;
}
else
{
newSize = HashHelpers.GetPrime(_buckets.Length * 2);
#if DEBUG
newSize = _buckets.Length + 3;
#endif
if (newSize <= _nextFreeEntry)
throw new OutOfMemoryException();
}
Entry[] newEntries = new Entry[newSize];
int[] newBuckets = new int[newSize];
for (int i = 0; i < newSize; i++)
newBuckets[i] = -1;
// Note that we walk the bucket chains rather than iterating over _entries. This is because we allow for the possibility
// of abandoned entries (with undefined contents) if a thread is killed between allocating an entry and linking it onto the
// bucket chain.
int newNextFreeEntry = 0;
for (int bucket = 0; bucket < _buckets.Length; bucket++)
{
for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next)
{
// Check if the weakreference has expired. If so, this is where we drop the entry altogether.
V? value;
if (_entries[entry]._weakValue.TryGetTarget(out value))
{
newEntries[newNextFreeEntry]._weakValue = _entries[entry]._weakValue;
newEntries[newNextFreeEntry]._hashCode = _entries[entry]._hashCode;
int newBucket = ComputeBucket(newEntries[newNextFreeEntry]._hashCode, newSize);
newEntries[newNextFreeEntry]._next = newBuckets[newBucket];
newBuckets[newBucket] = newNextFreeEntry;
newNextFreeEntry++;
}
}
}
// The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if
// a thread died between the time between we allocated the entry and the time we link it into the bucket stack.
// In addition, we don't bother copying entries where the weak reference has expired.
Debug.Assert(newNextFreeEntry <= _nextFreeEntry);
// The line that atomically installs the resize. If this thread is killed before this point,
// the table remains full and the next guy attempting an add will have to redo the resize.
_owner._container = new Container(_owner, newBuckets, newEntries, newNextFreeEntry);
_owner._container.VerifyUnifierConsistency();
}
private static int ComputeBucket(int hashCode, int numBuckets)
{
int bucket = (hashCode & 0x7fffffff) % numBuckets;
return bucket;
}
[Conditional("DEBUG")]
public void VerifyUnifierConsistency()
{
// There's a point at which this check becomes gluttonous, even by checked build standards...
if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100)))
return;
Debug.Assert(_owner._lock.IsAcquired);
Debug.Assert(_nextFreeEntry >= 0 && _nextFreeEntry <= _entries.Length);
int numEntriesEncountered = 0;
for (int bucket = 0; bucket < _buckets.Length; bucket++)
{
int walk1 = _buckets[bucket];
int walk2 = _buckets[bucket]; // walk2 advances two elements at a time - if walk1 ever meets walk2, we've detected a cycle.
while (walk1 != -1)
{
numEntriesEncountered++;
Debug.Assert(walk1 >= 0 && walk1 < _nextFreeEntry);
Debug.Assert(walk2 >= -1 && walk2 < _nextFreeEntry);
Debug.Assert(_entries[walk1]._weakValue != null);
V? value;
if (_entries[walk1]._weakValue.TryGetTarget(out value))
{
K key = value.Key;
Debug.Assert(key != null);
int hashCode = key.GetHashCode();
Debug.Assert(hashCode == _entries[walk1]._hashCode);
}
int storedBucket = ComputeBucket(_entries[walk1]._hashCode, _buckets.Length);
Debug.Assert(storedBucket == bucket);
walk1 = _entries[walk1]._next;
if (walk2 != -1)
walk2 = _entries[walk2]._next;
if (walk2 != -1)
walk2 = _entries[walk2]._next;
if (walk1 == walk2 && walk2 != -1)
Debug.Fail("Bucket " + bucket + " has a cycle in its linked list.");
}
}
// The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if
// a thread died between the time between we allocated the entry and the time we link it into the bucket stack.
Debug.Assert(numEntriesEncountered <= _nextFreeEntry);
}
private readonly int[] _buckets;
private readonly Entry[] _entries;
private int _nextFreeEntry;
private readonly ConcurrentUnifierWKeyed<K, V> _owner;
private const int _initialCapacity = 5;
private const double _growThreshold = 0.75;
}
private struct Entry
{
public WeakReference<V> _weakValue;
public int _hashCode;
public int _next;
}
}
}
| 48.912596 | 189 | 0.566721 | [
"MIT"
] | AlexanderSemenyak/runtime | src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs | 19,027 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
namespace CDSPractical
{
public class Questions
{
/// <summary>
/// Given an enumerable of strings, attempt to parse each string and if
/// it is an integer, add it to the returned enumerable.
///
/// For example:
///
/// ExtractNumbers(new List<string> { "123", "hello", "234" });
///
/// ; would return:
///
/// {
/// 123,
/// 234
/// }
/// </summary>
/// <param name="source">An enumerable containing words</param>
/// <returns> list containing only numbers else empty </returns>
public IEnumerable<int> ExtractNumbers(IEnumerable<string> source)
{
int number = 0;
foreach (string item in source)
{
if (int.TryParse(item, out number))
{
yield return number;
}
}
yield break;
}
/// <summary>
/// Given two enumerables of strings, find the longest common word.
///
/// For example:
///
/// LongestCommonWord(
/// new List<string> {
/// "love",
/// "wandering",
/// "goofy",
/// "sweet",
/// "mean",
/// "show",
/// "fade",
/// "scissors",
/// "shoes",
/// "gainful",
/// "wind",
/// "warn"
/// },
/// new List<string> {
/// "wacky",
/// "fabulous",
/// "arm",
/// "rabbit",
/// "force",
/// "wandering",
/// "scissors",
/// "fair",
/// "homely",
/// "wiggly",
/// "thankful",
/// "ear"
/// }
/// );
///
/// ; would return "wandering" as the longest common word.
/// </summary>
/// <param name="first">First list of words</param>
/// <param name="second">Second list of words</param>
/// <returns>longest common word between the two lists</returns>
public string LongestCommonWord(IEnumerable<string> first, IEnumerable<string> second)
{
if (first.Count() == 0 || second.Count() == 0)
{
return string.Empty;
}
IEnumerable<string> commonItems = first.ToList()
.ConvertAll(x => x.ToLower())
.Intersect(second.ToList()
.ConvertAll(y => y.ToLower()));
if (commonItems.Count() > 0)
{
var length = commonItems.Max(s => s.Length);
return commonItems.FirstOrDefault(s => s.Length == length);
}
else
{
return string.Empty;
}
}
/// <summary>
/// Write a method that converts kilometers to miles, given that there are
/// 1.6 kilometers per mile.
///
/// For example:
///
/// DistanceInMiles(16.00);
///
/// ; would return 10.00;
/// </summary>
/// <param name="km">distance in kilometers</param>
/// <returns></returns>
public double DistanceInMiles(double km)
{
return km / Constants.KmMilesFactor;
}
/// <summary>
/// Write a method that converts miles to kilometers, give that there are
/// 1.6 kilometers per mile.
///
/// For example:
///
/// DistanceInKm(10.00);
///
/// ; would return 16.00;
/// </summary>
/// <param name="miles">distance in miles</param>
/// <returns></returns>
public double DistanceInKm(double miles)
{
return miles * Constants.KmMilesFactor;
}
/// <summary>
/// Write a method that returns true if the word is a palindrome, false if
/// it is not.
///
/// For example:
///
/// IsPalindrome("bolton");
///
/// ; would return false, and:
///
/// IsPalindrome("Anna");
///
/// ; would return true.
///
/// Also complete the related test case for this method.
/// </summary>
/// <param name="word">The word to check</param>
/// <returns></returns>
public bool IsPalindrome(string word)
{
return Enumerable.Range(0, word.Length / 2)
.Select(i => char.ToLower(word[i]) == char.ToLower(word[word.Length - i - 1]))
.All(b => b);
}
/// <summary>
/// Write a method that takes an enumerable list of objects and shuffles
/// them into a different order.
///
/// For example:
///
/// Shuffle(new List<string>{ "one", "two" });
///
/// ; would return:
///
/// {
/// "two",
/// "one"
/// }
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public IEnumerable<object> Shuffle(IEnumerable<object> source)
{
IEnumerable<object> target = ExtendedMethods.ShuffleExtender(source);
while (Enumerable.SequenceEqual(source, target))
{
target = ExtendedMethods.ShuffleExtender(source);
}
return target;
}
/// <summary>
/// Write a method that sorts an array of integers into ascending
/// order - do not use any built in sorting mechanisms or frameworks.
///
/// Complete the test for this method.
/// </summary>
/// <param name="source">i.e. [1,3,4,2]</param>
/// <returns>acsending sort [1,2,3,4]</returns>
public int[] Sort(int[] source)
{
int temp;
for (int i = 0; i < source.Length - 1; i++)
for (int j = i + 1; j < source.Length; j++)
if (source[i] > source[j])
{
temp = source[i];
source[i] = source[j];
source[j] = temp;
}
return source;
}
/// <summary>
/// Each new term in the Fibonacci sequence is generated by adding the
/// previous two terms. By starting with 1 and 2, the first 10 terms will be:
///
/// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
///
/// By considering the terms in the Fibonacci sequence whose values do
/// not exceed four million, find the sum of the even-valued terms.
/// </summary>
/// <returns>4613732 </returns>
public int FibonacciSum()
{
long limit = Constants.LimitForFibonacci;
long even1 = 0, even2 = 2;
long sum = even1 + even2;
while (sum <= limit)
{
long even3 = 4 * even2 + even1;
if (even3 > limit)
break;
even1 = even2;
even2 = even3;
sum += even2;
}
return (int)sum;
}
/// <summary>
/// Generate a list of integers from 1 to 100.
///
/// This method is currently broken, fix it so that the tests pass.
/// </summary>
/// <returns>list from 1 to 100</returns>
public IEnumerable<int> GenerateList()
{
var ret = new List<int>();
var numThreads = 2;
object locker = new object();
Thread[] threads = new Thread[numThreads];
for (var i = 0; i < numThreads; i++)
{
threads[i] = new Thread(() =>
{
var complete = false;
while (!complete)
{
lock (locker)
{
var next = ret.Count + 1;
Thread.Sleep(new Random().Next(1, 10));
if (next <= 100)
{
ret.Add(next);
}
if (ret.Count >= 100)
{
complete = true;
}
}
}
});
threads[i].Start();
}
for (var i = 0; i < numThreads; i++)
{
threads[i].Join();
}
return ret;
}
}
}
| 31.501672 | 99 | 0.400149 | [
"Apache-2.0"
] | ShaswataTripathy/interview-questions | csharp/CDSPractical/Questions.cs | 9,421 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Net;
using System.Collections.Generic;
using ThirdParty.Json.LitJson;
using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeElasticLoadBalancers operation
/// </summary>
internal class DescribeElasticLoadBalancersResponseUnmarshaller : JsonResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeElasticLoadBalancersResponse response = new DescribeElasticLoadBalancersResponse();
context.Read();
UnmarshallResult(context,response);
return response;
}
private static void UnmarshallResult(JsonUnmarshallerContext context,DescribeElasticLoadBalancersResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
while (context.Read())
{
if (context.TestExpression("ElasticLoadBalancers", targetDepth))
{
context.Read();
response.ElasticLoadBalancers = new List<ElasticLoadBalancer>();
ElasticLoadBalancerUnmarshaller unmarshaller = ElasticLoadBalancerUnmarshaller.GetInstance();
while (context.Read())
{
JsonToken token = context.CurrentTokenType;
if (token == JsonToken.ArrayStart)
{
continue;
}
if (token == JsonToken.ArrayEnd)
{
break;
}
response.ElasticLoadBalancers.Add(unmarshaller.Unmarshall(context));
}
continue;
}
if (context.CurrentDepth <= originalDepth)
{
return;
}
}
return;
}
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return new ValidationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonOpsWorksException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeElasticLoadBalancersResponseUnmarshaller instance;
public static DescribeElasticLoadBalancersResponseUnmarshaller GetInstance()
{
if (instance == null)
{
instance = new DescribeElasticLoadBalancersResponseUnmarshaller();
}
return instance;
}
}
}
| 39.59633 | 165 | 0.611446 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.OpsWorks/Model/Internal/MarshallTransformations/DescribeElasticLoadBalancersResponseUnmarshaller.cs | 4,316 | C# |
/*
* Copyright (c) 2014, Alan L. Lovejoy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Essence Sharp Project.
*/
#region Using declarations
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using EssenceSharp.Properties;
using EssenceSharp.UtilityServices;
using EssenceSharp.Exceptions;
using EssenceSharp.Exceptions.System;
using EssenceSharp.Runtime;
#endregion
namespace EssenceSharp.ClientServices {
public class MultiScriptExecutive {
protected List<String> errors = new List<String>();
protected EssenceSharpOptionsBuilder optionsBuilder = new EssenceSharpOptionsBuilder();
protected String environmentName = "Smalltalk";
protected List<String> imports = new List<String>();
protected bool reportTimings = false;
protected bool beVerbose = false;
protected bool helpRequested = false;
protected List<ScriptExecutive> executives = new List<ScriptExecutive>();
protected ScriptExecutive currentExecutive;
public MultiScriptExecutive(String[] args) {
if (args == null || args.Length < 1) return;
var options = new List<Option>();
Argument keyword;
Argument operand;
var index = 0;
while (index < args.Length) {
var arg = args[index++];
keyword = Argument.parse(arg, ArgumentSyntax.Any);
if (keyword.OperandAffinity == OperandAffinity.RequiresOperand) {
if (index < args.Length) {
try {
arg = args[index++];
operand = Argument.parse(arg, keyword.OperandSyntax);
options.Add(keyword.asOptionWithOperand(operand));
} catch (Exception ex) {
errors.Add("Error in operand for " + keyword.OptionKeyword + " option: " + ex.Message);
}
} else {
throw new InvalidArgumentException("The " + keyword.OptionKeyword + " option requires an operand.");
}
} else {
try {
options.Add(keyword.asOption());
} catch {
errors.Add("Unknown/unrecognized argument: " + arg);
}
}
}
foreach (var option in options) option.applyTo(this);
}
public String EssenceSharpPath {
set { optionsBuilder.EssenceSharpPath = new DirectoryInfo(value);}
}
public void addLibrarySearchPath(String userLibrarySearchPath) {
optionsBuilder.addLibrarySearchPath(userLibrarySearchPath);
}
public void addScriptSearchPath(String userScriptSearchPath) {
optionsBuilder.addScriptSearchPath(userScriptSearchPath);
}
public void addLibrary(String userLibraryName) {
try {
var libraryName = new StringReader(userLibraryName).nextQualifiedIdentifier();
optionsBuilder.loadLibrary(libraryName);
} catch {
errors.Add("Library names must use qualified identifer syntax: " + userLibraryName);
}
}
protected void setEnvironmentName(String envName) {
if (currentExecutive == null) {
try {
environmentName = new StringReader(envName).nextQualifiedIdentifier();
} catch {
errors.Add("Invalid syntax for the name of the evaluation namespace.");
}
} else {
currentExecutive.EnvironmentName = envName;
}
}
public String EnvironmentName {
get { return environmentName;}
set { setEnvironmentName(value);}
}
public void addImport(String namespaceName) {
if (currentExecutive == null) {
imports.Add(namespaceName);
} else {
currentExecutive.addImport(namespaceName);
}
}
protected void setCurrentExecutive(ScriptExecutive executive) {
currentExecutive = executive;
if (currentExecutive != null) {
currentExecutive.ReportTimings = ReportTimings;
currentExecutive.BeVerbose = BeVerbose;
executives.Add(currentExecutive);
}
}
public void addScriptPathSuffix(String scriptPathSuffix) {
setCurrentExecutive(new NamedScriptExecutive(scriptPathSuffix, environmentName, imports));
}
public void addScriptText(String scriptText) {
setCurrentExecutive(new LiteralScriptExecutive(scriptText, environmentName, imports));
}
public void addScriptArg(Scalar scriptArg) {
if (currentExecutive == null) {
errors.Add("Script arguments may only be specified following the script to which they apply.");
} else {
currentExecutive.addScriptArg(scriptArg);
}
}
public bool ReportTimings {
get { return reportTimings;}
set { if (currentExecutive == null) {
reportTimings = value;
optionsBuilder.ReportTimings = value;
} else {
currentExecutive.ReportTimings = value;
}}
}
public bool BeVerbose {
get { return beVerbose;}
set { if (currentExecutive == null) {
beVerbose = value;
} else {
currentExecutive.BeVerbose = value;
}
optionsBuilder.LoadLibrariesVerbosely = value;}
}
public bool HelpRequested {
get { return helpRequested;}
set { helpRequested = value;}
}
public void provideHelp() {
Console.WriteLine("");
var helpText = Resources.ES_Help;
Console.WriteLine(helpText);
}
public void run() {
if (HelpRequested || errors.Count > 0) {
foreach (var error in errors) Console.WriteLine(error);
provideHelp();
return;
}
ScriptRuntime scriptRuntime = null;
try {
// ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); // This is the "standard" way to do it; but it's rather less flexible.
scriptRuntime = EssenceLaunchPad.CreateRuntime(optionsBuilder);
ScriptEngine engine = scriptRuntime.GetEngine("Essence#");
foreach (var executive in executives) executive.run(engine);
} finally {
if (scriptRuntime != null) scriptRuntime.Shutdown();
}
}
}
public abstract class ScriptExecutive {
protected List<String> errors = new List<String>();
protected String environmentName;
protected List<String> imports = new List<String>();
protected bool reportTimings = false;
protected bool beVerbose = false;
protected List<Scalar> scriptArguments = new List<Scalar>();
protected Object[] scriptArgs;
protected TimeSpan durationToRun = TimeSpan.Zero;
protected ScriptExecutive(String environmentName, List<String> imports) {
this.environmentName = environmentName ?? "Smalltalk";
if (imports != null) {
foreach (var nsName in imports) this.imports.Add(nsName);
}
}
public abstract String Identity { get; }
protected void setEnvironmentName(String envName) {
try {
environmentName = new StringReader(envName).nextQualifiedIdentifier();
} catch {
errors.Add("Invalid syntax for the name of the evaluation namespace.");
}
}
public String EnvironmentName {
get { return environmentName;}
set { setEnvironmentName(value);}
}
public bool ReportTimings {
get { return reportTimings;}
set { reportTimings = value;}
}
public bool BeVerbose {
get { return beVerbose;}
set { beVerbose = value;}
}
public void addImport(String namespaceName) {
imports.Add(namespaceName);
}
public void addScriptArg(Scalar scriptArg) {
scriptArguments.Add(scriptArg);
}
protected void evaluatScriptArguments(ESObjectSpace objectSpace, NamespaceObject environment) {
var argList = new List<Object>();
foreach (var argSpec in scriptArguments) {
try {
Object value;
FileInfo scriptPath;
if (argSpec.SpecifiesPathname) {
if (objectSpace.pathForScript(argSpec.Value, out scriptPath)) {
if (objectSpace.evaluate(scriptPath, environment, null, null, out value)) {
argList.Add(value);
} else {
errors.Add("Syntax error in script used as argument, pathname = " + argSpec.Value);
}
} else {
errors.Add("Script path (used as argument to base script) not found: " + argSpec.Value);
}
} else if (objectSpace.evaluate(new StringReader(argSpec.Value), environment, null, null, out value)) {
argList.Add(value);
} else {
errors.Add("Syntax error in argument: " + argSpec.Value);
}
} catch (Exception ex) {
errors.Add("Error in argument evaluation: " + ex.ToString());
}
}
scriptArgs = argList.ToArray();
}
protected abstract Object runScript(ScriptEngine engine, ESCompilerOptions compilationOptions, NamespaceObject environment);
public Object run(ScriptEngine engine) {
if (errors.Count > 0) {
foreach (var error in errors) Console.WriteLine(error);
return null;
}
Object value = null;
try {
var objectSpace = engine.essenceSharpObjectSpace();
var environment = objectSpace.findOrCreateNamespace(EnvironmentName);
foreach (var nsName in imports) {
var ns = objectSpace.findOrCreateNamespace(nsName);
environment.addImport(new ESImportSpec(ns, AccessPrivilegeLevel.InHierarchy, ImportTransitivity.Intransitive));
}
evaluatScriptArguments(objectSpace, environment);
if (errors.Count > 0) {
foreach (var error in errors) Console.WriteLine(error);
return null;
}
var compilationOptions = (ESCompilerOptions)engine.GetCompilerOptions();
compilationOptions.EnvironmentName = EnvironmentName;
try {
value = runScript(engine, compilationOptions, environment);
} catch (SyntaxErrorException syntaxError) {
value = syntaxError.Message;
errors.Add(syntaxError.Message);
}
Console.WriteLine("");
Console.WriteLine(Identity);
Console.WriteLine(" => " + value);
} finally {
if (ReportTimings) {
Console.WriteLine("________________________________________");
Console.WriteLine("Script run time = " + durationToRun.ToString());
Console.WriteLine("");
}
}
return value;
}
}
public class LiteralScriptExecutive : ScriptExecutive {
protected String text;
public LiteralScriptExecutive(String text, String environmentName, List<String> imports) : base(environmentName, imports) {
this.text = text;
}
public override String Identity {
get { return text;}
}
protected override Object runScript(ScriptEngine engine, ESCompilerOptions compilationOptions, NamespaceObject environment) {
var script = engine.CreateScriptSourceFromString(text);
return script.Execute(compilationOptions, scriptArgs, out durationToRun);
}
}
public class NamedScriptExecutive : ScriptExecutive {
protected String pathnameSuffix;
public NamedScriptExecutive(String pathnameSuffix, String environmentName, List<String> imports) : base(environmentName, imports) {
this.pathnameSuffix = pathnameSuffix;
}
public override String Identity {
get { return pathnameSuffix;}
}
protected override Object runScript(ScriptEngine engine, ESCompilerOptions compilationOptions, NamespaceObject environment) {
var script = engine.CreateScriptSourceFromPathSuffix(pathnameSuffix);
if (script == null) {
var message = "Script not found: " + pathnameSuffix;
Console.WriteLine(message);
return message;
} else {
try {
return script.Execute(compilationOptions, scriptArgs, out durationToRun);
} catch (InvalidFunctionCallException ex) {
var message = "Script argument mismatch: " + pathnameSuffix;
Console.WriteLine(message);
return message;
}
}
}
}
}
| 33.052219 | 149 | 0.714353 | [
"BSD-2-Clause"
] | EssenceSharp/cSharp | Source/ClientServices/ESScriptExecution.cs | 12,661 | C# |
using N3O.Umbraco.Financial;
using NodaTime;
using System.Threading;
using System.Threading.Tasks;
namespace N3O.Umbraco.Forex {
public interface IExchangeRateProvider {
Task<decimal> GetHistoricalRateAsync(LocalDate date,
Currency baseCurrency,
Currency quoteCurrency,
CancellationToken cancellationToken = default);
Task<decimal> GetLiveRateAsync(Currency baseCurrency,
Currency quoteCurrency,
CancellationToken cancellationToken = default);
}
}
| 38.166667 | 92 | 0.551674 | [
"MIT"
] | Osama-Tahboub1/N3O.Umbraco | src/Forex/N3O.Umbraco.Forex/Services/ExchangeRateProvider.I.cs | 687 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 13.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.NullableDateOnly.DateOnly{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.DateOnly>;
using T_DATA2 =System.DateOnly;
using T_DATA1_U=System.DateOnly;
using T_DATA2_U=System.DateOnly;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2021,05,11);
T_DATA2 vv2=new T_DATA2_U(2021,05,12);
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2021,05,11);
T_DATA2 vv2=new T_DATA2_U(2021,05,11);
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2021,05,12);
T_DATA2 vv2=new T_DATA2_U(2021,05,11);
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=new T_DATA2_U(2021,05,11);
var recs=db.testTable.Where(r => ((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2021,05,11);
object vv2__null_obj=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=new T_DATA2_U(2021,05,11);
var recs=db.testTable.Where(r => !(((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2021,05,11);
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.NullableDateOnly.DateOnly
| 25.723958 | 141 | 0.544138 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/LessThan/Complete/NullableDateOnly/DateOnly/TestSet_504__param__01__VV.cs | 9,880 | C# |
using System.ComponentModel;
namespace RiotGames.TeamfightTactics;
[EditorBrowsable(EditorBrowsableState.Never)]
public interface ITeamfightTacticsObject : IRiotGamesObject
{
}
public interface ILeagueId : ITeamfightTacticsObject
{
public string LeagueId { get; set; }
}
public interface IMatchId : ITeamfightTacticsObject
{
public string MatchId { get; set; }
} | 21.777778 | 60 | 0.757653 | [
"Unlicense"
] | mikaeldui/riot-games-dotnet-client | RiotGames.Client/TeamfightTactics/TeamfightTacticsInterfaces.cs | 394 | C# |
using FluentValidation;
using Monytor.Implementation.Collectors.RavenDb;
namespace Monytor.Implementation.Collectors.Sql {
public class StartingWithCollectorValidator : AbstractValidator<StartingWithCollector> {
public StartingWithCollectorValidator() {
RuleFor(x => x.Source)
.NotNull()
.WithMessage("The 'Source' must not be provided.");
RuleFor(x => x.Source.Database)
.NotEmpty()
.WithMessage("The 'Database' must not be provided.");
RuleFor(x => x.Source.Url)
.NotEmpty()
.WithMessage("The 'Url' name must not be empty.");
RuleFor(x => x.StartingWith)
.NotEmpty()
.WithMessage("The 'Starting With' name must not be empty.");
}
}
} | 35 | 92 | 0.577381 | [
"MIT"
] | MrDariusAD/monytor | Monytor.Implementation.Collectors.RavenDb/StartingWithCollectorValidator.cs | 842 | 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 System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class DocumentationCommentIDVisitor
{
/// <summary>
/// A visitor that generates the part of the documentation comment after the initial type
/// and colon.
/// </summary>
private sealed class PartVisitor : CSharpSymbolVisitor<StringBuilder, object>
{
// Everyone outside this type uses this one.
internal static readonly PartVisitor Instance = new PartVisitor(inParameterOrReturnType: false);
// Select callers within this type use this one.
private static readonly PartVisitor s_parameterOrReturnTypeInstance = new PartVisitor(inParameterOrReturnType: true);
private readonly bool _inParameterOrReturnType;
private PartVisitor(bool inParameterOrReturnType)
{
_inParameterOrReturnType = inParameterOrReturnType;
}
public override object VisitArrayType(ArrayTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.ElementType, builder);
// Rank-one arrays are displayed different than rectangular arrays
if (symbol.IsSZArray)
{
builder.Append("[]");
}
else
{
builder.Append("[0:");
for (int i = 0; i < symbol.Rank - 1; i++)
{
builder.Append(",0:");
}
builder.Append(']');
}
return null;
}
public override object VisitField(FieldSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(symbol.Name);
return null;
}
private void VisitParameters(ImmutableArray<ParameterSymbol> parameters, bool isVararg, StringBuilder builder)
{
builder.Append('(');
bool needsComma = false;
foreach (var parameter in parameters)
{
if (needsComma)
{
builder.Append(',');
}
Visit(parameter, builder);
needsComma = true;
}
if (isVararg && needsComma)
{
builder.Append(',');
}
builder.Append(')');
}
public override object VisitMethod(MethodSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Arity != 0)
{
builder.Append("``");
builder.Append(symbol.Arity);
}
if (symbol.Parameters.Any() || symbol.IsVararg)
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, symbol.IsVararg, builder);
}
if (symbol.MethodKind == MethodKind.Conversion)
{
builder.Append('~');
s_parameterOrReturnTypeInstance.Visit(symbol.ReturnType, builder);
}
return null;
}
public override object VisitProperty(PropertySymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Parameters.Any())
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, false, builder);
}
return null;
}
public override object VisitEvent(EventSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
return null;
}
public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder)
{
int ordinalOffset = 0;
// Is this a type parameter on a type?
Symbol containingSymbol = symbol.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.Method)
{
builder.Append("``");
}
else
{
Debug.Assert(containingSymbol is NamedTypeSymbol);
// If the containing type is nested within other types, then we need to add their arities.
// e.g. A<T>.B<U>.M<V>(T t, U u, V v) should be M(`0, `1, ``0).
for (NamedTypeSymbol curr = containingSymbol.ContainingType; (object)curr != null; curr = curr.ContainingType)
{
ordinalOffset += curr.Arity;
}
builder.Append('`');
}
builder.Append(symbol.Ordinal + ordinalOffset);
return null;
}
public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingSymbol != null && symbol.ContainingSymbol.Name.Length != 0)
{
Visit(symbol.ContainingSymbol, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
if (symbol.Arity != 0)
{
// Special case: dev11 treats types instances of the declaring type in the parameter list
// (and return type, for conversions) as constructed with its own type parameters.
if (!_inParameterOrReturnType && TypeSymbol.Equals(symbol, symbol.ConstructedFrom, TypeCompareKind.ConsiderEverything2))
{
builder.Append('`');
builder.Append(symbol.Arity);
}
else
{
builder.Append('{');
bool needsComma = false;
foreach (var typeArgument in symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
if (needsComma)
{
builder.Append(',');
}
Visit(typeArgument.Type, builder);
needsComma = true;
}
builder.Append('}');
}
}
return null;
}
public override object VisitPointerType(PointerTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.PointedAtType, builder);
builder.Append('*');
return null;
}
public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingNamespace != null && symbol.ContainingNamespace.Name.Length != 0)
{
Visit(symbol.ContainingNamespace, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
return null;
}
public override object VisitParameter(ParameterSymbol symbol, StringBuilder builder)
{
Debug.Assert(_inParameterOrReturnType);
Visit(symbol.Type, builder);
// ref and out params are suffixed with @
if (symbol.RefKind != RefKind.None)
{
builder.Append('@');
}
return null;
}
public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder)
{
return VisitNamedType(symbol, builder);
}
public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder)
{
// NOTE: this is a change from dev11, which did not allow dynamic in parameter types.
// If we wanted to be really conservative, we would actually visit the symbol for
// System.Object. However, the System.Object type must always have exactly this
// doc comment ID, so the hassle seems unjustifiable.
builder.Append("System.Object");
return null;
}
private static string GetEscapedMetadataName(Symbol symbol)
{
string metadataName = symbol.MetadataName;
int colonColonIndex = metadataName.IndexOf("::", StringComparison.Ordinal);
int startIndex = colonColonIndex < 0 ? 0 : colonColonIndex + 2;
PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
pooled.Builder.Append(metadataName, startIndex, metadataName.Length - startIndex);
pooled.Builder.Replace('.', '#').Replace('<', '{').Replace('>', '}');
return pooled.ToStringAndFree();
}
}
}
}
| 35.839721 | 140 | 0.516625 | [
"MIT"
] | 333fred/roslyn | src/Compilers/CSharp/Portable/DocumentationComments/DocumentationCommentIDVisitor.PartVisitor.cs | 10,288 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Docker.Compose.Rule.Net.Configuration
{
public class ProjectName
{
private readonly string _projectName;
private ProjectName(string projectName)
{
if (projectName.Trim().Length == 0)
{
throw new ArgumentException("ProjectName must not be blank.");
}
if (!projectName.All(char.IsLetterOrDigit))
{
throw new ArgumentException("ProjectName must not be blank.");
}
_projectName = projectName;
}
public List<string> ConstructComposeFileCommand() {
return new List<string>() {"--project-name", _projectName};
}
public static ProjectName Random()
{
// TODO:
return new ProjectName(Guid.NewGuid().ToString().Substring(0, 8));
}
public static ProjectName FromString(string name) {
return new ProjectName(name);
}
public string AsString()
{
return _projectName;
}
}
} | 25.195652 | 76 | 0.582399 | [
"Apache-2.0"
] | alexpantyukhin/Docker.Compose.Rule.Net | src/Docker.Compose.Rule.Net/Configuration/ProjectName.cs | 1,159 | 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;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Internal;
using Xunit.Abstractions;
namespace InteropTests.Helpers
{
public class WebsiteProcess : IDisposable
{
private readonly Process _process;
private readonly ProcessEx _processEx;
private readonly TaskCompletionSource<object> _startTcs;
private static readonly Regex NowListeningRegex = new Regex(@"^\s*Now listening on: .*:(?<port>\d*)$");
private readonly StringBuilder _output;
private readonly object _outputLock = new object();
public string ServerPort { get; private set; }
public bool IsReady => _startTcs.Task.IsCompletedSuccessfully;
public WebsiteProcess(string path, ITestOutputHelper output)
{
_output = new StringBuilder();
_process = new Process();
_process.StartInfo = new ProcessStartInfo
{
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = "dotnet",
Arguments = path
};
_process.EnableRaisingEvents = true;
_process.OutputDataReceived += Process_OutputDataReceived;
_process.ErrorDataReceived += Process_ErrorDataReceived;
_process.Start();
_processEx = new ProcessEx(output, _process, Timeout.InfiniteTimeSpan);
_startTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
}
public string GetOutput()
{
lock (_outputLock)
{
return _output.ToString();
}
}
public Task WaitForReady()
{
if (_processEx.HasExited)
{
return Task.FromException(new InvalidOperationException("Server is not running."));
}
return _startTcs.Task;
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
var data = e.Data;
if (data != null)
{
var m = NowListeningRegex.Match(data);
if (m.Success)
{
ServerPort = m.Groups["port"].Value;
}
if (data.Contains("Application started. Press Ctrl+C to shut down."))
{
_startTcs.TrySetResult(null);
}
lock (_outputLock)
{
_output.AppendLine(data);
}
}
}
private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
var data = e.Data;
if (data != null)
{
lock (_outputLock)
{
_output.AppendLine("ERROR: " + data);
}
}
}
public void Dispose()
{
_processEx.Dispose();
}
}
}
| 30.324074 | 111 | 0.557252 | [
"MIT"
] | 48355746/AspNetCore | src/Grpc/test/InteropTests/Helpers/WebsiteProcess.cs | 3,275 | 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: IMethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IDeviceCompliancePolicyAssignRequestBuilder.
/// </summary>
public partial interface IDeviceCompliancePolicyAssignRequestBuilder : IBaseRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IDeviceCompliancePolicyAssignRequest Request(IEnumerable<Option> options = null);
}
}
| 37.827586 | 153 | 0.592525 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IDeviceCompliancePolicyAssignRequestBuilder.cs | 1,097 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
// root level service for all Roslyn services
internal partial class CodeAnalysisService : IRemoteDocumentHighlights
{
public Task<IList<SerializableDocumentHighlights>> GetDocumentHighlightsAsync(
DocumentId documentId, int position, DocumentId[] documentIdsToSearch, CancellationToken cancellationToken)
{
return RunServiceAsync(async token =>
{
// NOTE: In projection scenarios, we might get a set of documents to search
// that are not all the same language and might not exist in the OOP process
// (like the JS parts of a .cshtml file). Filter them out here. This will
// need to be revisited if we someday support FAR between these languages.
var solution = await GetSolutionAsync(token).ConfigureAwait(false);
var document = solution.GetDocument(documentId);
var documentsToSearch = ImmutableHashSet.CreateRange(
documentIdsToSearch.Select(solution.GetDocument).WhereNotNull());
var service = document.GetLanguageService<IDocumentHighlightsService>();
var result = await service.GetDocumentHighlightsAsync(
document, position, documentsToSearch, token).ConfigureAwait(false);
return (IList<SerializableDocumentHighlights>)result.SelectAsArray(SerializableDocumentHighlights.Dehydrate);
}, cancellationToken);
}
}
}
| 49.65 | 161 | 0.70141 | [
"Apache-2.0"
] | AdamSpeight2008/roslyn-1 | src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_DocumentHighlights.cs | 1,988 | C# |
using System;
namespace CommandDemo
{
class Program
{
static void Main(string[] args)
{
Message msg = new Message();
msg.CustomMessage = "Welcome by Email";
EmailMessageCommand emailMsgCommand = new EmailMessageCommand(msg);
Message msg2 = new Message();
msg2.CustomMessage = "Welcome by Sms";
SmsMessageCommand smsMsgCommand = new SmsMessageCommand(msg2);
Broker broker = new Broker();
broker.SendMessage(emailMsgCommand);
broker.SendMessage(smsMsgCommand);
Console.ReadKey();
}
}
}
| 28.913043 | 80 | 0.566917 | [
"MIT"
] | codeyu/MediatR-in-action | src/CommandDemo/Program.cs | 667 | C# |
using IkeMtz.NRSRx.Core.SignalR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using NurseCron.Communications.SignalR.Hubs;
namespace NurseCron.Communications.SignalR
{
public class Startup : CoreSignalrStartup
{
public Startup(Microsoft.Extensions.Configuration.IConfiguration configuration) : base(configuration) { }
public override void MapHubs(IEndpointRouteBuilder endpoints)
{
_ = endpoints.MapHub<NotificationHub>("/notificationHub");
}
}
}
| 28 | 109 | 0.779762 | [
"MIT"
] | ikemtz/NurseCron | src/MicroServices/Communications/NurseCron.Communications.SignalR/Startup.cs | 504 | C# |
using System;
using System.Xml;
namespace SharpVectors.Dom.Css
{
public sealed class CssAbsPrimitiveValue : CssPrimitiveValue
{
private string _propertyName;
private XmlElement _element;
private CssPrimitiveValue _cssValue;
public CssAbsPrimitiveValue(CssPrimitiveValue cssValue, string propertyName, XmlElement element)
{
if (cssValue == null)
{
throw new ArgumentNullException(nameof(cssValue));
}
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
_cssValue = cssValue;
_propertyName = propertyName;
_element = element;
}
public override string CssText
{
get {
return _cssValue.CssText;
}
}
public override CssPrimitiveType PrimitiveType
{
get {
return _cssValue.PrimitiveType;
}
}
public override bool IsAbsolute
{
get {
return true;
}
}
public CssPrimitiveValue CssValue
{
get {
return _cssValue;
}
}
public override double GetFloatValue(CssPrimitiveType unitType)
{
return _cssValue.GetFloatValue(unitType);
}
public override string GetStringValue()
{
switch (PrimitiveType)
{
case CssPrimitiveType.Attr:
return _element.GetAttribute(_cssValue.GetStringValue(), string.Empty);
default:
return _cssValue.GetStringValue();
}
}
public override ICssRect GetRectValue()
{
return _cssValue.GetRectValue();
}
public override ICssColor GetRgbColorValue()
{
return _cssValue.GetRgbColorValue();
}
}
}
| 25.829268 | 105 | 0.499528 | [
"MIT",
"BSD-3-Clause"
] | Altua/SharpVectors | Source/SharpVectorCss/Css/CssAbsPrimitiveValue.cs | 2,118 | C# |
//Problem 8. Maximal sum
//Write a program that finds the sequence of maximal sum in given array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class MaxSum
{
static void Main()
{
Console.WriteLine("Enter an arrat in the format \"2, 3, -6, -1, 2, -1, 6, 4, -8, 8\"");
string str = Console.ReadLine();
int[] array = str.Split(new char[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();
int finalSum = 0;
int finalStartIndex = 0;
int finalCounter = 0;
int currentSum = 0;
int currentCounter = 0;
for (int i = 0; i < array.Length; i++)
{
currentSum += array[i];
currentCounter++;
if(currentSum <= 0)
{
currentSum = 0;
currentCounter = 0;
}
if(finalSum < currentSum)
{
finalSum = currentSum;
finalStartIndex = i;
finalCounter = currentCounter;
}
}
//Print result
for (int i = finalStartIndex - finalCounter+1; i <= finalStartIndex ; i++)
{
Console.Write(array[i] + " ");
}
}
} | 25.074074 | 138 | 0.502954 | [
"MIT"
] | bkerefeyski/Telerik-Academy-Tasks | C# 2 Homeworks/1.Arrays/MaximalSum/MaxSum.cs | 1,356 | C# |
/*
* Copyright 2014 Alastair Wyse (https://github.com/alastairwyse/ApplicationMetrics/)
*
* 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 ApplicationMetrics.MetricLoggers.UnitTests
{
/// <summary>
/// A sample status metric for testing implementations of interface IMetricLogger.
/// </summary>
class TestAvailableMemoryMetric : StatusMetric
{
public TestAvailableMemoryMetric()
{
base.name = "AvailableMemory";
base.description = "A single instance of this metric represents the amount of free memory in the system at a given time.";
}
}
}
| 36.774194 | 134 | 0.708772 | [
"Apache-2.0"
] | alastairwyse/ApplicationMetrics | ApplicationMetrics.MetricLoggers.UnitTests/TestAvailableMemoryMetric.cs | 1,140 | C# |
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
namespace Macad.Presentation
{
// See: http://drwpf.com/blog/2009/03/17/tips-and-tricks-making-value-converters-more-accessible-in-markup/
// Base class
public abstract class MultiConverterMarkupExtension<T> : MarkupExtension, IMultiValueConverter where T : class, new()
{
protected static T _Instance = null;
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_Instance == null)
{
_Instance = new T();
}
return _Instance;
}
#region IMultiValueConverter Members
public virtual object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
public virtual object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
}
| 29.230769 | 122 | 0.619298 | [
"MIT"
] | Macad3D/Macad3D | Source/Macad.Presentation/MultiConverter/MultiConverterMarkupExtension.cs | 1,142 | C# |
// The FinderOuter
// Copyright (c) 2020 Coding Enthusiast
// Distributed under the MIT software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
using Autarkysoft.Bitcoin.ImprovementProposals;
using FinderOuter.Backend;
using FinderOuter.Models;
using FinderOuter.Services;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace FinderOuter.ViewModels
{
public enum PassRecoveryMode
{
[Description("A password consisting of random characters")]
Alphanumeric
}
public class MissingMnemonicPassViewModel : OptionVmBase
{
public MissingMnemonicPassViewModel()
{
WordListsList = ListHelper.GetAllEnumValues<BIP0039.WordLists>().ToArray();
MnemonicTypesList = ListHelper.GetAllEnumValues<MnemonicTypes>().ToArray();
InputTypeList = ListHelper.GetEnumDescItems<InputType>().ToArray();
SelectedInputType = InputTypeList.First();
MnService = new MnemonicExtensionService(Result);
PassRecoveryModeList = ListHelper.GetEnumDescItems<PassRecoveryMode>().ToArray();
SelectedPassRecoveryMode = PassRecoveryModeList.First();
IObservable<bool> isFindEnabled = this.WhenAnyValue(
x => x.Mnemonic,
x => x.AdditionalInfo,
x => x.KeyPath,
x => x.Result.CurrentState,
(mn, extra, path, state) =>
!string.IsNullOrEmpty(mn) &&
!string.IsNullOrEmpty(extra) &&
!string.IsNullOrEmpty(path) &&
state != State.Working);
FindCommand = ReactiveCommand.Create(Find, isFindEnabled);
HasExample = true;
IObservable<bool> isExampleVisible = this.WhenAnyValue(
x => x.Result.CurrentState,
(state) => state != State.Working && HasExample);
ExampleCommand = ReactiveCommand.Create(Example, isExampleVisible);
SetExamples(GetExampleData());
}
public override string OptionName => "Missing Mnemonic Pass";
public override string Description => "This option can recover missing mnemonic passphrases also known as extra " +
"or extension words. Enter the mnemonic, a child key or address for comparisson and the full path of that key. " +
"The path is the full BIP-32 defined path of the child key including the key's index (eg. m/44'/0'/0'/0)." +
$"{Environment.NewLine}" +
$"Choose a recovery mode and enter the required information. Finally click Find button.";
public MnemonicExtensionService MnService { get; }
public IEnumerable<BIP0039.WordLists> WordListsList { get; }
public IEnumerable<MnemonicTypes> MnemonicTypesList { get; }
public IEnumerable<DescriptiveItem<InputType>> InputTypeList { get; }
public IEnumerable<DescriptiveItem<PassRecoveryMode>> PassRecoveryModeList { get; }
private MnemonicTypes _selMnT;
public MnemonicTypes SelectedMnemonicType
{
get => _selMnT;
set => this.RaiseAndSetIfChanged(ref _selMnT, value);
}
private BIP0039.WordLists _selWordLst;
public BIP0039.WordLists SelectedWordListType
{
get => _selWordLst;
set => this.RaiseAndSetIfChanged(ref _selWordLst, value);
}
private DescriptiveItem<InputType> _inT;
public DescriptiveItem<InputType> SelectedInputType
{
get => _inT;
set => this.RaiseAndSetIfChanged(ref _inT, value);
}
private DescriptiveItem<PassRecoveryMode> _recMode;
public DescriptiveItem<PassRecoveryMode> SelectedPassRecoveryMode
{
get => _recMode;
set => this.RaiseAndSetIfChanged(ref _recMode, value);
}
private string _mnemonic;
public string Mnemonic
{
get => _mnemonic;
set => this.RaiseAndSetIfChanged(ref _mnemonic, value);
}
private int _passLen = 1;
public int PassLength
{
get => _passLen;
set
{
if (value < 1)
value = 1;
this.RaiseAndSetIfChanged(ref _passLen, value);
}
}
private string _additional;
public string AdditionalInfo
{
get => _additional;
set => this.RaiseAndSetIfChanged(ref _additional, value);
}
private string _path;
public string KeyPath
{
get => _path;
set => this.RaiseAndSetIfChanged(ref _path, value);
}
private bool _isUpper;
public bool IsUpperCase
{
get => _isUpper;
set => this.RaiseAndSetIfChanged(ref _isUpper, value);
}
private bool _isLower;
public bool IsLowerCase
{
get => _isLower;
set => this.RaiseAndSetIfChanged(ref _isLower, value);
}
private bool _isNum;
public bool IsNumber
{
get => _isNum;
set => this.RaiseAndSetIfChanged(ref _isNum, value);
}
private bool _isSymbol;
public bool IsSymbol
{
get => _isSymbol;
set => this.RaiseAndSetIfChanged(ref _isSymbol, value);
}
public static string AllSymbols => $"Symbols ({ConstantsFO.AllSymbols})";
public PasswordType PassType
{
get
{
PasswordType result = PasswordType.None;
if (IsUpperCase)
{
result |= PasswordType.UpperCase;
}
if (IsLowerCase)
{
result |= PasswordType.LowerCase;
}
if (IsNumber)
{
result |= PasswordType.Numbers;
}
if (IsSymbol)
{
result |= PasswordType.Symbols;
}
return result;
}
}
public override void Find()
{
MnService.Find(Mnemonic, SelectedMnemonicType, SelectedWordListType,
AdditionalInfo, SelectedInputType.Value, KeyPath, PassLength, PassType);
}
public void Example()
{
object[] ex = GetNextExample();
Mnemonic = (string)ex[0];
int temp1 = (int)ex[1];
Debug.Assert(temp1 < MnemonicTypesList.Count());
SelectedMnemonicType = MnemonicTypesList.ElementAt(temp1);
int temp2 = (int)ex[2];
Debug.Assert(temp2 < WordListsList.Count());
SelectedWordListType = WordListsList.ElementAt(temp2);
int temp3 = (int)ex[3];
Debug.Assert(temp3 < InputTypeList.Count());
SelectedInputType = InputTypeList.ElementAt(temp3);
AdditionalInfo = (string)ex[4];
KeyPath = (string)ex[5];
PassLength = (int)ex[6];
PasswordType flag = (PasswordType)(ulong)ex[7];
IsUpperCase = flag.HasFlag(PasswordType.UpperCase);
IsLowerCase = flag.HasFlag(PasswordType.LowerCase);
IsNumber = flag.HasFlag(PasswordType.Numbers);
IsSymbol = flag.HasFlag(PasswordType.Symbols);
Result.Message = $"Example {exampleIndex} of {totalExampleCount}. Source: {(string)ex[8]}";
}
private ExampleData GetExampleData()
{
return new ExampleData<string, int, int, int, string, string, int, ulong, string>()
{
{
"uphold cotton arch always museum hidden tent grape spot winter impose height curtain awake retire",
0, // MnemonicType
0, // WordList,
0, // InputType
"1K2gAgfcs3oBb2hpa6XodakQJm1my9KuZg",
"m/0'/0",
3, // Pass length
2, // Pass type flag
$"Random.{Environment.NewLine}" +
$"This example is a BIP39 mnemonic with a simple passphrase using only lower case letters (kqe)." +
$"{Environment.NewLine}" +
$"Estimated time: <10 sec"
},
{
"uphold cotton arch always museum hidden tent grape spot winter impose height curtain awake retire",
0, // MnemonicType
0, // WordList,
0, // InputType
"19h1BJtUS7KxZaKd1dBejeZirG9bvwfSu7",
"m/0'/0",
3, // Pass length
12, // Pass type flag
$"Random.{Environment.NewLine}" +
$"This example is a BIP39 mnemonic with a simple passphrase using numbers and symbols (3+[)." +
$"{Environment.NewLine}" +
$"Estimated time: <20 sec"
},
};
}
}
}
| 34.651852 | 126 | 0.553228 | [
"MIT"
] | 1Biggirl/FinderOuter | Src/FinderOuter/ViewModels/MissingMnemonicPassViewModel.cs | 9,358 | C# |
/// MyMenuItem.cs Agosto 22/2016 MoonPincho
///
using UnityEngine;
using UnityEditor;
namespace MoonPincho
{
#if UNITY_5_4
public class MyMenuItem : MonoBehaviour
{
[MenuItem("MoonPincho/My Custom SubMenu/My Custom Menu Item #%w")]
private static void Init()
{
Debug.Log("Init was called");
}
[MenuItem("CONTEXT/Rigidbody/My Rigidbody Debug")]
private static void RigidbodyDebug()
{
Debug.Log("RigidbodyDebug was called on: " + Selection.activeTransform.gameObject.name);
}
}
#endif
}
| 22.692308 | 100 | 0.625424 | [
"Apache-2.0"
] | lPinchol/unity-attribute | UA Project/Assets/UA Project/Scripts/MyMenuItem.cs | 592 | C# |
using OpenDreamRuntime.Procs;
using OpenDreamShared.Dream;
namespace OpenDreamRuntime.Objects.MetaObjects {
class DreamMetaObjectMob : DreamMetaObjectMovable {
public DreamMetaObjectMob(DreamRuntime runtime)
: base(runtime)
{}
public override void OnObjectCreated(DreamObject dreamObject, DreamProcArguments creationArguments) {
base.OnObjectCreated(dreamObject, creationArguments);
Runtime.Mobs.Add(dreamObject);
}
public override void OnObjectDeleted(DreamObject dreamObject) {
base.OnObjectDeleted(dreamObject);
Runtime.Mobs.Remove(dreamObject);
}
public override void OnVariableSet(DreamObject dreamObject, string variableName, DreamValue variableValue, DreamValue oldVariableValue) {
base.OnVariableSet(dreamObject, variableName, variableValue, oldVariableValue);
if (variableName == "key" || variableName == "ckey") {
DreamConnection newClientConnection =
Runtime.Server.GetConnectionFromCKey(variableValue.GetValueAsString());
newClientConnection.MobDreamObject = dreamObject;
}
else if (variableName == "see_invisible") {
string ckey = dreamObject.GetVariable("ckey").GetValueAsString();
Runtime.StateManager.AddClientSeeInvisibleDelta(ckey, (byte)variableValue.GetValueAsInteger());
} else if (variableName == "client" && variableValue != oldVariableValue) {
DreamObject newClient = variableValue.GetValueAsDreamObject();
DreamObject oldClient = oldVariableValue.GetValueAsDreamObject();
if (newClient != null) {
Runtime.Server.GetConnectionFromClient(newClient).MobDreamObject = dreamObject;
} else if (oldClient != null) {
Runtime.Server.GetConnectionFromClient(oldClient).MobDreamObject = null;
}
}
}
public override DreamValue OnVariableGet(DreamObject dreamObject, string variableName, DreamValue variableValue) {
if (variableName == "key" || variableName == "ckey") {
DreamObject clientObject = dreamObject.GetVariable("client").GetValueAsDreamObject();
if (clientObject != null && clientObject.IsSubtypeOf(DreamPath.Client)) {
return clientObject.GetVariable(variableName);
} else {
return DreamValue.Null;
}
} else if (variableName == "client") {
DreamConnection connection = Runtime.Server.GetConnectionFromMob(dreamObject);
if (connection != null && connection.ClientDreamObject != null) {
return new DreamValue(connection.ClientDreamObject);
} else {
return DreamValue.Null;
}
} else {
return base.OnVariableGet(dreamObject, variableName, variableValue);
}
}
public override DreamValue OperatorOutput(DreamValue a, DreamValue b) {
DreamObject client = a.GetValueAsDreamObjectOfType(DreamPath.Mob).GetVariable("client").GetValueAsDreamObjectOfType(DreamPath.Client);
DreamConnection connection = Runtime.Server.GetConnectionFromClient(client);
connection.OutputDreamValue(b);
return new DreamValue(0);
}
}
}
| 46.065789 | 146 | 0.633248 | [
"MIT"
] | Eskjjlj/OpenDream | OpenDreamRuntime/Objects/MetaObjects/DreamMetaObjectMob.cs | 3,503 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460/blob/master/LICENSE
*
*/
#endregion
using Classes.Colours;
using ComponentFactory.Krypton.Toolkit;
using Core.Classes.Other;
using Core.Interfaces;
using Core.UX;
using KryptonExtendedToolkit.Base.Code;
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using ToolkitSettings.Classes.Global;
using ToolkitSettings.Classes.PaletteExplorer.Colours;
namespace PaletteEditor.UX.New
{
public partial class MainWindow : KryptonForm
{
#region Variables
private bool _dirty, _loaded, _debugMode, _useCircularPictureBoxes;
private string _fileName;
private KryptonPalette _palette;
private PaletteMode _paletteMode;
private ConversionMethods _conversionMethods = new ConversionMethods();
private AllMergedColourSettingsManager _colourSettingsManager = new AllMergedColourSettingsManager();
private Classes.GlobalMethods _globalMethods = new Classes.GlobalMethods();
private GlobalStringSettingsManager _globalStringSettingsManager = new GlobalStringSettingsManager();
private GlobalBooleanSettingsManager _globalBooleanSettingsManager = new GlobalBooleanSettingsManager();
private MostRecentlyUsedFileManager _mostRecentlyUsedFileManager;
private Version _currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
private Timer _colourUpdateTimer;
private IAboutStripped _about;
#endregion
#region Properties
public bool DebugMode { get { return _debugMode; } set { _debugMode = value; } }
public bool Dirty { get { return _dirty; } set { _dirty = value; } }
public bool Loaded { get { return _loaded; } set { _loaded = value; } }
public bool UseCircularPictureBoxes { get { return _useCircularPictureBoxes; } set { _useCircularPictureBoxes = value; } }
public string FileName { get { return _fileName; } set { _fileName = value; } }
public new KryptonPalette Palette { get { return _palette; } set { _palette = value; } }
public new PaletteMode PaletteMode { get { return _paletteMode; } set { _paletteMode = value; } }
#endregion
public MainWindow()
{
InitializeComponent();
InitialiseVariables();
}
#region Methods
private void InitialiseVariables()
{
_colourUpdateTimer = new Timer();
_colourUpdateTimer.Interval = 250;
_colourUpdateTimer.Tick += new EventHandler(Tick);
DebugMode = _globalBooleanSettingsManager.GetIsInDeveloperMode();
UseCircularPictureBoxes = _globalBooleanSettingsManager.GetUseCircularPictureBoxes();
}
private void InitialiseWindow()
{
New();
_mostRecentlyUsedFileManager = new MostRecentlyUsedFileManager(recentPaletteDefinitionsToolStripMenuItem, "Palette Editor", MyOwnRecentPaletteFileGotClicked_Handler, MyOwnRecentPaletteFilesGotCleared_Handler);
ColourUtilities.PropagateBasePaletteModes(kcmbBasePaletteMode);
_colourSettingsManager.ResetToDefaults();
if (UseCircularPictureBoxes)
{
ShowCircularPreviewBoxes(_globalBooleanSettingsManager.GetUseCircularPictureBoxes());
}
TextExtra = $"(Build: { _currentVersion.Build.ToString() } - experimental)";
}
private void ExitPaletteEditor()
{
if (Dirty)
{
DialogResult result = KryptonMessageBox.Show("The palette has not yet been saved.\nDo you want to save now?", "Palette Editor Save Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
if (Loaded)
{
Save();
Application.Exit();
}
else
{
Save();
Application.Exit();
}
}
else
{
Application.Exit();
}
}
else
{
Application.Exit();
}
}
/// <summary>
/// Gets the current saved palette mode.
/// </summary>
private void GetCurrentSavedPaletteMode()
{
tslStatus.Text = $"The current palette mode is: { _globalMethods.GetSelectedPaletteMode() }";
}
private void ExportPaletteColours(bool useCircularPictureBoxes)
{
if (useCircularPictureBoxes)
{
//PaletteEditorEngine.ExportPalette(_globalMethods.GetSelectedPaletteMode(), cbxBaseColourPreview, cbxDarkColourPreview, cbxMiddleColourPreview, cbxLightColourPreview, cbxLightestColourPreview, cbxBorderColourPreview, cbxAlternativeNormalTextColourPreview, cbxNormalTextColourPreview, cbxDisabledTextColourPreview, cbxFocusedTextColourPreview, cbxPressedTextColourPreview, cbxDisabledColourPreview, cbxLinkNormalColourPreview, cbxLinkHoverColourPreview, cbxLinkVisitedColourPreview, cbxCustomColourOnePreview, cbxCustomColourTwoPreview, cbxCustomColourThreePreview, cbxCustomColourFourPreview, cbxCustomColourFivePreview, cbxCustomTextColourOnePreview, cbxCustomTextColourTwoPreview, cbxCustomTextColourThreePreview, cbxCustomTextColourFourPreview, cbxCustomTextColourFivePreview, cbxMenuTextColourPreview, cbxStatusTextColourPreview, tslStatus);
}
else
{
//PaletteEditorEngine.ExportPalette(_globalMethods.GetSelectedPaletteMode(), pbxBaseColour, pbxDarkColour, pbxMiddleColour, pbxLightColour, pbxLightestColour, pbxBorderColourPreview, pbxAlternativeNormalTextColour, pbxNormalTextColourPreview, pbxDisabledTextColourPreview, pbxFocusedTextColourPreview, pbxPressedTextColourPreview, pbxDisabledColourPreview, pbxLinkNormalColourPreview, pbxLinkHoverColourPreview, pbxLinkVisitedColourPreview, pbxCustomColourOnePreview, pbxCustomColourTwoPreview, pbxCustomColourThreePreview, pbxCustomColourFourPreview, pbxCustomColourFivePreview, pbxCustomTextColourOnePreview, pbxCustomTextColourTwoPreview, pbxCustomTextColourThreePreview, pbxCustomTextColourFourPreview, pbxCustomTextColourFivePreview, pbxMenuTextColourPreview, pbxStatusTextColourPreview, tslStatus);
}
}
private void ResetColours(bool useCircularPictureBoxes)
{
if (useCircularPictureBoxes)
{
kgbPreviewPane.Visible = false;
kgbCircularColourPreviewPane.Visible = true;
//ColourUtilities.ResetColourDefinitions(cbxBaseColourPreview, cbxDarkColourPreview, cbxMiddleColourPreview, cbxLightColourPreview, cbxLightestColourPreview, cbxBorderColourPreview, cbxAlternativeNormalTextColourPreview, cbxNormalTextColourPreview, cbxDisabledTextColourPreview, cbxFocusedTextColourPreview, cbxPressedTextColourPreview, cbxDisabledColourPreview, cbxLinkNormalColourPreview, cbxLinkHoverColourPreview, cbxLinkVisitedColourPreview, cbxCustomColourOnePreview, cbxCustomColourTwoPreview, cbxCustomColourThreePreview, cbxCustomColourFourPreview, cbxCustomColourFivePreview, cbxCustomTextColourOnePreview, cbxCustomTextColourTwoPreview, cbxCustomTextColourThreePreview, cbxCustomTextColourFourPreview, cbxCustomTextColourFivePreview, cbxMenuTextColourPreview, cbxStatusTextColourPreview);
}
else
{
kgbPreviewPane.Visible = true;
kgbCircularColourPreviewPane.Visible = false;
//ColourUtilities.ResetColourDefinitions(pbxBaseColour, pbxDarkColour, pbxMiddleColour, pbxLightColour, pbxLightestColour, pbxBorderColourPreview, pbxAlternativeNormalTextColour, pbxNormalTextColourPreview, pbxDisabledTextColourPreview, pbxFocusedTextColourPreview, pbxPressedTextColourPreview, pbxDisabledColourPreview, pbxLinkNormalColourPreview, pbxLinkHoverColourPreview, pbxLinkVisitedColourPreview, pbxCustomColourOnePreview, pbxCustomColourTwoPreview, pbxCustomColourThreePreview, pbxCustomColourFourPreview, pbxCustomColourFivePreview, pbxCustomTextColourOnePreview, pbxCustomTextColourTwoPreview, pbxCustomTextColourThreePreview, pbxCustomTextColourFourPreview, pbxCustomTextColourFivePreview, pbxMenuTextColourPreview, pbxStatusTextColourPreview);
}
}
private void RevertColours(bool useCircularPictureBoxes)
{
if (useCircularPictureBoxes)
{
// ColourUtilities.RevertColours(cbxBaseColourPreview, cbxDarkColourPreview, cbxMiddleColourPreview, cbxLightColourPreview, cbxLightestColourPreview, cbxBorderColourPreview, cbxAlternativeNormalTextColourPreview, cbxNormalTextColourPreview, cbxDisabledTextColourPreview, cbxFocusedTextColourPreview, cbxPressedTextColourPreview, cbxDisabledColourPreview, cbxLinkNormalColourPreview, cbxLinkHoverColourPreview, cbxLinkVisitedColourPreview, cbxCustomColourOnePreview, cbxCustomColourTwoPreview, cbxCustomColourThreePreview, cbxCustomColourFourPreview, cbxCustomColourFivePreview, cbxCustomTextColourOnePreview, cbxCustomTextColourTwoPreview, cbxCustomTextColourThreePreview, cbxCustomTextColourFourPreview, cbxCustomTextColourFivePreview, cbxMenuTextColourPreview, cbxStatusTextColourPreview);
invertColoursToolStripMenuItem.Checked = false;
kchkInvertColours.Checked = false;
}
}
private void InvertColours(bool useCircularPictureBoxes)
{
if (useCircularPictureBoxes)
{
//ColourUtilities.InvertColours(cbxBaseColourPreview, cbxDarkColourPreview, cbxMiddleColourPreview, cbxLightColourPreview, cbxLightestColourPreview, cbxBorderColourPreview, cbxAlternativeNormalTextColourPreview, cbxNormalTextColourPreview, cbxDisabledTextColourPreview, cbxFocusedTextColourPreview, cbxPressedTextColourPreview, cbxDisabledColourPreview, cbxLinkNormalColourPreview, cbxLinkHoverColourPreview, cbxLinkVisitedColourPreview, cbxCustomColourOnePreview, cbxCustomColourTwoPreview, cbxCustomColourThreePreview, cbxCustomColourFourPreview, cbxCustomColourFivePreview, cbxCustomTextColourOnePreview, cbxCustomTextColourTwoPreview, cbxCustomTextColourThreePreview, cbxCustomTextColourFourPreview, cbxCustomTextColourFivePreview, cbxMenuTextColourPreview, cbxStatusTextColourPreview);
invertColoursToolStripMenuItem.Checked = true;
kchkInvertColours.Checked = true;
}
else
{
//ColourUtilities.InvertColours(pbxBaseColour, pbxDarkColour, pbxMiddleColour, pbxLightColour, pbxLightestColour, pbxBorderColourPreview, pbxAlternativeNormalTextColour, pbxNormalTextColourPreview, pbxDisabledTextColourPreview, pbxFocusedTextColourPreview, pbxPressedTextColourPreview, pbxDisabledColourPreview, pbxLinkNormalColourPreview, pbxLinkHoverColourPreview, pbxLinkVisitedColourPreview, pbxCustomColourOnePreview, pbxCustomColourTwoPreview, pbxCustomColourThreePreview, pbxCustomColourFourPreview, pbxCustomColourFivePreview, pbxCustomTextColourOnePreview, pbxCustomTextColourTwoPreview, pbxCustomTextColourThreePreview, pbxCustomTextColourFourPreview, pbxCustomTextColourFivePreview, pbxMenuTextColourPreview, pbxStatusTextColourPreview);
invertColoursToolStripMenuItem.Checked = true;
kchkInvertColours.Checked = true;
}
}
/// <summary>
/// Updates the UI.
/// </summary>
private void UpdateUI()
{
if (kcmbBasePaletteMode.Text != string.Empty)
{
kbtnExportPalette.Enabled = true;
}
else
{
kbtnExportPalette.Enabled = false;
}
if (_globalBooleanSettingsManager.GetLoadColoursOnOpenPalette())
{
GrabPaletteColours(UseCircularPictureBoxes);
}
}
/// <summary>
/// Updates the colour palette.
/// </summary>
/// <param name="useCircularPictureBoxes">if set to <c>true</c> [use circular picture boxes].</param>
private void UpdateColourPalette(bool useCircularPictureBoxes)
{
try
{
if (useCircularPictureBoxes)
{
kgbPreviewPane.Visible = false;
kgbCircularColourPreviewPane.Visible = true;
//ColourUtilities.GrabColourDefinitions(cbxBaseColourPreview, cbxDarkColourPreview, cbxMiddleColourPreview, cbxLightColourPreview, cbxLightestColourPreview, cbxBorderColourPreview, cbxAlternativeNormalTextColourPreview, cbxNormalTextColourPreview, cbxDisabledTextColourPreview, cbxFocusedTextColourPreview, cbxPressedTextColourPreview, cbxDisabledColourPreview, cbxLinkNormalColourPreview, cbxLinkHoverColourPreview, cbxLinkVisitedColourPreview, cbxCustomColourOnePreview, cbxCustomColourTwoPreview, cbxCustomColourThreePreview, cbxCustomColourFourPreview, cbxCustomColourFivePreview, cbxCustomTextColourOnePreview, cbxCustomTextColourTwoPreview, cbxCustomTextColourThreePreview, cbxCustomTextColourFourPreview, cbxCustomTextColourFivePreview, cbxMenuTextColourPreview, cbxStatusTextColourPreview);
}
else
{
kgbPreviewPane.Visible = true;
kgbCircularColourPreviewPane.Visible = false;
//ColourUtilities.GrabColourDefinitions(pbxBaseColour, pbxDarkColour, pbxMiddleColour, pbxLightColour, pbxLightestColour, pbxBorderColourPreview, pbxAlternativeNormalTextColour, pbxNormalTextColourPreview, pbxDisabledTextColourPreview, pbxFocusedTextColourPreview, pbxPressedTextColourPreview, pbxDisabledColourPreview, pbxLinkNormalColourPreview, pbxLinkHoverColourPreview, pbxLinkVisitedColourPreview, pbxCustomColourOnePreview, pbxCustomColourTwoPreview, pbxCustomColourThreePreview, pbxCustomColourFourPreview, pbxCustomColourFivePreview, pbxCustomTextColourOnePreview, pbxCustomTextColourTwoPreview, pbxCustomTextColourThreePreview, pbxCustomTextColourFourPreview, pbxCustomTextColourFivePreview, pbxMenuTextColourPreview, pbxStatusTextColourPreview);
}
}
catch (Exception exc)
{
KryptonMessageBox.Show($"Error: { exc.Message }", "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Shows or hides the circular preview boxes.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
private void ShowCircularPreviewBoxes(bool value)
{
GlobalBooleanSettingsManager globalBooleanSettingsManager = new GlobalBooleanSettingsManager();
#region Old Code
//pbxBaseColour.Visible = value;
//pbxDarkColour.Visible = value;
//pbxMiddleColour.Visible = value;
//pbxLightColour.Visible = value;
//pbxLightestColour.Visible = value;
//pbxBorderColourPreview.Visible = value;
//pbxAlternativeNormalTextColour.Visible = value;
//pbxNormalTextColourPreview.Visible = value;
//pbxDisabledTextColourPreview.Visible = value;
//pbxFocusedTextColourPreview.Visible = value;
//pbxPressedTextColourPreview.Visible = value;
//pbxDisabledColourPreview.Visible = value;
//pbxLinkNormalColourPreview.Visible = value;
//pbxLinkHoverColourPreview.Visible = value;
//pbxLinkVisitedColourPreview.Visible = value;
//pbxCustomColourOnePreview.Visible = value;
//pbxCustomColourTwoPreview.Visible = value;
//pbxCustomColourThreePreview.Visible = value;
//pbxCustomColourFourPreview.Visible = value;
//pbxCustomColourFivePreview.Visible = value;
//pbxCustomTextColourOnePreview.Visible = value;
//pbxCustomTextColourTwoPreview.Visible = value;
//pbxCustomTextColourThreePreview.Visible = value;
//pbxCustomTextColourFourPreview.Visible = value;
//pbxCustomTextColourFivePreview.Visible = value;
//pbxMenuTextColourPreview.Visible = value;
//pbxStatusTextColourPreview.Visible = value;
#endregion
if (value)
{
kgbCircularColourPreviewPane.Visible = true;
kgbPreviewPane.Visible = false;
standardToolStripMenuItem.Checked = false;
circularToolStripMenuItem.Checked = true;
}
else
{
kgbCircularColourPreviewPane.Visible = false;
kgbPreviewPane.Visible = true;
standardToolStripMenuItem.Checked = true;
circularToolStripMenuItem.Checked = false;
}
_globalBooleanSettingsManager.SetUseCircularPictureBoxes(value);
UseCircularPictureBoxes = _globalBooleanSettingsManager.GetUseCircularPictureBoxes();
_globalBooleanSettingsManager.SaveBooleanSettings();
}
private void GenerateColourScheme(Color baseColour)
{
ColourMixer colourMixer = new ColourMixer(true, baseColour);
colourMixer.Show();
}
private void GrabPaletteColours(bool useCircularPictureBoxes)
{
if (useCircularPictureBoxes)
{
UpdateColourPalette(useCircularPictureBoxes);
ShowCircularPreviewBoxes(true);
}
}
private void NullifyStatusText()
{
//lblColourOutput.Text = "";
InformationControlManager.ResetColourValueInformation(lblColourOutput);
}
private void DisplayColourInformation(Control control, string colourDescription)
{
InformationControlManager.DisplayColourInformation(control, false, colourDescription, lblColourOutput);
}
private void ExitApplication(bool useFileName = false)
{
try
{
if (Dirty)
{
if (useFileName)
{
string fileName = Path.GetFileName(_palette.GetCustomisedKryptonPaletteFilePath());
DialogResult result = KryptonMessageBox.Show($"The current palette: { fileName } has not yet been saved. Save now?", "Unsaved Palette", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Save();
}
else
{
Application.Exit();
}
}
else
{
DialogResult result = KryptonMessageBox.Show("The current palette has not yet been saved. Save now?", "Unsaved Palette", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Save();
}
else
{
Application.Exit();
}
}
}
_globalBooleanSettingsManager.SaveBooleanSettings();
}
catch (Exception err)
{
KryptonMessageBox.Show($"Error: { err.Message }", "An Unexpected Error has Occurred0", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Operations
private void New()
{
// If the current palette has been changed
if (Dirty)
{
// Ask user if the current palette should be saved
switch (KryptonMessageBox.Show(this,
"Save changes to the current palette?",
"Palette Changed",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning))
{
case DialogResult.Yes:
// Use existing save method
Save();
break;
case DialogResult.Cancel:
// Cancel out entirely
return;
}
}
// Generate a fresh palette from scratch
CreateNewPalette();
}
private void Open()
{
tslStatus.Text = "Attempting to inport colours from selected palette. Please wait...";
// If the current palette has been changed
if (Dirty)
{
// Ask user if the current palette should be saved
switch (KryptonMessageBox.Show(this,
"Save changes to the current palette?",
"Palette Changed",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning))
{
case DialogResult.Yes:
// Use existing save method
Save();
break;
case DialogResult.Cancel:
// Cancel out entirely
return;
}
}
// Create a fresh palette instance for loading into
KryptonPalette palette = new KryptonPalette();
// Get the name of the file we imported from
Cursor = Cursors.WaitCursor;
Application.DoEvents();
string filename = palette.Import();
Cursor = Cursors.Default;
// If the load succeeded
if (filename.Length > 0)
{
// Need to unhook from any existing palette
if (Palette != null)
Palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint);
// Use the new instance instead
Palette = palette;
// We need to know when a change occurs to the palette settings
Palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint);
// Hook up the property grid to the palette
labelGridNormal.SelectedObject = Palette;
// Use the loaded filename
FileName = filename;
// Reset the state flags
Loaded = true;
Dirty = false;
// Define the initial title bar string
UpdateTitlebar();
}
PaletteImportManager paletteImportManager = new PaletteImportManager();
paletteImportManager.ImportColourScheme(palette);
kchkUpdateColours.Enabled = true;
kcmbBasePaletteMode.Text = _globalStringSettingsManager.GetBasePaletteMode();
tslStatus.Text = _globalStringSettingsManager.GetFeedbackText();
kchkUpdateColours.Checked = true;
invertColoursToolStripMenuItem.Enabled = true;
kchkInvertColours.Enabled = true;
_mostRecentlyUsedFileManager.AddRecentFile(filename);
}
private void Save()
{
// If we already have a file associated with the palette...
if (Loaded)
{
// ...then just save it straight away
Cursor = Cursors.WaitCursor;
Application.DoEvents();
Palette.Export(FileName, true, false);
Cursor = Cursors.Default;
// No longer dirty
Dirty = false;
// Define the initial title bar string
UpdateTitlebar();
}
else
{
// No association and so perform a save as instead
SaveAs();
}
}
private void SaveAs()
{
// Get back the filename selected by the user
Cursor = Cursors.WaitCursor;
Application.DoEvents();
string filename = Palette.Export();
Cursor = Cursors.Default;
// If the save succeeded
if (filename.Length > 0)
{
// Remember associated file details
FileName = filename;
Loaded = true;
// No longer dirty
Dirty = false;
// Define the initial title bar string
UpdateTitlebar();
}
}
private void Exit()
{
// If the current palette has been changed
if (Dirty)
{
// Ask user if the current palette should be saved
switch (KryptonMessageBox.Show(this,
"Save changes to the current palette?",
"Palette Changed",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning))
{
case DialogResult.Yes:
// Use existing save method
Save();
break;
case DialogResult.Cancel:
// Cancel out entirely
return;
}
}
Close();
}
#endregion
#region Palettes
private void CreateNewPalette()
{
// Need to unhook from any existing palette
if (Palette != null)
Palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint);
// Create a fresh palette instance
Palette = new KryptonPalette();
// We need to know when a change occurs to the palette settings
Palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint);
// Hook up the property grid to the palette
labelGridNormal.SelectedObject = Palette;
// Does not have a filename as yet
FileName = "(New Palette)";
// Reset the state flags
Dirty = false;
Loaded = false;
// Define the initial title bar string
UpdateTitlebar();
}
private void OnPalettePaint(object sender, PaletteLayoutEventArgs e)
{
// Only interested the first time the palette is changed
if (!Dirty)
{
Dirty = true;
UpdateTitlebar();
}
}
#endregion
#region Implementation
private void UpdateTitlebar()
{
// Mark a changed file with a star
Text = "Palette Editor - " + FileName + (Dirty ? "*" : string.Empty);
}
#endregion
#region Mouse Picturebox Events
private void pbxBaseColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxBaseColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxBaseColour_MouseLeave(object sender, EventArgs e)
{
}
private void pbxMiddleColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxMiddleColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxMiddleColour_MouseLeave(object sender, EventArgs e)
{
}
private void pbxLightColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxLightColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxLightColour_MouseLeave(object sender, EventArgs e)
{
}
private void pbxLightestColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxLightestColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxLightestColour_MouseLeave(object sender, EventArgs e)
{
}
private void pbxBorderColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxBorderColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxBorderColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxAlternativeNormalTextColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxAlternativeNormalTextColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxAlternativeNormalTextColour_MouseLeave(object sender, EventArgs e)
{
}
private void pbxNormalTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxNormalTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxNormalTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxDisabledTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxDisabledTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxDisabledTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxFocusedTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxFocusedTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxFocusedTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxPressedTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxPressedTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxPressedTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxDisabledColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxDisabledColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxDisabledColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxLinkNormalColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxLinkNormalColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxLinkNormalColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxLinkHoverColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxLinkHoverColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxLinkHoverColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxLinkVisitedColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxLinkVisitedColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxLinkVisitedColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomColourOnePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomColourOnePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomColourOnePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomColourTwoPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomColourTwoPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomColourTwoPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomColourThreePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomColourThreePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomColourThreePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomColourFourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomColourFourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomColourFourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomColourFivePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomColourFivePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomColourFivePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomTextColourOnePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomTextColourOnePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomTextColourOnePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomTextColourTwoPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomTextColourTwoPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomTextColourTwoPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomTextColourThreePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomTextColourThreePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomTextColourThreePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFivePreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFivePreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxCustomTextColourFivePreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxMenuTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxMenuTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxMenuTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxStatusTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void pbxStatusTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void pbxStatusTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void pbxDarkColour_MouseEnter(object sender, EventArgs e)
{
}
private void pbxDarkColour_MouseHover(object sender, EventArgs e)
{
}
private void pbxDarkColour_MouseLeave(object sender, EventArgs e)
{
}
#endregion
#region Mouse Circular Picturebox Events
private void cbxBaseColourPreview_MouseEnter(object sender, EventArgs e)
{
DisplayColourInformation(cbxBaseColourPreview, "Base Colour");
}
private void cbxBaseColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxBaseColourPreview_MouseLeave(object sender, EventArgs e)
{
NullifyStatusText();
}
private void cbxMiddleColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxMiddleColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxMiddleColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxLightColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxLightColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxLightColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxLightestColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxLightestColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxLightestColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxBorderColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxBorderColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxBorderColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxAlternativeNormalTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxAlternativeNormalTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxAlternativeNormalTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxNormalTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxNormalTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxNormalTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxDisabledTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxDisabledTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxDisabledTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxFocusedTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxFocusedTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxFocusedTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxPressedTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxPressedTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxPressedTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxDisabledColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxDisabledColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxDisabledColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxLinkNormalColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxLinkNormalColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxLinkNormalColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxLinkHoverColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxLinkHoverColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxLinkHoverColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxLinkVisitedColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxLinkVisitedColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxLinkVisitedColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomColourOnePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomColourOnePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomColourOnePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomColourTwoPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomColourTwoPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomColourTwoPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomColourThreePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomColourThreePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomColourThreePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomColourFourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomColourFourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomColourFourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomColourFivePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomColourFivePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomColourFivePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomTextColourOnePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomTextColourOnePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomTextColourOnePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomTextColourTwoPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomTextColourTwoPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomTextColourTwoPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomTextColourThreePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomTextColourThreePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomTextColourThreePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFivePreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFivePreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxCustomTextColourFivePreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxMenuTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxMenuTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxMenuTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxStatusTextColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxStatusTextColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxStatusTextColourPreview_MouseLeave(object sender, EventArgs e)
{
}
private void cbxDarkColourPreview_MouseEnter(object sender, EventArgs e)
{
}
private void cbxDarkColourPreview_MouseHover(object sender, EventArgs e)
{
}
private void cbxDarkColourPreview_MouseLeave(object sender, EventArgs e)
{
}
#endregion
#region Event Handlers
private void MainWindow_Load(object sender, EventArgs e)
{
InitialiseWindow();
}
private void kcmbBasePaletteMode_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Tick(object sender, EventArgs e)
{
UpdateColourPalette(UseCircularPictureBoxes);
ShowCircularPreviewBoxes(UseCircularPictureBoxes);
}
private void kbtnImportColourScheme_Click(object sender, EventArgs e)
{
Open();
}
private void kbtnGetColourInformation_Click(object sender, EventArgs e)
{
ColourInformation colourInformation = new ColourInformation();
colourInformation.Show();
}
private void newPaletteDefinitionToolStripMenuItem_Click(object sender, EventArgs e)
{
New();
}
private void MyOwnRecentPaletteFileGotClicked_Handler(object sender, EventArgs e)
{
string fileName = (sender as ToolStripItem).Text;
if (!File.Exists(fileName))
{
if (KryptonMessageBox.Show($"{ fileName } doesn't exist. Remove from recent workspaces?", "File not found", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
_mostRecentlyUsedFileManager.RemoveRecentFile(fileName);
}
else
{
return;
}
}
_palette.Import(fileName);
//OpenFile(fileName);
}
private void MyOwnRecentPaletteFilesGotCleared_Handler(object sender, EventArgs e)
{
}
private void kbtnGetColours_Click(object sender, EventArgs e)
{
GrabPaletteColours(UseCircularPictureBoxes);
}
private void tmrUpdateUI_Tick(object sender, EventArgs e)
{
UpdateUI();
}
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
ExitApplication(true);
}
private void savePaletteDefinitionToolStripMenuItem_Click(object sender, EventArgs e)
{
Save();
}
private void kbtnExportPalette_Click(object sender, EventArgs e)
{
ExportPaletteColours(UseCircularPictureBoxes);
}
private void exportPaletteColoursToolStripMenuItem_Click(object sender, EventArgs e)
{
ExportPaletteColours(UseCircularPictureBoxes);
}
private void kbtnGenerate_Click(object sender, EventArgs e)
{
if (UseCircularPictureBoxes)
{
GenerateColourScheme(cbxBaseColourPreview.BackColor);
}
else
{
GenerateColourScheme(pbxBaseColour.BackColor);
}
}
private void generateColoursToolStripMenuItem_Click(object sender, EventArgs e)
{
if (UseCircularPictureBoxes)
{
GenerateColourScheme(cbxBaseColourPreview.BackColor);
}
else
{
GenerateColourScheme(pbxBaseColour.BackColor);
}
}
private void savePaletteDefinitionAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveAs();
}
private void resetColoursToolStripMenuItem_Click(object sender, EventArgs e)
{
ResetColours(UseCircularPictureBoxes);
}
private void loadColoursOnOpenToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
_globalBooleanSettingsManager.SetLoadColoursOnOpenPalette(loadColoursOnOpenToolStripMenuItem.Checked);
_globalBooleanSettingsManager.SaveBooleanSettings();
}
#endregion
}
} | 30.718284 | 862 | 0.630003 | [
"BSD-3-Clause"
] | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460 | Source/Krypton Toolkit Suite Extended/Applications/Palette Editor/UX/New/MainWindow.cs | 49,397 | C# |
// Copyright (c) Drew Noakes and contributors. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace MetadataExtractor.Formats.Gif
{
/// <author>Drew Noakes https://drewnoakes.com</author>
/// <author>Kevin Mott https://github.com/kwhopper</author>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public class GifCommentDirectory : Directory
{
public const int TagComment = 1;
private static readonly Dictionary<int, string> _tagNameMap = new Dictionary<int, string>
{
{ TagComment, "Comment" }
};
public GifCommentDirectory(StringValue comment)
{
SetDescriptor(new GifCommentDescriptor(this));
Set(TagComment, comment);
}
public override string Name => "GIF Comment";
protected override bool TryGetTagName(int tagType, out string tagName)
{
return _tagNameMap.TryGetValue(tagType, out tagName);
}
}
}
| 33.382353 | 172 | 0.672247 | [
"Apache-2.0"
] | GwG422/metadata-extractor-dotnet | MetadataExtractor/Formats/Gif/GifCommentDirectory.cs | 1,135 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace SocialWeather;
public interface IStreamFormatter<T>
{
Task<T> ReadAsync(Stream stream);
Task WriteAsync(T value, Stream stream);
}
| 26.181818 | 71 | 0.753472 | [
"MIT"
] | 3ejki/aspnetcore | src/SignalR/samples/SocialWeather/IStreamFormatter.cs | 288 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// GroupFundsImcomeDetails Data Structure.
/// </summary>
public class GroupFundsImcomeDetails : AlipayObject
{
/// <summary>
/// 待付款金额,只支持两位小数点的正数,单位元
/// </summary>
[JsonPropertyName("amount")]
public string Amount { get; set; }
/// <summary>
/// 资金分配明细,Map类型,key为收款对象支付宝账户ID,value为分配的金额,两位小数点的正数,单位元
/// </summary>
[JsonPropertyName("fund_distributions")]
public string FundDistributions { get; set; }
/// <summary>
/// 付款方支付宝账户ID
/// </summary>
[JsonPropertyName("payer_id")]
public string PayerId { get; set; }
}
}
| 26.310345 | 65 | 0.584535 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/GroupFundsImcomeDetails.cs | 897 | 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 Hub.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.233333 | 151 | 0.578997 | [
"MIT"
] | RamilGauss/TornadoHub | Sources/Hub/Properties/Settings.Designer.cs | 1,059 | C# |
/*
* Upcloud api
*
* The UpCloud API consists of operations used to control resources on UpCloud. The API is a web service interface. HTTPS is used to connect to the API. The API follows the principles of a RESTful web service wherever possible. The base URL for all API operations is https://api.upcloud.com/. All API operations require authentication.
*
* OpenAPI spec version: 1.2.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = Upcloud.Client.SwaggerDateConverter;
namespace Upcloud.Model
{
/// <summary>
/// Storage
/// </summary>
[DataContract]
public partial class Storage : IEquatable<Storage>
{
/// <summary>
/// Gets or Sets Access
/// </summary>
[DataMember(Name="access", EmitDefaultValue=false)]
public StorageAccessType? Access { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public StorageState? State { get; set; }
/// <summary>
/// Gets or Sets Tier
/// </summary>
[DataMember(Name="tier", EmitDefaultValue=false)]
public StorageTier? Tier { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=false)]
public StorageType? Type { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Storage" /> class.
/// </summary>
/// <param name="access">access.</param>
/// <param name="backupRule">backupRule.</param>
/// <param name="backups">backups.</param>
/// <param name="license">license.</param>
/// <param name="servers">servers.</param>
/// <param name="size">size.</param>
/// <param name="state">state.</param>
/// <param name="tier">tier.</param>
/// <param name="title">title.</param>
/// <param name="type">type.</param>
/// <param name="uuid">uuid.</param>
/// <param name="zone">zone.</param>
/// <param name="origin">origin.</param>
/// <param name="progress">progress.</param>
/// <param name="created">created.</param>
public Storage(StorageAccessType? access = default(StorageAccessType?), BackupRule backupRule = default(BackupRule), StorageBackups backups = default(StorageBackups), decimal? license = default(decimal?), StorageServers servers = default(StorageServers), decimal? size = default(decimal?), StorageState? state = default(StorageState?), StorageTier? tier = default(StorageTier?), string title = default(string), StorageType? type = default(StorageType?), Guid? uuid = default(Guid?), string zone = default(string), Guid? origin = default(Guid?), decimal? progress = default(decimal?), string created = default(string))
{
this.Access = access;
this.BackupRule = backupRule;
this.Backups = backups;
this.License = license;
this.Servers = servers;
this.Size = size;
this.State = state;
this.Tier = tier;
this.Title = title;
this.Type = type;
this.Uuid = uuid;
this.Zone = zone;
this.Origin = origin;
this.Progress = progress;
this.Created = created;
}
/// <summary>
/// Gets or Sets BackupRule
/// </summary>
[DataMember(Name="backup_rule", EmitDefaultValue=false)]
public BackupRule BackupRule { get; set; }
/// <summary>
/// Gets or Sets Backups
/// </summary>
[DataMember(Name="backups", EmitDefaultValue=false)]
public StorageBackups Backups { get; set; }
/// <summary>
/// Gets or Sets License
/// </summary>
[DataMember(Name="license", EmitDefaultValue=false)]
public decimal? License { get; set; }
/// <summary>
/// Gets or Sets Servers
/// </summary>
[DataMember(Name="servers", EmitDefaultValue=false)]
public StorageServers Servers { get; set; }
/// <summary>
/// Gets or Sets Size
/// </summary>
[DataMember(Name="size", EmitDefaultValue=false)]
public decimal? Size { get; set; }
/// <summary>
/// Gets or Sets Title
/// </summary>
[DataMember(Name="title", EmitDefaultValue=false)]
public string Title { get; set; }
/// <summary>
/// Gets or Sets Uuid
/// </summary>
[DataMember(Name="uuid", EmitDefaultValue=false)]
public Guid? Uuid { get; set; }
/// <summary>
/// Gets or Sets Zone
/// </summary>
[DataMember(Name="zone", EmitDefaultValue=false)]
public string Zone { get; set; }
/// <summary>
/// Gets or Sets Origin
/// </summary>
[DataMember(Name="origin", EmitDefaultValue=false)]
public Guid? Origin { get; set; }
/// <summary>
/// Gets or Sets Progress
/// </summary>
[DataMember(Name="progress", EmitDefaultValue=false)]
public decimal? Progress { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=false)]
public string Created { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Storage {\n");
sb.Append(" Access: ").Append(Access).Append("\n");
sb.Append(" BackupRule: ").Append(BackupRule).Append("\n");
sb.Append(" Backups: ").Append(Backups).Append("\n");
sb.Append(" License: ").Append(License).Append("\n");
sb.Append(" Servers: ").Append(Servers).Append("\n");
sb.Append(" Size: ").Append(Size).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Tier: ").Append(Tier).Append("\n");
sb.Append(" Title: ").Append(Title).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Uuid: ").Append(Uuid).Append("\n");
sb.Append(" Zone: ").Append(Zone).Append("\n");
sb.Append(" Origin: ").Append(Origin).Append("\n");
sb.Append(" Progress: ").Append(Progress).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Storage);
}
/// <summary>
/// Returns true if Storage instances are equal
/// </summary>
/// <param name="input">Instance of Storage to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Storage input)
{
if (input == null)
return false;
return
(
this.Access == input.Access ||
(this.Access != null &&
this.Access.Equals(input.Access))
) &&
(
this.BackupRule == input.BackupRule ||
(this.BackupRule != null &&
this.BackupRule.Equals(input.BackupRule))
) &&
(
this.Backups == input.Backups ||
(this.Backups != null &&
this.Backups.Equals(input.Backups))
) &&
(
this.License == input.License ||
(this.License != null &&
this.License.Equals(input.License))
) &&
(
this.Servers == input.Servers ||
(this.Servers != null &&
this.Servers.Equals(input.Servers))
) &&
(
this.Size == input.Size ||
(this.Size != null &&
this.Size.Equals(input.Size))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Tier == input.Tier ||
(this.Tier != null &&
this.Tier.Equals(input.Tier))
) &&
(
this.Title == input.Title ||
(this.Title != null &&
this.Title.Equals(input.Title))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.Uuid == input.Uuid ||
(this.Uuid != null &&
this.Uuid.Equals(input.Uuid))
) &&
(
this.Zone == input.Zone ||
(this.Zone != null &&
this.Zone.Equals(input.Zone))
) &&
(
this.Origin == input.Origin ||
(this.Origin != null &&
this.Origin.Equals(input.Origin))
) &&
(
this.Progress == input.Progress ||
(this.Progress != null &&
this.Progress.Equals(input.Progress))
) &&
(
this.Created == input.Created ||
(this.Created != null &&
this.Created.Equals(input.Created))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Access != null)
hashCode = hashCode * 59 + this.Access.GetHashCode();
if (this.BackupRule != null)
hashCode = hashCode * 59 + this.BackupRule.GetHashCode();
if (this.Backups != null)
hashCode = hashCode * 59 + this.Backups.GetHashCode();
if (this.License != null)
hashCode = hashCode * 59 + this.License.GetHashCode();
if (this.Servers != null)
hashCode = hashCode * 59 + this.Servers.GetHashCode();
if (this.Size != null)
hashCode = hashCode * 59 + this.Size.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.Tier != null)
hashCode = hashCode * 59 + this.Tier.GetHashCode();
if (this.Title != null)
hashCode = hashCode * 59 + this.Title.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.Uuid != null)
hashCode = hashCode * 59 + this.Uuid.GetHashCode();
if (this.Zone != null)
hashCode = hashCode * 59 + this.Zone.GetHashCode();
if (this.Origin != null)
hashCode = hashCode * 59 + this.Origin.GetHashCode();
if (this.Progress != null)
hashCode = hashCode * 59 + this.Progress.GetHashCode();
if (this.Created != null)
hashCode = hashCode * 59 + this.Created.GetHashCode();
return hashCode;
}
}
}
}
| 38.442136 | 625 | 0.496565 | [
"MIT"
] | kaleho/upcloud-dotnetcore-api | src/Upcloud/Model/Storage.cs | 12,955 | C# |
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.TagHelpers.LayUI.Common
{
public class LayuiUIService : IUIService
{
public string MakeDialogButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool showDialog = true, bool resizable = true)
{
if (buttonID == null)
{
buttonID = Guid.NewGuid().ToString();
}
var innerClick = "";
string windowid = Guid.NewGuid().ToString();
if (showDialog == true)
{
innerClick = $"ff.OpenDialog('{url}', '{windowid}', '{title ?? ""}',{width?.ToString() ?? "null"}, {height?.ToString() ?? "null"});";
}
else
{
innerClick = $"$.ajax({{cache: false,type: 'GET',url: '{url}',async: true,success: function(data, textStatus, request) {{eval(data);}} }});";
}
var click = $"<script>$('#{buttonID}').on('click',function(){{{innerClick};return false;}});</script>";
string rv = "";
if(buttonType == ButtonTypesEnum.Link)
{
rv = $"<a id='{buttonID}' style='color:blue;cursor:pointer'>{buttonText}</a>";
}
if(buttonType == ButtonTypesEnum.Button)
{
rv = $"<a id='{buttonID}' class='layui-btn layui-btn-primary layui-btn-xs'>{buttonText}</a>";
}
rv += click;
return rv;
}
public string MakeDownloadButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, string _DONOT_USE_CS = "default")
{
string rv = "";
if (buttonType == ButtonTypesEnum.Link)
{
rv = $"<a style='color:blue;cursor:pointer' href='/_Framework/GetFile/{fileID}?_DONOT_USE_CS={_DONOT_USE_CS}'>{buttonText}</a>";
}
if (buttonType == ButtonTypesEnum.Button)
{
rv = $"<a class='layui-btn layui-btn-primary layui-btn-xs' href='/_Framework/GetFile/{fileID}?_DONOT_USE_CS={_DONOT_USE_CS}'>{buttonText}</a>";
}
return rv;
}
public string MakeCheckBox(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false)
{
var disable = isReadOnly ? " disabled=\"\" class=\"layui-disabled\"" : " ";
var selected = ischeck ? " checked" : " ";
return $@"<input lay-skin=""primary"" type=""checkbox"" name=""{name ?? ""}"" id=""{(name == null ? "" : Utils.GetIdByName(name))}"" value=""{value ?? ""}"" title=""{text ?? ""}"" {selected} {disable}/>";
}
public string MakeRadio(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false)
{
var selected = ischeck ? " checked" : " ";
var disable = isReadOnly ? " disabled=\"\" class=\"layui-disabled\"" : " ";
return $@"<input lay-skin=""primary"" type=""radio"" name=""{name ?? ""}"" id=""{(name == null ? "" : Utils.GetIdByName(name))}"" value=""{value ?? ""}"" title=""{text ?? ""}"" {selected} {disable}/>";
}
public string MakeCombo(string name = null, List<ComboSelectListItem> value = null, string selectedValue = null, string emptyText = null, bool isReadOnly = false)
{
var disable = isReadOnly ? " disabled=\"\" class=\"layui-disabled\"" : " ";
string rv = $"<select name=\"{name}\" id=\"{(name == null? "": Utils.GetIdByName(name))}\" class=\"layui-input\" style=\"height:28px\" lay-ignore>";
if(string.IsNullOrEmpty(emptyText) == false)
{
rv += $@"
<option value=''>{emptyText}</option>";
}
if (value != null)
{
foreach (var item in value)
{
if (item.Value == selectedValue)
{
rv += $@"
<option value='{item.Value}' selected>{item.Text}</option>";
}
else
{
rv += $@"
<option value='{item.Value}'>{item.Text}</option>";
}
}
}
rv += $@"
</select>
";
return rv;
}
public string MakeTextBox(string name = null, string value = null, string emptyText = null, bool isReadOnly = false)
{
var disable = isReadOnly ? " disabled=\"\" class=\"layui-disabled\"" : " ";
return $@"<input class=""layui-input"" style=""height:28px"" name=""{name ?? ""}"" id=""{(name == null? "": Utils.GetIdByName(name))}"" value=""{value ?? ""}"" {disable} />";
}
public string MakeRedirectButton(ButtonTypesEnum buttonType, string url, string buttonText)
{
return "";
}
public string MakeViewButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, int? width = null, int? height = null, string title = null, bool resizable = true, string _DONOT_USE_CS = "default")
{
return MakeDialogButton(buttonType, $"/_Framework/ViewFile/{fileID}?_DONOT_USE_CS={_DONOT_USE_CS}", buttonText, width, height, title, null, true, resizable);
}
public string MakeScriptButton(ButtonTypesEnum buttonType, string buttonText, string script = "", string buttonID = null, string url = null)
{
if (buttonID == null)
{
buttonID = Guid.NewGuid().ToString();
}
var innerClick = script;
var click = $"<script>$('#{buttonID}').on('click',function(){{{innerClick};return false;}});</script>";
string rv = "";
if (buttonType == ButtonTypesEnum.Link)
{
rv = $"<a id='{buttonID}' style='color:blue;cursor:pointer'>{buttonText}</a>";
}
if (buttonType == ButtonTypesEnum.Button)
{
rv = $"<a id='{buttonID}' class='layui-btn layui-btn-primary layui-btn-xs'>{buttonText}</a>";
}
rv += click;
return rv;
}
}
}
| 45.928058 | 222 | 0.526003 | [
"MIT"
] | jiangdad/WTM | src/WalkingTec.Mvvm.TagHelpers.LayUI/Common/LayuiUIService.cs | 6,386 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace JikanDotNet
{
/// <summary>
/// User's friends model class.
/// </summary>
public class UserFriends: BaseJikanRequest
{
/// <summary>
/// Collection of user's friends basic information
/// </summary>
[JsonProperty(PropertyName = "friends")]
public ICollection<Friend> Friends { get; set; }
}
} | 22.235294 | 52 | 0.695767 | [
"MIT"
] | EZ1SGT/jikan.net | JikanDotNet/Model/Core/UserFriends.cs | 380 | C# |
namespace School.Authorization.Roles
{
public static class StaticRoleNames
{
public static class Host
{
public const string Admin = "Admin";
}
public static class Tenants
{
public const string Admin = "Admin";
public const string User = "User";
}
}
} | 20.529412 | 48 | 0.541547 | [
"MIT"
] | ourcredit/School | aspnet-core/src/School.Core/Authorization/Roles/StaticRoleNames.cs | 351 | C# |
using NUnit.Framework;
using TicTacToe;
using System.Linq;
namespace TikTacToeTests
{
[TestFixture]
public class BoardTests
{
[Test]
public void IsFullShouldReturnTrueOrFullBoard()
{
Board board = new Board(3,3);
Assert.IsFalse(board.IsFull());
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Assert.IsFalse(board.IsFull());
board.PlaceSymbol(new TicTacToe.Index(i, j), Symbol.X);
}
}
Assert.IsTrue(board.IsFull());
}
[Test]
public void GetRowSymbolShouldWorkCorrectly()
{
Board board = new Board(4, 4);
for (int i = 0; i < board.Columns; i++)
{
board.PlaceSymbol(new TicTacToe.Index(2, i), Symbol.O);
}
Assert.AreEqual(Symbol.O, board.GetRowSymbol(2));
}
[Test]
public void GetColSymbolShouldWorkCorrectly()
{
Board board = new Board(5, 5);
for (int i = 0; i < board.Rows; i++)
{
board.PlaceSymbol(new TicTacToe.Index(i, 1), Symbol.X);
}
Assert.AreEqual(Symbol.X, board.GetColSymbol(1));
}
[Test]
public void GetEmptyPositionsShouldReturnAllPositionsForEmptyBoard()
{
var board = new Board(3, 3);
var positions = board.GetEmptyPositions();
Assert.AreEqual(3 * 3, positions.Count());
}
[Test]
public void GetEmptyPositionsShouldReturnCorrenctNumberOfPositions()
{
var board = new Board(4, 4);
board.PlaceSymbol(new TicTacToe.Index(1, 1), Symbol.X);
board.PlaceSymbol(new TicTacToe.Index(2, 2), Symbol.O);
var positions = board.GetEmptyPositions();
Assert.AreEqual(4 * 4 - 2, positions.Count());
}
}
}
| 25.2 | 76 | 0.50744 | [
"MIT"
] | Karnalow/SoftUni | C# OOP/12. Workshop/TicTacToe/TikTacToeTests/BoardTests.cs | 2,018 | C# |
//------------------------------------------------------------------------------------------------
// This file has been programatically generated; DON´T EDIT!
//------------------------------------------------------------------------------------------------
#pragma warning disable SA1001
#pragma warning disable SA1027
#pragma warning disable SA1028
#pragma warning disable SA1121
#pragma warning disable SA1205
#pragma warning disable SA1309
#pragma warning disable SA1402
#pragma warning disable SA1505
#pragma warning disable SA1507
#pragma warning disable SA1508
#pragma warning disable SA1652
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Text.Json;
namespace SharpGLTF.Schema2
{
using Collections;
partial class KHR_lights_punctualnodeextension : ExtraProperties
{
private Int32 _light;
protected override void SerializeProperties(Utf8JsonWriter writer)
{
base.SerializeProperties(writer);
SerializeProperty(writer, "light", _light);
}
protected override void DeserializeProperty(string jsonPropertyName, ref Utf8JsonReader reader)
{
switch (jsonPropertyName)
{
case "light": _light = DeserializePropertyValue<Int32>(ref reader); break;
default: base.DeserializeProperty(jsonPropertyName,ref reader); break;
}
}
}
}
| 26.192308 | 98 | 0.665932 | [
"MIT"
] | pmxEr5lZwZ/StackBuilder | Sources/SharpGLTF.Core/Schema2/Generated/ext.NodeLightsPunctual.g.cs | 1,363 | C# |
using System;
using System.Reflection;
using HotChocolate.Types.Descriptors.Definitions;
using static HotChocolate.Properties.TypeResources;
#nullable enable
namespace HotChocolate.Types.Relay.Descriptors
{
public class NodeDescriptor
: NodeDescriptorBase
, INodeDescriptor
{
private readonly IObjectTypeDescriptor _typeDescriptor;
public NodeDescriptor(IObjectTypeDescriptor descriptor, Type? nodeType = null)
: base(descriptor.Extend().Context)
{
_typeDescriptor = descriptor;
_typeDescriptor
.Implements<NodeType>()
.Extend()
.OnBeforeCreate(OnCompleteDefinition);
Definition.NodeType = nodeType;
}
private void OnCompleteDefinition(ObjectTypeDefinition definition)
{
if (Definition.Resolver is not null)
{
definition.ContextData[WellKnownContextData.NodeResolver] =
Definition.Resolver;
}
}
protected override IObjectFieldDescriptor ConfigureNodeField()
{
return Definition.IdMember is null
? _typeDescriptor
.Field(NodeType.Names.Id)
.Type<NonNullType<IdType>>()
.Use<IdMiddleware>()
: _typeDescriptor
.Field(Definition.IdMember)
.Name(NodeType.Names.Id)
.Type<NonNullType<IdType>>()
.Use<IdMiddleware>();
}
public INodeDescriptor IdField(MemberInfo propertyOrMethod)
{
if (propertyOrMethod is null)
{
throw new ArgumentNullException(nameof(propertyOrMethod));
}
if (propertyOrMethod is PropertyInfo or MethodInfo)
{
Definition.IdMember = propertyOrMethod;
return this;
}
throw new ArgumentException(NodeDescriptor_IdField_MustBePropertyOrMethod);
}
public IObjectFieldDescriptor NodeResolver(
NodeResolverDelegate<object, object> nodeResolver) =>
ResolveNode(nodeResolver);
public IObjectFieldDescriptor NodeResolver<TId>(
NodeResolverDelegate<object, TId> nodeResolver) =>
ResolveNode(nodeResolver);
public IObjectFieldDescriptor ResolveNodeWith<TResolver>() =>
ResolveNodeWith(Context.TypeInspector.GetNodeResolverMethod(
Definition.NodeType ?? typeof(TResolver),
typeof(TResolver)));
public IObjectFieldDescriptor ResolveNodeWith(Type type) =>
ResolveNodeWith(Context.TypeInspector.GetNodeResolverMethod(
Definition.NodeType ?? type,
type));
}
}
| 32.793103 | 87 | 0.598318 | [
"MIT"
] | vbornand/hotchocolate | src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor.cs | 2,853 | C# |
using AutoMapper;
using Caco.API.Models;
using Caco.API.Resources;
namespace Caco.API.Mapping
{
public class ModelToResourceProfile : Profile
{
public ModelToResourceProfile()
{
CreateMap<Board, BoardResource>();
CreateMap<Column, ColumnResource>();
CreateMap<Card, CardResource>();
}
}
} | 22.5625 | 49 | 0.626039 | [
"Unlicense"
] | alutrin/caco | api/Mapping/ModelToResourceProfile.cs | 361 | C# |
using System;
using System.Linq;
using System.Text;
namespace MultidimArr
{
public class Exercises
{
public static void Main()
{
}
/// <summary>
/// Exercise 4
/// </summary>
public static void PascalTriangle()
{
var size = int.Parse(Console.ReadLine());
var matrix = new long[size][];
for (var row = 0; row < size; row++)
{
matrix[row] = new long[row + 1];
matrix[row][0] = 1;
matrix[row][row] = 1;
if (row < 2) continue;
for (var col = 1; col < row; col++)
{
matrix[row][col] = matrix[row - 1][col - 1] + matrix[row - 1][col];
}
}
foreach (var row in matrix)
{
Console.WriteLine(string.Join(" ", row));
}
}
/// <summary>
/// Exercise 3
/// </summary>
public static void GroupNumbers()
{
var data = Console.ReadLine()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
var resultSet = new StringBuilder[3];
resultSet[0] = new StringBuilder();
resultSet[1] = new StringBuilder();
resultSet[2] = new StringBuilder();
foreach (var number in data)
{
switch (Math.Abs(number % 3))
{
case 0:
resultSet[0].Append($"{number} ");
break;
case 1:
resultSet[1].Append($"{number} ");
break;
case 2:
resultSet[2].Append($"{number} ");
break;
}
}
Console.WriteLine(resultSet[0]);
Console.WriteLine(resultSet[1]);
Console.WriteLine(resultSet[2]);
}
/// <summary>
/// Exercise 2
/// </summary>
public static void SquareMaximumSum()
{
var dimensions = Console.ReadLine()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
var matrix = new int[dimensions[0], dimensions[1]];
for (var row = 0; row < dimensions[0]; row++)
{
var data = Console.ReadLine()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
var dimensionLength = matrix.GetLength(1);
for (var column = 0; column < dimensionLength; column++)
{
matrix[row, column] = data.Skip(column).Take(1).Min();
}
}
var maxSum = long.MinValue;
int w = 0, x = 0, y = 0, z = 0;
for (var row = 0; row < matrix.GetLength(0) - 1; row++)
{
for (var column = 0; column < matrix.GetLength(1) - 1; column++)
{
var currentSum = matrix[row, column] + matrix[row, column + 1] +
matrix[row + 1, column] + matrix[row + 1, column + 1];
if (maxSum >= currentSum)
continue;
maxSum = currentSum;
w = matrix[row, column];
x = matrix[row, column + 1];
y = matrix[row + 1, column];
z = matrix[row + 1, column + 1];
}
}
Console.WriteLine($"{w} {x}");
Console.WriteLine($"{y} {z}");
Console.WriteLine(maxSum);
}
/// <summary>
/// Exercise 1
/// </summary>
public static void SumMatrixElements()
{
var dimensions = Console.ReadLine()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
var sum = 0;
for (var rows = 0; rows < dimensions[0]; rows++)
{
var elements = Console.ReadLine()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
sum += elements.Sum();
}
Console.WriteLine(dimensions[0]);
Console.WriteLine(dimensions[1]);
Console.WriteLine(sum);
}
}
}
| 30.320513 | 91 | 0.41797 | [
"MIT"
] | jackofdiamond5/Software-University | C# Fundamentals/C# Advanced/Multidimensional Arrays/Multidimensional Arrays_Lab/MultidimArr/MultidimArr/Exercises.cs | 4,732 | C# |
using UnityEngine;
namespace Memoria.Scenes
{
internal class GOWidget : GOBase
{
public readonly UIWidget Widget;
public GOWidget(GameObject obj)
: base(obj)
{
Widget = obj.GetExactComponent<UIWidget>();
}
}
} | 18.6 | 55 | 0.577061 | [
"MIT"
] | Albeoris/Memoria | Assembly-CSharp/Memoria/Scenes/GOWidget.cs | 279 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace StringTemplateParser
{
public class TemplateRegexMatcher
{
readonly string _pattern; readonly char[] _placeHolders;
public TemplateRegexMatcher(string pattern, char[] placeHolders)
{
_pattern = pattern;
_placeHolders = placeHolders;
}
public IEnumerable<string> IterateTemplateFields(string template)
{
var matches = new Regex(_pattern).Matches(template);
foreach (Match item in matches)
{
yield return item.Value;
}
}
public string ApplyTransformars(string template, params Func<string, string>[] transformars)
{
var tansformedTemplate = template;
foreach (var item in transformars)
{
tansformedTemplate = item(tansformedTemplate);
}
return tansformedTemplate;
}
public string FlattenNormalizeScope(string template, string pattern)
{
var normalizedTemplate = NormalizeScope(template, pattern);
var group = Regex.Match(normalizedTemplate, pattern).Groups.Cast<Group>().Where(g => Regex.Match(g.Value, pattern).Success).LastOrDefault();
if (group == null || !group.Success)
return normalizedTemplate;
return FlattenNormalizeScope(normalizedTemplate, pattern);
}
public string NormalizeScope(string template, string pattern)
{
var outerMatch = Regex.Match(template, pattern);
var group = outerMatch.Groups.Cast<Group>().Where(g => Regex.Match(g.Value, pattern).Success).LastOrDefault();
if (group == null || !group.Success)
return template;
if (!string.IsNullOrEmpty(group.Value))
{
var outer = new Regex(pattern).Replace(group.Value, match =>
{
//get scope
var scope = new Regex(pattern).Match(match.Value)?.Value;
var withScopeValue = Regex.Match(scope, RegexHelper.WITH_CLAUSE_TEMPLATE)?.Value;
var scopeValue = Regex.Matches(withScopeValue, RegexHelper.WITH_SCOPE_TEMPLATE).Cast<Match>().LastOrDefault()?.Value;
//add scope to fields
var inner = new Regex(RegexHelper.VALID_TEMPLATE).Replace(scope, innerMatch =>
{
var value = innerMatch.Value.Trim(_placeHolders);
return $"[{scopeValue}.{value}]";
});
var innerValue = Regex.Match(inner, RegexHelper.VALID_WITH_CLAUSE_TEMPLATE).Groups.Cast<Group>().LastOrDefault()?.Value;
return innerValue;
});
var ajustetedMatch = outerMatch.Value.Replace(group.Value, outer);
return ajustetedMatch;
}
return template;
}
public string MatchReplace(string template, IDictionary<string, object> dictorany)
{
return new Regex(_pattern).Replace(template, match =>
{
var value = match.Value.Trim(_placeHolders);
return dictorany.ContainsKey(value) ? match.Result(dictorany[value].ToString()) : string.Empty;
});
}
}
}
| 43.938272 | 153 | 0.565608 | [
"Apache-2.0"
] | mohamed-abdo/string-template-parser | TemplateParser/TemplateRegexMatcher.cs | 3,561 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SugCon.Models.Analytics
{
[Serializable]
public class InteractionStatistics
{
public long Interactions { get; set; }
}
}
| 18.2 | 46 | 0.721612 | [
"MIT"
] | avwolferen/SitecoreBot | src/SugCon.Models/Analytics/InteractionStatistics.cs | 275 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WpfColorPicker.Properties {
using System;
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをビルドし直します。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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>
/// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfColorPicker.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 40.828125 | 180 | 0.613854 | [
"Apache-2.0"
] | MT224244/WpfColorPicker | Properties/Resources.Designer.cs | 3,245 | C# |
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* 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 System.Diagnostics;
using System.Linq;
using Thinktecture.IdentityServer.Core.Models;
namespace Thinktecture.IdentityServer.Core.Extensions
{
public static class ScopeExtensions
{
[DebuggerStepThrough]
public static string ToSpaceSeparatedString(this IEnumerable<Scope> scopes)
{
var scopeNames = from s in scopes
select s.Name;
return string.Join(" ", scopeNames.ToArray());
}
[DebuggerStepThrough]
public static bool IncludesAllClaimsForUserRule(this IEnumerable<Scope> scopes, ScopeType type)
{
foreach (var scope in scopes)
{
if (scope.Type == type)
{
if (scope.IncludeAllClaimsForUser)
{
return true;
}
}
}
return false;
}
}
} | 30.673077 | 103 | 0.618182 | [
"Apache-2.0"
] | Acidburn0zzz/Thinktecture.IdentityServer.v3 | source/Core/Extensions/ScopeExtensions.cs | 1,597 | C# |
// Copyright 2019 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.
using leaderboardapp.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace leaderboardapp
{
public interface ILeaderboardRepository
{
Task<bool> PostScoreAsync(ScoreModel score);
Task<IList<LeaderboardItemModel>> RetrieveScoresAsync(RetrieveScoresDetails retrievalDetails);
}
} | 37.64 | 103 | 0.743889 | [
"Apache-2.0"
] | GoogleCloudPlatform/memstore-gaming-leaderboard | leaderboardapp/ILeaderboardRepository.cs | 943 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Storage
{
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.WindowsAzure.Commands.Common.Storage.Properties;
using Microsoft.WindowsAzure.Storage;
using System;
using System.Collections.Generic;
/// <summary>
/// Storage context
/// </summary>
public class AzureStorageContext : IStorageContext
{
private static AzureStorageContext emptyContextInstance = new AzureStorageContext();
/// <summary>
/// Storage account name used in this context
/// </summary>
public string StorageAccountName { get; protected set; }
/// <summary>
/// Blob end point of the storage context
/// </summary>
public virtual string BlobEndPoint { get; protected set; }
/// <summary>
/// Table end point of the storage context
/// </summary>
public virtual string TableEndPoint { get; protected set; }
/// <summary>
/// Queue end point of the storage context
/// </summary>
public virtual string QueueEndPoint { get; protected set; }
/// <summary>
/// File end point of the storage context
/// </summary>
public virtual string FileEndPoint { get; protected set; }
/// <summary>
/// Self reference, it could enable New-AzStorageContext can be used in pipeline
/// </summary>
public IStorageContext Context { get; protected set; }
/// <summary>
/// Name place holder, and force pipeline to ignore this property
/// </summary>
public virtual string Name { get; protected set; }
/// <summary>
/// Storage account in context
/// </summary>
public virtual CloudStorageAccount StorageAccount { get; protected set; }
/// <summary>
/// Endpoint suffix (everything after "table.", "blob." or "queue.")
/// </summary>
/// <returns>
/// This will return an empty string if the endpoints are not correctly set.
/// </returns>
public string EndPointSuffix
{
get
{
if (!string.IsNullOrEmpty(BlobEndPoint))
{
string blobSpliter = "blob.";
if (BlobEndPoint.LastIndexOf(blobSpliter) >= 0)
return BlobEndPoint.Substring(BlobEndPoint.LastIndexOf(blobSpliter) + blobSpliter.Length);
}
if (!string.IsNullOrEmpty(TableEndPoint))
{
string tableSpliter = "table.";
if (TableEndPoint.LastIndexOf(tableSpliter) >= 0)
return TableEndPoint.Substring(TableEndPoint.LastIndexOf(tableSpliter) + tableSpliter.Length);
}
if (!string.IsNullOrEmpty(QueueEndPoint))
{
string queueSpliter = "queue.";
if (QueueEndPoint.LastIndexOf(queueSpliter) >= 0)
return QueueEndPoint.Substring(QueueEndPoint.LastIndexOf(queueSpliter) + queueSpliter.Length);
}
if (!string.IsNullOrEmpty(FileEndPoint))
{
string fileSpliter = "file.";
if (FileEndPoint.LastIndexOf(fileSpliter) >= 0)
return FileEndPoint.Substring(FileEndPoint.LastIndexOf(fileSpliter) + fileSpliter.Length);
}
return string.Empty;
}
}
/// <summary>
/// Get the connection string for this storage account
/// </summary>
public string ConnectionString {
get
{
string returnValue = null;
if (this.StorageAccount != null)
{
returnValue = this.StorageAccount.ToString(true);
}
return returnValue;
}
}
/// <summary>
/// Custom propeties for the storage context
/// </summary>
public IDictionary<string, string> ExtendedProperties { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Create a storage context usign cloud storage account
/// </summary>
/// <param name="account">cloud storage account</param>
public AzureStorageContext(CloudStorageAccount account)
{
StorageAccount = account;
if (account.BlobEndpoint != null)
{
BlobEndPoint = account.BlobEndpoint.ToString();
}
if (account.TableEndpoint != null)
{
TableEndPoint = account.TableEndpoint.ToString();
}
if (account.QueueEndpoint != null)
{
QueueEndPoint = account.QueueEndpoint.ToString();
}
if (account.FileEndpoint != null)
{
FileEndPoint = account.FileEndpoint.ToString();
}
StorageAccountName = account.Credentials.AccountName;
Context = this;
Name = String.Empty;
if (string.IsNullOrEmpty(StorageAccountName))
{
if (account.Credentials.IsSAS)
{
StorageAccountName = "[SasToken]";
}
else if (account.Credentials.IsToken)
{
StorageAccountName = "[AccessToken]";
}
else
{
StorageAccountName = "[Anonymous]";
}
}
}
/// <summary>
/// Proivides a private constructor for building empty instance which
/// contains no account information.
/// </summary>
protected AzureStorageContext()
{
}
public static AzureStorageContext EmptyContextInstance
{
get
{
return emptyContextInstance;
}
}
}
}
| 36.394872 | 139 | 0.524447 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/Storage/Commands.Storage/Common/AzureStorageContext.cs | 6,905 | C# |
using System;
using NUnit.Framework;
using Service.CandlesHistory.Domain.Models;
using Service.CandlesHistory.Services;
namespace Service.CandlesHistory.Tests
{
public class CandleFrameSelectorTest
{
private readonly CandleFrameSelector _selector = new CandleFrameSelector();
[SetUp]
public void Setup()
{
}
[Test]
public void Test1()
{
var time = DateTime.Parse("2021-02-15 15:00:59");
var candle = CandleType.Minute;
var expectedFrame = DateTime.Parse("2021-02-15 15:00:00");
var frame = _selector.SelectFrame(time, candle);
Assert.AreEqual(expectedFrame, frame, $"{time:O} to {candle}");
}
[TestCase("2021-02-15 15:35:23", "2021-02-15 15:35:00")]
[TestCase("2021-02-15 15:00:00", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:00:01", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:00:59", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:01:00", "2021-02-15 15:01:00")]
[TestCase("2021-02-15 00:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 23:59:59", "2021-02-15 23:59:00")]
public void Minute(string timeStr, string expectedStr)
{
var candle = CandleType.Minute;
var time = DateTime.Parse(timeStr);
var expectedFrame = DateTime.Parse(expectedStr);
var frame = _selector.SelectFrame(time, candle);
Assert.AreEqual(expectedFrame, frame, $"{time:O} to {candle}");
}
[TestCase("2021-02-15 15:35:23", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:00:00", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:00:01", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:00:59", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 15:01:00", "2021-02-15 15:00:00")]
[TestCase("2021-02-15 00:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 23:59:59", "2021-02-15 23:00:00")]
[TestCase("2021-02-15 00:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-01-01 03:23:19", "2021-01-01 03:00:00")]
public void Hour(string timeStr, string expectedStr)
{
var candle = CandleType.Hour;
var time = DateTime.Parse(timeStr);
var expectedFrame = DateTime.Parse(expectedStr);
var frame = _selector.SelectFrame(time, candle);
Assert.AreEqual(expectedFrame, frame, $"{time:O} to {candle}");
}
[TestCase("2021-02-15 15:35:23", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 15:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 15:00:01", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 15:00:59", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 15:01:00", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 00:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 23:59:59", "2021-02-15 00:00:00")]
[TestCase("2021-02-15 00:00:00", "2021-02-15 00:00:00")]
[TestCase("2021-01-01 03:23:19", "2021-01-01 00:00:00")]
[TestCase("2021-02-28 12:41:30", "2021-02-28 00:00:00")]
[TestCase("2021-01-31 03:23:19", "2021-01-31 00:00:00")]
public void Day(string timeStr, string expectedStr)
{
var candle = CandleType.Day;
var time = DateTime.Parse(timeStr);
var expectedFrame = DateTime.Parse(expectedStr);
var frame = _selector.SelectFrame(time, candle);
Assert.AreEqual(expectedFrame, frame, $"{time:O} to {candle}");
}
[TestCase("2021-02-15 15:35:23", "2021-02-01 00:00:00")]
[TestCase("2021-02-15 15:00:00", "2021-02-01 00:00:00")]
[TestCase("2021-04-15 15:00:01", "2021-04-01 00:00:00")]
[TestCase("2021-02-15 15:00:59", "2021-02-01 00:00:00")]
[TestCase("2021-02-15 15:01:00", "2021-02-01 00:00:00")]
[TestCase("2021-11-15 00:00:00", "2021-11-01 00:00:00")]
[TestCase("2021-02-15 23:59:59", "2021-02-01 00:00:00")]
[TestCase("2020-02-15 00:00:00", "2020-02-01 00:00:00")]
[TestCase("2021-01-01 03:23:19", "2021-01-01 00:00:00")]
[TestCase("2021-02-28 12:41:30", "2021-02-01 00:00:00")]
[TestCase("2021-01-31 03:23:19", "2021-01-01 00:00:00")]
[TestCase("2021-01-23 12:41:30", "2021-01-01 00:00:00")]
[TestCase("2021-12-31 03:23:19", "2021-12-01 00:00:00")]
public void Month(string timeStr, string expectedStr)
{
var candle = CandleType.Month;
var time = DateTime.Parse(timeStr);
var expectedFrame = DateTime.Parse(expectedStr);
var frame = _selector.SelectFrame(time, candle);
Assert.AreEqual(expectedFrame, frame, $"{time:O} to {candle}");
}
}
}
| 46.432692 | 83 | 0.574032 | [
"MIT"
] | MyJetWallet/Service.CandlesHistory | test/Service.CandlesHistory.Tests/TestExample.cs | 4,831 | C# |
namespace XMPPEngineer.Extensions
{
/// <summary>
/// Invoked when a CustomIqRequest is made.
/// </summary>
/// <param name="jid">The jid</param>
/// <param name="str">The serialised data stream</param>
/// <returns>The serialised anwser string</returns>
public delegate string CustomIqRequestDelegate(Jid jid, string str);
} | 35.5 | 72 | 0.670423 | [
"MIT"
] | ParamountVentures/Sharp.Xmpp | Extensions/CustomExtension/CustomIqRequestDelegate.cs | 357 | C# |
namespace ShopIM.UI.Forms
{
partial class AdminDashboard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AdminDashboard));
this.metroPanelSide = new MetroFramework.Controls.MetroPanel();
this.menuSidePanel = new System.Windows.Forms.FlowLayoutPanel();
this.AdminPanelButton = new MetroFramework.Controls.MetroLink();
this.SalesButton = new MetroFramework.Controls.MetroLink();
this.ProductButton = new MetroFramework.Controls.MetroLink();
this.InventoryButton = new MetroFramework.Controls.MetroLink();
this.SettingsButton = new MetroFramework.Controls.MetroLink();
this.LockButton = new MetroFramework.Controls.MetroLink();
this.StatisticButton = new MetroFramework.Controls.MetroLink();
this.LogButton = new MetroFramework.Controls.MetroLink();
this.LogoutButton = new MetroFramework.Controls.MetroLink();
this.UserImage = new System.Windows.Forms.PictureBox();
this.UserButton = new MetroFramework.Controls.MetroLink();
this.metroPanel1 = new MetroFramework.Controls.MetroPanel();
this.metroPanelBackground = new MetroFramework.Controls.MetroPanel();
this.metroPanel2 = new MetroFramework.Controls.MetroPanel();
this.Header = new MetroFramework.Controls.MetroLabel();
this.NotificationLink = new MetroFramework.Controls.MetroLink();
this.ExitButton = new MetroFramework.Controls.MetroLink();
this.SettingContextMenu = new MetroFramework.Controls.MetroContextMenu(this.components);
this.minimizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.maximizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.lockToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SettingLink = new MetroFramework.Controls.MetroLink();
this.metroPanelSide.SuspendLayout();
this.menuSidePanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.UserImage)).BeginInit();
this.metroPanel2.SuspendLayout();
this.SettingContextMenu.SuspendLayout();
this.SuspendLayout();
//
// metroPanelSide
//
this.metroPanelSide.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.metroPanelSide.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(43)))), ((int)(((byte)(38)))), ((int)(((byte)(40)))));
this.metroPanelSide.Controls.Add(this.UserImage);
this.metroPanelSide.Controls.Add(this.menuSidePanel);
this.metroPanelSide.Controls.Add(this.UserButton);
this.metroPanelSide.Controls.Add(this.metroPanel1);
this.metroPanelSide.HorizontalScrollbarBarColor = true;
this.metroPanelSide.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanelSide.HorizontalScrollbarSize = 10;
this.metroPanelSide.Location = new System.Drawing.Point(0, 35);
this.metroPanelSide.Name = "metroPanelSide";
this.metroPanelSide.Size = new System.Drawing.Size(217, 517);
this.metroPanelSide.TabIndex = 0;
this.metroPanelSide.UseCustomBackColor = true;
this.metroPanelSide.VerticalScrollbarBarColor = true;
this.metroPanelSide.VerticalScrollbarHighlightOnWheel = false;
this.metroPanelSide.VerticalScrollbarSize = 10;
//
// menuSidePanel
//
this.menuSidePanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.menuSidePanel.AutoScroll = true;
this.menuSidePanel.Controls.Add(this.AdminPanelButton);
this.menuSidePanel.Controls.Add(this.SalesButton);
this.menuSidePanel.Controls.Add(this.ProductButton);
this.menuSidePanel.Controls.Add(this.InventoryButton);
this.menuSidePanel.Controls.Add(this.SettingsButton);
this.menuSidePanel.Controls.Add(this.LockButton);
this.menuSidePanel.Controls.Add(this.StatisticButton);
this.menuSidePanel.Controls.Add(this.LogButton);
this.menuSidePanel.Controls.Add(this.LogoutButton);
this.menuSidePanel.Location = new System.Drawing.Point(0, 80);
this.menuSidePanel.Name = "menuSidePanel";
this.menuSidePanel.Size = new System.Drawing.Size(217, 437);
this.menuSidePanel.TabIndex = 19;
//
// AdminPanelButton
//
this.AdminPanelButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.AdminPanelButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.AdminPanelButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.AdminPanelButton.Location = new System.Drawing.Point(1, 1);
this.AdminPanelButton.Margin = new System.Windows.Forms.Padding(1);
this.AdminPanelButton.Name = "AdminPanelButton";
this.AdminPanelButton.Size = new System.Drawing.Size(215, 50);
this.AdminPanelButton.Style = MetroFramework.MetroColorStyle.White;
this.AdminPanelButton.TabIndex = 26;
this.AdminPanelButton.Text = "Admin Panel";
this.AdminPanelButton.UseCustomBackColor = true;
this.AdminPanelButton.UseSelectable = true;
this.AdminPanelButton.UseStyleColors = true;
this.AdminPanelButton.Click += new System.EventHandler(this.AdminPanelButton_Click);
//
// SalesButton
//
this.SalesButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.SalesButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.SalesButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.SalesButton.Location = new System.Drawing.Point(1, 53);
this.SalesButton.Margin = new System.Windows.Forms.Padding(1);
this.SalesButton.Name = "SalesButton";
this.SalesButton.Size = new System.Drawing.Size(215, 50);
this.SalesButton.Style = MetroFramework.MetroColorStyle.White;
this.SalesButton.TabIndex = 25;
this.SalesButton.Text = "Sales";
this.SalesButton.UseCustomBackColor = true;
this.SalesButton.UseSelectable = true;
this.SalesButton.UseStyleColors = true;
this.SalesButton.Click += new System.EventHandler(this.SalesButton_Click);
//
// ProductButton
//
this.ProductButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.ProductButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.ProductButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.ProductButton.Location = new System.Drawing.Point(1, 105);
this.ProductButton.Margin = new System.Windows.Forms.Padding(1);
this.ProductButton.Name = "ProductButton";
this.ProductButton.Size = new System.Drawing.Size(215, 50);
this.ProductButton.Style = MetroFramework.MetroColorStyle.White;
this.ProductButton.TabIndex = 20;
this.ProductButton.Text = "Products";
this.ProductButton.UseCustomBackColor = true;
this.ProductButton.UseSelectable = true;
this.ProductButton.UseStyleColors = true;
this.ProductButton.Click += new System.EventHandler(this.ProductButton_Click);
//
// InventoryButton
//
this.InventoryButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.InventoryButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.InventoryButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.InventoryButton.Location = new System.Drawing.Point(1, 157);
this.InventoryButton.Margin = new System.Windows.Forms.Padding(1);
this.InventoryButton.Name = "InventoryButton";
this.InventoryButton.Size = new System.Drawing.Size(215, 50);
this.InventoryButton.Style = MetroFramework.MetroColorStyle.White;
this.InventoryButton.TabIndex = 21;
this.InventoryButton.Text = "Inventory";
this.InventoryButton.UseCustomBackColor = true;
this.InventoryButton.UseSelectable = true;
this.InventoryButton.UseStyleColors = true;
this.InventoryButton.Click += new System.EventHandler(this.InventoryButton_Click);
//
// SettingsButton
//
this.SettingsButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.SettingsButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.SettingsButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.SettingsButton.Location = new System.Drawing.Point(1, 209);
this.SettingsButton.Margin = new System.Windows.Forms.Padding(1);
this.SettingsButton.Name = "SettingsButton";
this.SettingsButton.Size = new System.Drawing.Size(215, 50);
this.SettingsButton.Style = MetroFramework.MetroColorStyle.White;
this.SettingsButton.TabIndex = 22;
this.SettingsButton.Text = "Settings";
this.SettingsButton.UseCustomBackColor = true;
this.SettingsButton.UseSelectable = true;
this.SettingsButton.UseStyleColors = true;
this.SettingsButton.Click += new System.EventHandler(this.SettingsButton_Click);
//
// LockButton
//
this.LockButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.LockButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.LockButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.LockButton.Location = new System.Drawing.Point(1, 261);
this.LockButton.Margin = new System.Windows.Forms.Padding(1);
this.LockButton.Name = "LockButton";
this.LockButton.Size = new System.Drawing.Size(215, 50);
this.LockButton.Style = MetroFramework.MetroColorStyle.White;
this.LockButton.TabIndex = 23;
this.LockButton.Text = "Lock";
this.LockButton.UseCustomBackColor = true;
this.LockButton.UseSelectable = true;
this.LockButton.UseStyleColors = true;
this.LockButton.Click += new System.EventHandler(this.LockButton_Click);
//
// StatisticButton
//
this.StatisticButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.StatisticButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.StatisticButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.StatisticButton.Location = new System.Drawing.Point(1, 313);
this.StatisticButton.Margin = new System.Windows.Forms.Padding(1);
this.StatisticButton.Name = "StatisticButton";
this.StatisticButton.Size = new System.Drawing.Size(215, 50);
this.StatisticButton.Style = MetroFramework.MetroColorStyle.White;
this.StatisticButton.TabIndex = 28;
this.StatisticButton.Text = "Statistics";
this.StatisticButton.UseCustomBackColor = true;
this.StatisticButton.UseSelectable = true;
this.StatisticButton.UseStyleColors = true;
this.StatisticButton.Click += new System.EventHandler(this.StatisticButton_Click);
//
// LogButton
//
this.LogButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.LogButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.LogButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.LogButton.Location = new System.Drawing.Point(1, 365);
this.LogButton.Margin = new System.Windows.Forms.Padding(1);
this.LogButton.Name = "LogButton";
this.LogButton.Size = new System.Drawing.Size(215, 50);
this.LogButton.Style = MetroFramework.MetroColorStyle.White;
this.LogButton.TabIndex = 27;
this.LogButton.Text = "Log";
this.LogButton.UseCustomBackColor = true;
this.LogButton.UseSelectable = true;
this.LogButton.UseStyleColors = true;
this.LogButton.Click += new System.EventHandler(this.LogButton_click);
//
// LogoutButton
//
this.LogoutButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(30)))), ((int)(((byte)(35)))));
this.LogoutButton.FontSize = MetroFramework.MetroLinkSize.Tall;
this.LogoutButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.LogoutButton.Location = new System.Drawing.Point(1, 417);
this.LogoutButton.Margin = new System.Windows.Forms.Padding(1);
this.LogoutButton.Name = "LogoutButton";
this.LogoutButton.Size = new System.Drawing.Size(215, 50);
this.LogoutButton.Style = MetroFramework.MetroColorStyle.White;
this.LogoutButton.TabIndex = 24;
this.LogoutButton.Text = "Logout";
this.LogoutButton.UseCustomBackColor = true;
this.LogoutButton.UseSelectable = true;
this.LogoutButton.UseStyleColors = true;
this.LogoutButton.Click += new System.EventHandler(this.LogoutButton_Click);
//
// UserImage
//
this.UserImage.BackColor = System.Drawing.Color.Transparent;
this.UserImage.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.UserImage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.UserImage.ErrorImage = global::ShopIM.UI.Properties.Resources.DefaultUserImage1;
this.UserImage.Location = new System.Drawing.Point(0, 0);
this.UserImage.Name = "UserImage";
this.UserImage.Size = new System.Drawing.Size(80, 79);
this.UserImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.UserImage.TabIndex = 18;
this.UserImage.TabStop = false;
//
// UserButton
//
this.UserButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(138)))), ((int)(((byte)(212)))));
this.UserButton.FontSize = MetroFramework.MetroLinkSize.Medium;
this.UserButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(170)))), ((int)(((byte)(170)))), ((int)(((byte)(170)))));
this.UserButton.Location = new System.Drawing.Point(74, 0);
this.UserButton.Name = "UserButton";
this.UserButton.Size = new System.Drawing.Size(143, 79);
this.UserButton.Style = MetroFramework.MetroColorStyle.White;
this.UserButton.TabIndex = 16;
this.UserButton.Text = " User";
this.UserButton.UseCustomBackColor = true;
this.UserButton.UseSelectable = true;
this.UserButton.UseStyleColors = true;
this.UserButton.Click += new System.EventHandler(this.UserButton_Click);
//
// metroPanel1
//
this.metroPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.metroPanel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(150)))), ((int)(((byte)(150)))));
this.metroPanel1.HorizontalScrollbarBarColor = true;
this.metroPanel1.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanel1.HorizontalScrollbarSize = 10;
this.metroPanel1.Location = new System.Drawing.Point(0, 78);
this.metroPanel1.Name = "metroPanel1";
this.metroPanel1.Size = new System.Drawing.Size(217, 1);
this.metroPanel1.TabIndex = 2;
this.metroPanel1.UseCustomBackColor = true;
this.metroPanel1.VerticalScrollbarBarColor = true;
this.metroPanel1.VerticalScrollbarHighlightOnWheel = false;
this.metroPanel1.VerticalScrollbarSize = 10;
//
// metroPanelBackground
//
this.metroPanelBackground.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.metroPanelBackground.AutoScroll = true;
this.metroPanelBackground.BackColor = System.Drawing.Color.WhiteSmoke;
this.metroPanelBackground.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.metroPanelBackground.HorizontalScrollbar = true;
this.metroPanelBackground.HorizontalScrollbarBarColor = true;
this.metroPanelBackground.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanelBackground.HorizontalScrollbarSize = 10;
this.metroPanelBackground.Location = new System.Drawing.Point(223, 131);
this.metroPanelBackground.Name = "metroPanelBackground";
this.metroPanelBackground.Size = new System.Drawing.Size(688, 407);
this.metroPanelBackground.TabIndex = 2;
this.metroPanelBackground.UseCustomBackColor = true;
this.metroPanelBackground.VerticalScrollbar = true;
this.metroPanelBackground.VerticalScrollbarBarColor = true;
this.metroPanelBackground.VerticalScrollbarHighlightOnWheel = false;
this.metroPanelBackground.VerticalScrollbarSize = 10;
//
// metroPanel2
//
this.metroPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.metroPanel2.AutoScroll = true;
this.metroPanel2.BackColor = System.Drawing.Color.WhiteSmoke;
this.metroPanel2.Controls.Add(this.Header);
this.metroPanel2.HorizontalScrollbar = true;
this.metroPanel2.HorizontalScrollbarBarColor = true;
this.metroPanel2.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanel2.HorizontalScrollbarSize = 10;
this.metroPanel2.Location = new System.Drawing.Point(223, 35);
this.metroPanel2.Name = "metroPanel2";
this.metroPanel2.Size = new System.Drawing.Size(688, 79);
this.metroPanel2.TabIndex = 3;
this.metroPanel2.UseCustomBackColor = true;
this.metroPanel2.VerticalScrollbar = true;
this.metroPanel2.VerticalScrollbarBarColor = true;
this.metroPanel2.VerticalScrollbarHighlightOnWheel = false;
this.metroPanel2.VerticalScrollbarSize = 10;
//
// Header
//
this.Header.AutoSize = true;
this.Header.FontSize = MetroFramework.MetroLabelSize.Tall;
this.Header.FontWeight = MetroFramework.MetroLabelWeight.Bold;
this.Header.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
this.Header.Location = new System.Drawing.Point(3, 12);
this.Header.Name = "Header";
this.Header.Size = new System.Drawing.Size(74, 25);
this.Header.Style = MetroFramework.MetroColorStyle.Silver;
this.Header.TabIndex = 2;
this.Header.Text = "Header";
this.Header.UseCustomBackColor = true;
this.Header.UseStyleColors = true;
//
// NotificationLink
//
this.NotificationLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.NotificationLink.FontSize = MetroFramework.MetroLinkSize.Medium;
this.NotificationLink.ForeColor = System.Drawing.SystemColors.Desktop;
this.NotificationLink.Image = global::ShopIM.UI.Properties.Resources.Notification;
this.NotificationLink.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.NotificationLink.ImageSize = 30;
this.NotificationLink.Location = new System.Drawing.Point(767, 0);
this.NotificationLink.Name = "NotificationLink";
this.NotificationLink.Size = new System.Drawing.Size(56, 35);
this.NotificationLink.TabIndex = 21;
this.NotificationLink.Text = "(0)";
this.NotificationLink.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.NotificationLink.UseCustomBackColor = true;
this.NotificationLink.UseCustomForeColor = true;
this.NotificationLink.UseSelectable = true;
this.NotificationLink.Click += new System.EventHandler(this.NotificationLink_Click);
//
// ExitButton
//
this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ExitButton.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.ExitButton.Image = ((System.Drawing.Image)(resources.GetObject("ExitButton.Image")));
this.ExitButton.ImageSize = 28;
this.ExitButton.Location = new System.Drawing.Point(876, 0);
this.ExitButton.Name = "ExitButton";
this.ExitButton.Size = new System.Drawing.Size(35, 35);
this.ExitButton.TabIndex = 19;
this.ExitButton.UseCustomBackColor = true;
this.ExitButton.UseCustomForeColor = true;
this.ExitButton.UseSelectable = true;
this.ExitButton.Click += new System.EventHandler(this.ExitButton_click);
//
// SettingContextMenu
//
this.SettingContextMenu.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SettingContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.minimizeToolStripMenuItem,
this.maximizeToolStripMenuItem,
this.toolStripMenuItem1,
this.lockToolStripMenuItem});
this.SettingContextMenu.Name = "SettingContextMenu";
this.SettingContextMenu.Size = new System.Drawing.Size(132, 76);
//
// minimizeToolStripMenuItem
//
this.minimizeToolStripMenuItem.Name = "minimizeToolStripMenuItem";
this.minimizeToolStripMenuItem.Size = new System.Drawing.Size(131, 22);
this.minimizeToolStripMenuItem.Text = "Minimize";
this.minimizeToolStripMenuItem.Click += new System.EventHandler(this.minimizeToolStripMenuItem_Click);
//
// maximizeToolStripMenuItem
//
this.maximizeToolStripMenuItem.Name = "maximizeToolStripMenuItem";
this.maximizeToolStripMenuItem.Size = new System.Drawing.Size(131, 22);
this.maximizeToolStripMenuItem.Text = "Maximize";
this.maximizeToolStripMenuItem.Click += new System.EventHandler(this.maximizeToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(128, 6);
//
// lockToolStripMenuItem
//
this.lockToolStripMenuItem.Name = "lockToolStripMenuItem";
this.lockToolStripMenuItem.Size = new System.Drawing.Size(131, 22);
this.lockToolStripMenuItem.Text = "Lock";
this.lockToolStripMenuItem.Click += new System.EventHandler(this.lockToolStripMenuItem_Click);
//
// SettingLink
//
this.SettingLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.SettingLink.BackColor = System.Drawing.Color.White;
this.SettingLink.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.SettingLink.Image = global::ShopIM.UI.Properties.Resources.Setting;
this.SettingLink.ImageSize = 25;
this.SettingLink.Location = new System.Drawing.Point(838, 0);
this.SettingLink.Name = "SettingLink";
this.SettingLink.Size = new System.Drawing.Size(35, 35);
this.SettingLink.TabIndex = 23;
this.SettingLink.UseCustomBackColor = true;
this.SettingLink.UseCustomForeColor = true;
this.SettingLink.UseSelectable = true;
this.SettingLink.Click += new System.EventHandler(this.SettingLink_Click);
//
// AdminDashboard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(921, 552);
this.ControlBox = false;
this.Controls.Add(this.SettingLink);
this.Controls.Add(this.metroPanel2);
this.Controls.Add(this.NotificationLink);
this.Controls.Add(this.ExitButton);
this.Controls.Add(this.metroPanelBackground);
this.Controls.Add(this.metroPanelSide);
this.Name = "AdminDashboard";
this.Resizable = false;
this.Style = MetroFramework.MetroColorStyle.White;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.AdminDashboard_Load);
this.metroPanelSide.ResumeLayout(false);
this.menuSidePanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.UserImage)).EndInit();
this.metroPanel2.ResumeLayout(false);
this.metroPanel2.PerformLayout();
this.SettingContextMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private MetroFramework.Controls.MetroPanel metroPanelSide;
private MetroFramework.Controls.MetroPanel metroPanelBackground;
private MetroFramework.Controls.MetroPanel metroPanel1;
private MetroFramework.Controls.MetroLink UserButton;
private MetroFramework.Controls.MetroLink ExitButton;
private MetroFramework.Controls.MetroPanel metroPanel2;
private MetroFramework.Controls.MetroLabel Header;
private MetroFramework.Controls.MetroLink LogButton;
private MetroFramework.Controls.MetroLink AdminPanelButton;
private MetroFramework.Controls.MetroLink SalesButton;
private MetroFramework.Controls.MetroLink LogoutButton;
private MetroFramework.Controls.MetroLink SettingsButton;
private MetroFramework.Controls.MetroLink LockButton;
private MetroFramework.Controls.MetroLink InventoryButton;
private MetroFramework.Controls.MetroLink ProductButton;
private System.Windows.Forms.PictureBox UserImage;
private System.Windows.Forms.FlowLayoutPanel menuSidePanel;
public MetroFramework.Controls.MetroLink NotificationLink;
private MetroFramework.Controls.MetroContextMenu SettingContextMenu;
private System.Windows.Forms.ToolStripMenuItem minimizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem maximizeToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private MetroFramework.Controls.MetroLink SettingLink;
private System.Windows.Forms.ToolStripMenuItem lockToolStripMenuItem;
private MetroFramework.Controls.MetroLink StatisticButton;
}
} | 61.123016 | 169 | 0.642927 | [
"BSD-3-Clause"
] | 2TakarDeveloper/ShopIM | ShopIM/ShopIM.UI/Forms/AdminDashboard.Designer.cs | 30,808 | C# |
using LivrariaVirtualApp.Domain.Models;
using LivrariaVirtualApp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LivrariaVirtualApp.Infrastructure.Repositories
{
public class WishlistRepository : Repository<Wishlist>, IWishlistRepository
{
public WishlistRepository(LivrariaVirtualDbContext dbContext) : base(dbContext)
{
}
public Task<List<Wishlist>> FindAllByUserIdAsync(int userId)
{
return _dbContext.Wishlists
.Where(e => e.User_id == userId).ToListAsync();
}
public Task<List<Wishlist>> FindAllByNameStartWithAsync(string name_wishlist)
{
return _dbContext.Wishlists.Where(c => c.Name.StartsWith(name_wishlist))
.OrderBy(c => c.Name)
.ToListAsync();
}
public Task<Wishlist> FindByNameAsync(string name_wishlist)
{
return _dbContext.Wishlists.SingleOrDefaultAsync(c => c.Name == name_wishlist);
}
public override async Task<Wishlist> FindOrCreate(Wishlist e)
{
var c = await _dbContext.Wishlists.SingleOrDefaultAsync(i => i.Name == e.Name);
if (c == null)
{
c = await CreateAsync(e);
await _dbContext.SaveChangesAsync();
}
return c;
}
public override Task<IEnumerable<Wishlist>> GetAsync(string search)
{
throw new NotImplementedException();
}
public override Task<Wishlist> GetAsync(int id)
{
throw new NotImplementedException();
}
public override Task<IEnumerable<Wishlist>> GetAsync()
{
throw new NotImplementedException();
}
public override async Task<Wishlist> UpsertAsync(Wishlist e)
{
Wishlist f = null;
Wishlist existing = await FindByNameAsync(e.Name);
if (existing == null)
{
if (e.Id == 0)
{
f = await CreateAsync(e);
}
else
{
f = await UpdateAsync(e);
}
}
else if (existing.Id == e.Id)
{
_dbContext.Entry(existing).State = EntityState.Detached;
f = await UpdateAsync(e);
}
await _dbContext.SaveChangesAsync();
return f;
}
}
} | 29.896552 | 91 | 0.556324 | [
"MIT"
] | 3dylson/Windows-UWP-Livraria | LivrariaVirtualApp.Infrastructure/Repositories/WishlistRepository.cs | 2,603 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using CovidCommunity.Api.Authorization;
using CovidCommunity.Api.Authorization.Roles;
using CovidCommunity.Api.Authorization.Users;
using CovidCommunity.Api.Roles.Dto;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace CovidCommunity.Api.Roles
{
[AbpAuthorize(PermissionNames.Pages_Roles)]
public class RoleAppService : AsyncCrudAppService<Role, RoleDto, int, PagedRoleResultRequestDto, CreateRoleDto, RoleDto>, IRoleAppService
{
private readonly RoleManager _roleManager;
private readonly UserManager _userManager;
public RoleAppService(IRepository<Role> repository, RoleManager roleManager, UserManager userManager)
: base(repository)
{
_roleManager = roleManager;
_userManager = userManager;
}
public override async Task<RoleDto> CreateAsync(CreateRoleDto input)
{
CheckCreatePermission();
var role = ObjectMapper.Map<Role>(input);
role.SetNormalizedName();
CheckErrors(await _roleManager.CreateAsync(role));
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.GrantedPermissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
return MapToEntityDto(role);
}
public async Task<ListResultDto<RoleListDto>> GetRolesAsync(GetRolesInput input)
{
var roles = await _roleManager
.Roles
.WhereIf(
!input.Permission.IsNullOrWhiteSpace(),
r => r.Permissions.Any(rp => rp.Name == input.Permission && rp.IsGranted)
)
.ToListAsync();
return new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(roles));
}
public override async Task<RoleDto> UpdateAsync(RoleDto input)
{
CheckUpdatePermission();
var role = await _roleManager.GetRoleByIdAsync(input.Id);
ObjectMapper.Map(input, role);
CheckErrors(await _roleManager.UpdateAsync(role));
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.GrantedPermissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
return MapToEntityDto(role);
}
public override async Task DeleteAsync(EntityDto<int> input)
{
CheckDeletePermission();
var role = await _roleManager.FindByIdAsync(input.Id.ToString());
var users = await _userManager.GetUsersInRoleAsync(role.NormalizedName);
foreach (var user in users)
{
CheckErrors(await _userManager.RemoveFromRoleAsync(user, role.NormalizedName));
}
CheckErrors(await _roleManager.DeleteAsync(role));
}
public Task<ListResultDto<PermissionDto>> GetAllPermissions()
{
var permissions = PermissionManager.GetAllPermissions();
return Task.FromResult(new ListResultDto<PermissionDto>(
ObjectMapper.Map<List<PermissionDto>>(permissions).OrderBy(p => p.DisplayName).ToList()
));
}
protected override IQueryable<Role> CreateFilteredQuery(PagedRoleResultRequestDto input)
{
return Repository.GetAllIncluding(x => x.Permissions)
.WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Keyword)
|| x.DisplayName.Contains(input.Keyword)
|| x.Description.Contains(input.Keyword));
}
protected override async Task<Role> GetEntityByIdAsync(int id)
{
return await Repository.GetAllIncluding(x => x.Permissions).FirstOrDefaultAsync(x => x.Id == id);
}
protected override IQueryable<Role> ApplySorting(IQueryable<Role> query, PagedRoleResultRequestDto input)
{
return query.OrderBy(r => r.DisplayName);
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
public async Task<GetRoleForEditOutput> GetRoleForEdit(EntityDto input)
{
var permissions = PermissionManager.GetAllPermissions();
var role = await _roleManager.GetRoleByIdAsync(input.Id);
var grantedPermissions = (await _roleManager.GetGrantedPermissionsAsync(role)).ToArray();
var roleEditDto = ObjectMapper.Map<RoleEditDto>(role);
return new GetRoleForEditOutput
{
Role = roleEditDto,
Permissions = ObjectMapper.Map<List<FlatPermissionDto>>(permissions).OrderBy(p => p.DisplayName).ToList(),
GrantedPermissionNames = grantedPermissions.Select(p => p.Name).ToList()
};
}
}
}
| 36.248322 | 141 | 0.64451 | [
"Apache-2.0"
] | eventually-apps/covid-community | api/src/CovidCommunity.Api.Application/Roles/RoleAppService.cs | 5,403 | C# |
namespace FactoryPattern.Entities.Contracts
{
public interface IFighter : IMachine
{
bool AggressiveMode { get; }
void ToggleAggressiveMode();
}
} | 19.555556 | 44 | 0.659091 | [
"Apache-2.0"
] | KostadinovK/Design-Patterns | 04-Factory Pattern/FactoryPattern/FactoryPattern/Entities/Contracts/IFighter.cs | 178 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MoreMountains.Feedbacks
{
/// <summary>
/// This class, meant to be used in MMFeedbacks demos, will check for requirements, and output an
/// error message if necessary.
/// </summary>
public class DemoPackageTester : MonoBehaviour
{
[MMFInformation("This component is only used to display an error in the console in case dependencies for this demo haven't been installed. You can safely remove it if you want, and typically you wouldn't want to keep that in your own game.", MMFInformationAttribute.InformationType.Warning, false)]
/// does the scene require post processing to be installed?
public bool RequiresPostProcessing;
/// does the scene require TextMesh Pro to be installed?
public bool RequiresTMP;
/// does the scene require Cinemachine to be installed?
public bool RequiresCinemachine;
/// <summary>
/// On Awake we test for dependencies
/// </summary>
protected virtual void Awake()
{
TestForDependencies();
}
/// <summary>
/// Checks whether or not dependencies have been correctly installed
/// </summary>
protected virtual void TestForDependencies()
{
bool missingDependencies = false;
string missingString = "";
bool cinemachineFound = false;
bool tmpFound = false;
bool postProcessingFound = false;
#if MOREMOUNTAINS_CINEMACHINE_INSTALLED
cinemachineFound = true;
#endif
#if MOREMOUNTAINS_TEXTMESHPRO_INSTALLED
tmpFound = true;
#endif
#if MOREMOUNTAINS_POSTPROCESSING_INSTALLED
postProcessingFound = true;
#endif
if (RequiresCinemachine && !cinemachineFound)
{
missingDependencies = true;
missingString += "Cinemachine";
}
if (RequiresTMP && !tmpFound)
{
missingDependencies = true;
if (missingString != "") { missingString += ", "; }
missingString += "TextMeshPro";
}
if (RequiresPostProcessing && !postProcessingFound)
{
missingDependencies = true;
if (missingString != "") { missingString += ", "; }
missingString += "PostProcessing";
}
if (missingDependencies)
{
Debug.LogError("[DemoPackageTester] It looks like you're missing some dependencies required by this demo ("+missingString+")." +
" You'll have to install them to run this demo. You can learn more about how to do so in the documentation, at http://feel-docs.moremountains.com/how-to-install.html" +
"\n\n");
}
}
}
}
| 37.804878 | 306 | 0.565806 | [
"MIT"
] | DuLovell/Battle-Simulator | Assets/Imported Assets/Feel/MMFeedbacks/Demos/MMFeedbacksDemo/Scripts/DemoPackageTester.cs | 3,100 | C# |
using System.Windows.Forms;
namespace AryuwatSystem.UserControls
{
public partial class ButtonPrint : UserControl
{
public ButtonPrint()
{
InitializeComponent();
}
public delegate void ButtonClick();
public event ButtonClick BtnClick;
public delegate void ButtonKeyDown(object sender, KeyEventArgs e);
public event ButtonKeyDown BtnKeyDown;
private void picTmp_MouseLeave(object sender, System.EventArgs e)
{
// picTmp.Image = global::AryuwatSystem.Properties.Resources.Search64;
}
private void picTmp_MouseMove(object sender, MouseEventArgs e)
{
//picTmp.Image = global::AryuwatSystem.Properties.Resources.Search64Over;
}
private void picTmp_Click(object sender, System.EventArgs e)
{
if (BtnClick != null)
{
BtnClick();
}
}
private void ButtonFind_KeyDown(object sender, KeyEventArgs e)
{
if (BtnKeyDown != null)
{
BtnKeyDown(sender, e);
}
}
}
}
| 27.162791 | 85 | 0.57363 | [
"Unlicense"
] | Krailit/Aryuwat_Nurse | AryuwatSystem/UserControls/ButtonPrint.cs | 1,168 | C# |
using System.Runtime.InteropServices;
using CommandPattern;
using SurveySync.Soe.Commands;
using SurveySync.Soe.Configuration;
using SurveySync.Soe.Infastructure;
using SurveySync.Soe.Infastructure.IOC;
using ESRI.ArcGIS.SOESupport;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.esriSystem;
using SurveySync.Soe.Startup;
namespace SurveySync.Soe {
/// <summary>
/// The main server object extension
/// </summary>
[ComVisible(true), Guid("a48951e3-a7a8-4d30-8331-a43ad0122a3b"), ClassInterface(ClassInterfaceType.None),
ServerObjectExtension("MapServer",
AllCapabilities = "",
//These create checkboxes to determine allowed functionality
DefaultCapabilities = "",
Description = "Keeps HistoricSurvey's in sync with the Contribution Container",
//shows up in manager under capabilities
DisplayName = "UDSH Survey Sync",
//Properties that can be set on the capabilities tab in manager.
//must be camelCased!
Properties = "connectionString=;propertySurveyRecordTableName=;featureServiceUrl=;contributionPropertyPoint.PropertyId=;contributionPropertyPoint.LayerName=;survey.SurveyId=;survey.PropertyId=;survey.ReturnFields=;buildings.PropertyId=;buildings.LayerName=;",
SupportsREST = true,
SupportsSOAP = false)]
public class SurveySyncSoe : SoeBase, IServerObjectExtension, IObjectConstruct, IRESTRequestHandler {
public ServerLogger Logger = new ServerLogger();
/// <summary>
/// Initializes a new instance of the <see cref="SurveySyncSoe" /> class. If you have business logic
/// that you want to run when the SOE first becomes enabled, don’t here; instead, use the following
/// IObjectConstruct.Construct() method found in SoeBase.cs
/// </summary>
public SurveySyncSoe() {
Logger.LogMessage(ServerLogger.msgType.infoSimple, "SurveySyncSoe", 2472, "SurveySyc - Starting up");
ReqHandler = CommandExecutor.ExecuteCommand(
new CreateRestImplementationCommand(typeof (FindAllEndpointsCommand).Assembly));
Kernel = new Container();
#if DEBUG
Kernel.Register<IConfigurable>(x => new DebugConfiguration());
#elif STAGE
Kernel.Register<IConfigurable>(x => new StageConfiguration());
#else
Kernel.Register<IConfigurable>(x => new RestEndPointConfiguration());
#endif
}
private Container Kernel { get; set; }
#region IObjectConstruct Members
/// <summary>
/// This is where you put any expensive business logic that you don’t need to run on each request. For example, if you
/// know you’re always working with the same layer in the map, you can put the code to get the layer here.
/// </summary>
/// <param name="props"> The props. </param>
public override void Construct(IPropertySet props) {
Logger.LogMessage(ServerLogger.msgType.infoSimple, "Construct", 2472, "SurveySyc - Constructing");
base.Construct(props);
CacheConfig.Cache(ServerObjectHelper, props, Kernel);
Logger.LogMessage(ServerLogger.msgType.infoSimple, "Construct", 2472, "SurveySyc - Constructing Done");
}
#endregion
}
}
| 48.926471 | 268 | 0.683799 | [
"MIT"
] | agrc/UDSH-SurveySync | src/SurveySync.Soe/SurveySyncSoe.cs | 3,335 | C# |
using MoneyBunny.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace MoneyBunny.Rules
{
public enum RuleType
{
Reference,
Value,
Date,
Type,
}
static class RuleTypesExtensions
{
public static string ToDisplayString(this RuleType type)
{
switch (type)
{
case RuleType.Date:
return "Date Rule";
case RuleType.Reference:
return "Reference Rule";
case RuleType.Type:
return "Type Rule";
case RuleType.Value:
return "Value Rule";
}
throw new InvalidEnumArgumentException(
nameof(type),
(int)type,
typeof(RuleType));
}
public static RuleType ToRuleType(this string text)
{
if (text == "Date Rule")
{
return RuleType.Date;
}
if (text == "Reference Rule")
{
return RuleType.Reference;
}
if (text == "Type Rule")
{
return RuleType.Type;
}
if (text == "Value Rule")
{
return RuleType.Value;
}
throw new ArgumentException(
"The text provided does not translate to a rule type.",
nameof(text));
}
public static IEnumerable<string> GetComparators(this RuleType type)
{
if (type == RuleType.Date)
{
return EnumExtensions.GetValues<Comparator>()
.Select(c => c.ToDisplayString());
}
if (type == RuleType.Value)
{
return EnumExtensions.GetValues<Comparator>()
.Select(c => c.ToDisplayString());
}
if (type == RuleType.Reference)
{
return new []{ "Contains any" };
}
if (type == RuleType.Type)
{
return new[] { "Contains any" };
}
throw new InvalidEnumArgumentException(
nameof(type),
(int)type,
typeof(RuleType));
}
}
}
| 25.691489 | 76 | 0.452174 | [
"MIT"
] | SebastianBecker2/MoneyBunny | MoneyBunny/Rules/RuleType.cs | 2,417 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _03SchoolLibrary
{
class StartUp
{
static void Main(string[] args)
{
var bookCollection = Console.ReadLine().Split("&").ToList();
while (true)
{
var input = Console.ReadLine().Split(" | ").ToArray();
if (input[0]== "Done")
{
break;
}
else
{
switch (input[0])
{
case "Add Book":
if (!bookCollection.Contains(input[1]))
{
bookCollection.Insert(0, input[1]);
}
break;
case "Take Book":
if (bookCollection.Contains(input[1]))
{
bookCollection.Remove(input[1]);
}
break;
case "Swap Books":
if (bookCollection.Contains(input[1]) && bookCollection.Contains(input[2]))
{
var firstIndex = bookCollection.IndexOf(input[1]);
var secondIndex = bookCollection.IndexOf(input[2]);
bookCollection[firstIndex] = input[2];
bookCollection[secondIndex] = input[1];
}
break;
case "Insert Book":
bookCollection.Add(input[1]);
break;
case "Check Book":
var index = int.Parse(input[1]);
if (index < bookCollection.Count && index >= 0)
{
Console.WriteLine(bookCollection[index]);
}
break;
}
}
}
Console.WriteLine(string.Join(", ", bookCollection));
}
}
}
| 31.189189 | 103 | 0.341854 | [
"MIT"
] | veloman86/SoftUni-CSharp | Tech Modul/10. Mid Exam/Mid Exam Retake 10 December 2019/03SchoolLibrary/StartUp.cs | 2,310 | C# |
//Licensed to the Apache Software Foundation(ASF) under one
//or more contributor license agreements.See the NOTICE file
//distributed with this work for additional information
//regarding copyright ownership.The ASF licenses this file
//to you under the Apache License, Version 2.0 (the
//"License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing,
//software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//KIND, either express or implied. See the License for the
//specific language governing permissions and limitations
//under the License.
using System.Collections.Generic;
using System.ComponentModel;
using Newtonsoft.Json;
using Paragon.Plugins;
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Paragon.Runtime.PackagedApplication
{
public sealed class ApplicationManifest : IApplicationManifest
{
/// <summary>
/// Application startup information. Required.
/// </summary>
[JsonProperty(Required = Required.Always)]
public AppInfo App { get; set; }
public IconInfo Icons { get; set; }
public List<NativeService> NativeServices { get; set; }
public List<ApplicationPlugin> ApplicationPlugins { get; set; }
public CORSBypassEntry[] CORSBypassList{ get; set; }
/// <summary>
/// Id of the application. Required.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Id { get; set; }
/// <summary>
/// Application type as defined in the gallery (one of Packaged or Hosted). Required.
/// </summary>
public ApplicationType Type { get; set; }
/// <summary>
/// Name of the application. Required.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
/// <summary>
/// Version of the application. Required.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Version { get; set; }
/// <summary>
/// Description of the application. Required.
/// </summary>
//[JsonProperty(Required = Required.Always)]
public string Description { get; set; }
/// <summary>
/// Use the app name as WindowName irrespective of title changes via the html doc
/// </summary>
public bool UseAppNameAsWindowTitle { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the app is single instance or not.
/// </summary>
public bool SingleInstance { get; set; }
/// <summary>
/// Gets or sets the default window frame type.
/// </summary>
public FrameType DefaultFrameType { get; set; }
IAppInfo IApplicationManifest.App
{
get { return App; }
set
{
if (value != null)
{
var app = new AppInfo
{
StartupTimeout = value.StartupTimeout,
Urls = value.Urls
};
IAppInfo iapp = app;
iapp.Launch = value.Launch;
iapp.Background = value.Background;
App = app;
}
else
{
App = null;
}
}
}
// Optional
private string _processGroup = string.Empty;
public string ProcessGroup
{
get
{
// By default use the application Id as the ProcessGroup, which means all instances of the same application share a browser process.
return string.IsNullOrEmpty(_processGroup) ? Id : _processGroup;
}
set
{
_processGroup = value;
}
}
public string[] Permissions { get; set; }
public string[] ExternalUrlWhitelist { get; set; }
ICORSBypassEntry[] IApplicationManifest.CORSBypassList
{
get
{
return CORSBypassList;
}
set
{
if (value != null)
{
var list = new List<CORSBypassEntry>();
foreach (var e in value)
{
list.Add(new CORSBypassEntry() { SourceUrl = e.SourceUrl, TargetDomain = e.TargetDomain, Protocol = e.Protocol, AllowTargetSubdomains = e.AllowTargetSubdomains });
}
CORSBypassList = list.ToArray();
}
}
}
public string[] CustomProtocolWhitelist { get; set; }
public bool DisableSpellChecking { get; set; }
public bool EnableMediaStream { get; set; }
public string BrowserLanguage { get; set; }
public string CustomTheme { get; set; }
IIconInfo IApplicationManifest.Icons
{
get { return Icons; }
set { Icons = value != null ? new IconInfo {Icon128 = value.Icon128, Icon16 = value.Icon16} : null; }
}
INativeServiceInfo[] IApplicationManifest.NativeServices
{
get { return NativeServices != null ? NativeServices.ToArray() : new INativeServiceInfo[0]; }
}
IPluginInfo[] IApplicationManifest.ApplicationPlugins
{
get { return ApplicationPlugins != null ? ApplicationPlugins.ToArray() : new IPluginInfo[0]; }
}
public static ApplicationType GetApplicationType(IAppInfo appInfo)
{
var launchInfo = (appInfo != null) ? appInfo.Launch : null;
var backgroundInfo = (appInfo != null) ? appInfo.Background : null;
var applicationType = ApplicationType.Packaged;
if (backgroundInfo != null)
{
applicationType = ApplicationType.Packaged;
}
else
{
if (launchInfo != null)
{
applicationType = ApplicationType.Hosted;
}
}
return applicationType;
}
}
public class IconInfo : IIconInfo
{
[JsonProperty("128")]
public string Icon128 { get; set; }
[JsonProperty("16")]
public string Icon16 { get; set; }
}
public class CORSBypassEntry : ICORSBypassEntry
{
[JsonProperty(Required = Required.Always)]
public string SourceUrl { get; set; }
[JsonProperty(Required = Required.Always)]
public string TargetDomain { get; set; }
[JsonProperty(Required = Required.Always)]
public string Protocol { get; set; }
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling=DefaultValueHandling.Populate)]
public bool AllowTargetSubdomains { get; set; }
}
public class ApplicationPlugin : IPluginInfo
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
[DefaultValue("")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string Path { get; set; }
[JsonProperty(Required = Required.Always)]
public string Assembly { get; set; }
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool RunInRenderer { get; set; }
public List<string> UnmanagedDlls { get; set; }
}
public class AppInfo : IAppInfo
{
public AppInfo()
{
StartupTimeout = System.Diagnostics.Debugger.IsAttached ? 1000 : 10;
}
/// <summary>
/// Background script information for a packaged application. Required for packaged applications.
/// </summary>
public BackgroundInfo Background { get; set; }
/// <summary>
/// Launch information for a hosted application. Required for hosted applications. This is used for JsonSerialization.
/// </summary>
public LaunchInfo Launch { get; set; }
IBackgroundInfo IAppInfo.Background
{
get { return Background; }
set { Background = value != null ? new BackgroundInfo {Scripts = value.Scripts} : null; }
}
/// <summary>
/// Currently unused.
/// </summary>
public string[] Urls { get; set; }
ILaunchInfo IAppInfo.Launch
{
get { return Launch; }
set
{
if (value != null)
{
Launch = new LaunchInfo
{
Container = value.Container,
Height = value.Height,
Width = value.Width,
Left = value.Left,
Top = value.Top,
MaxHeight = value.MaxHeight,
MaxWidth = value.MaxWidth,
MinHeight = value.MinHeight,
MinWidth = value.MinWidth,
WebUrl = value.WebUrl
};
}
else
{
Launch = null;
}
}
}
/// <summary>
/// Timeout for the creation of the first window of the application. If no window is created within this period, the application will cloase.
/// Optional. Default value is 10 seconds.
/// </summary>
public int StartupTimeout { get; set; }
}
public class BackgroundInfo : IBackgroundInfo
{
[JsonProperty(Required = Required.Always)]
public string[] Scripts { get; set; }
}
public class LaunchInfo : ILaunchInfo
{
public LaunchInfo()
{
Height = 750;
Width = 1000;
MinHeight = -1;
MinWidth = -1;
MaxHeight = -1;
MaxWidth = -1;
Left = -1;
Top = -1;
AutoSaveLocation = true;
}
/// <summary>
/// The start url for a hosted application.
/// </summary>
[JsonProperty("web_url", Required = Required.Always)]
public string WebUrl { get; set; }
/// <summary>
/// Id (optional) to identify the window. This will be used to remember the size
/// and position of the window and restore that geometry when a window with the same id is later opened.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Default true. Used to say if the window position and geometry if remembered if
/// a window with the same id is opened later.
/// </summary>
public bool AutoSaveLocation { get; set; }
public string Container { get; set; }
/// <summary>
/// Height for the main window. Optional. Default is 750.
/// </summary>
public int Height { get; set; }
/// <summary>
/// Width for the main window. Optional. Default is 1000.
/// </summary>
public int Width { get; set; }
public int MinHeight { get; set; }
public int MinWidth { get; set; }
public int MaxHeight { get; set; }
public int MaxWidth { get; set; }
/// <summary>
/// Left for the main window. Optional. Default is -1 (no value).
/// </summary>
public int Left { get; set; }
/// <summary>
/// Top for the main window. Optional. Default is -1 (no value).
/// </summary>
public int Top { get; set; }
}
public class NativeService : INativeServiceInfo
{
public string Name { get; set; }
public string Executable { get; set; }
}
} | 32.442667 | 187 | 0.546194 | [
"Apache-2.0"
] | mcleo-d/SFE-Minuet-DesktopClient | minuet/Paragon.Runtime/PackagedApplication/ApplicationManifest.cs | 12,168 | 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.
namespace Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT
{
/// <summary>
/// <see cref="Windows.UI.Xaml.FocusState"/>
/// </summary>
public enum FocusState
{
Unfocused = 0,
Pointer = 1,
Keyboard = 2,
Programmatic = 3,
}
} | 28.705882 | 72 | 0.639344 | [
"MIT"
] | devsko/Microsoft.Toolkit.Win32 | Microsoft.Toolkit.Win32.UI.Controls/Interop/WinRT/FocusState.cs | 488 | 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.Gaming.V1Beta.Snippets
{
using Google.Cloud.Gaming.V1Beta;
public sealed partial class GeneratedGameServerDeploymentsServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetGameServerDeployment</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetGameServerDeploymentResourceNames()
{
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(name);
}
}
}
| 42.487179 | 142 | 0.718769 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/gaming/v1beta/google-cloud-gaming-v1beta-csharp/Google.Cloud.Gaming.V1Beta.StandaloneSnippets/GameServerDeploymentsServiceClient.GetGameServerDeploymentResourceNamesSnippet.g.cs | 1,657 | C# |
namespace ClearHl7.Codes.V270
{
/// <summary>
/// HL7 Version 2 Table 0250 - Relatedness Assessment.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0250</remarks>
public enum CodeRelatednessAssessment
{
/// <summary>
/// H - Highly probable.
/// </summary>
HighlyProbable,
/// <summary>
/// I - Improbable.
/// </summary>
Improbable,
/// <summary>
/// M - Moderately probable.
/// </summary>
ModeratelyProbable,
/// <summary>
/// N - Not related.
/// </summary>
NotRelated,
/// <summary>
/// S - Somewhat probable.
/// </summary>
SomewhatProbable
}
}
| 21.514286 | 59 | 0.484728 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7.Codes/V270/CodeRelatednessAssessment.cs | 755 | C# |
using CaptureSampleCore;
using Robmikh.WindowsRuntimeHelpers;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using Windows.Foundation.Metadata;
using Windows.Graphics.Capture;
using Windows.UI.Composition;
namespace WPFCaptureSample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
#if DEBUG
// force graphicscapture.dll to load
var picker = new GraphicsCapturePicker();
#endif
}
private async void PickerButton_Click(object sender, RoutedEventArgs e)
{
StopCapture();
WindowComboBox.SelectedIndex = -1;
MonitorComboBox.SelectedIndex = -1;
await StartPickerCaptureAsync();
}
private void PrimaryMonitorButton_Click(object sender, RoutedEventArgs e)
{
StopCapture();
WindowComboBox.SelectedIndex = -1;
MonitorComboBox.SelectedIndex = -1;
StartPrimaryMonitorCapture();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var interopWindow = new WindowInteropHelper(this);
_hwnd = interopWindow.Handle;
var presentationSource = PresentationSource.FromVisual(this);
var dpiX = 1.0;
var dpiY = 1.0;
if (presentationSource != null)
{
dpiX = presentationSource.CompositionTarget.TransformToDevice.M11;
dpiY = presentationSource.CompositionTarget.TransformToDevice.M22;
}
var controlsWidth = (float)(ControlsGrid.ActualWidth * dpiX);
InitComposition(controlsWidth);
InitWindowList();
InitMonitorList();
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
StopCapture();
WindowComboBox.SelectedIndex = -1;
MonitorComboBox.SelectedIndex = -1;
}
private void WindowComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = (ComboBox)sender;
var process = (Process)comboBox.SelectedItem;
if (process != null)
{
StopCapture();
MonitorComboBox.SelectedIndex = -1;
var hwnd = process.MainWindowHandle;
try
{
StartHwndCapture(hwnd);
}
catch (Exception)
{
Debug.WriteLine($"Hwnd 0x{hwnd.ToInt32():X8} is not valid for capture!");
_processes.Remove(process);
comboBox.SelectedIndex = -1;
}
}
}
private void MonitorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = (ComboBox)sender;
var monitor = (MonitorInfo)comboBox.SelectedItem;
if (monitor != null)
{
StopCapture();
WindowComboBox.SelectedIndex = -1;
var hmon = monitor.Hmon;
try
{
StartHmonCapture(hmon);
}
catch (Exception)
{
Debug.WriteLine($"Hmon 0x{hmon.ToInt32():X8} is not valid for capture!");
_monitors.Remove(monitor);
comboBox.SelectedIndex = -1;
}
}
}
private void InitComposition(float controlsWidth)
{
// Create our compositor
_compositor = new Compositor();
// Create a target for our window
_target = _compositor.CreateDesktopWindowTarget(_hwnd, true);
// Attach our root visual
_root = _compositor.CreateContainerVisual();
_root.RelativeSizeAdjustment = Vector2.One;
_root.Size = new Vector2(-controlsWidth, 0);
_root.Offset = new Vector3(controlsWidth, 0, 0);
_target.Root = _root;
// Setup the rest of our sample application
_sample = new BasicSampleApplication(_compositor);
_root.Children.InsertAtTop(_sample.Visual);
}
private void InitWindowList()
{
if (ApiInformation.IsApiContractPresent(typeof(Windows.Foundation.UniversalApiContract).FullName, 8))
{
var processesWithWindows = from p in Process.GetProcesses()
where !string.IsNullOrWhiteSpace(p.MainWindowTitle) && WindowEnumerationHelper.IsWindowValidForCapture(p.MainWindowHandle)
select p;
_processes = new ObservableCollection<Process>(processesWithWindows);
WindowComboBox.ItemsSource = _processes;
}
else
{
WindowComboBox.IsEnabled = false;
}
}
private void InitMonitorList()
{
if (ApiInformation.IsApiContractPresent(typeof(Windows.Foundation.UniversalApiContract).FullName, 8))
{
var monitors = MonitorEnumerationHelper.GetMonitors();
_monitors = new ObservableCollection<MonitorInfo>(monitors);
MonitorComboBox.ItemsSource = _monitors;
}
else
{
MonitorComboBox.IsEnabled = false;
PrimaryMonitorButton.IsEnabled = false;
}
}
private async Task StartPickerCaptureAsync()
{
var picker = new GraphicsCapturePicker();
picker.SetWindow(_hwnd);
var item = await picker.PickSingleItemAsync();
if (item != null)
{
_sample.StartCaptureFromItem(item);
}
}
private void StartHwndCapture(IntPtr hwnd)
{
var item = CaptureHelper.CreateItemForWindow(hwnd);
if (item != null)
{
_sample.StartCaptureFromItem(item);
}
}
private void StartHmonCapture(IntPtr hmon)
{
var item = CaptureHelper.CreateItemForMonitor(hmon);
if (item != null)
{
_sample.StartCaptureFromItem(item);
}
}
private void StartPrimaryMonitorCapture()
{
var monitor = (from m in MonitorEnumerationHelper.GetMonitors()
where m.IsPrimary
select m).First();
StartHmonCapture(monitor.Hmon);
}
private void StopCapture()
{
_sample.StopCapture();
}
private IntPtr _hwnd;
private Compositor _compositor;
private CompositionTarget _target;
private ContainerVisual _root;
private BasicSampleApplication _sample;
private ObservableCollection<Process> _processes;
private ObservableCollection<MonitorInfo> _monitors;
}
}
| 32.766816 | 165 | 0.55919 | [
"MIT"
] | robmikh/WPFCaptureSample | WPFCaptureSample/MainWindow.xaml.cs | 7,309 | C# |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Interop;
namespace NCubeSolver.Screensaver
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
// Used to host WPF content in preview mode, attach HwndSource to parent Win32 window.
private HwndSource m_winWpfContent;
private MainWindow m_winSaver;
private void App_OnStartup(object sender, StartupEventArgs e)
{
var mode = e.Args.Any() ? e.Args[0] : "/s";
// Preview mode--display in little window in Screen Saver dialog
// (Not invoked with Preview button, which runs Screen Saver in
// normal /s mode).
if (mode.ToLower().StartsWith("/p"))
{
m_winSaver = new MainWindow();
Int32 previewHandle = Convert.ToInt32(e.Args[1]);
//WindowInteropHelper interopWin1 = new WindowInteropHelper(win);
//interopWin1.Owner = new IntPtr(previewHandle);
var pPreviewHnd = new IntPtr(previewHandle);
var lpRect = new RECT();
Win32API.GetClientRect(pPreviewHnd, ref lpRect);
var sourceParams = new HwndSourceParameters("sourceParams")
{
PositionX = 0,
PositionY = 0,
Height = lpRect.Bottom - lpRect.Top,
Width = lpRect.Right - lpRect.Left,
ParentWindow = pPreviewHnd,
WindowStyle = (int)(WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN)
};
m_winWpfContent = new HwndSource(sourceParams);
m_winWpfContent.Disposed += winWPFContent_Disposed;
m_winWpfContent.RootVisual = m_winSaver.Grid;
// ReSharper disable once CSharpWarnings::CS4014
m_winSaver.StartAnimation();
}
// Normal screensaver mode. Either screen saver kicked in normally,
// or was launched from Preview button
else if (mode.ToLower().StartsWith("/s"))
{
var win = new MainWindow { WindowState = WindowState.Maximized };
win.Show();
}
// Config mode, launched from Settings button in screen saver dialog
else if (mode.ToLower().StartsWith("/c"))
{
var win = new SettingsWindow();
win.Show();
}
// If not running in one of the sanctioned modes, shut down the app
// immediately (because we don't have a GUI).
else
{
Current.Shutdown();
}
}
/// <summary>
/// Event that triggers when parent window is disposed--used when doing
/// screen saver preview, so that we know when to exit. If we didn't
/// do this, Task Manager would get a new .scr instance every time
/// we opened Screen Saver dialog or switched dropdown to this saver.
/// </summary>
///<param name="sender"></param>
///<param name="e"></param>
void winWPFContent_Disposed(object sender, EventArgs e)
{
m_winSaver.Close();
// Application.Current.Shutdown();
}
}
}
| 37.206522 | 119 | 0.552732 | [
"MIT"
] | EdwardSalter/NCubeSolver | src/NCubeSolver.Screensaver/App.xaml.cs | 3,425 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Zeltex
{
[CustomPropertyDrawer(typeof(EditorAction))]
public class EditorActionEditor : ZeltexEditor
{
EditorAction MyAction;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MyAction = GetTargetObjectOfProperty(property) as EditorAction;
Color BeforeColor = GUI.color;
GUI.color = new Color(0, 255, 255);
if (GUI.Button(position, property.name))
{
MyAction.Trigger();
EditorUtility.SetDirty(property.serializedObject.targetObject);
}
GUI.color = BeforeColor;
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 30;
}
}
} | 28.8125 | 96 | 0.631236 | [
"Apache-2.0"
] | Deus0/Zeltexium | Assets/Scripts/Editor/EditorActionEditor.cs | 924 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.As.V20180419.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyLoadBalancersResponse : AbstractModel
{
/// <summary>
/// 伸缩活动ID
/// </summary>
[JsonProperty("ActivityId")]
public string ActivityId{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ActivityId", this.ActivityId);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.627451 | 83 | 0.646607 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/As/V20180419/Models/ModifyLoadBalancersResponse.cs | 1,628 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// alipay.data.aiservice.bikeprice.data.sync
/// </summary>
public class AlipayDataAiserviceBikepriceDataSyncRequest : IAlipayRequest<AlipayDataAiserviceBikepriceDataSyncResponse>
{
/// <summary>
/// 智能定价数据回流服务
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.data.aiservice.bikeprice.data.sync";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if (udfParams == null)
{
udfParams = new Dictionary<string, string>();
}
udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
if (udfParams != null)
{
parameters.AddAll(udfParams);
}
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.731884 | 123 | 0.542595 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Request/AlipayDataAiserviceBikepriceDataSyncRequest.cs | 3,297 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UniRx;
using UniRx.Triggers;
namespace Scripts.Core.Inputs
{
public class GeneralInput : MonoBehaviour
{
[SerializeField] private KeyboardInput _keyboardInput;
[SerializeField] private MouseInput _mouseInput;
public IObservable<Vector2> MoveObservable { get { return _keyboardInput.MoveObservable; } }
public IObservable<Vector2> RotationObservable { get { return _mouseInput.RotationObservable; } }
public IObservable<bool> LockCursorObservable { get { return _keyboardInput.LockCursorObservable; } }
public IObservable<bool> FireObservable { get { return _mouseInput.FireObservable; } }
private static GeneralInput _instance;
public static GeneralInput Instance
{
get
{
if (_instance==null)
{
_instance = FindObjectOfType<GeneralInput>();
if (_instance==null)
{
throw new ArgumentNullException("there is no active GO with GeneralInput");
}
}
return _instance;
}
}
}
}
| 34.27027 | 109 | 0.614353 | [
"MIT"
] | ViktorDubov/SimpleShooter | Assets/Scripts/Core/Inputs/GeneralInput.cs | 1,270 | C# |
using HKumar.RoleManagement.Interfaces.Services;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using HKumar.RoleManagement.Interfaces.Providers;
using Microsoft.AspNetCore.Mvc;
namespace HKumar.RoleManagement.Attributes
{
/// <summary>
/// Attibute to validate if user has access to that endpoint
/// This attribute require <see cref="IRoleManagementUserInformationProvider"/> to get the user roles
/// </summary>
public class RoleAutorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var errorId = Guid.NewGuid();
var isValid = true;
var message = "Unauthorized";
var user = context.HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
isValid = false;
}
else
{
message = $"You are not authorized to perform this action.";
isValid = false;
IRoleManagementService securityService = context.HttpContext.RequestServices.GetService<IRoleManagementService>();
IRoleManagementUserInformationProvider userInformationProvider = context.HttpContext.RequestServices.GetService<IRoleManagementUserInformationProvider>();
var userRoles = userInformationProvider.UserRoleIds;
var rolePermissions = securityService.GetRoleOperationAsync().Result;
var userRolesPermission = from userRole in userRoles join rolePermission in rolePermissions on userRole equals rolePermission.RoleId select rolePermission;
var controllername = context.RouteData.Values["controller"].ToString();
switch (context.HttpContext.Request.Method.ToLowerInvariant())
{
case "get":
isValid = userRolesPermission.Where(x => x.Read == true && x.Operation.ControllerName == controllername).Any();
break;
case "post":
isValid = userRolesPermission.Where(x => x.Create == true && x.Operation.ControllerName == controllername).Any();
break;
case "patch":
case "put":
isValid = userRolesPermission.Where(x => x.Update == true && x.Operation.ControllerName == controllername).Any();
break;
case "delete":
isValid = userRolesPermission.Where(x => x.Delete == true && x.Operation.ControllerName == controllername).Any();
break;
default:
isValid = true; // We dont care about other verbs because we are not handling it.
break;
}
}
if (!isValid)
{
context.Result = new ObjectResult(new ProblemDetails()
{
Status = 401,
Detail = message,
Title = message
});
}
}
}
}
| 44.819444 | 171 | 0.575767 | [
"Apache-2.0"
] | hunnysharma102/HKumar.RoleManagement | src/HKumar.RoleManagement/Attributes/RoleAutorizeAttribute.cs | 3,229 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SkiResort.XamarinApp.Entities
{
class WeatherSummary
{
public int MaxTemperature { get; set; }
public int MinTemperature { get; set; }
public int Wind { get; set; }
public int BaseDepth { get; set; }
}
}
| 22.117647 | 47 | 0.667553 | [
"MIT"
] | Bhaskers-Blu-Org2/AdventureWorksSkiApp | src/SkiResort.XamarinApp/SkiResort.XamarinApp/Entities/WeatherSummary.cs | 378 | 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 Skype_Web_Demo {
public partial class ViewSwitcher {
}
}
| 27.75 | 80 | 0.412162 | [
"Apache-2.0"
] | HildebrandDevelopment/SkypeDemo | SKYPE_DEMO_SOLN/Skype_Web_Demo/ViewSwitcher.ascx.designer.cs | 444 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Requests.Abstractions;
using Telegram.Bot.Types;
// ReSharper disable once CheckNamespace
namespace Telegram.Bot.Requests
{
/// <summary>
/// Use this method to set default chat permissions for all members. The bot must be an administrator
/// in the group or a supergroup for this to work and must have the can_restrict_members admin rights.
/// Returns <c>true</c> on success.
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class SetChatPermissionsRequest : RequestBase<bool>, IChatTargetable
{
/// <inheritdoc />
[JsonProperty(Required = Required.Always)]
public ChatId ChatId { get; }
/// <summary>
/// New default chat permissions
/// </summary>
[JsonProperty(Required = Required.Always)]
public ChatPermissions Permissions { get; }
/// <summary>
/// Initializes a new request with chatId and new default permissions
/// </summary>
/// <param name="chatId">Unique identifier for the target chat or username of the target channel
/// (in the format <c>@channelusername</c>)
/// </param>
/// <param name="permissions">New default chat permissions</param>
public SetChatPermissionsRequest(ChatId chatId, ChatPermissions permissions)
: base("setChatPermissions")
{
ChatId = chatId;
Permissions = permissions;
}
}
}
| 37.690476 | 106 | 0.65698 | [
"MIT"
] | AKomyshan/Telegram.Bot | src/Telegram.Bot/Requests/Available methods/Manage Chat/SetChatPermissionsRequest.cs | 1,583 | C# |
namespace Barracks.Core.Commands
{
using System;
using System.Reflection;
using Barracks.Attributes;
using Barracks.Contracts;
using Barracks.ExtensionMethods;
public class CommandInterpreter : ICommandInterpreter
{
private const string Path = "Barracks.Core.Commands.";
public CommandInterpreter(IRepository repository, IUnitFactory unitFactory)
{
this.UnitFactory = unitFactory;
this.Repository = repository;
}
public IUnitFactory UnitFactory { get; set; }
public IRepository Repository { get; set; }
public IExecutable InterpretCommand(string[] data, string commandName)
{
string fullCommandName = commandName.ToPascalCase() + "Command";
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
Type commandType = Type.GetType(Path + fullCommandName);
ConstructorInfo ctor = commandType.GetConstructor(flags, null,
new[] { typeof(string[]) }, null);
IExecutable instance = ctor.Invoke(new object[] { data }) as IExecutable;
FieldInfo[] fields = commandType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo field in fields)
{
bool hasInjectAttribute = field.GetCustomAttributes(typeof(InjectAttribute), false).Length > 0;
if (hasInjectAttribute)
{
string fieldTypeName = field.FieldType.Name;
switch (fieldTypeName)
{
case "IUnitFactory":
field.SetValue(instance, this.UnitFactory);
break;
case "IRepository":
field.SetValue(instance, this.Repository);
break;
}
}
}
return instance;
}
}
} | 35.948276 | 112 | 0.544365 | [
"MIT"
] | ballaholic/Barracks | Barracks/Core/Commands/CommandInterpreter.cs | 2,087 | C# |
using System;
using System.Windows.Media;
using Microsoft.CSS.Editor;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.Web.Editor;
using Microsoft.CSS.Editor.Completion;
using Microsoft.CSS.Editor.Schemas.Browsers;
using Microsoft.Web.Editor.Completion;
using Microsoft.Web.Editor.Imaging;
namespace MadsKristensen.EditorExtensions.Css
{
internal class CompletionListEntry : ICssCompletionListEntry
{
private string _name;
private StandardGlyphGroup _glyph;
public CompletionListEntry(string name, int sortingPriority = 0, StandardGlyphGroup glyph = StandardGlyphGroup.GlyphGroupEnumMember)
{
_name = name;
_glyph = glyph;
SortingPriority = sortingPriority;
}
public string Description { get; set; }
public string DisplayText
{
get { return _name; }
}
public string GetSyntax(Version version)
{
return string.Empty;
}
public string GetAttribute(string name)
{
return string.Empty;
}
public string GetInsertionText(CssTextSource textSource, ITrackingSpan typingSpan)
{
return DisplayText;
}
public string GetVersionedAttribute(string name, Version version)
{
return GetAttribute(name);
}
public bool AllowQuotedString
{
get { return false; }
}
public bool IsBuilder
{
get { return false; }
}
public int SortingPriority { get; set; }
public bool IsSupported(BrowserVersion browser)
{
return true;
}
public bool IsSupported(Version cssVersion)
{
return true;
}
public ITrackingSpan ApplicableTo
{
get { return null; }
}
public CompletionEntryFilterTypes FilterType
{
get { return CompletionEntryFilterTypes.MatchTyping; }
}
public ImageSource Icon
{
get { return GlyphService.GetGlyph(_glyph, StandardGlyphItem.GlyphItemPublic); }
}
public bool IsCommitChar(char typedCharacter)
{
return false;
}
public bool IsMuteCharacter(char typedCharacter)
{
return false;
}
public bool RetriggerIntellisense
{
get { return false; }
}
}
}
| 23.775701 | 140 | 0.595126 | [
"Apache-2.0"
] | GProulx/WebEssentials2015 | EditorExtensions/CSS/Completion/CompletionListEntry.cs | 2,546 | C# |
using System.ComponentModel;
using PropertyChanged;
namespace GBCLV3.Models.Auxiliary
{
public class ShaderPack : INotifyPropertyChanged
{
[DoNotNotify]
public string Id { get; set; }
[DoNotNotify]
public string Path { get; set; }
public bool IsEnabled { get; set; }
[DoNotNotify]
public bool IsExtracted { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 21.045455 | 65 | 0.643629 | [
"MIT"
] | FerxTG/GBCLV3 | GBCLV3/Models/Auxiliary/ShaderPack.cs | 465 | C# |
namespace Osnowa.Tests.Pathfinding
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using NUnit.Framework;
[TestFixture]
public class PathfindingLoadTests
{
[Test]
public void PrintTestedMaps()
{
int xSize = 500;
int ySize = 500;
var density = TestGridInfoProvider.GridDensity.Medium;
bool hasWalls = true;
int seed = 333;
var gip = new TestGridInfoProvider(xSize, ySize, density, hasWalls, seed);
string header = String.Format("xSize: {0}, ySize: {1}, density: {2}, walls: {3}, seed: {4}",
xSize, ySize, density, hasWalls, seed);
Console.WriteLine(header);
Console.Write(gip.Walkability());
Console.WriteLine();
}
//[Ignore("This test should be run with DotMemory Unit framework (free)")]
[DotMemoryUnit(CollectAllocations = true)]
[Test]
public void LoadTest_PathfindingPerformanceAndMemoryOverhead()
{
int xSize = 500;
int ySize = 500;
var density = TestGridInfoProvider.GridDensity.Medium;
bool hasWalls = true;
int rngSeed = 333;
int trailsCount = 100;
var gip = new TestGridInfoProvider(xSize, ySize, density, hasWalls, rngSeed);
var rng = new RandomNumberGenerator(rngSeed);
IRasterLineCreator bresenham = new BresenhamLineCreator();
var pathfinder = new Pathfinder(gip, new NaturalLineCalculator(bresenham), bresenham);
var stopwatch = new Stopwatch();
var trailsToTest = new Dictionary<Position, Position>();
for (int i = 0; i < trailsCount; i++)
{
Position first = GetRandomWalkablePosition(rng, gip);
Position second = GetRandomWalkablePosition(rng, gip);
trailsToTest[first] = second;
}
Func<Position, Position, PathfindingResult>[] findersToTest = {
pathfinder.FindJumpPointsWithJps,
pathfinder.FindJumpPointsWithSpatialAstar,
};
MemoryCheckPoint lastCheckPoint = new MemoryCheckPoint();// = dotMemory.Check();
if (GC.TryStartNoGCRegion(240111000))
{
lastCheckPoint = RunPathfindingAndPrintResults(xSize, ySize, density, hasWalls, trailsCount, rngSeed, findersToTest, stopwatch, trailsToTest,
lastCheckPoint);
if (GCSettings.LatencyMode == GCLatencyMode.NoGCRegion)
GC.EndNoGCRegion();
}
}
private static MemoryCheckPoint RunPathfindingAndPrintResults(int xSize, int ySize, TestGridInfoProvider.GridDensity density, bool hasWalls,
int trailsCount, int seed, Func<Position, Position, PathfindingResult>[] findersToTest, Stopwatch stopwatch, Dictionary<Position, Position> trails,
MemoryCheckPoint lastCheckPoint)
{
foreach (Func<Position, Position, PathfindingResult> finder in findersToTest)
{
Console.WriteLine("Method name;" + finder.Method.Name);
Console.WriteLine("xSize;" + xSize);
Console.WriteLine("ySize;" + ySize);
Console.WriteLine("density;" + density);
Console.WriteLine("hasWalls;" + hasWalls);
Console.WriteLine("trailsCount;" + trailsCount);
Console.WriteLine("seed;" + seed);
stopwatch.Start();
int pathNotFoundCount = 0;
int totalStepsCount = 0;
foreach (var startToEnd in trails)
{
List<Position> jumpPoints = finder(startToEnd.Key, startToEnd.Value).Positions;
if (jumpPoints != null)
totalStepsCount += jumpPoints.Count;
else
{
++pathNotFoundCount;
}
}
stopwatch.Stop();
Console.WriteLine("total time;" + stopwatch.ElapsedMilliseconds);
Console.WriteLine("paths found;" + (trailsCount - pathNotFoundCount));
Console.WriteLine("paths not found;" + pathNotFoundCount);
Console.WriteLine("total count of steps to follow;" + totalStepsCount);
stopwatch.Reset();
/*
var previousCheckPoint = lastCheckPoint;
lastCheckPoint = dotMemory.Check(memory =>
{
var traffic = memory.GetTrafficFrom(previousCheckPoint);
var difference = memory.GetDifference(previousCheckPoint);
Console.WriteLine("DIFFERENCE — NEW OBJECTS COUNT;" + difference.GetNewObjects().ObjectsCount);
Console.WriteLine("DIFFERENCE — NEW OBJECTS SIZE IN BYTES;" + difference.GetNewObjects().SizeInBytes);
Console.WriteLine("TRAFFIC — ALLOCATED OBJECTS COUNT;" + traffic.AllocatedMemory.ObjectsCount);
Console.WriteLine("TRAFFIC — ALLOCATED SIZE IN BYTESl" + traffic.AllocatedMemory.SizeInBytes);
Console.WriteLine("TRAFFIC — COLLECTED OBJECTS COUNT;" + traffic.CollectedMemory.ObjectsCount);
Console.WriteLine("TRAFFIC — COLLECTED SIZE IN BYTESl" + traffic.CollectedMemory.SizeInBytes);
Console.WriteLine();
Console.WriteLine("NEW OBJECTS WITH COUNT OVER 50:");
Console.WriteLine("OBJECT NAME;COUNT;BYTES");
var types = difference.GetNewObjects().GroupByType();
foreach (var tmi in types)
{
if (tmi.ObjectsCount < 50) continue;
string full = String.Format("{0};{1};{2}", tmi.Type.ToString(), tmi.ObjectsCount,
tmi.SizeInBytes);
Console.WriteLine(full);
}
Console.WriteLine();
Console.WriteLine("TRAFFIC OF TYPES WITH COUNT OVER 50:");
Console.WriteLine("TYPE NAME;ALLOCATED MEMORY;COLLECTED MEMORY");
var types2 = traffic.GroupByType();
foreach (var tmi in types2)
{
if (tmi.AllocatedMemoryInfo.ObjectsCount > 50)
{
string full = String.Format("{0};{1};{2}", tmi.Type.ToString(), tmi.AllocatedMemoryInfo,
tmi.CollectedMemoryInfo);
Console.WriteLine(full);
}
}
Console.WriteLine("-------------------------------------------------------------");
});*/
}
return lastCheckPoint;
}
private Position GetRandomWalkablePosition(RandomNumberGenerator rng, TestGridInfoProvider gip)
{
Position position;
do
{
position = rng.NextPosition(gip.Bounds);
} while (!gip.IsWalkable(position));
return position;
}
}
} | 36.974684 | 151 | 0.689832 | [
"MIT"
] | azsdaja/Osnowa | Osnowa.Tests/Pathfinding/PathfindingLoadTests.cs | 5,856 | C# |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Veldrid.PBR.BinaryData;
namespace Veldrid.PBR
{
public class ContentWriter : IDisposable
{
private const int MaxStructSize = 512;
private readonly Stream _writer;
private readonly bool _disposeWriter;
private byte[] _buffer;
public ContentWriter(Stream stream, bool disposeStream = false)
{
_writer = stream;
_disposeWriter = disposeStream;
_buffer = ArrayPool<byte>.Shared.Rent(MaxStructSize);
if (Position != 0)
throw new NotImplementedException("Stream should be at 0 position.");
}
public int Position => (int) _writer.Position;
public void Write(ContentToWrite content)
{
Write(PbrContent.Magic);
Write(PbrContent.CurrentVersion);
var lumps = new Chunks();
var lumpPos = Position;
Write(ref lumps);
{
// Saving binary blobs and strings
var binaryBlobs = new IndexRange[content.BinaryBlobs.Count];
for (var index = 0; index < content.BinaryBlobs.Count; index++)
{
var contentBinaryBlob = content.BinaryBlobs[index];
binaryBlobs[index] = new IndexRange(Position, contentBinaryBlob.Count);
Write(contentBinaryBlob.Array, contentBinaryBlob.Offset, contentBinaryBlob.Count);
}
lumps.BinaryBlobs.Offset = Position;
lumps.BinaryBlobs.Count = content.BinaryBlobs.Count;
Write(binaryBlobs);
}
{
var strings = new IndexRange[content.Strings.Count];
for (var index = 0; index < content.Strings.Count; index++)
{
var str = content.Strings[index];
var buffer = Encoding.Unicode.GetBytes(str);
strings[index] = new IndexRange(Position, buffer.Length);
Write(buffer, 0, buffer.Length);
}
lumps.Strings.Offset = Position;
lumps.Strings.Count = strings.Length;
Write(strings);
}
lumps.Buffers.Offset = Position;
lumps.Buffers.Count = content.Buffers.Count;
for (var index = 0; index < content.Buffers.Count; index++)
{
var bufferData = content.Buffers[index];
if (bufferData.BlobIndex < 0 || bufferData.BlobIndex >= content.BinaryBlobs.Count)
throw new IndexOutOfRangeException(
$"BlobIndex {bufferData.BlobIndex} doesn't match number of binary blobs {content.BinaryBlobs.Count}.");
Write(bufferData);
}
lumps.Textures.Offset = Position;
lumps.Textures.Count = content.Textures.Count;
for (var index = 0; index < content.Textures.Count; index++)
{
var texture = content.Textures[index];
if (texture.BlobIndex < 0 || texture.BlobIndex >= content.BinaryBlobs.Count)
throw new IndexOutOfRangeException(
$"BlobIndex {texture.BlobIndex} doesn't match number of binary blobs {content.BinaryBlobs.Count}.");
Write(texture);
}
lumps.Samplers.Offset = Position;
lumps.Samplers.Count = content.Samplers.Count;
Write(content.Samplers);
lumps.VertexElements.Offset = Position;
lumps.VertexElements.Count = content.VertexElements.Count;
Write(content.VertexElements);
lumps.BufferViews.Offset = Position;
lumps.BufferViews.Count = content.BufferViews.Count;
Write(content.BufferViews);
lumps.UnlitMaterials.Offset = Position;
lumps.UnlitMaterials.Count = content.UnlitMaterials.Count;
Write(content.UnlitMaterials);
lumps.MetallicRoughnessMaterials.Offset = Position;
lumps.MetallicRoughnessMaterials.Count = content.MetallicRoughnessMaterials.Count;
Write(content.MetallicRoughnessMaterials);
lumps.SpecularGlossinessMaterials.Offset = Position;
lumps.SpecularGlossinessMaterials.Count = content.SpecularGlossinessMaterials.Count;
Write(content.SpecularGlossinessMaterials);
lumps.MaterialBindings.Offset = Position;
lumps.MaterialBindings.Count = content.MaterialBindings.Count;
Write(content.MaterialBindings);
lumps.Primitives.Offset = Position;
lumps.Primitives.Count = content.Primitive.Count;
Write(content.Primitive);
lumps.Meshes.Offset = Position;
lumps.Meshes.Count = content.Mesh.Count;
Write(content.Mesh);
lumps.Nodes.Offset = Position;
lumps.Nodes.Count = content.Node.Count;
Write(content.Node);
_writer.Position = lumpPos;
Write(ref lumps);
}
public void Write(byte[] buffer, int offset, int count)
{
_writer.Write(buffer, offset, count);
}
public void Dispose()
{
if (_disposeWriter)
_writer.Dispose();
ArrayPool<byte>.Shared.Return(_buffer);
}
private void Write(byte[] buffer)
{
_writer.Write(buffer, 0, buffer.Length);
}
private void Write<T>(ref T value) where T : struct
{
var size = Marshal.SizeOf<T>();
if (size > _buffer.Length)
{
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = ArrayPool<byte>.Shared.Rent(size);
}
MemoryMarshal.Write(_buffer.AsSpan(0, size), ref value);
Write(_buffer, 0, size);
}
private void Write<T>(T value) where T : struct
{
Write(ref value);
}
private void Write<T>(T[] value) where T : struct
{
for (var index = 0; index < value.Length; index++) Write(ref value[index]);
}
private void Write<T>(IList<T> value) where T : struct
{
for (var index = 0; index < value.Count; index++) Write(value[index]);
}
}
} | 36.47486 | 127 | 0.570838 | [
"MIT"
] | gleblebedev/Veldrid.PBR | src/Veldrid.PBR/ContentWriter.cs | 6,531 | C# |
using Medic.AppModels.Plannings;
using Medic.EHR.Extracts;
using Medic.EHR.RM.Base;
using Medic.EHRBuilders.Contracts;
using Medic.ModelToEHR.Base;
using System;
using System.Linq;
namespace Medic.ModelToEHR.Helpers
{
internal class PlannedToEHRConverter : ToEHRBaseConverter
{
internal PlannedToEHRConverter(IEHRManager ehrManager)
: base(ehrManager) { }
internal EhrExtract Convert(PlannedViewModel model, string name, string systemId)
{
if (model == default)
{
throw new ArgumentNullException(nameof(model));
}
IEntryBuilder entryPlannedBuilder = EhrManager
.EntryBuilder
.AddItems(
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.PatientBranch)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.PatientBranch).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.PatientHRegion)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.PatientHRegion).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.InType)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue(model.InType).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendDate)).Build())
.AddValue(EhrManager.DATEBuilder.Clear().AddDate(model.SendDate).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendUrgency)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue(model.SendUrgency).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.UniqueIdentifier)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.UniqueIdentifier).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.ExaminationDate)).Build())
.AddValue(EhrManager.DATEBuilder.Clear().AddDate(model.ExaminationDate).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.Urgency)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue(model.Urgency).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.NZOKPay)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue(model.NZOKPay).Build()).Build(),
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.CPFile)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.CPFile).Build()).Build()
);
if (model.PlannedNumber != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.PlannedNumber)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue((int)model.PlannedNumber).Build())
.Build());
}
if (model.SendAPr != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendAPr)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.SendAPr).Build())
.Build());
}
if (model.InAPr != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.InAPr)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.InAPr).Build())
.Build());
}
if (model.PackageType != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.PackageType)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue((int)model.PackageType).Build())
.Build());
}
if (model.SendPackageType != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendPackageType)).Build())
.AddValue(EhrManager.INTBuilder.Clear().AddValue((int)model.SendPackageType).Build())
.Build());
}
if (model.SendClinicalPath != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendClinicalPath)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.SendClinicalPath).Build()).Build());
}
if (model.PlannedEntryDate != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.PlannedEntryDate)).Build())
.AddValue(EhrManager.DATEBuilder.Clear().AddDate((DateTime)model.PlannedEntryDate).Build()).Build());
}
if (model.ClinicalPath != default)
{
entryPlannedBuilder.AddItems(
EhrManager.ElementBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.ClinicalPath)).Build())
.AddValue(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(model.ClinicalPath).Build()).Build());
}
ICompositionBuilder compositionBuilder = EhrManager.CompositionBuilder
.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(name).Build());
Content entryContent = entryPlannedBuilder.Build();
if (model.Patient != default)
{
compositionBuilder.AddContent(
EhrManager.SectionBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.Patient)).Build())
.AddMembers(base.CreatePatientEntry(model.Patient))
.Build());
}
if (model.Sender != default)
{
compositionBuilder.AddContent(
EhrManager.SectionBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.Sender)).Build())
.AddMembers(base.CreatePractitionerEntry(model.Sender))
.Build());
}
if (model.SendDiagnoses != default && model.SendDiagnoses.Count > 0)
{
compositionBuilder.AddContent(
EhrManager.SectionBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.SendDiagnoses)).Build())
.AddMembers(model.SendDiagnoses.Where(sd => sd != default).Select(sd => base.CreateDiagnoseEntry(sd)).ToArray())
.Build());
}
if (model.Diagnoses != default && model.Diagnoses.Count > 0)
{
compositionBuilder.AddContent(
EhrManager.SectionBuilder.Clear()
.AddName(EhrManager.SimpleTextBuilder.Clear().AddOriginalText(nameof(model.Diagnoses)).Build())
.AddMembers(model.Diagnoses.Where(d => d != default).Select(d => base.CreateDiagnoseEntry(d)).ToArray())
.Build());
}
compositionBuilder.AddContent(EhrManager.SectionBuilder.Clear().AddMembers(entryContent).Build());
EhrExtract ehrExtractModel = EhrManager
.EhrExtractModelBuilder
.AddEhrSystem(EhrManager.IIBuilder.Clear().AddRoot(EhrManager.OIDBuilder.Build(systemId)).Build())
.AddSubjectOfCare(EhrManager.IIBuilder.Clear().AddRoot(EhrManager.OIDBuilder.Build(model.Patient.IdentityNumber)).Build())
.AddTimeCreated(EhrManager.TSBuilder.Clear().AddTime(DateTime.Now).Build())
.AddComposition(compositionBuilder.Build())
.Build();
return ehrExtractModel;
}
}
}
| 53.148936 | 138 | 0.579864 | [
"MIT"
] | eeevgeniev/ITSPMedic | src/Medic.ModelToEHR/Helpers/PlannedToEHRConverter.cs | 9,994 | C# |
//
// ProtocolException.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.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;
#if SERIALIZABLE
using System.Security;
using System.Runtime.Serialization;
#endif
namespace MailKit {
/// <summary>
/// The exception that is thrown when there is a protocol error.
/// </summary>
/// <remarks>
/// <para>A <see cref="ProtocolException"/> can be thrown by any of the various client
/// methods in MailKit.</para>
/// <para>Since many protocol exceptions are fatal, it is important to check whether
/// or not the client is still connected using the <see cref="IMailService.IsConnected"/>
/// property when this exception is thrown.</para>
/// </remarks>
#if SERIALIZABLE
[Serializable]
#endif
public abstract class ProtocolException : Exception
{
#if SERIALIZABLE
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.ProtocolException"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="ProtocolException"/>.
/// </remarks>
/// <param name="info">The serialization info.</param>
/// <param name="context">The streaming context.</param>
[SecuritySafeCritical]
protected ProtocolException (SerializationInfo info, StreamingContext context) : base (info, context)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.ProtocolException"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="ProtocolException"/>.
/// </remarks>
/// <param name="message">The error message.</param>
/// <param name="innerException">An inner exception.</param>
protected ProtocolException (string message, Exception innerException) : base (message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.ProtocolException"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="ProtocolException"/>.
/// </remarks>
/// <param name="message">The error message.</param>
protected ProtocolException (string message) : base (message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.ProtocolException"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="ProtocolException"/>.
/// </remarks>
protected ProtocolException ()
{
}
}
}
| 34.867347 | 105 | 0.706175 | [
"MIT"
] | muffadalis/rrod | lib/MailKit/ProtocolException.cs | 3,417 | C# |
namespace P01._DrawingShape_After.Contracts
{
public interface IShape
{
double Area { get; }
}
}
| 14.75 | 44 | 0.627119 | [
"MIT"
] | A-Manev/SoftUni-CSharp-Advanced-january-2020 | CSharp OOP/SOLID - Lab/01. SRP/P01. DrawingShape-After/Contracts/IShape.cs | 120 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.AI.Translation.Document.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.AI.Translation.Document
{
internal partial class DocumentTranslationRestClient
{
private string endpoint;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
/// <summary> Initializes a new instance of DocumentTranslationRestClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="endpoint"> Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). </param>
/// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> is null. </exception>
public DocumentTranslationRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
this.endpoint = endpoint;
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
internal HttpMessage CreateStartTranslationRequest(StartTranslationDetails body)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches", false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(body);
request.Content = content;
return message;
}
/// <summary>
/// Use this API to submit a bulk (batch) translation request to the Document Translation service.
///
/// Each request can contain multiple documents and must contain a source and destination container for each document.
///
///
///
/// The prefix and suffix filter (if supplied) are used to filter folders. The prefix is applied to the subpath after the container name.
///
///
///
/// Glossaries / Translation memory can be included in the request and are applied by the service when the document is translated.
///
///
///
/// If the glossary is invalid or unreachable during translation, an error is indicated in the document status.
///
/// If a file with the same name already exists at the destination, it will be overwritten. The targetUrl for each target language must be unique.
/// </summary>
/// <param name="body"> request details. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="body"/> is null. </exception>
public async Task<ResponseWithHeaders<DocumentTranslationStartTranslationHeaders>> StartTranslationAsync(StartTranslationDetails body, CancellationToken cancellationToken = default)
{
if (body == null)
{
throw new ArgumentNullException(nameof(body));
}
using var message = CreateStartTranslationRequest(body);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationStartTranslationHeaders(message.Response);
switch (message.Response.Status)
{
case 202:
return ResponseWithHeaders.FromValue(headers, message.Response);
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Use this API to submit a bulk (batch) translation request to the Document Translation service.
///
/// Each request can contain multiple documents and must contain a source and destination container for each document.
///
///
///
/// The prefix and suffix filter (if supplied) are used to filter folders. The prefix is applied to the subpath after the container name.
///
///
///
/// Glossaries / Translation memory can be included in the request and are applied by the service when the document is translated.
///
///
///
/// If the glossary is invalid or unreachable during translation, an error is indicated in the document status.
///
/// If a file with the same name already exists at the destination, it will be overwritten. The targetUrl for each target language must be unique.
/// </summary>
/// <param name="body"> request details. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="body"/> is null. </exception>
public ResponseWithHeaders<DocumentTranslationStartTranslationHeaders> StartTranslation(StartTranslationDetails body, CancellationToken cancellationToken = default)
{
if (body == null)
{
throw new ArgumentNullException(nameof(body));
}
using var message = CreateStartTranslationRequest(body);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationStartTranslationHeaders(message.Response);
switch (message.Response.Status)
{
case 202:
return ResponseWithHeaders.FromValue(headers, message.Response);
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetTranslationsStatusRequest(int? top, int? skip, int? maxpagesize, IEnumerable<Guid> ids, IEnumerable<string> statuses, DateTimeOffset? createdDateTimeUtcStart, DateTimeOffset? createdDateTimeUtcEnd, IEnumerable<string> orderBy)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches", false);
if (top != null)
{
uri.AppendQuery("$top", top.Value, true);
}
if (skip != null)
{
uri.AppendQuery("$skip", skip.Value, true);
}
if (maxpagesize != null)
{
uri.AppendQuery("$maxpagesize", maxpagesize.Value, true);
}
if (ids != null)
{
uri.AppendQueryDelimited("ids", ids, ",", true);
}
if (statuses != null)
{
uri.AppendQueryDelimited("statuses", statuses, ",", true);
}
if (createdDateTimeUtcStart != null)
{
uri.AppendQuery("createdDateTimeUtcStart", createdDateTimeUtcStart.Value, "O", true);
}
if (createdDateTimeUtcEnd != null)
{
uri.AppendQuery("createdDateTimeUtcEnd", createdDateTimeUtcEnd.Value, "O", true);
}
if (orderBy != null)
{
uri.AppendQueryDelimited("$orderBy", orderBy, ",", true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Returns a list of batch requests submitted and the status for each request.
///
/// This list only contains batch requests submitted by the user (based on the resource).
///
///
///
/// If the number of requests exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and include a continuation token in the response.
///
/// The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of batches based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled operations.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// The server honors the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token.
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<TranslationsStatus, DocumentTranslationGetTranslationsStatusHeaders>> GetTranslationsStatusAsync(int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
using var message = CreateGetTranslationsStatusRequest(top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetTranslationsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationsStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = TranslationsStatus.DeserializeTranslationsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Returns a list of batch requests submitted and the status for each request.
///
/// This list only contains batch requests submitted by the user (based on the resource).
///
///
///
/// If the number of requests exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and include a continuation token in the response.
///
/// The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of batches based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled operations.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// The server honors the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token.
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<TranslationsStatus, DocumentTranslationGetTranslationsStatusHeaders> GetTranslationsStatus(int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
using var message = CreateGetTranslationsStatusRequest(top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetTranslationsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationsStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = TranslationsStatus.DeserializeTranslationsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetDocumentStatusRequest(Guid id, Guid documentId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches/", false);
uri.AppendPath(id, true);
uri.AppendPath("/documents/", false);
uri.AppendPath(documentId, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Returns the translation status for a specific document based on the request Id and document Id. </summary>
/// <param name="id"> Format - uuid. The batch id. </param>
/// <param name="documentId"> Format - uuid. The document id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<DocumentStatus, DocumentTranslationGetDocumentStatusHeaders>> GetDocumentStatusAsync(Guid id, Guid documentId, CancellationToken cancellationToken = default)
{
using var message = CreateGetDocumentStatusRequest(id, documentId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetDocumentStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = DocumentStatus.DeserializeDocumentStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Returns the translation status for a specific document based on the request Id and document Id. </summary>
/// <param name="id"> Format - uuid. The batch id. </param>
/// <param name="documentId"> Format - uuid. The document id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<DocumentStatus, DocumentTranslationGetDocumentStatusHeaders> GetDocumentStatus(Guid id, Guid documentId, CancellationToken cancellationToken = default)
{
using var message = CreateGetDocumentStatusRequest(id, documentId);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetDocumentStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = DocumentStatus.DeserializeDocumentStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetTranslationStatusRequest(Guid id)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches/", false);
uri.AppendPath(id, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Returns the status for a document translation request.
///
/// The status includes the overall request status, as well as the status for documents that are being translated as part of that request.
/// </summary>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<TranslationStatus, DocumentTranslationGetTranslationStatusHeaders>> GetTranslationStatusAsync(Guid id, CancellationToken cancellationToken = default)
{
using var message = CreateGetTranslationStatusRequest(id);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetTranslationStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = TranslationStatus.DeserializeTranslationStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Returns the status for a document translation request.
///
/// The status includes the overall request status, as well as the status for documents that are being translated as part of that request.
/// </summary>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<TranslationStatus, DocumentTranslationGetTranslationStatusHeaders> GetTranslationStatus(Guid id, CancellationToken cancellationToken = default)
{
using var message = CreateGetTranslationStatusRequest(id);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetTranslationStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = TranslationStatus.DeserializeTranslationStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCancelTranslationRequest(Guid id)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches/", false);
uri.AppendPath(id, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Cancel a currently processing or queued translation.
///
/// Cancel a currently processing or queued translation.
///
/// A translation will not be cancelled if it is already completed or failed or cancelling. A bad request will be returned.
///
/// All documents that have completed translation will not be cancelled and will be charged.
///
/// All pending documents will be cancelled if possible.
/// </summary>
/// <param name="id"> Format - uuid. The operation-id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<TranslationStatus>> CancelTranslationAsync(Guid id, CancellationToken cancellationToken = default)
{
using var message = CreateCancelTranslationRequest(id);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
TranslationStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = TranslationStatus.DeserializeTranslationStatus(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Cancel a currently processing or queued translation.
///
/// Cancel a currently processing or queued translation.
///
/// A translation will not be cancelled if it is already completed or failed or cancelling. A bad request will be returned.
///
/// All documents that have completed translation will not be cancelled and will be charged.
///
/// All pending documents will be cancelled if possible.
/// </summary>
/// <param name="id"> Format - uuid. The operation-id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<TranslationStatus> CancelTranslation(Guid id, CancellationToken cancellationToken = default)
{
using var message = CreateCancelTranslationRequest(id);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
TranslationStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = TranslationStatus.DeserializeTranslationStatus(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetDocumentsStatusRequest(Guid id, int? top, int? skip, int? maxpagesize, IEnumerable<Guid> ids, IEnumerable<string> statuses, DateTimeOffset? createdDateTimeUtcStart, DateTimeOffset? createdDateTimeUtcEnd, IEnumerable<string> orderBy)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/batches/", false);
uri.AppendPath(id, true);
uri.AppendPath("/documents", false);
if (top != null)
{
uri.AppendQuery("$top", top.Value, true);
}
if (skip != null)
{
uri.AppendQuery("$skip", skip.Value, true);
}
if (maxpagesize != null)
{
uri.AppendQuery("$maxpagesize", maxpagesize.Value, true);
}
if (ids != null)
{
uri.AppendQueryDelimited("ids", ids, ",", true);
}
if (statuses != null)
{
uri.AppendQueryDelimited("statuses", statuses, ",", true);
}
if (createdDateTimeUtcStart != null)
{
uri.AppendQuery("createdDateTimeUtcStart", createdDateTimeUtcStart.Value, "O", true);
}
if (createdDateTimeUtcEnd != null)
{
uri.AppendQuery("createdDateTimeUtcEnd", createdDateTimeUtcEnd.Value, "O", true);
}
if (orderBy != null)
{
uri.AppendQueryDelimited("$orderBy", orderBy, ",", true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Returns the status for all documents in a batch document translation request.
///
///
///
/// If the number of documents in the response exceeds our paging limit, server-side paging is used.
///
/// Paginated responses indicate a partial result and include a continuation token in the response. The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of document status held by the server based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled documents.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<DocumentsStatus, DocumentTranslationGetDocumentsStatusHeaders>> GetDocumentsStatusAsync(Guid id, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
using var message = CreateGetDocumentsStatusRequest(id, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetDocumentsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentsStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = DocumentsStatus.DeserializeDocumentsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Returns the status for all documents in a batch document translation request.
///
///
///
/// If the number of documents in the response exceeds our paging limit, server-side paging is used.
///
/// Paginated responses indicate a partial result and include a continuation token in the response. The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of document status held by the server based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled documents.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<DocumentsStatus, DocumentTranslationGetDocumentsStatusHeaders> GetDocumentsStatus(Guid id, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
using var message = CreateGetDocumentsStatusRequest(id, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetDocumentsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentsStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = DocumentsStatus.DeserializeDocumentsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSupportedDocumentFormatsRequest()
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/documents/formats", false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// The list of supported document formats supported by the Document Translation service.
///
/// The list includes the common file extension, as well as the content-type if using the upload API.
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<SupportedFileFormats, DocumentTranslationGetSupportedDocumentFormatsHeaders>> GetSupportedDocumentFormatsAsync(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedDocumentFormatsRequest();
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetSupportedDocumentFormatsHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedFileFormats value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SupportedFileFormats.DeserializeSupportedFileFormats(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// The list of supported document formats supported by the Document Translation service.
///
/// The list includes the common file extension, as well as the content-type if using the upload API.
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<SupportedFileFormats, DocumentTranslationGetSupportedDocumentFormatsHeaders> GetSupportedDocumentFormats(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedDocumentFormatsRequest();
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetSupportedDocumentFormatsHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedFileFormats value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SupportedFileFormats.DeserializeSupportedFileFormats(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSupportedGlossaryFormatsRequest()
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/glossaries/formats", false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// The list of supported glossary formats supported by the Document Translation service.
///
/// The list includes the common file extension used.
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<SupportedFileFormats, DocumentTranslationGetSupportedGlossaryFormatsHeaders>> GetSupportedGlossaryFormatsAsync(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedGlossaryFormatsRequest();
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetSupportedGlossaryFormatsHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedFileFormats value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SupportedFileFormats.DeserializeSupportedFileFormats(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// The list of supported glossary formats supported by the Document Translation service.
///
/// The list includes the common file extension used.
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<SupportedFileFormats, DocumentTranslationGetSupportedGlossaryFormatsHeaders> GetSupportedGlossaryFormats(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedGlossaryFormatsRequest();
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetSupportedGlossaryFormatsHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedFileFormats value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SupportedFileFormats.DeserializeSupportedFileFormats(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSupportedStorageSourcesRequest()
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendPath("/storagesources", false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Returns a list of storage sources/options supported by the Document Translation service. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<ResponseWithHeaders<SupportedStorageSources, DocumentTranslationGetSupportedStorageSourcesHeaders>> GetSupportedStorageSourcesAsync(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedStorageSourcesRequest();
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetSupportedStorageSourcesHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedStorageSources value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SupportedStorageSources.DeserializeSupportedStorageSources(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Returns a list of storage sources/options supported by the Document Translation service. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public ResponseWithHeaders<SupportedStorageSources, DocumentTranslationGetSupportedStorageSourcesHeaders> GetSupportedStorageSources(CancellationToken cancellationToken = default)
{
using var message = CreateGetSupportedStorageSourcesRequest();
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetSupportedStorageSourcesHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
SupportedStorageSources value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SupportedStorageSources.DeserializeSupportedStorageSources(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetTranslationsStatusNextPageRequest(string nextLink, int? top, int? skip, int? maxpagesize, IEnumerable<Guid> ids, IEnumerable<string> statuses, DateTimeOffset? createdDateTimeUtcStart, DateTimeOffset? createdDateTimeUtcEnd, IEnumerable<string> orderBy)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Returns a list of batch requests submitted and the status for each request.
///
/// This list only contains batch requests submitted by the user (based on the resource).
///
///
///
/// If the number of requests exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and include a continuation token in the response.
///
/// The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of batches based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled operations.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// The server honors the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token.
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public async Task<ResponseWithHeaders<TranslationsStatus, DocumentTranslationGetTranslationsStatusHeaders>> GetTranslationsStatusNextPageAsync(string nextLink, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetTranslationsStatusNextPageRequest(nextLink, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetTranslationsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationsStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = TranslationsStatus.DeserializeTranslationsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Returns a list of batch requests submitted and the status for each request.
///
/// This list only contains batch requests submitted by the user (based on the resource).
///
///
///
/// If the number of requests exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and include a continuation token in the response.
///
/// The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of batches based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled operations.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// The server honors the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token.
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public ResponseWithHeaders<TranslationsStatus, DocumentTranslationGetTranslationsStatusHeaders> GetTranslationsStatusNextPage(string nextLink, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetTranslationsStatusNextPageRequest(nextLink, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetTranslationsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
TranslationsStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = TranslationsStatus.DeserializeTranslationsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetDocumentsStatusNextPageRequest(string nextLink, Guid id, int? top, int? skip, int? maxpagesize, IEnumerable<Guid> ids, IEnumerable<string> statuses, DateTimeOffset? createdDateTimeUtcStart, DateTimeOffset? createdDateTimeUtcEnd, IEnumerable<string> orderBy)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRaw("/translator/text/batch/v1.0", false);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary>
/// Returns the status for all documents in a batch document translation request.
///
///
///
/// If the number of documents in the response exceeds our paging limit, server-side paging is used.
///
/// Paginated responses indicate a partial result and include a continuation token in the response. The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of document status held by the server based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled documents.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public async Task<ResponseWithHeaders<DocumentsStatus, DocumentTranslationGetDocumentsStatusHeaders>> GetDocumentsStatusNextPageAsync(string nextLink, Guid id, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetDocumentsStatusNextPageRequest(nextLink, id, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
var headers = new DocumentTranslationGetDocumentsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentsStatus value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = DocumentsStatus.DeserializeDocumentsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary>
/// Returns the status for all documents in a batch document translation request.
///
///
///
/// If the number of documents in the response exceeds our paging limit, server-side paging is used.
///
/// Paginated responses indicate a partial result and include a continuation token in the response. The absence of a continuation token means that no additional pages are available.
///
///
///
/// $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection.
///
///
///
/// $top indicates the total number of records the user wants to be returned across all pages.
///
/// $skip indicates the number of records to skip from the list of document status held by the server based on the sorting method specified. By default, we sort by descending start time.
///
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc").
///
/// The default sorting is descending by createdDateTimeUtc.
///
/// Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled documents.
///
/// createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by.
///
/// The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd).
///
///
///
/// When both $top and $skip are included, the server should first apply $skip and then $top on the collection.
///
/// Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options.
///
/// This reduces the risk of the client making assumptions about the data returned.
/// </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="id"> Format - uuid. The operation id. </param>
/// <param name="top">
/// $top indicates the total number of records the user wants to be returned across all pages.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="skip">
/// $skip indicates the number of records to skip from the list of records held by the server based on the sorting method specified. By default, we sort by descending start time.
///
///
///
/// Clients MAY use $top and $skip query parameters to specify a number of results to return and an offset into the collection.
///
/// When both $top and $skip are given by a client, the server SHOULD first apply $skip and then $top on the collection.
///
///
///
/// Note: If the server can't honor $top and/or $skip, the server MUST return an error to the client informing about it instead of just ignoring the query options.
/// </param>
/// <param name="maxpagesize">
/// $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), @nextLink will contain the link to the next page.
///
///
///
/// Clients MAY request server-driven paging with a specific page size by specifying a $maxpagesize preference. The server SHOULD honor this preference if the specified page size is smaller than the server's default page size.
/// </param>
/// <param name="ids"> Ids to use in filtering. </param>
/// <param name="statuses"> Statuses to use in filtering. </param>
/// <param name="createdDateTimeUtcStart"> the start datetime to get items after. </param>
/// <param name="createdDateTimeUtcEnd"> the end datetime to get items before. </param>
/// <param name="orderBy"> the sorting query for the collection (ex: 'CreatedDateTimeUtc asc', 'CreatedDateTimeUtc desc'). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public ResponseWithHeaders<DocumentsStatus, DocumentTranslationGetDocumentsStatusHeaders> GetDocumentsStatusNextPage(string nextLink, Guid id, int? top = null, int? skip = null, int? maxpagesize = null, IEnumerable<Guid> ids = null, IEnumerable<string> statuses = null, DateTimeOffset? createdDateTimeUtcStart = null, DateTimeOffset? createdDateTimeUtcEnd = null, IEnumerable<string> orderBy = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetDocumentsStatusNextPageRequest(nextLink, id, top, skip, maxpagesize, ids, statuses, createdDateTimeUtcStart, createdDateTimeUtcEnd, orderBy);
_pipeline.Send(message, cancellationToken);
var headers = new DocumentTranslationGetDocumentsStatusHeaders(message.Response);
switch (message.Response.Status)
{
case 200:
{
DocumentsStatus value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = DocumentsStatus.DeserializeDocumentsStatus(document.RootElement);
return ResponseWithHeaders.FromValue(value, headers, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 58.996678 | 471 | 0.631141 | [
"MIT"
] | AzureSDKAutomation/azure-sdk-for-net | sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentTranslationRestClient.cs | 88,790 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* iotcloudgateway实例接口
* iotcloudgateway实例相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Iotcloudgateway.Model;
namespace JDCloudSDK.Iotcloudgateway.Apis
{
/// <summary>
/// 查询iotcloudgateway实例详情
/// </summary>
public class DescribeInstanceResult : JdcloudResult
{
///<summary>
/// 实例相关信息
///</summary>
public Instance Instance{ get; set; }
}
} | 26.152174 | 76 | 0.705736 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Iotcloudgateway/Apis/DescribeInstanceResult.cs | 1,247 | C# |
namespace Rediska.Commands.Keys
{
using System;
using System.Collections.Generic;
using Protocol;
using Protocol.Visitors;
public sealed class PEXPIRE : Command<ExpireResponse>
{
private static readonly PlainBulkString name = new PlainBulkString("PEXPIRE");
private readonly Key key;
private readonly long milliseconds;
// todo milliseconds to semantic struct
public PEXPIRE(Key key, long milliseconds)
{
if (milliseconds < 0)
throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds, "Must be nonnegative");
this.key = key;
this.milliseconds = milliseconds;
}
public override IEnumerable<BulkString> Request(BulkStringFactory factory) => new[]
{
name,
key.ToBulkString(factory),
factory.Create(milliseconds)
};
public override Visitor<ExpireResponse> ResponseStructure => CompositeVisitors.ExpireResult;
}
} | 32.30303 | 114 | 0.625704 | [
"MIT"
] | TwoUnderscorez/Rediska | Rediska/Commands/Keys/PEXPIRE.cs | 1,068 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Balivo.AppCenterClient
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Builds.
/// </summary>
public static partial class BuildsExtensions
{
/// <summary>
/// Public webhook sink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Webhook(this IBuilds operations)
{
operations.WebhookAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Public webhook sink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task WebhookAsync(this IBuilds operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.WebhookWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the Xcode versions available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static IList<XcodeVersion> ListXcodeVersions(this IBuilds operations, string ownerName, string appName)
{
return operations.ListXcodeVersionsAsync(ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the Xcode versions available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<XcodeVersion>> ListXcodeVersionsAsync(this IBuilds operations, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListXcodeVersionsWithHttpMessagesAsync(ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the Xamarin SDK bundles available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static IList<XamarinSDKBundle> ListXamarinSDKBundles(this IBuilds operations, string ownerName, string appName)
{
return operations.ListXamarinSDKBundlesAsync(ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the Xamarin SDK bundles available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<XamarinSDKBundle>> ListXamarinSDKBundlesAsync(this IBuilds operations, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListXamarinSDKBundlesWithHttpMessagesAsync(ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the Mono versions available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static IList<MonoVersion> ListMonoVersions(this IBuilds operations, string ownerName, string appName)
{
return operations.ListMonoVersionsAsync(ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the Mono versions available to this app
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<MonoVersion>> ListMonoVersionsAsync(this IBuilds operations, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListMonoVersionsWithHttpMessagesAsync(ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the build log
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static BuildLog GetLog(this IBuilds operations, int buildId, string ownerName, string appName)
{
return operations.GetLogAsync(buildId, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Get the build log
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BuildLog> GetLogAsync(this IBuilds operations, int buildId, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLogWithHttpMessagesAsync(buildId, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the download URI
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='downloadType'>
/// The download type. Possible values include: 'build', 'symbols', 'logs'
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static DownloadContainer GetDownloadUri(this IBuilds operations, int buildId, string downloadType, string ownerName, string appName)
{
return operations.GetDownloadUriAsync(buildId, downloadType, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the download URI
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='downloadType'>
/// The download type. Possible values include: 'build', 'symbols', 'logs'
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DownloadContainer> GetDownloadUriAsync(this IBuilds operations, int buildId, string downloadType, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDownloadUriWithHttpMessagesAsync(buildId, downloadType, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Distribute a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='distributeInfo'>
/// The distribution details
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static DistributionResponse Distribute(this IBuilds operations, int buildId, DistributionRequest distributeInfo, string ownerName, string appName)
{
return operations.DistributeAsync(buildId, distributeInfo, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Distribute a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='distributeInfo'>
/// The distribution details
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DistributionResponse> DistributeAsync(this IBuilds operations, int buildId, DistributionRequest distributeInfo, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DistributeWithHttpMessagesAsync(buildId, distributeInfo, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the build detail for the given build ID
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static Build Get(this IBuilds operations, int buildId, string ownerName, string appName)
{
return operations.GetAsync(buildId, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the build detail for the given build ID
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Build> GetAsync(this IBuilds operations, int buildId, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(buildId, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Cancels a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='properties'>
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static Build Update(this IBuilds operations, int buildId, BuildPatch properties, string ownerName, string appName)
{
return operations.UpdateAsync(buildId, properties, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Cancels a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='buildId'>
/// The build ID
/// </param>
/// <param name='properties'>
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Build> UpdateAsync(this IBuilds operations, int buildId, BuildPatch properties, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(buildId, properties, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Application specific build service status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static BuildServiceStatus GetStatusByAppId(this IBuilds operations, string ownerName, string appName)
{
return operations.GetStatusByAppIdAsync(ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Application specific build service status
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BuildServiceStatus> GetStatusByAppIdAsync(this IBuilds operations, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatusByAppIdWithHttpMessagesAsync(ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the projects in the repository for the branch, for all toolsets
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='os'>
/// The desired OS for the project scan; normally the same as the app OS.
/// Possible values include: 'iOS', 'Android', 'Windows', 'macOS'
/// </param>
/// <param name='platform'>
/// The desired platform for the project scan. Possible values include:
/// 'Objective-C-Swift', 'React-Native', 'Xamarin', 'Java', 'UWP'
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static ToolsetProjects ListToolsetProjects(this IBuilds operations, string branch, string os, string platform, string ownerName, string appName)
{
return operations.ListToolsetProjectsAsync(branch, os, platform, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the projects in the repository for the branch, for all toolsets
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='os'>
/// The desired OS for the project scan; normally the same as the app OS.
/// Possible values include: 'iOS', 'Android', 'Windows', 'macOS'
/// </param>
/// <param name='platform'>
/// The desired platform for the project scan. Possible values include:
/// 'Objective-C-Swift', 'React-Native', 'Xamarin', 'Java', 'UWP'
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ToolsetProjects> ListToolsetProjectsAsync(this IBuilds operations, string branch, string os, string platform, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListToolsetProjectsWithHttpMessagesAsync(branch, os, platform, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the list of builds for the branch
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static IList<Build> ListByBranch(this IBuilds operations, string branch, string ownerName, string appName)
{
return operations.ListByBranchAsync(branch, ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the list of builds for the branch
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Build>> ListByBranchAsync(this IBuilds operations, string branch, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByBranchWithHttpMessagesAsync(branch, ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='paramsParameter'>
/// Parameters of the build
/// </param>
public static Build Create(this IBuilds operations, string branch, string ownerName, string appName, BuildParams paramsParameter = default(BuildParams))
{
return operations.CreateAsync(branch, ownerName, appName, paramsParameter).GetAwaiter().GetResult();
}
/// <summary>
/// Create a build
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='branch'>
/// The branch name
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='paramsParameter'>
/// Parameters of the build
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Build> CreateAsync(this IBuilds operations, string branch, string ownerName, string appName, BuildParams paramsParameter = default(BuildParams), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(branch, ownerName, appName, paramsParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the list of Git branches for this application
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
public static IList<BranchStatus> ListBranches(this IBuilds operations, string ownerName, string appName)
{
return operations.ListBranchesAsync(ownerName, appName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the list of Git branches for this application
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='ownerName'>
/// The name of the owner
/// </param>
/// <param name='appName'>
/// The name of the application
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<BranchStatus>> ListBranchesAsync(this IBuilds operations, string ownerName, string appName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBranchesWithHttpMessagesAsync(ownerName, appName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 42.721286 | 248 | 0.51812 | [
"MIT"
] | balivo/appcenter-openapi-sdk | generated/BuildsExtensions.cs | 27,897 | C# |
//-------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
// </copyright>
//
// <summary>
//
//
//
// </summary>
//-------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Routing;
using FUSE.Paxos;
using FUSE.Paxos.Azure;
using FUSE.Paxos.Esent;
using FUSE.Weld.Azure;
using FUSE.Weld.Base;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using SignalR.Hubs;
using ReverseProxy.Hubs;
using System.Security.Cryptography.X509Certificates;
namespace ReverseProxy
{
public class ProxyStateMachine : AdaptiveStateMachine<SerialilzableWebRequest, HttpStatusCode>
{
Dictionary<Guid, TaskCompletionSource<HttpWebResponse>> completions = new Dictionary<Guid, TaskCompletionSource<HttpWebResponse>>();
public Func<SerialilzableWebRequest, Task<HttpWebResponse>> GetResponse { get; set; }
public string ServiceName { get; private set; }
CloudStorageAccount cloudStorageAccount;
public ProxyStateMachine(string self, IDictionary<string, Uri> endpoints, ISubject<Tuple<Uri, Message>> mesh, IStorage<string, SerialilzableWebRequest> storage, string serviceName, IEnumerable<string> preferedLeaders)
: base(self, endpoints, mesh, storage, preferedLeaders)
{
this.ServiceName = serviceName;
this.cloudStorageAccount = Utility.GetStorageAccount(true);
}
public Task<HttpWebResponse> SubmitAsync(SerialilzableWebRequest r)
{
var proposal = new Proposal<string, SerialilzableWebRequest>(r);
var tcs = new TaskCompletionSource<HttpWebResponse>();
completions.Add(proposal.guid, tcs);
return this.ReplicateAsync(proposal, CancellationToken.None).ContinueWith(ant => { ant.Wait(); return tcs.Task; }).Unwrap();
}
public override Task<HttpStatusCode> ExecuteAsync(int instance, Proposal<string, SerialilzableWebRequest> command)
{
return Concurrency.Iterate<HttpStatusCode>(tcs => _executeAsync(tcs, instance, command));
}
private IEnumerable<Task> _executeAsync(TaskCompletionSource<HttpStatusCode> tcs, int instance, Proposal<string, SerialilzableWebRequest> proposal)
{
Action<string> trace = s => FUSE.Paxos.Events.TraceInfo(s, proposal.guid, _paxos.Self, instance, proposal.value.Headers["x-ms-client-request-id"] ?? "");
trace("ExecuteAsync Enter");
var getResponseTask = Concurrency.RetryOnFaultOrCanceledAsync<HttpWebResponse>(() => GetResponse(proposal.value), t => ShouldRetryGetResponse(t, instance, proposal.guid), 1000);
yield return getResponseTask;
trace("ExecuteAsync ResponseReceived");
if (!proposal.value.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
{
var logTask = Concurrency.RetryOnFaultOrCanceledAsync(() => LogResultAsync(instance), _ => true, 1000);
yield return logTask;
try
{
logTask.Wait();
trace("ExecuteAsync Logged");
}
catch (Exception e)
{
Validation.TraceException(e, "Exception incrementing LSN");
}
}
TaskCompletionSource<HttpWebResponse> completion;
if (completions.TryGetValue(proposal.guid, out completion))
{
completion.SetFromTask(getResponseTask);
completions.Remove(proposal.guid);
}
tcs.SetResult(GetStatusCode(getResponseTask));
trace("ExecuteAsync Exit");
}
static HttpStatusCode GetStatusCode(Task<HttpWebResponse> task)
{
if (task.IsFaulted)
{
return Validation.HttpStatusCodes(task.Exception).Single();
}
else
{
return task.Result.StatusCode;
}
}
static IList<HttpStatusCode> RetryableHttpStatusCodes = new List<HttpStatusCode> {
HttpStatusCode.RequestTimeout,
HttpStatusCode.InternalServerError,
HttpStatusCode.ServiceUnavailable,
HttpStatusCode.GatewayTimeout
};
private bool ShouldRetryGetResponse(Task<HttpWebResponse> task, int instance, Guid guid)
{
if (ShouldRetryGetResponse(task))
{
FUSE.Paxos.Events.TraceInfo("ExecuteAsync Retry", guid, _paxos.Self, instance);
return true;
}
else
{
return false;
}
}
private bool ShouldRetryGetResponse(Task<HttpWebResponse> task)
{
if (task.IsCanceled)
{
return true;
}
else if (task.IsFaulted)
{
var httpStatusCodes = Validation.HttpStatusCodes(task.Exception).ToArray();
if (httpStatusCodes.Length == 1)
{
var httpStatusCode = httpStatusCodes[0];
if (RetryableHttpStatusCodes.Contains(httpStatusCode))
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
throw new ArgumentException("Task must be in faulted or canceled state");
}
}
private Task LogResultAsync(int instance)
{
return Task.Factory.Iterate(_logOperation(instance));
}
private IEnumerable<Task> _logOperation(int instance)
{
var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("root");
var blob = container.GetBlobReference(ServiceName + "LogPosition");
while (true)
{
using (var task = blob.UploadTextAsync((instance + 1).ToString()))
{
yield return task;
if (task.Status == TaskStatus.RanToCompletion)
{
break;
}
else
{
Trace.Write("LogPositionUpload " + task.Exception.ToString());
yield return Task.Factory.StartNewDelayed(30 * 1000);
continue;
}
}
}
}
public static ProxyStateMachine New(string location, string serviceName)
{
ProxyStateMachine stateMachine;
var nodeConfig = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".Nodes");
var nodeDescriptors = nodeConfig.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var nodes = new Dictionary<string, Uri>();
foreach (var d in nodeDescriptors)
{
var n = d.Split('=');
try
{
nodes.Add(n[0], new UriBuilder() { Host = n[1] }.Uri);
}
catch (Exception x)
{
Trace.TraceError(x.ToString());
}
}
Uri host;
if (nodes.TryGetValue(location, out host))
{
var preferedLeaders = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".PreferedActiveMembers").Split(';');
var localStorage = RoleEnvironment.GetLocalResource("LocalStorage").RootPath;
var storagePath = Path.Combine(localStorage, serviceName);
if (!Directory.Exists(storagePath))
{
Directory.CreateDirectory(storagePath);
}
var storage = new EsentStorage<string, SerialilzableWebRequest>(storagePath, new Counters(location));
var configuration = new Configuration<string>(preferedLeaders, preferedLeaders, nodes.Keys);
storage.TryInitialize(configuration);
Trace.WriteLine("Local Storage Initialized");
var meshPath = serviceName + "Mesh.ashx";
var uri = new UriBuilder(host) { Path = meshPath }.Uri;
X509Certificate2 cert = Utility.GetCert();
var mesh = new MeshHandler<Message>(uri, null, cert);
RouteTable.Routes.Add(new Route(meshPath, new FuncRouteHandler(_ => mesh)));
FUSE.Weld.Azure.Configuration.SetConfigurationSettingPublisher();
var s2 = Utility.GetStorageAccount(true);
var container = s2.CreateCloudBlobClient().GetContainerReference("root");
container.CreateIfNotExist();
Trace.Write("Remote Storage Loaded");
stateMachine = new ProxyStateMachine(location, nodes, mesh, storage, serviceName, preferedLeaders);
stateMachine.Paxos.WhenDiverged.Subscribe(d =>
{
Utility.DisableService(stateMachine.ServiceName);
});
Global.lastMessages[serviceName] = new Queue<Timestamped<Tuple<string, Message, string>>>();
Global.stateMachines[serviceName] = stateMachine;
var o = stateMachine.Mesh
.Where(m => Interesting(m.Item2))
.Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1))
.Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "To"))
.Timestamp();
var i = mesh
.Where(m => Interesting(m.Item2))
.Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1))
.Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "From"))
.Timestamp();
i
.Merge(o)
.Subscribe(m =>
{
try
{
lock (Global.lastMessages)
{
var lastMessages = Global.lastMessages[serviceName];
lastMessages.Enqueue(m);
while (lastMessages.Count > 1000)
{
lastMessages.Dequeue();
}
}
}
catch
{
}
});
var enabled = false;
var enabledState = container.GetBlobReference(serviceName + "EnabledState.txt");
try
{
enabled = Boolean.Parse(enabledState.DownloadText());
}
catch
{
}
mesh.enabled = enabled;
return stateMachine;
}
else
{
throw new ArgumentException("Location not found");
}
}
static string GetConfigurationSettingValueIfPresent(string setting)
{
try
{
return RoleEnvironment.GetConfigurationSettingValue(setting);
}
catch (RoleEnvironmentException)
{
return null;
}
}
static bool Interesting(Message m)
{
if (m is Message.Gossip)
{
return false;
}
if (m is Message.Query)
{
return false;
}
if (m is Message.Initiate<string, SerialilzableWebRequest>)
{
return false;
}
if (m is Message.RejectionHint<string>)
{
return false;
}
var p = m as Message.Propose<string, SerialilzableWebRequest>;
if (p != null)
{
return p.proposal is ProposalConfiguration<string>;
}
var a = m as Message.Accepted<string, SerialilzableWebRequest>;
if (a != null)
{
return a.proposal is ProposalConfiguration<string>;
}
var l = m as Message.Learn<string, SerialilzableWebRequest>;
if (l != null)
{
return l.proposal is ProposalConfiguration<string>;
}
return true;
}
}
} | 37.281915 | 225 | 0.53467 | [
"Apache-2.0"
] | AzureAD/availability-proxy-for-rest-services | Proxy/ProxyStateMachine.cs | 14,018 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.