content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Volo.SqliteDemo.Configuration;
using Volo.SqliteDemo.Web;
namespace Volo.SqliteDemo.EntityFrameworkCore
{
/* This class is needed to run "dotnet ef ..." commands from command line on development. Not used anywhere else */
public class SqliteDemoDbContextFactory : IDesignTimeDbContextFactory<SqliteDemoDbContext>
{
public SqliteDemoDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<SqliteDemoDbContext>();
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
SqliteDemoDbContextConfigurer.Configure(builder, configuration.GetConnectionString(SqliteDemoConsts.ConnectionStringName));
return new SqliteDemoDbContext(builder.Options);
}
}
}
| 40.869565 | 135 | 0.765957 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | SqliteDemo/aspnet-core/src/Volo.SqliteDemo.EntityFrameworkCore/EntityFrameworkCore/SqliteDemoDbContextFactory.cs | 942 | C# |
using SqlSugar;
namespace NQI_LIMS.IRepository.UnitOfWork
{
public interface IUnitOfWork
{
SqlSugarClient GetDbClient();
void BeginTran();
void CommitTran();
void RollbackTran();
}
}
| 15.4 | 41 | 0.627706 | [
"Apache-2.0"
] | gaiwenlin/nqilims | NQI_LIMS.IRepository/UnitOfWork/IUnitOfWork.cs | 233 | C# |
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
using Microsoft.IdentityModel.Tokens;
namespace MaskinportenTokenGenerator
{
public class TokenHandler
{
private readonly string _issuer;
private readonly string _audience;
private readonly string _resource;
private readonly string _scopes;
private readonly string _tokenEndpoint;
private readonly int _tokenTtl;
private readonly X509Certificate2 _signingCertificate;
private readonly string _kidClaim;
private readonly string _consumerOrg;
public string LastTokenRequest { get; private set; }
public Exception LastException { get; private set; }
public string CurlDebugCommand { get; private set; }
public TokenHandler(string certificateThumbprint, string kidClaim, string tokenEndpoint, string audience, string resource,
string scopes, string issuer, int tokenTtl, string consumerOrg)
{
_signingCertificate = GetCertificateFromKeyStore(certificateThumbprint, StoreName.My, StoreLocation.LocalMachine);
_kidClaim = kidClaim;
_tokenEndpoint = tokenEndpoint;
_audience = audience;
_resource = resource;
_scopes = scopes;
_issuer = issuer;
_tokenTtl = tokenTtl;
_consumerOrg = consumerOrg;
}
public TokenHandler(string p12KeyStoreFile, string p12KeyStorePassword, string kidClaim, string tokenEndpoint, string audience, string resource,
string scopes, string issuer, int tokenTtl, string consumerOrg)
{
_signingCertificate = new X509Certificate2();
_signingCertificate.Import(File.ReadAllBytes(p12KeyStoreFile), p12KeyStorePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
_kidClaim = kidClaim;
_tokenEndpoint = tokenEndpoint;
_audience = audience;
_resource = resource;
_scopes = scopes;
_issuer = issuer;
_tokenTtl = tokenTtl;
_consumerOrg = consumerOrg;
}
public string GetTokenFromAuthCodeGrant(string assertion, string code, string clientId, string redirectUri, out bool isError)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var formContent = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
// FIXME! This somehow breaks with an error claiming that the redirectUri does not match
//new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new KeyValuePair<string, string>("client_assertion", assertion),
});
LastTokenRequest = formContent.ReadAsStringAsync().Result;
return SendTokenRequest(formContent, out isError);
}
public string GetTokenFromJwtBearerGrant(string assertion, out bool isError)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var formContent = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
new KeyValuePair<string, string>("assertion", assertion),
});
LastTokenRequest = formContent.ReadAsStringAsync().Result;
return SendTokenRequest(formContent, out isError);
}
public static void PrettyPrintException(Exception e)
{
Console.WriteLine("############");
Console.WriteLine("Failed request to token endpoint, Exception thrown: " + e.GetType().FullName);
Console.WriteLine("Message:" + e.Message);
Console.WriteLine("Stack trace:");
Console.WriteLine(e.StackTrace);
while (e.InnerException != null)
{
Console.WriteLine("Inner Exception:" + e.InnerException.GetType().FullName);
Console.WriteLine("Message:" + e.InnerException.Message);
Console.WriteLine("Stack trace:");
Console.WriteLine(e.InnerException.StackTrace);
e = e.InnerException;
}
Console.WriteLine("############");
}
public string GetJwtAssertion()
{
var dateTimeOffset = new DateTimeOffset(DateTime.UtcNow);
var securityKey = new X509SecurityKey(_signingCertificate);
var header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256))
{
{"x5c", new List<string>() {Convert.ToBase64String(_signingCertificate.GetRawCertData())}}
};
header.Remove("typ");
// kid claim by default is set to x5t (certificate thumbprint). This can only be supplied if
// the client is configured with a custom public key, and must be removed if signing the assertion
// with a enterprise certificate. For convenience, the magic value "thumbprint" allows the
// kid to stay the same as certificate thumbprint
if (_kidClaim != null && _kidClaim != "thumbprint")
{
header.Remove("kid");
header.Add("kid", _kidClaim);
}
else if (_kidClaim == null)
{
header.Remove("kid");
}
var payload = new JwtPayload
{
{ "aud", _audience },
{ "resource", _resource },
{ "scope", _scopes },
{ "iss", _issuer },
{ "exp", dateTimeOffset.ToUnixTimeSeconds() + _tokenTtl },
{ "iat", dateTimeOffset.ToUnixTimeSeconds() },
{ "jti", Guid.NewGuid().ToString() },
};
if (_consumerOrg != null) {
payload.Add("consumer_org", _consumerOrg);
}
var securityToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(securityToken);
}
private string SendTokenRequest(FormUrlEncodedContent formContent, out bool isError)
{
var client = new HttpClient();
CurlDebugCommand = "curl -v -X POST -d '" + formContent.ReadAsStringAsync().Result + "' " + _tokenEndpoint;
try {
var response = client.PostAsync(_tokenEndpoint, formContent).Result;
isError = !response.IsSuccessStatusCode;
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
LastException = e;
isError = true;
PrettyPrintException(e);
return null;
}
}
private static X509Certificate2 GetCertificateFromKeyStore(string thumbprint, StoreName storeName, StoreLocation storeLocation, bool onlyValid = false)
{
var store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, onlyValid);
var enumerator = certCollection.GetEnumerator();
X509Certificate2 cert = null;
while (enumerator.MoveNext())
{
cert = enumerator.Current;
}
if (cert == null)
{
throw new ArgumentException("Unable to find certificate in store with thumbprint: " + thumbprint + ". Check your config, and make sure the certificate is installed in the \"LocalMachine\\My\" store.");
}
return cert;
}
}
}
| 42.522613 | 217 | 0.609667 | [
"MIT"
] | Altinn/MaskinportenTokenGenerator | src/MaskinportenTokenGenerator/TokenHandler.cs | 8,464 | C# |
using System;
using System.Collections.Generic;
/*
|| AUTHOR Arsium ||
|| github : https://github.com/arsium ||
*/
namespace PacketLib.Packet
{
[Serializable]
public class KeywordsPacket : IPacket
{
//server
public KeywordsPacket() : base()
{
packetType = PacketType.RECOVERY_KEYWORDS;
}
//client
public KeywordsPacket(List<object[]> keywords, string baseIp, string HWID) : base()
{
packetType = PacketType.RECOVERY_KEYWORDS;
this.baseIp = baseIp;
this.HWID = HWID;
this.keywordsList = keywords;
}
public string HWID { get; set; }
public string baseIp { get; set; }
public byte[] plugin { get; set; }
public PacketType packetType { get; }
public PacketState packetState { get; set; }
public string status { get; set; }
public string datePacketStatus { get; set; }
public List<object[]> keywordsList { get; set; }
}
}
| 25.243902 | 91 | 0.574879 | [
"MIT"
] | arsium/EagleMonitorRAT | Remote Access Tool/PacketLib/Packet/KeywordsPacket.cs | 1,037 | C# |
namespace WorldHeightmap.Client.Popups
{
partial class SaveDataForm
{
/// <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.saveConfirm = new System.Windows.Forms.Button();
this.includeData = new System.Windows.Forms.CheckBox();
this.heightmapName = new System.Windows.Forms.TextBox();
this.heighmapNameLabel = new System.Windows.Forms.Label();
this.saveElevation = new System.Windows.Forms.CheckBox();
this.elevationDatasetName = new System.Windows.Forms.TextBox();
this.elevationDatasetNameLabel = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// saveConfirm
//
this.saveConfirm.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.saveConfirm.DialogResult = System.Windows.Forms.DialogResult.OK;
this.saveConfirm.Location = new System.Drawing.Point(99, 145);
this.saveConfirm.Name = "saveConfirm";
this.saveConfirm.Size = new System.Drawing.Size(236, 32);
this.saveConfirm.TabIndex = 0;
this.saveConfirm.Text = "Save";
this.saveConfirm.UseVisualStyleBackColor = true;
this.saveConfirm.Click += new System.EventHandler(this.SaveConfirm_Click);
//
// includeData
//
this.includeData.AutoSize = true;
this.includeData.Location = new System.Drawing.Point(12, 60);
this.includeData.Name = "includeData";
this.includeData.Size = new System.Drawing.Size(121, 19);
this.includeData.TabIndex = 1;
this.includeData.Text = "Include Extra Data";
this.includeData.UseVisualStyleBackColor = true;
//
// heightmapName
//
this.heightmapName.Location = new System.Drawing.Point(12, 31);
this.heightmapName.Name = "heightmapName";
this.heightmapName.Size = new System.Drawing.Size(323, 23);
this.heightmapName.TabIndex = 2;
this.heightmapName.TextChanged += new System.EventHandler(this.HeightmapName_TextChanged);
//
// heighmapNameLabel
//
this.heighmapNameLabel.AutoSize = true;
this.heighmapNameLabel.Location = new System.Drawing.Point(13, 13);
this.heighmapNameLabel.Name = "heighmapNameLabel";
this.heighmapNameLabel.Size = new System.Drawing.Size(102, 15);
this.heighmapNameLabel.TabIndex = 3;
this.heighmapNameLabel.Text = "Heightmap Name";
//
// saveElevation
//
this.saveElevation.AutoSize = true;
this.saveElevation.Location = new System.Drawing.Point(12, 85);
this.saveElevation.Name = "saveElevation";
this.saveElevation.Size = new System.Drawing.Size(143, 19);
this.saveElevation.TabIndex = 4;
this.saveElevation.Text = "Save Elevation Dataset";
this.saveElevation.UseVisualStyleBackColor = true;
this.saveElevation.CheckedChanged += new System.EventHandler(this.SaveElevation_CheckedChanged);
//
// elevationDatasetName
//
this.elevationDatasetName.Enabled = false;
this.elevationDatasetName.Location = new System.Drawing.Point(154, 110);
this.elevationDatasetName.Name = "elevationDatasetName";
this.elevationDatasetName.Size = new System.Drawing.Size(181, 23);
this.elevationDatasetName.TabIndex = 5;
//
// elevationDatasetNameLabel
//
this.elevationDatasetNameLabel.AutoSize = true;
this.elevationDatasetNameLabel.Location = new System.Drawing.Point(13, 113);
this.elevationDatasetNameLabel.Name = "elevationDatasetNameLabel";
this.elevationDatasetNameLabel.Size = new System.Drawing.Size(135, 15);
this.elevationDatasetNameLabel.TabIndex = 6;
this.elevationDatasetNameLabel.Text = "Elevation Dataset Name:";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button1.DialogResult = System.Windows.Forms.DialogResult.Abort;
this.button1.Location = new System.Drawing.Point(12, 145);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(78, 32);
this.button1.TabIndex = 7;
this.button1.Text = "Cancel";
this.button1.UseVisualStyleBackColor = true;
//
// SaveDataForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(347, 189);
this.Controls.Add(this.button1);
this.Controls.Add(this.elevationDatasetNameLabel);
this.Controls.Add(this.elevationDatasetName);
this.Controls.Add(this.saveElevation);
this.Controls.Add(this.heighmapNameLabel);
this.Controls.Add(this.heightmapName);
this.Controls.Add(this.includeData);
this.Controls.Add(this.saveConfirm);
this.Name = "SaveDataForm";
this.Text = "Save Heightmap Options";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button saveConfirm;
private System.Windows.Forms.CheckBox includeData;
private System.Windows.Forms.TextBox heightmapName;
private System.Windows.Forms.Label heighmapNameLabel;
private System.Windows.Forms.CheckBox saveElevation;
private System.Windows.Forms.TextBox elevationDatasetName;
private System.Windows.Forms.Label elevationDatasetNameLabel;
private System.Windows.Forms.Button button1;
}
} | 47.196078 | 160 | 0.613627 | [
"MIT"
] | Soyvolon/WorldHeightmapForFAF | WorldHeightmap.Client/Popups/SaveDataForm.Designer.cs | 7,223 | C# |
using System.Web.Mvc;
namespace YiHan.Cms.Web.Areas.Mpa
{
public class MpaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Mpa";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Mpa_default",
"Mpa/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | 24.125 | 89 | 0.497409 | [
"MIT"
] | Letheloney/YiHanCms | src/YiHan.Cms.Web/Areas/Mpa/MpaAreaRegistration.cs | 581 | 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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class ExplicitInterfaceMemberCompletionProvider : CommonCompletionProvider
{
private const string InsertionTextOnOpenParen = nameof(InsertionTextOnOpenParen);
private static readonly SymbolDisplayFormat s_signatureDisplayFormat =
new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return text[characterPosition] == '.';
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
var document = context.Document;
var position = context.Position;
var options = context.Options;
var cancellationToken = context.CancellationToken;
var span = new TextSpan(position, length: 0);
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var syntaxTree = semanticModel.SyntaxTree;
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) ||
semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken))
{
return;
}
if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken))
{
return;
}
var node = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
.GetPreviousTokenIfTouchingWord(position)
.Parent;
if (node.Kind() != SyntaxKind.ExplicitInterfaceSpecifier)
{
return;
}
// Bind the interface name which is to the left of the dot
var name = ((ExplicitInterfaceSpecifierSyntax)node).Name;
var symbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol as ITypeSymbol;
if (symbol?.TypeKind != TypeKind.Interface)
{
return;
}
var members = semanticModel.LookupSymbols(
position: name.SpanStart,
container: symbol)
.WhereAsArray(s => !s.IsStatic)
.FilterToVisibleAndBrowsableSymbols(options.GetOption(CompletionOptions.HideAdvancedMembers, semanticModel.Language), semanticModel.Compilation);
// We're going to create a entry for each one, including the signature
var namePosition = name.SpanStart;
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
foreach (var member in members)
{
var displayText = member.ToMinimalDisplayString(
semanticModel, namePosition, s_signatureDisplayFormat);
var insertionText = displayText;
var item = SymbolCompletionItem.CreateWithSymbolId(
displayText,
insertionText: insertionText,
symbols: ImmutableArray.Create(member),
contextPosition: position,
rules: CompletionItemRules.Default);
item = item.AddProperty(InsertionTextOnOpenParen, member.Name);
context.AddItem(item);
}
}
protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
=> SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
public override Task<TextChange?> GetTextChangeAsync(
Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken)
{
if (ch == '(')
{
if (selectedItem.Properties.TryGetValue(InsertionTextOnOpenParen, out var insertionText))
{
return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, insertionText));
}
}
return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, selectedItem.DisplayText));
}
}
} | 44.421875 | 165 | 0.651952 | [
"Apache-2.0"
] | Trieste-040/https-github.com-dotnet-roslyn | src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProvider.cs | 5,686 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("FigmaSharp.Graphics.Cocoa")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 37.37037 | 82 | 0.745292 | [
"MIT"
] | Youssef1313/FigmaSharp | FigmaSharp.Views.Graphics/FigmaSharp.Graphics.Cocoa/Properties/AssemblyInfo.cs | 1,011 | C# |
using System.Collections.Generic;
#if !NETSTANDARD2_1
using System.Runtime.Serialization;
#else
using System.Text.Json.Serialization;
#endif
namespace Docker.DotNet.Models
{
#if !NETSTANDARD2_1
[DataContract]
#endif
public class PluginConfigLinux // (types.PluginConfigLinux)
{
#if NETSTANDARD2_1
[JsonPropertyName("AllowAllDevices")]
#else
[DataMember(Name = "AllowAllDevices", EmitDefaultValue = false)]
#endif
public bool AllowAllDevices { get; set; }
#if NETSTANDARD2_1
[JsonPropertyName("Capabilities")]
#else
[DataMember(Name = "Capabilities", EmitDefaultValue = false)]
#endif
public IList<string> Capabilities { get; set; }
#if NETSTANDARD2_1
[JsonPropertyName("Devices")]
#else
[DataMember(Name = "Devices", EmitDefaultValue = false)]
#endif
public IList<PluginDevice> Devices { get; set; }
}
}
| 24.189189 | 72 | 0.698324 | [
"Apache-2.0"
] | ewisted/Docker.DotNet | src/Docker.DotNet/Models/PluginConfigLinux.Generated.cs | 895 | C# |
/* ========================================================================
* Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* 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.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System.Runtime.Serialization;
using System.IO;
namespace Opc.Ua.Configuration
{
/// <summary>
/// Specifies how to configure an application during installation.
/// </summary>
public partial class InstalledApplication
{
#region Public Methods
/// <summary>
/// Loads the application configuration from a configuration section.
/// </summary>
public static InstalledApplicationCollection Load(string filePath)
{
FileInfo file = new FileInfo(filePath);
// look in current directory.
if (!file.Exists)
{
file = new FileInfo(Utils.Format("{0}{1}{2}", Directory.GetCurrentDirectory(), Path.DirectorySeparatorChar, filePath));
}
// look in executable directory.
if (!file.Exists)
{
file = new FileInfo(Utils.GetAbsoluteFilePath(filePath));
}
// file not found.
if (!file.Exists)
{
throw ServiceResultException.Create(
StatusCodes.BadConfigurationError,
"File does not exist: {0}\r\nCurrent directory is: {1}",
filePath,
Directory.GetCurrentDirectory());
}
return Load(file);
}
/// <summary>
/// Loads a collection of security applications.
/// </summary>
public static InstalledApplicationCollection Load(FileInfo file)
{
FileStream reader = file.Open(FileMode.Open, FileAccess.Read);
try
{
DataContractSerializer serializer = new DataContractSerializer(typeof(InstalledApplicationCollection));
return serializer.ReadObject(reader) as InstalledApplicationCollection;
}
finally
{
reader.Dispose();
}
}
#endregion
}
}
| 36.946237 | 135 | 0.603318 | [
"MIT"
] | Hpshboss/OpcuaCncControl | UANETStandardCNC/SampleApplications/SDK/Opc.Ua.Configuration/Schema/InstalledApplicationHelper.cs | 3,436 | C# |
using IdentityServer4;
using IdentityServer4.Models;
using System.Collections.Generic;
namespace Microsoft.eShopOnContainers.Services.Identity.API.Configuration
{
public class Config
{
// ApiResources define the apis in your system
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("orders", "Orders Service"),
new ApiResource("basket", "Basket Service"),
new ApiResource("mobileshoppingagg", "Mobile Shopping Aggregator"),
new ApiResource("webshoppingagg", "Web Shopping Aggregator"),
new ApiResource("orders.signalrhub", "Ordering Signalr Hub"),
new ApiResource("webhooks", "Webhooks registration Service"),
};
}
// Identity resources are data like user ID, name, or email address of a user
// see: http://docs.identityserver.io/en/release/configuration/resources.html
public static IEnumerable<IdentityResource> GetResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
// client want to access resources (aka scopes)
public static IEnumerable<Client> GetClients(Dictionary<string, string> clientsUrl)
{
return new List<Client>
{
// JavaScript Client
new Client
{
ClientId = "js",
ClientName = "eShop SPA OpenId Client",
AllowedGrantTypes = GrantTypes.Implicit,
// NOTE_JBOY: to allow to pass tokens via browser URL (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["Spa"]}/" },
// NOTE_JBOY: Consent screen is only needed if there is a thrid party client app that wants to authenticate with us (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
// If you are the one creating the client and you know all the information you will grab, you will NOT need a consent screen.
RequireConsent = false,
PostLogoutRedirectUris = { $"{clientsUrl["Spa"]}/" },
// NOTE_JBOY: Because people are going from different domains to authenticate, you need to specify CORS origins.
// We are basically saying "we are expecting authentication from this guy, and then this is something we can validate " (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
AllowedCorsOrigins = { $"{clientsUrl["Spa"]}" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"orders",
"basket",
"webshoppingagg",
"orders.signalrhub",
"webhooks"
},
},
new Client
{
ClientId = "xamarin",
ClientName = "eShop Xamarin OpenId Client",
AllowedGrantTypes = GrantTypes.Hybrid,
//Used to retrieve the access token on the back channel.
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { clientsUrl["Xamarin"] },
RequireConsent = false,
// NOTE_JBOY: to allow code flow through the browser (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
RequirePkce = true,
PostLogoutRedirectUris = { $"{clientsUrl["Xamarin"]}/Account/Redirecting" },
//AllowedCorsOrigins = { "http://eshopxamarin" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"orders",
"basket",
"mobileshoppingagg",
"webhooks"
},
//Allow requesting refresh tokens for long lived API access
AllowOfflineAccess = true,
AllowAccessTokensViaBrowser = true
},
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
ClientUri = $"{clientsUrl["Mvc"]}", // public uri of the client
// NOTE_JBOY: how our application is going to authenticate -- the code flow (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
AllowedGrantTypes = GrantTypes.Hybrid,
AllowAccessTokensViaBrowser = false,
RequireConsent = false,
// NOTE_JBOY: enable support for refresh tokens via the AllowOfflineAccess property (from https://docs.identityserver.io/en/latest/quickstarts/3_aspnetcore_and_apis.html)
AllowOfflineAccess = true,
AlwaysIncludeUserClaimsInIdToken = true,
// NOTE_JBOY: where to go to authenticate (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
RedirectUris = new List<string>
{
$"{clientsUrl["Mvc"]}/signin-oidc"
},
// NOTE_JBOY: where to go after logout(from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
PostLogoutRedirectUris = new List<string>
{
$"{clientsUrl["Mvc"]}/signout-callback-oidc"
},
// NOTE_JBOY: Scope is the area of information or category of information you want to extract. (from "ASP.NET Core, C#, IdentityServer4 - Authentication - Tricking Library Ep28" - https://www.youtube.com/watch?v=Ql0ZB67J0TQ)
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"orders",
"basket",
"webshoppingagg",
"orders.signalrhub",
"webhooks"
},
AccessTokenLifetime = 60*60*2, // 2 hours
IdentityTokenLifetime= 60*60*2 // 2 hours
},
new Client
{
ClientId = "webhooksclient",
ClientName = "Webhooks Client",
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
ClientUri = $"{clientsUrl["WebhooksWeb"]}", // public uri of the client
AllowedGrantTypes = GrantTypes.Hybrid,
AllowAccessTokensViaBrowser = false,
RequireConsent = false,
AllowOfflineAccess = true,
AlwaysIncludeUserClaimsInIdToken = true,
RedirectUris = new List<string>
{
$"{clientsUrl["WebhooksWeb"]}/signin-oidc"
},
PostLogoutRedirectUris = new List<string>
{
$"{clientsUrl["WebhooksWeb"]}/signout-callback-oidc"
},
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"webhooks"
},
AccessTokenLifetime = 60*60*2, // 2 hours
IdentityTokenLifetime= 60*60*2 // 2 hours
},
new Client
{
ClientId = "mvctest",
ClientName = "MVC Client Test",
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
ClientUri = $"{clientsUrl["Mvc"]}", // public uri of the client
AllowedGrantTypes = GrantTypes.Hybrid,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
AllowOfflineAccess = true,
RedirectUris = new List<string>
{
$"{clientsUrl["Mvc"]}/signin-oidc"
},
PostLogoutRedirectUris = new List<string>
{
$"{clientsUrl["Mvc"]}/signout-callback-oidc"
},
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"orders",
"basket",
"webshoppingagg",
"webhooks"
},
},
new Client
{
ClientId = "basketswaggerui",
ClientName = "Basket Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["BasketApi"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{clientsUrl["BasketApi"]}/swagger/" },
AllowedScopes =
{
"basket"
}
},
new Client
{
ClientId = "orderingswaggerui",
ClientName = "Ordering Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["OrderingApi"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{clientsUrl["OrderingApi"]}/swagger/" },
AllowedScopes =
{
"orders"
}
},
new Client
{
ClientId = "mobileshoppingaggswaggerui",
ClientName = "Mobile Shopping Aggregattor Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["MobileShoppingAgg"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{clientsUrl["MobileShoppingAgg"]}/swagger/" },
AllowedScopes =
{
"mobileshoppingagg"
}
},
new Client
{
ClientId = "webshoppingaggswaggerui",
ClientName = "Web Shopping Aggregattor Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["WebShoppingAgg"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{clientsUrl["WebShoppingAgg"]}/swagger/" },
AllowedScopes =
{
"webshoppingagg",
"basket"
}
},
new Client
{
ClientId = "webhooksswaggerui",
ClientName = "WebHooks Service Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{clientsUrl["WebhooksApi"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{clientsUrl["WebhooksApi"]}/swagger/" },
AllowedScopes =
{
"webhooks"
}
}
};
}
}
} | 49.596429 | 269 | 0.48477 | [
"MIT"
] | jeremiahflaga/eShopOnContainers-with-notes | src/Services/Identity/Identity.API/Configuration/Config.cs | 13,889 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Methods for Parsing numbers and Strings.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.CompilerServices;
namespace System
{
internal static class ParseNumbers
{
internal const int LeftAlign = 0x0001;
internal const int RightAlign = 0x0004;
internal const int PrefixSpace = 0x0008;
internal const int PrintSign = 0x0010;
internal const int PrintBase = 0x0020;
internal const int PrintAsI1 = 0x0040;
internal const int PrintAsI2 = 0x0080;
internal const int PrintAsI4 = 0x0100;
internal const int TreatAsUnsigned = 0x0200;
internal const int TreatAsI1 = 0x0400;
internal const int TreatAsI2 = 0x0800;
internal const int IsTight = 0x1000;
internal const int NoSpace = 0x2000;
internal const int PrintRadixBase = 0x4000;
private const int MinRadix = 2;
private const int MaxRadix = 36;
public unsafe static long StringToLong(System.String s, int radix, int flags)
{
int pos = 0;
return StringToLong(s, radix, flags, ref pos);
}
public static long StringToLong(string s, int radix, int flags, ref int currPos)
{
long result = 0;
int sign = 1;
int length;
int i;
int grabNumbersStart = 0;
int r;
if (s != null)
{
i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
grabNumbersStart = i;
result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
//If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
throw new OverflowException(SR.Overflow_Int64);
if (r == 10)
result *= sign;
}
else
{
result = 0;
}
return result;
}
public static int StringToInt(string s, int radix, int flags)
{
int pos = 0;
return StringToInt(s, radix, flags, ref pos);
}
public static int StringToInt(string s, int radix, int flags, ref int currPos)
{
int result = 0;
int sign = 1;
int length;
int i;
int grabNumbersStart = 0;
int r;
if (s != null)
{
// They're requied to tell me where to start parsing.
i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
// Consume the 0x if we're in an unknown base or in base-16.
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
grabNumbersStart = i;
result = GrabInts(r, s, ref i, ((flags & TreatAsUnsigned) != 0));
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((flags & TreatAsI1) != 0)
{
if ((uint)result > 0xFF)
throw new OverflowException(SR.Overflow_SByte);
}
else if ((flags & TreatAsI2) != 0)
{
if ((uint)result > 0xFFFF)
throw new OverflowException(SR.Overflow_Int16);
}
else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
{
throw new OverflowException(SR.Overflow_Int32);
}
if (r == 10)
result *= sign;
}
else
{
result = 0;
}
return result;
}
public static String IntToString(int n, int radix, int width, char paddingChar, int flags)
{
bool isNegative = false;
int index = 0;
int buffLength;
int i;
uint l;
char[] buffer = new char[66]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
// If the number is negative, make it positive and remember the sign.
// If the number is MIN_VALUE, this will still be negative, so we'll have to
// special case this later.
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
if (10 == radix)
l = (uint)-n;
else
l = (uint)n;
}
else
{
l = (uint)n;
}
// The conversion to a uint will sign extend the number. In order to ensure
// that we only get as many bits as we expect, we chop the number.
if ((flags & PrintAsI1) != 0)
l &= 0xFF;
else if ((flags & PrintAsI2) != 0)
l &= 0xFFFF;
// Special case the 0.
if (0 == l)
{
buffer[0] = '0';
index = 1;
}
else
{
do
{
uint charVal = l % (uint)radix;
l /= (uint)radix;
if (charVal < 10)
buffer[index++] = (char)(charVal + '0');
else
buffer[index++] = (char)(charVal + 'a' - 10);
}
while (l != 0);
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
}
if (10 == radix)
{
// If it was negative, append the sign, else if they requested, add the '+'.
// If they requested a leading space, put it on.
if (isNegative)
buffer[index++] = '-';
else if ((flags & PrintSign) != 0)
buffer[index++] = '+';
else if ((flags & PrefixSpace) != 0)
buffer[index++] = ' ';
}
// Figure out the size of our string.
if (width <= index)
buffLength = index;
else
buffLength = width;
StringBuilder sb = new StringBuilder(buffLength);
// Put the characters into the String in reverse order
// Fill the remaining space -- if there is any --
// with the correct padding character.
if ((flags & LeftAlign) != 0)
{
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
}
else
{
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
}
return sb.ToString();
}
public static String LongToString(long n, int radix, int width, char paddingChar, int flags)
{
bool isNegative = false;
int index = 0;
int charVal;
ulong ul;
int i;
int buffLength = 0;
char[] buffer = new char[67];//Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
//If the number is negative, make it positive and remember the sign.
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
if (10 == radix)
ul = (ulong)(-n);
else
ul = (ulong)n;
}
else
{
ul = (ulong)n;
}
if ((flags & PrintAsI1) != 0)
ul = ul & 0xFF;
else if ((flags & PrintAsI2) != 0)
ul = ul & 0xFFFF;
else if ((flags & PrintAsI4) != 0)
ul = ul & 0xFFFFFFFF;
//Special case the 0.
if (0 == ul)
{
buffer[0] = '0';
index = 1;
}
else
{
//Pull apart the number and put the digits (in reverse order) into the buffer.
for (index = 0; ul > 0; ul = ul / (ulong)radix, index++)
{
if ((charVal = (int)(ul % (ulong)radix)) < 10)
buffer[index] = (char)(charVal + '0');
else
buffer[index] = (char)(charVal + 'a' - 10);
}
}
//If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
else if ((flags & PrintRadixBase) != 0)
{
buffer[index++] = '#';
buffer[index++] = (char)((radix % 10) + '0');
buffer[index++] = (char)((radix / 10) + '0');
}
}
if (10 == radix)
{
//If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
//else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
//If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
//Figure out the size of our string.
if (width <= index)
buffLength = index;
else
buffLength = width;
StringBuilder sb = new StringBuilder(buffLength);
//Put the characters into the String in reverse order
//Fill the remaining space -- if there is any --
//with the correct padding character.
if ((flags & LeftAlign) != 0)
{
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
}
else
{
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
}
return sb.ToString();
}
private static void EatWhiteSpace(string s, ref int i)
{
for (; i < s.Length && char.IsWhiteSpace(s[i]); i++)
;
}
private static long GrabLongs(int radix, string s, ref int i, bool isUnsigned)
{
ulong result = 0;
int value;
ulong maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = 0x7FFFFFFFFFFFFFFF / 10;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || ((long)result) < 0)
throw new OverflowException(SR.Overflow_Int64);
result = result * (ulong)radix + (ulong)value;
i++;
}
if ((long)result < 0 && result != 0x8000000000000000)
throw new OverflowException(SR.Overflow_Int64);
}
else
{
maxVal = 0xffffffffffffffff / (ulong)radix;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
throw new OverflowException(SR.Overflow_UInt64);
ulong temp = result * (ulong)radix + (ulong)value;
if (temp < result) // this means overflow as well
throw new OverflowException(SR.Overflow_UInt64);
result = temp;
i++;
}
}
return (long)result;
}
private static int GrabInts(int radix, string s, ref int i, bool isUnsigned)
{
uint result = 0;
int value;
uint maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = (0x7FFFFFFF / 10);
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || (int)result < 0)
throw new OverflowException(SR.Overflow_Int32);
result = result * (uint)radix + (uint)value;
i++;
}
if ((int)result < 0 && result != 0x80000000)
throw new OverflowException(SR.Overflow_Int32);
}
else
{
maxVal = 0xffffffff / (uint)radix;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
throw new OverflowException(SR.Overflow_UInt32);
// the above check won't cover 4294967296 to 4294967299
uint temp = result * (uint)radix + (uint)value;
if (temp < result) // this means overflow as well
throw new OverflowException(SR.Overflow_UInt32);
result = temp;
i++;
}
}
return (int)result;
}
private static bool IsDigit(char c, int radix, out int result)
{
if (c >= '0' && c <= '9')
result = c - '0';
else if (c >= 'A' && c <= 'Z')
result = c - 'A' + 10;
else if (c >= 'a' && c <= 'z')
result = c - 'a' + 10;
else
result = -1;
if ((result >= 0) && (result < radix))
return true;
return false;
}
}
}
| 34.289689 | 122 | 0.421555 | [
"MIT"
] | OceanYan/corert | src/System.Private.CoreLib/src/System/ParseNumbers.cs | 20,951 | C# |
using BizStream.Kentico.Xperience.Administration.StatusCodePages;
using CMS;
[assembly: RegisterModule( typeof( StatusCodePagesModule ) )]
| 28 | 65 | 0.828571 | [
"MIT"
] | BizStream/xperience-status-code-pages | src/Administration/src/RegisterModules.cs | 140 | 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: EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ManagedIOSLobAppRequest.
/// </summary>
public partial class ManagedIOSLobAppRequest : BaseRequest, IManagedIOSLobAppRequest
{
/// <summary>
/// Constructs a new ManagedIOSLobAppRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ManagedIOSLobAppRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified ManagedIOSLobApp using POST.
/// </summary>
/// <param name="managedIOSLobAppToCreate">The ManagedIOSLobApp to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ManagedIOSLobApp.</returns>
public async System.Threading.Tasks.Task<ManagedIOSLobApp> CreateAsync(ManagedIOSLobApp managedIOSLobAppToCreate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
var newEntity = await this.SendAsync<ManagedIOSLobApp>(managedIOSLobAppToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Creates the specified ManagedIOSLobApp using POST and returns a <see cref="GraphResponse{ManagedIOSLobApp}"/> object.
/// </summary>
/// <param name="managedIOSLobAppToCreate">The ManagedIOSLobApp to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{ManagedIOSLobApp}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedIOSLobApp>> CreateResponseAsync(ManagedIOSLobApp managedIOSLobAppToCreate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<ManagedIOSLobApp>(managedIOSLobAppToCreate, cancellationToken);
}
/// <summary>
/// Deletes the specified ManagedIOSLobApp.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.DELETE;
await this.SendAsync<ManagedIOSLobApp>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the specified ManagedIOSLobApp and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse"/> to await.</returns>
public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.DELETE;
return this.SendAsyncWithGraphResponse(null, cancellationToken);
}
/// <summary>
/// Gets the specified ManagedIOSLobApp.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ManagedIOSLobApp.</returns>
public async System.Threading.Tasks.Task<ManagedIOSLobApp> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var retrievedEntity = await this.SendAsync<ManagedIOSLobApp>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Gets the specified ManagedIOSLobApp and returns a <see cref="GraphResponse{ManagedIOSLobApp}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{ManagedIOSLobApp}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedIOSLobApp>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<ManagedIOSLobApp>(null, cancellationToken);
}
/// <summary>
/// Updates the specified ManagedIOSLobApp using PATCH.
/// </summary>
/// <param name="managedIOSLobAppToUpdate">The ManagedIOSLobApp to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated ManagedIOSLobApp.</returns>
public async System.Threading.Tasks.Task<ManagedIOSLobApp> UpdateAsync(ManagedIOSLobApp managedIOSLobAppToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PATCH;
var updatedEntity = await this.SendAsync<ManagedIOSLobApp>(managedIOSLobAppToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Updates the specified ManagedIOSLobApp using PATCH and returns a <see cref="GraphResponse{ManagedIOSLobApp}"/> object.
/// </summary>
/// <param name="managedIOSLobAppToUpdate">The ManagedIOSLobApp to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The <see cref="GraphResponse{ManagedIOSLobApp}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedIOSLobApp>> UpdateResponseAsync(ManagedIOSLobApp managedIOSLobAppToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PATCH;
return this.SendAsyncWithGraphResponse<ManagedIOSLobApp>(managedIOSLobAppToUpdate, cancellationToken);
}
/// <summary>
/// Updates the specified ManagedIOSLobApp using PUT.
/// </summary>
/// <param name="managedIOSLobAppToUpdate">The ManagedIOSLobApp object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task<ManagedIOSLobApp> PutAsync(ManagedIOSLobApp managedIOSLobAppToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PUT;
var updatedEntity = await this.SendAsync<ManagedIOSLobApp>(managedIOSLobAppToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Updates the specified ManagedIOSLobApp using PUT and returns a <see cref="GraphResponse{ManagedIOSLobApp}"/> object.
/// </summary>
/// <param name="managedIOSLobAppToUpdate">The ManagedIOSLobApp object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await of <see cref="GraphResponse{ManagedIOSLobApp}"/>.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedIOSLobApp>> PutResponseAsync(ManagedIOSLobApp managedIOSLobAppToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PUT;
return this.SendAsyncWithGraphResponse<ManagedIOSLobApp>(managedIOSLobAppToUpdate, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IManagedIOSLobAppRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IManagedIOSLobAppRequest Expand(Expression<Func<ManagedIOSLobApp, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IManagedIOSLobAppRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IManagedIOSLobAppRequest Select(Expression<Func<ManagedIOSLobApp, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="managedIOSLobAppToInitialize">The <see cref="ManagedIOSLobApp"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(ManagedIOSLobApp managedIOSLobAppToInitialize)
{
}
}
}
| 51.068 | 185 | 0.650114 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ManagedIOSLobAppRequest.cs | 12,767 | C# |
using System;
namespace CryptoBase.Abstractions.SymmetricCryptos;
public interface IBlockCryptoMode
{
IBlockCrypto InternalBlockCrypto { get; init; }
ReadOnlyMemory<byte> Iv { get; init; }
}
| 17.818182 | 51 | 0.785714 | [
"MIT"
] | HMBSbige/CryptoBase | CryptoBase.Abstractions/SymmetricCryptos/IBlockCryptoMode.cs | 196 | C# |
// ===========================================================
// Copyright (c) 2014-2015, Enrico Da Ros/kendar.org
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ===========================================================
using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
namespace SharpTemplate.Compilers
{
/// <summary>
/// Compiler interface
/// </summary>
public interface IAppDomainCompiler
{
List<string> Errors { get; }
void Initialize(int bestEffort, string assemblyName, string assemblyPath,
ISourceCompilerDescriptor compilerDescriptor, string tempPath);
string Compile(bool log=false);
void Dispose();
object GetLifetimeService();
object InitializeLifetimeService();
ObjRef CreateObjRef(Type requestedType);
}
}
| 40.980392 | 82 | 0.713397 | [
"BSD-2-Clause"
] | endaroza/SharpTemplateEngine | SharpTemplate/SharpTemplate/Compilers/IAppDomainCompiler.cs | 2,090 | C# |
/*
* Clarify.PCL
*
* This file was automatically generated by APIMATIC BETA v2.0 on 10/06/2014
*/
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net.request;
using Clarify.PCL;
using Clarify.PCL.Models;
namespace Clarify.PCL.Controllers
{
public class SearchController
{
/// <summary>
/// Searches the bundles and returns a list of matching bundles, along with what matched and where for each bundle.
/// </summary>
/// <param name="query">Required parameter: query is used to search for text in the audio and metadata. It uses a simple query language similar to Google. At its simplest, it can be a space separated list of words (ex. open voice) which will find all bundles matching all the words. To search for a phrase, put it in quotes (ex. "open source") You can exclude bundles that contain a word by putting a minus (hyphen) in front of the word (ex. -opaque) To search for one word or another, use OR (in uppercase) between the words (ex. pizza OR pasta). As an alternative to OR, you can use | (pipe character). A full query could look something like: restaurant "little italy" pizza OR pasta -mushrooms</param>
/// <param name="queryFields">Required parameter: list of insights, metadata, and bundle fields to search with the query. Use insights.audio_words for searching audio, metadata.* for all metadata fields, bundle.* for all bundle fields, * for audio and all fields. Default is insights.audio_words and metadata.*. List is space or comma separated single string or an array of strings. If single string, up to 1024 characters.</param>
/// <param name="filter">Required parameter: filter expression, typically programmatically generated based on input controls and data segregation rules etc. Up to 400 characters.</param>
/// <param name="limit">Required parameter: limit results to specified number of bundles. Default is 10. Max 100.</param>
/// <param name="embed">Required parameter: ist of link relations to embed in the result collection. Zero or more of: items, tracks, metadata. List is space or comma separated single string or an array of strings</param>
/// <param name="iterator">Required parameter: opaque value, automatically provided in next/prev links</param>
/// <return>Returns the SearchResponseModel response from the API call</return>
public SearchResponseModel GetSearch(
string query,
string queryFields,
string filter,
int limit,
string embed,
string iterator)
{
//the base uri for api requests
string baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder queryBuilder = new StringBuilder(baseUri);
queryBuilder.Append("/search");
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary<string, object>()
{
{ "query", query },
{ "query_fields", queryFields },
{ "filter", filter },
{ "limit", limit },
{ "embed", embed },
{ "iterator", iterator }
});
//validate and preprocess url
string queryUrl = APIHelper.CleanUrl(queryBuilder);
//prepare and invoke the API call request to fetch the response
HttpRequest request = Unirest.get(queryUrl)
//append request with appropriate headers and parameters
.header("User-Agent", "APIMATIC 2.0")
.header("Accept", "application/json")
.header("Authorization", string.Format("Bearer {0}", Configuration.OAuthAccessToken));
//invoke request and get response
HttpResponse<String> response = request.asString();
//Error handling using HTTP status codes
if (response.Code == 400)
throw new APIException(@"Bad request", 400);
else if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
throw new APIException(@"HTTP Response Not OK", response.Code);
return APIHelper.JsonDeserialize<SearchResponseModel>(response.Body);
}
}
} | 55.46988 | 713 | 0.640313 | [
"MIT"
] | Clarify/clarify-csharp | Clarify.PCL/Controllers/SearchController.cs | 4,604 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BoligrafosTorneadosApp.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("BoligrafosTorneadosApp.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("BoligrafosTorneadosApp.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("BoligrafosTorneadosApp.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("BoligrafosTorneadosApp.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 34.700461 | 117 | 0.500797 | [
"Apache-2.0"
] | sierz/TurnedPensApp | BoligrafosTorneadosApp/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs | 7,532 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using ColossalFramework;
using ICities;
using NetworkSkins.Data;
using NetworkSkins.Detour;
using NetworkSkins.Net;
using UnityEngine;
namespace NetworkSkins.Props
{
public class PropCustomizer : LoadingExtensionBase
{
public static PropCustomizer Instance;
private readonly List<TreeInfo> _availableTrees = new List<TreeInfo>();
private readonly List<PropInfo> _availableStreetLights = new List<PropInfo>();
public int[] StreetLightPrefabDataIndices;
public override void OnCreated(ILoading loading)
{
base.OnCreated(loading);
Instance = this;
RenderManagerDetour.EventUpdateData += OnUpdateData;
NetLaneDetour.Deploy();
}
/// <summary>
/// Like OnLevelLoaded, but executed earlier.
/// </summary>
/// <param name="mode"></param>
public void OnUpdateData(SimulationManager.UpdateMode mode)
{
if (mode != SimulationManager.UpdateMode.LoadMap && mode != SimulationManager.UpdateMode.NewMap
&& mode != SimulationManager.UpdateMode.LoadGame && mode != SimulationManager.UpdateMode.NewGameFromMap
&& mode != SimulationManager.UpdateMode.NewGameFromScenario) return;
// no trees
_availableTrees.Add(null);
for (uint i = 0; i < PrefabCollection<TreeInfo>.LoadedCount(); i++)
{
var prefab = PrefabCollection<TreeInfo>.GetLoaded(i);
if (prefab == null) continue;
_availableTrees.Add(prefab);
}
// no street lights
_availableStreetLights.Add(null);
for (uint i = 0; i < PrefabCollection<PropInfo>.LoadedCount(); i++)
{
var prefab = PrefabCollection<PropInfo>.GetLoaded(i);
if (prefab == null) continue;
if (prefab.m_class.m_service == ItemClass.Service.Road ||
prefab.m_class.m_subService == ItemClass.SubService.PublicTransportPlane ||
prefab.name.ToLower().Contains("streetlamp") || prefab.name.ToLower().Contains("streetlight") || prefab.name.ToLower().Contains("lantern"))
{
if (prefab.m_effects != null && prefab.m_effects.Length > 0)
{
if (prefab.name.ToLower().Contains("taxiway")) continue;
if (prefab.name.ToLower().Contains("runway")) continue;
if (prefab.m_effects.Where(effect => effect.m_effect != null).Any(effect => effect.m_effect is LightEffect))
{
_availableStreetLights.Add(prefab);
}
}
}
}
// compile list of data indices for fast check if a prefab is a street light:
StreetLightPrefabDataIndices = _availableStreetLights.Where(prop => prop != null).Select(prop => prop.m_prefabDataIndex).ToArray();
}
public override void OnLevelUnloading()
{
_availableTrees.Clear();
_availableStreetLights.Clear();
}
public override void OnReleased()
{
Instance = null;
RenderManagerDetour.EventUpdateData -= OnUpdateData;
NetLaneDetour.Revert();
}
public bool HasTrees(NetInfo prefab, LanePosition position)
{
if (prefab.m_lanes == null) return false;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null && position.IsCorrectSide(lane.m_position))
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalTree != null && _availableStreetLights.Contains(laneProp.m_finalProp)) return true;
}
return false;
}
public bool HasStreetLights(NetInfo prefab)
{
if (prefab.m_lanes == null) return false;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null)
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalProp != null && _availableStreetLights.Contains(laneProp.m_finalProp)) return true;
}
return false;
}
public List<TreeInfo> GetAvailableTrees(NetInfo prefab)
{
return _availableTrees;
}
public List<PropInfo> GetAvailableStreetLights(NetInfo prefab)
{
return _availableStreetLights;
}
public TreeInfo GetActiveTree(NetInfo prefab, LanePosition position)
{
var segmentData = SegmentDataManager.Instance.GetActiveOptions(prefab);
if (segmentData == null || !segmentData.Features.IsFlagSet(position.ToTreeFeatureFlag()))
{
return GetDefaultTree(prefab, position);
}
else
{
switch (position)
{
case LanePosition.Left: return segmentData.TreeLeftPrefab;
case LanePosition.Middle: return segmentData.TreeMiddlePrefab;
case LanePosition.Right: return segmentData.TreeRightPrefab;
default: throw new ArgumentOutOfRangeException(nameof(position));
}
}
}
public PropInfo GetActiveStreetLight(NetInfo prefab)
{
var segmentData = SegmentDataManager.Instance.GetActiveOptions(prefab);
if (segmentData == null || !segmentData.Features.IsFlagSet(SegmentData.FeatureFlags.StreetLight))
{
return GetDefaultStreetLight(prefab);
}
else
{
return segmentData.StreetLightPrefab;
}
}
public TreeInfo GetDefaultTree(NetInfo prefab, LanePosition position)
{
if (prefab.m_lanes == null) return null;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null && position.IsCorrectSide(lane.m_position))
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalTree != null) return laneProp.m_finalTree;
}
return null;
}
public PropInfo GetDefaultStreetLight(NetInfo prefab)
{
if (prefab.m_lanes == null) return null;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null)
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalProp != null && _availableStreetLights.Contains(laneProp.m_finalProp)) return laneProp.m_finalProp;
}
return null;
}
public void SetTree(NetInfo prefab, LanePosition position, TreeInfo tree)
{
var newSegmentData = new SegmentData(SegmentDataManager.Instance.GetActiveOptions(prefab));
if (tree != GetDefaultTree(prefab, position))
{
newSegmentData.SetPrefabFeature(position.ToTreeFeatureFlag(), tree);
}
else
{
newSegmentData.UnsetFeature(position.ToTreeFeatureFlag());
}
SegmentDataManager.Instance.SetActiveOptions(prefab, newSegmentData);
}
public void SetStreetLight(NetInfo prefab, PropInfo prop)
{
var newSegmentData = new SegmentData(SegmentDataManager.Instance.GetActiveOptions(prefab));
if (prop != GetDefaultStreetLight(prefab))
{
newSegmentData.SetPrefabFeature(SegmentData.FeatureFlags.StreetLight, prop);
}
else
{
newSegmentData.UnsetFeature(SegmentData.FeatureFlags.StreetLight);
}
SegmentDataManager.Instance.SetActiveOptions(prefab, newSegmentData);
}
public void SetStreetLightDistance(NetInfo prefab, float val)
{
var newSegmentData = new SegmentData(SegmentDataManager.Instance.GetActiveOptions(prefab));
var distanceVector = newSegmentData.RepeatDistances;
distanceVector.w = Math.Abs(val - GetDefaultStreetLightDistance(prefab)) > .01f ? val : 0f;
if (distanceVector != Vector4.zero)
{
newSegmentData.SetStructFeature(SegmentData.FeatureFlags.RepeatDistances, distanceVector);
}
else
{
newSegmentData.UnsetFeature(SegmentData.FeatureFlags.RepeatDistances);
}
SegmentDataManager.Instance.SetActiveOptions(prefab, newSegmentData);
}
public void SetTreeDistance(NetInfo prefab, LanePosition position, float val)
{
var newSegmentData = new SegmentData(SegmentDataManager.Instance.GetActiveOptions(prefab));
var distanceVector = newSegmentData.RepeatDistances;
var value = Mathf.Abs(val - GetDefaultTreeDistance(prefab, position)) > .01f ? val : 0f;
switch (position)
{
case LanePosition.Left:
distanceVector.x = value;
break;
case LanePosition.Middle:
distanceVector.y = value;
break;
case LanePosition.Right:
distanceVector.z = value;
break;
default:
throw new ArgumentOutOfRangeException(nameof(position));
}
if (distanceVector != Vector4.zero)
{
newSegmentData.SetStructFeature(SegmentData.FeatureFlags.RepeatDistances, distanceVector);
}
else
{
newSegmentData.UnsetFeature(SegmentData.FeatureFlags.RepeatDistances);
}
SegmentDataManager.Instance.SetActiveOptions(prefab, newSegmentData);
}
public float GetDefaultStreetLightDistance(NetInfo prefab)
{
if (prefab.m_lanes == null) return -1f;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null)
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalProp != null && _availableStreetLights.Contains(laneProp.m_finalProp)) return laneProp.m_repeatDistance;
}
return -1f;
}
public float GetDefaultTreeDistance(NetInfo prefab, LanePosition position)
{
if (prefab.m_lanes == null) return -1f;
foreach (var lane in prefab.m_lanes)
if (lane?.m_laneProps?.m_props != null && position.IsCorrectSide(lane.m_position))
foreach (var laneProp in lane.m_laneProps.m_props)
{
if (laneProp?.m_finalTree != null) return laneProp.m_repeatDistance;
}
return -1f;
}
public float GetActiveStreetLightDistance(NetInfo prefab)
{
var segmentData = SegmentDataManager.Instance.GetActiveOptions(prefab);
if (segmentData != null && segmentData.Features.IsFlagSet(SegmentData.FeatureFlags.RepeatDistances) && segmentData.RepeatDistances.w > 0f)
{
return segmentData.RepeatDistances.w;
}
else
{
return GetDefaultStreetLightDistance(prefab);
}
}
public float GetActiveTreeDistance(NetInfo prefab, LanePosition position)
{
var segmentData = SegmentDataManager.Instance.GetActiveOptions(prefab);
var result = 0f;
if (segmentData != null && segmentData.Features.IsFlagSet(SegmentData.FeatureFlags.RepeatDistances))
{
switch (position)
{
case LanePosition.Left:
result = segmentData.RepeatDistances.x;
break;
case LanePosition.Middle:
result = segmentData.RepeatDistances.y;
break;
case LanePosition.Right:
result = segmentData.RepeatDistances.z;
break;
default:
throw new ArgumentOutOfRangeException(nameof(position));
}
}
return result > 0f ? result : GetDefaultTreeDistance(prefab, position);
}
}
}
| 36.928977 | 159 | 0.564197 | [
"MIT"
] | boformer/LegacyNetworkSkins | NetworkSkins/Props/PropCustomizer.cs | 13,001 | 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 Development.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")]
public 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;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<ArrayOfString xmlns:xsi=\"http://www.w3." +
"org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <s" +
"tring>demo.core.order.dll</string>\r\n</ArrayOfString>")]
public global::System.Collections.Specialized.StringCollection Plugins {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["Plugins"]));
}
}
}
}
| 46.657895 | 159 | 0.604625 | [
"MIT"
] | maikvandergaag/msft-demo-development | msft-demo-development/msft-demo-development/Properties/Settings.Designer.cs | 1,775 | C# |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class GameManager {
#region STATIC_ENUM_CONSTANTS
public static readonly int MAX_TIME_IN_GAME = 600000;
public static readonly string CHARACTER_GO_TAG = "Player";
public enum GAME_MODE{
NORMAL = 0,
MODE_AR = 1
}
#endregion
#region FIELDS
public event Action onEndGame = delegate { };
private Game currentGame;
private GameStats currentGameStats;
private GameObject characterGO;
private GAME_MODE gameMode;
private bool pauseFlag;
private bool finishGameFlag;
private bool winFlag = false;
private CoroutineTask timeTask;
private static GameManager instance = null;
#endregion
#region ACCESSORS
public Game CurrentGame{
get{
if (currentGame == null){
currentGame = new Game();
currentGameStats = new GameStats();
Console.Warning("GAME IN EDIT MODE...");
}
return currentGame;
}
}
public bool IsPaused
{
get { return pauseFlag; }
}
public GameObject Character{
get{ return characterGO; }
set{ characterGO = value; }
}
public GAME_MODE GameMode{
get { return gameMode; }
set { gameMode = value; }
}
public int TimeGame{
get{
if (currentGameStats == null)
{
return 0;
}
else
{
return currentGameStats.timeGame;
}
}
}
public int Plasma
{
get
{
if (currentGameStats == null)
{
return 0;
}
else
{
return currentGameStats.plasma;
}
}
}
public int TotalSpiderKilled
{
get { return currentGameStats.totalSpiderKilled; }
}
public int TotalWaspKilled
{
get { return currentGameStats.totalWaspKilled; }
}
public bool WinGame{
get { return winFlag; }
}
public bool FinishedGame
{
get { return finishGameFlag; }
}
public static GameManager Instance{
get{
if (instance == null){
instance = new GameManager();
}
return instance;
}
}
#endregion
#region METHODS_CONSTRUCTORS
private GameManager(){}
#endregion
#region METHODS_CUSTOM
public void SetGame(Game game){
currentGame = game;
}
public void StartGame(){
timeTask = TaskManager.Launch(TimeCounter());
finishGameFlag = false;
winFlag = false;
pauseFlag = false;
characterGO = GameObject.FindGameObjectWithTag(CHARACTER_GO_TAG);
ResetStats();
}
public void ResetStats(){
currentGameStats = new GameStats ();
}
public void EnemyDestroyed(EnemyController.ENEMY_TYPE enemyType){
currentGameStats.totalEnemyDestroyed++;
if (enemyType == EnemyController.ENEMY_TYPE.SPIDER)
{
currentGameStats.totalSpiderKilled++;
}
else
{
currentGameStats.totalWaspKilled++;
}
}
public void AddPlasma(int plasma)
{
System.TimeSpan timeSpan = System.TimeSpan.FromMilliseconds ((double)currentGameStats.timeGame);
currentGameStats.plasma += plasma * (timeSpan.Minutes+1);
}
public void Pause(){
if (pauseFlag) {
pauseFlag = false;
Time.timeScale = 1;
} else {
pauseFlag = true;
Time.timeScale = 0;
}
}
public void GameWin(){
Debug.Log("Gana el jugador");
winFlag = true;
timeTask.Stop ();
finishGameFlag = true;
RootApp.Instance.ChangeState (StateReferenceApp.TYPE_STATE.END);
}
public void GameFail(){
if (!winFlag) {
Debug.Log("Pierde el jugador");
winFlag = false;
timeTask.Stop ();
finishGameFlag = true;
onEndGame();
AudioManager.Instance.StopFXSound(AudioManager.MOVE_TOWER);
RootApp.Instance.ChangeState (StateReferenceApp.TYPE_STATE.END);
}
}
private IEnumerator TimeCounter(){
while (true) {
yield return new WaitForSeconds(0.1f);
currentGameStats.timeGame += 100;
if (currentGameStats.timeGame >= MAX_TIME_IN_GAME)
{
GameWin();
}
}
}
#endregion
#region METHODS_EVENT
#endregion
}
| 20.706161 | 104 | 0.600137 | [
"MIT"
] | chrislugram/TDAR | Assets/Scripts/Managers/GameManager.cs | 4,369 | C# |
namespace Yobao.Models {
using System.ComponentModel.DataAnnotations;
public class Category {
[Key]
public int Id { get; set; }
public string Description { get; set; }
}
} | 22.625 | 45 | 0.707182 | [
"MIT"
] | YoloDev/YOBAO | Source/Yobao/Models/Category.cs | 183 | C# |
namespace Stone_Red_Utilities.Logging
{
/// <summary>
/// Specifies the target of the log message.
/// </summary>
public enum LogTarget
{
/// <summary>
/// Writes log to console
/// </summary>
Console = 1,
/// <summary>
/// Writes log to debug console
/// </summary>
DebugConsole = 2,
/// <summary>
/// Writes log to file
/// </summary>
File = 3
}
} | 20.521739 | 48 | 0.476695 | [
"MIT"
] | Stone-Red-Code/Stone_Red-C-Sharp-Utilities | Stone_Red-C-Sharp-Utilities/Logging/LogTarget.cs | 474 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.400)
// Version 5.400.0.0 www.ComponentFactory.com
// *****************************************************************************
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Extends the ViewLayoutRibbonQATContents by providing the definitions from the ribbon control itself.
/// </summary>
internal class ViewLayoutRibbonQATFromRibbon : ViewLayoutRibbonQATContents
{
#region Identity
/// <summary>
/// Initialize a new instance of the ViewLayoutRibbonQATFromRibbon class.
/// </summary>
/// <param name="ribbon">Owning ribbon control instance.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
/// <param name="showExtraButton">Should the extra button be shown.</param>
public ViewLayoutRibbonQATFromRibbon(KryptonRibbon ribbon,
NeedPaintHandler needPaint,
bool showExtraButton)
: base(ribbon, needPaint, showExtraButton)
{
}
#endregion
#region DisplayButtons
/// <summary>
/// Returns a collection of all the quick access toolbar definitions.
/// </summary>
public override IQuickAccessToolbarButton[] QATButtons
{
get
{
IQuickAccessToolbarButton[] qatButtons = new IQuickAccessToolbarButton[Ribbon.QATButtons.Count];
// Copy all the entries into the new array
Ribbon.QATButtons.CopyTo(qatButtons, 0);
return qatButtons;
}
}
#endregion
}
}
| 42.709091 | 157 | 0.596424 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.400 | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Layout/ViewLayoutRibbonQATFromRibbon.cs | 2,352 | C# |
namespace Advobot.Attributes.ParameterPreconditions.Numbers;
/// <summary>
/// Validates the passed in number allowing 0 to <see cref="int.MaxValue"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class NotNegativeAttribute : RangeParameterPreconditionAttribute
{
/// <inheritdoc />
public override string NumberType => "not negative number";
/// <summary>
/// Creates an instance of <see cref="NotNegativeAttribute"/>.
/// </summary>
public NotNegativeAttribute() : base(0, int.MaxValue) { }
} | 35.8125 | 85 | 0.74171 | [
"MIT"
] | advorange/Advobot | src/Advobot.Core/Attributes/ParameterPreconditions/Numbers/NotNegativeAttribute.cs | 575 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFormation.Model
{
/// <summary>
/// Container for the parameters to the DescribeAccountLimits operation.
/// Retrieves your account's AWS CloudFormation limits, such as the maximum number of
/// stacks that you can create in your account. For more information about account limits,
/// see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html">AWS
/// CloudFormation Limits</a> in the <i>AWS CloudFormation User Guide</i>.
/// </summary>
public partial class DescribeAccountLimitsRequest : AmazonCloudFormationRequest
{
private string _nextToken;
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A string that identifies the next page of limits that you want to retrieve.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 35.112903 | 116 | 0.658705 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CloudFormation/Generated/Model/DescribeAccountLimitsRequest.cs | 2,177 | C# |
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// TODO - split this up into files! It's just kept growing and growing ...
namespace Requestoring {
/// <summary> /// All Requestors must implement this simple, single method interface /// </summary>
public interface IRequestor {
IResponse GetResponse(string verb, string url, IDictionary<string, string> postVariables, IDictionary<string, string> requestHeaders);
}
/// <summary>Any Requestor that supports Cookies needs to implement this.</summary>
public interface IHaveCookies {
void EnableCookies();
void DisableCookies();
void ResetCookies();
}
public class RealRequestsDisabledException : Exception {
public RealRequestsDisabledException(string message) : base(message) {}
}
public class FakeResponse {
public int TimesUsed = 0;
public int MaxUsage = -1;
public string Method { get; set; }
public string Url { get; set; }
public IResponse Response { get; set; }
}
public class FakeResponseList : List<FakeResponse>, IRequestor {
public FakeResponseList Add(string method, string url, IResponse response) {
Add(new FakeResponse {
Method = method,
Url = url,
Response = response
});
return this;
}
public FakeResponseList Add(int times, string method, string url, IResponse response) {
Add(new FakeResponse {
Method = method,
Url = url,
Response = response,
MaxUsage = times
});
return this;
}
// This is a safe way to get a fake response. It does NOT increment TimesUsed
public FakeResponse GetFakeResponse(string verb, string url) {
return this.FirstOrDefault(fake => fake.Method == verb && fake.Url == url);
}
// This will increment TimesUsed and remove the FakeResponse after its last usage
public IResponse GetResponse(string verb, string url, IDictionary<string, string> postVariables, IDictionary<string, string> requestHeaders) {
var fake = GetFakeResponse(verb, url);
if (fake != null && fake.MaxUsage > 0) {
fake.TimesUsed++;
if (fake.TimesUsed >= fake.MaxUsage)
this.Remove(fake);
}
if (fake == null)
return null;
else
return fake.Response;
}
}
/// <summary>
/// <c>Requestor</c> has the main API for making requests. Uses a <c>IRequestor</c> implementation behind the scenes.
/// </summary>
public class Requestor {
public class GlobalConfiguration {
public bool AutoRedirect { get; set; }
public bool AllowRealRequests { get; set; }
bool _verbose;
public bool Verbose {
get {
if (Environment.GetEnvironmentVariable("VERBOSE") != null && Environment.GetEnvironmentVariable("VERBOSE") == "true")
return true;
else
return _verbose;
}
set { _verbose = value; }
}
public IDictionary<string,string> DefaultHeaders = new Dictionary<string,string>();
// Faking responses ... copy/pasted from Requestor ... TODO DRY this up!
public GlobalConfiguration EnableRealRequests() { AllowRealRequests = true; return this; }
public GlobalConfiguration DisableRealRequests() { AllowRealRequests = false; return this; }
public FakeResponseList FakeResponses = new FakeResponseList();
public GlobalConfiguration FakeResponse(string method, string url, IResponse response) {
FakeResponses.Add(method, url, response); return this;
}
public GlobalConfiguration FakeResponse(int times, string method, string url, IResponse response) {
FakeResponses.Add(times, method, url, response); return this;
}
public GlobalConfiguration FakeResponseOnce(string method, string url, IResponse response) {
FakeResponse(1, method, url, response); return this;
}
public string RootUrl;
public GlobalConfiguration Reset() {
FakeResponses.Clear();
DefaultHeaders.Clear();
Implementation = null;
return this;
}
IRequestor _implementation;
public IRequestor Implementation {
get {
if (_implementation == null)
_implementation = Activator.CreateInstance(Requestor.DefaultIRequestor) as IRequestor;
return _implementation;
}
set { _implementation = value; }
}
}
#region Static
static Type _defaultIRequestor = typeof(HttpRequestor);
public static Type DefaultIRequestor {
get { return _defaultIRequestor; }
set {
if (IsIRequestor(value))
_defaultIRequestor = value;
else
throw new InvalidCastException("DefaultIRequestor must implement IRequestor");
}
}
public static bool IsIRequestor(Type type) {
return (type.GetInterface(typeof(IRequestor).FullName) != null);
}
static GlobalConfiguration _global = new GlobalConfiguration {
AllowRealRequests = true
};
public static GlobalConfiguration Global {
get { return _global; }
set { _global = value; }
}
#endregion
#region Instance
public Requestor() {}
public Requestor(string rootUrl) {
RootUrl = rootUrl;
}
public Requestor(IRequestor implementation) {
Implementation = implementation;
}
bool? _autoRedirect;
public bool AutoRedirect {
get { return (bool)(_autoRedirect ?? Requestor.Global.AutoRedirect); }
set { _autoRedirect = value; }
}
bool? _allowRealRequests;
public bool AllowRealRequests {
get { return (bool)(_allowRealRequests ?? Requestor.Global.AllowRealRequests); }
set { _allowRealRequests = value; }
}
bool? _verbose;
public bool Verbose {
get { return (bool)(_verbose ?? Requestor.Global.Verbose); }
set { _verbose = value; }
}
// Faking responses
public Requestor DisableRealRequests() { AllowRealRequests = false; return this; }
public Requestor EnableRealRequests() { AllowRealRequests = true; return this; }
public FakeResponseList FakeResponses = new FakeResponseList();
public Requestor FakeResponse(string method, string url, IResponse response) {
FakeResponses.Add(method, url, response); return this;
}
public Requestor FakeResponse(int times, string method, string url, IResponse response) {
FakeResponses.Add(times, method, url, response); return this;
}
public Requestor FakeResponseOnce(string method, string url, IResponse response) {
FakeResponse(1, method, url, response); return this;
}
public IDictionary<string,string> DefaultHeaders = new Dictionary<string,string>();
public IDictionary<string,string> Headers = new Dictionary<string,string>();
public IDictionary<string,string> QueryStrings = new Dictionary<string,string>();
public IDictionary<string,string> PostData = new Dictionary<string,string>();
string _rootUrl;
public string RootUrl {
get { return _rootUrl ?? Global.RootUrl; }
set { _rootUrl = value; }
}
IRequestor _implementation;
public IRequestor Implementation {
get { return _implementation ?? Global.Implementation; }
set { _implementation = value; }
}
public Uri CurrentUri { get; set; }
public string CurrentUrl { get { return (CurrentUri == null) ? null : CurrentUri.ToString(); } }
public string CurrentPath { get { return (CurrentUri == null) ? null : CurrentUri.PathAndQuery; } }
public string Url(string path) {
if (IsAbsoluteUrl(path))
return path;
if (RootUrl == null)
return path;
else
return RootUrl + path;
}
public string Url(string path, IDictionary<string, string> queryStrings) {
if (queryStrings != null && queryStrings.Count > 0) {
var url = Url(path) + "?";
foreach (var queryString in queryStrings)
url += queryString.Key + "=" + HttpUtility.UrlEncode(queryString.Value) + "&";
url.TrimEnd('&');
return url;
} else
return Url(path);
}
public IResponse Get( string path){ return Get(path, null); }
public IResponse Post( string path){ return Post(path, null); }
public IResponse Put( string path){ return Put(path, null); }
public IResponse Delete( string path){ return Delete(path, null); }
public IResponse Get( string path, object variables){ return Request("GET", path, variables, "QueryStrings"); }
public IResponse Post( string path, object variables){ return Request("POST", path, variables, "PostData"); }
public IResponse Put( string path, object variables){ return Request("PUT", path, variables, "PostData"); }
public IResponse Delete(string path, object variables){ return Request("DELETE", path, variables, "PostData"); }
public IResponse Request(string method, string path) {
return Request(method, path, null, null);
}
public IResponse Request(string method, string path, object variables, string defaultVariableType) {
return Request(method, path, MergeInfo(new RequestInfo(variables, defaultVariableType)));
}
/// <summary>This is THE Request methd that all other ones use. It will process fake and real requests.</summary>
public IResponse Request(string method, string path, RequestInfo info) {
if (Verbose) {
Console.WriteLine("{0} {1}", method, path);
foreach (var queryString in info.QueryStrings)
Console.WriteLine("\tQUERY {0}: {1}", queryString.Key, queryString.Value);
foreach (var postItem in info.PostData)
Console.WriteLine("\tPOST {0}: {1}", postItem.Key, postItem.Value);
foreach (var header in info.Headers)
Console.WriteLine("\tHEADER {0}: {1}", header.Key, header.Value);
}
// try instance fake requests
var instanceFakeResponse = Request(method, path, info, this.FakeResponses);
if (instanceFakeResponse != null)
return instanceFakeResponse;
// then try global fake requests
var globalFakeResponse = Request(method, path, info, Requestor.Global.FakeResponses);
if (globalFakeResponse != null)
return globalFakeResponse;
// then, if real requests are disabled, raise exception, else fall back to real implementation
if (AllowRealRequests)
return Request(method, path, info, Implementation);
else
throw new RealRequestsDisabledException(string.Format("Real requests are disabled. {0} {1}", method, Url(path, info.QueryStrings)));
}
public IResponse Request(string method, string path, RequestInfo info, IRequestor requestor) {
var url = Url(path, info.QueryStrings);
try {
CurrentUri = new Uri(url);
} catch (Exception ex) {
Console.WriteLine("BAD URI. method:{0} path:{1} url:{2}", method, path, url);
LastException = ex;
// We don't return null here because a custom IRequestor could support this URL, even if it's not a valid URI
}
IResponse response;
try {
response = requestor.GetResponse(method, url, info.PostData, MergeWithDefaultHeaders(info.Headers));
} catch (Exception ex) {
Console.WriteLine("Requestor ({0}) failed to respond for {1} {2} [{3}]", requestor.GetType(), method, path, url);
Console.WriteLine("Requested info:");
Console.WriteLine("\t{0} {1}", method, url);
Console.WriteLine("\tPostData: " + string.Join(", ", info.PostData.Select(item => string.Format("{0} => {1}", item.Key, item.Value)).ToArray()));
Console.WriteLine("\tHeaders: " + string.Join(", ", info.Headers.Select(item => string.Format("{0} => {1}", item.Key, item.Value)).ToArray()));
LastException = ex;
return null;
}
if (response == null)
return null;
if (AutoRedirect)
while (IsRedirect(response))
response = FollowRedirect(response);
return SetLastResponse(response);
}
IResponse _lastResponse;
public IResponse LastResponse {
get { return _lastResponse; }
set { _lastResponse = value; }
}
public Exception LastException { get; set; }
public bool IsRedirect(IResponse response) {
return (response.Status.ToString().StartsWith("3") && response.Headers.Keys.Contains("Location"));
}
public IResponse FollowRedirect() {
return FollowRedirect(LastResponse);
}
public IResponse FollowRedirect(IResponse response) {
if (response == null)
throw new Exception("Cannot follow redirect. response is null.");
else if (!response.Headers.Keys.Contains("Location"))
throw new Exception("Cannot follow redirect. Location header of response is null.");
else {
PostData.Clear(); // You cannot have PostData when doing a GET
return Get(response.Headers["Location"]);
}
}
public Requestor EnableCookies() {
if (Implementation is IHaveCookies)
(Implementation as IHaveCookies).EnableCookies();
else
throw new Exception(string.Format("Cannot enable cookies. Requestor Implementation {0} does not implement IHaveCookies", Implementation));
return this;
}
public Requestor DisableCookies() {
if (Implementation is IHaveCookies)
(Implementation as IHaveCookies).DisableCookies();
else
throw new Exception(string.Format("Cannot disable cookies. Requestor Implementation {0} does not implement IHaveCookies", Implementation));
return this;
}
public Requestor ResetCookies() {
if (Implementation is IHaveCookies)
(Implementation as IHaveCookies).ResetCookies();
else
throw new Exception(string.Format("Cannot reset cookies. Requestor Implementation {0} does not implement IHaveCookies", Implementation));
return this;
}
public Requestor Reset() {
Implementation = null;
ResetLastResponse();
DefaultHeaders.Clear();
FakeResponses.Clear();
return this;
}
public Requestor ResetLastResponse() {
LastResponse = null;
return this;
}
public Requestor AddHeader(string key, string value) {
Headers.Add(key, value);
return this;
}
public Requestor AddQueryString(string key, string value) {
QueryStrings.Add(key, value);
return this;
}
public Requestor AddPostData(string key, string value) {
PostData.Add(key, value);
return this;
}
public Requestor SetPostData(string value) {
PostData.Clear();
PostData.Add(value, null);
return this;
}
#endregion
#region private
bool IsAbsoluteUrl(string path) {
return Regex.IsMatch(path, @"^\w+://"); // if it starts with whatever://, then it's absolute.
}
IDictionary<string,string> MergeWithDefaultHeaders(IDictionary<string,string> headers) {
return MergeDictionaries(MergeDictionaries(Requestor.Global.DefaultHeaders, DefaultHeaders), headers);
}
IDictionary<string,string> MergeDictionaries(IDictionary<string,string> defaults, IDictionary<string,string> overrides) {
var result = new Dictionary<string,string>(defaults);
foreach (var item in overrides)
result[item.Key] = item.Value;
return result;
}
public IResponse SetLastResponse(IResponse response) {
// clear out the stored headers, querystrings, and post data for this request
Headers = new Dictionary<string,string>();
QueryStrings = new Dictionary<string,string>();
PostData = new Dictionary<string,string>();
_lastResponse = response;
return response;
}
public static IDictionary<string, string> ToStringDictionary(object anonymousType) {
if (anonymousType is Dictionary<string, string>)
return anonymousType as Dictionary<string, string>;
var dict = new Dictionary<string, string>();
foreach (var item in ToObjectDictionary(anonymousType))
if (item.Value == null)
dict.Add(item.Key, null);
else
dict.Add(item.Key, item.Value.ToString());
return dict;
}
public static IDictionary<string, object> ToObjectDictionary(object anonymousType) {
if (anonymousType is Dictionary<string, object>)
return anonymousType as Dictionary<string, object>;
var dict = new Dictionary<string, object>();
if (anonymousType is Dictionary<string, string>) {
foreach (var item in (anonymousType as Dictionary<string, string>))
dict.Add(item.Key, item.Value);
return dict;
}
foreach (var property in anonymousType.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
if (property.CanRead)
dict.Add(property.Name, property.GetValue(anonymousType, null));
return dict;
}
RequestInfo MergeInfo(RequestInfo info) {
info.QueryStrings = MergeDictionaries(info.QueryStrings, QueryStrings);
info.Headers = MergeDictionaries(info.Headers, Headers);
info.PostData = MergeDictionaries(info.PostData, PostData);
return info;
}
#endregion
#region RequestInfo
// new RequestInfo(new { Foo = "Bar" }, "QueryStrings"); will add Foo to QueryStrings
// new RequestInfo(new { Foo = "Bar" }, "PostData"); will add Foo to PostData
// new RequestInfo(new { QueryStrings = new { Foo = "Bar" } }, "PostData"); will add Foo to QueryStrings
// new RequestInfo(new { QueryStrings = new { Foo = "Bar" }, PostData = new { Hi = "There" } }, "PostData"); will add Foo to QueryStrings and Hi to PostData
// new RequestInfo(new { Hi = "There", QueryStrings = new { Foo = "Bar" }}, "PostData"); will add Foo to QueryStrings and Hi to PostData
// new RequestInfo(new { Hi = "There", QueryStrings = new { Foo = "Bar" }}, "Headers"); will add Foo to QueryStrings and Hi to Headers
public class RequestInfo {
public IDictionary<string, string> QueryStrings = new Dictionary<string, string>();
public IDictionary<string, string> PostData = new Dictionary<string, string>();
public IDictionary<string, string> Headers = new Dictionary<string, string>();
public RequestInfo(object anonymousType, string defaultField) {
if (anonymousType == null) return;
// PostData can be a simple string, eg. Post("/dogs", "name=Rover&breed=Something");
if (defaultField == "PostData" && anonymousType is string) {
PostData.Add(anonymousType as string, null);
return;
}
foreach (var variable in Requestor.ToObjectDictionary(anonymousType)) {
switch (variable.Key) {
case "QueryStrings":
QueryStrings = Requestor.ToStringDictionary(variable.Value); break;
// PostData can be a simple string
case "PostData":
if (variable.Value is string)
PostData.Add(variable.Value.ToString(), null);
else
PostData = Requestor.ToStringDictionary(variable.Value);
break;
case "Headers":
Headers = Requestor.ToStringDictionary(variable.Value); break;
default:
switch (defaultField) {
case "QueryStrings": QueryStrings.Add(variable.Key, variable.Value.ToString()); break;
case "PostData": PostData.Add(variable.Key, variable.Value.ToString()); break;
case "Headers": Headers.Add(variable.Key, variable.Value.ToString()); break;
default: throw new Exception("Unknown default type: " + defaultField + ". Expected QueryStrings, PostData, or Headers.");
}
break;
}
}
}
}
#endregion
}
}
| 36.623352 | 162 | 0.675117 | [
"MIT"
] | beccasaurus/mooget | spec/content/moo_dir_for_moo_show/packages/Requestor-1.0.2.2/src/Requestor.cs | 19,449 | C# |
using BlazQ.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazQ.Shared
{
public interface ILobbyClient
{
public Task NewPlayer(ServerSidePlayerOverview newPlayer);
public Task PlayerJoinedLobby(ServerSidePlayerOverview newPlayer);
public Task PlayerLeavedLobby(Guid playerId);
}
}
| 22.882353 | 74 | 0.755784 | [
"MIT"
] | just-the-benno/BlazQ | episode7/BlazQ.Episode7Finished/BlazQ.Shared/ILobbyClient.cs | 391 | C# |
// PeerCastStation, a P2P streaming servent.
// Copyright (C) 2013 PROGRE (djyayutto@gmail.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Windows;
using System.Windows.Controls;
namespace PeerCastStation.WPF.CoreSettings
{
/// <summary>
/// Settings.xaml の相互作用ロジック
/// </summary>
public partial class SettingControl : UserControl
{
public SettingControl()
{
InitializeComponent();
}
private void BandwidthCheckButton_Click(object sender, RoutedEventArgs args)
{
var dialog = new BandwidthCheckDialog();
dialog.Owner = Window.GetWindow(this);
dialog.ShowDialog();
if (dialog.Result.HasValue) {
((SettingViewModel)this.DataContext).MaxUpstreamRate = dialog.Result.Value;
}
}
private void PortCheckButton_Click(object sender, RoutedEventArgs args)
{
((SettingViewModel)this.DataContext).CheckPort();
}
}
}
| 31.854167 | 83 | 0.714192 | [
"Apache-2.0"
] | progre/peercaststation | PeerCastStation/PeerCastStation.WPF/CoreSettings/SettingControl.xaml.cs | 1,549 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using FluentAssertions;
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using IdentityServer4.UnitTests.Common;
using IdentityServer4.Validation;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer4.UnitTests.Validation.EndSessionRequestValidation
{
public class EndSessionRequestValidatorTests
{
private EndSessionRequestValidator _subject;
private IdentityServerOptions _options;
private StubTokenValidator _stubTokenValidator = new StubTokenValidator();
private StubRedirectUriValidator _stubRedirectUriValidator = new StubRedirectUriValidator();
private MockHttpContextAccessor _context = new MockHttpContextAccessor();
private MockUserSession _userSession = new MockUserSession();
private MockMessageStore<EndSession> _mockEndSessionMessageStore = new MockMessageStore<EndSession>();
private InMemoryClientStore _clientStore;
private ClaimsPrincipal _user;
public EndSessionRequestValidatorTests()
{
_user = new IdentityServerUser("alice").CreatePrincipal();
_clientStore = new InMemoryClientStore(new Client[0]);
_options = TestIdentityServerOptions.Create();
_subject = new EndSessionRequestValidator(
_context,
_options,
_stubTokenValidator,
_stubRedirectUriValidator,
_userSession,
_clientStore,
_mockEndSessionMessageStore,
TestLogger.Create<EndSessionRequestValidator>());
}
[Fact]
public async Task anonymous_user_when_options_require_authenticated_user_should_return_error()
{
_options.Authentication.RequireAuthenticatedUserForSignOutMessage = true;
var parameters = new NameValueCollection();
var result = await _subject.ValidateAsync(parameters, null);
result.IsError.Should().BeTrue();
result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal());
result.IsError.Should().BeTrue();
result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(new ClaimsIdentity()));
result.IsError.Should().BeTrue();
}
[Fact]
public async Task valid_params_should_return_success()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult()
{
IsError = false,
Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) },
Client = new Client() { ClientId = "client"}
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true;
var parameters = new NameValueCollection();
parameters.Add("id_token_hint", "id_token");
parameters.Add("post_logout_redirect_uri", "http://client/signout-cb");
parameters.Add("client_id", "client1");
parameters.Add("state", "foo");
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeFalse();
result.ValidatedRequest.Client.ClientId.Should().Be("client");
result.ValidatedRequest.PostLogOutUri.Should().Be("http://client/signout-cb");
result.ValidatedRequest.State.Should().Be("foo");
result.ValidatedRequest.Subject.GetSubjectId().Should().Be(_user.GetSubjectId());
}
[Fact]
public async Task no_post_logout_redirect_uri_should_use_single_registered_uri()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult()
{
IsError = false,
Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) },
Client = new Client() { ClientId = "client1", PostLogoutRedirectUris = new List<string> { "foo" } }
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true;
var parameters = new NameValueCollection();
parameters.Add("id_token_hint", "id_token");
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeFalse();
result.ValidatedRequest.PostLogOutUri.Should().Be("foo");
}
[Fact]
public async Task no_post_logout_redirect_uri_should_not_use_multiple_registered_uri()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult()
{
IsError = false,
Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) },
Client = new Client() { ClientId = "client1", PostLogoutRedirectUris = new List<string> { "foo", "bar" } }
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true;
var parameters = new NameValueCollection();
parameters.Add("id_token_hint", "id_token");
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeFalse();
result.ValidatedRequest.PostLogOutUri.Should().BeNull();
}
[Fact]
public async Task post_logout_uri_fails_validation_should_return_error()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult()
{
IsError = false,
Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) },
Client = new Client() { ClientId = "client" }
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = false;
var parameters = new NameValueCollection();
parameters.Add("id_token_hint", "id_token");
parameters.Add("post_logout_redirect_uri", "http://client/signout-cb");
parameters.Add("client_id", "client1");
parameters.Add("state", "foo");
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeTrue();
}
[Fact]
public async Task subject_mismatch_should_return_error()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult()
{
IsError = false,
Claims = new Claim[] { new Claim("sub", "xoxo") },
Client = new Client() { ClientId = "client" }
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true;
var parameters = new NameValueCollection();
parameters.Add("id_token_hint", "id_token");
parameters.Add("post_logout_redirect_uri", "http://client/signout-cb");
parameters.Add("client_id", "client1");
parameters.Add("state", "foo");
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeTrue();
}
[Fact]
public async Task successful_request_should_return_inputs()
{
var parameters = new NameValueCollection();
var result = await _subject.ValidateAsync(parameters, _user);
result.IsError.Should().BeFalse();
result.ValidatedRequest.Raw.Should().BeSameAs(parameters);
}
}
}
| 42.142077 | 122 | 0.637578 | [
"Apache-2.0"
] | 284171004/IdentityServer4 | src/IdentityServer4/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs | 7,714 | C# |
using System.Reflection;
namespace Bam.Net.CoreServices
{
public interface IAssemblyResolver
{
Assembly ResolveAssembly(string assemblyName, string assemblyDirectory = null);
}
} | 22.222222 | 87 | 0.74 | [
"MIT"
] | BryanApellanes/bam.net.shared | CoreServices/AssemblyManagement/IAssemblyResolver.cs | 202 | C# |
using SPID.AspNetCore.Authentication.Resources;
using System;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
using System.Xml.Serialization;
namespace SPID.AspNetCore.Authentication.Helpers
{
internal static class XmlHelpers
{
/// <summary>
/// Signs the XML document.
/// </summary>
/// <param name="doc">The document.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="referenceUri">The reference URI.</param>
/// <param name="signatureMethod">The signature method.</param>
/// <param name="digestMethod">The digest method.</param>
/// <returns></returns>
/// <exception cref="FieldAccessException"></exception>
internal static XmlElement SignXMLDoc(XmlDocument doc,
X509Certificate2 certificate,
string referenceUri,
string signatureMethod,
string digestMethod)
{
BusinessValidation.ValidationNotNull(doc, ErrorLocalization.XmlDocNull);
BusinessValidation.ValidationNotNull(certificate, ErrorLocalization.CertificateNull);
BusinessValidation.ValidationNotNullNotWhitespace(referenceUri, ErrorLocalization.ReferenceUriNullOrWhitespace);
AsymmetricAlgorithm privateKey;
try
{
privateKey = certificate.PrivateKey;
}
catch (Exception ex)
{
throw new FieldAccessException(ErrorLocalization.PrivateKeyNotFound, ex);
}
SignedXml signedXml = new SignedXml(doc)
{
SigningKey = privateKey
};
signedXml.SignedInfo.SignatureMethod = signatureMethod;
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
Reference reference = new Reference
{
DigestMethod = digestMethod,
Uri = "#" + referenceUri
};
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
signedXml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(certificate));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
return signedXml.GetXml();
}
/// <summary>
/// Verifies the signature.
/// </summary>
/// <param name="signedDocument">The signed document.</param>
/// <param name="xmlMetadata">The XML metadata.</param>
/// <returns></returns>
internal static bool VerifySignature(XmlDocument signedDocument, Saml.EntityDescriptor xmlMetadata = null)
{
BusinessValidation.Argument(signedDocument, string.Format(ErrorLocalization.ParameterCantNullOrEmpty, nameof(signedDocument)));
try
{
SignedXml signedXml = new SignedXml(signedDocument);
if (xmlMetadata is not null)
{
var publicMetadataCert = new X509Certificate2(Convert.FromBase64String(xmlMetadata.IDPSSODescriptor.KeyDescriptor.KeyInfo.X509Data.X509Certificate));
XmlNodeList nodeList = (signedDocument.GetElementsByTagName("ds:Signature")?.Count > 1) ?
signedDocument.GetElementsByTagName("ds:Signature") :
(signedDocument.GetElementsByTagName("ns2:Signature")?.Count > 1) ?
signedDocument.GetElementsByTagName("ns2:Signature") :
signedDocument.GetElementsByTagName("Signature");
signedXml.LoadXml((XmlElement)nodeList[0]);
return signedXml.CheckSignature(publicMetadataCert, true);
}
else
{
XmlNodeList nodeList = (signedDocument.GetElementsByTagName("ds:Signature")?.Count > 0) ?
signedDocument.GetElementsByTagName("ds:Signature") :
signedDocument.GetElementsByTagName("Signature");
signedXml.LoadXml((XmlElement)nodeList[0]);
return signedXml.CheckSignature();
}
}
catch (Exception)
{
return false;
}
}
private static readonly ConcurrentDictionary<Type, XmlSerializer> serializers = new ConcurrentDictionary<Type, XmlSerializer>();
/// <summary>
/// Serializes to XML document.
/// </summary>
/// <param name="o">The o.</param>
/// <returns></returns>
public static XmlDocument SerializeToXmlDoc(this object o)
{
XmlDocument doc = new XmlDocument() { PreserveWhitespace = true };
using XmlWriter writer = doc.CreateNavigator().AppendChild();
if (!serializers.ContainsKey(o.GetType()))
{
var serializer = new XmlSerializer(o.GetType());
serializers.AddOrUpdate(o.GetType(), serializer, (key, value) => serializer);
}
serializers[o.GetType()].Serialize(writer, o);
return doc;
}
}
}
| 42.44697 | 169 | 0.584151 | [
"MIT"
] | danielegiallonardo/spid-aspnetcore | SPID.AspNetCore.Authentication/SPID.AspNetCore.Authentication/Helpers/XmlHelpers.cs | 5,605 | C# |
#region Copyright
// Copyright (c) Tobias Wilker and contributors
// This file is licensed under MIT
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Agents.Net;
using Agents.Net.Designer.Model.Messages;
namespace Agents.Net.Designer.Model.Agents
{
[Intercepts(typeof(ModificationRequestExtending))]
public class AutomaticMessageModelCreator : InterceptorAgent
{
public AutomaticMessageModelCreator(IMessageBoard messageBoard) : base(messageBoard)
{
}
protected override InterceptionAction InterceptCore(Message messageData)
{
messageData.Get<ModificationRequestExtending>().RegisterExtender(ExtendModifications);
return InterceptionAction.Continue;
}
private bool ExtendModifications(List<Modification> modifications)
{
bool modified = false;
foreach (Modification modification in modifications.ToArray())
{
if (modification.ModificationType != ModificationType.Add ||
modification.Target is not AgentModel agentModel ||
!(modification.Property is AgentConsumingMessagesProperty ||
modification.Property is AgentProducedMessagesProperty ||
modification.Property is InterceptorAgentInterceptingMessagesProperty) ||
modification.NewValue is not string)
{
continue;
}
string messageDefinition = modification.NewValue.AssertTypeOf<string>();
MessageModel newMessageModel = new(
GetName(messageDefinition),
GetNamespace(messageDefinition, agentModel));
Modification addMessage = new(ModificationType.Add,
null,
newMessageModel,
agentModel.ContainingPackage,
new PackageMessagesProperty());
Modification modifyMessage = new(modification.ModificationType,
modification.OldValue,
newMessageModel.Id,
modification.Target, modification.Property);
modifications.InsertRange(modifications.IndexOf(modification),
new[] {addMessage, modifyMessage});
modifications.Remove(modification);
modified = true;
}
return modified;
string GetName(string messageDefinition)
{
return messageDefinition.Substring(messageDefinition.LastIndexOf('.') + 1);
}
string GetNamespace(string messageDefinition, AgentModel agentModel)
{
return messageDefinition.Contains('.')
? messageDefinition.Substring(
0, messageDefinition.LastIndexOf('.'))
: GetAgentMessageNamespace(agentModel);
}
}
private string GetAgentMessageNamespace(AgentModel agentModel)
{
string agentNamespace = agentModel.Namespace;
if (agentNamespace.EndsWith(".Agents", StringComparison.Ordinal))
{
return agentNamespace.Substring(0, agentNamespace.Length - ".Agents".Length)
+ ".Messages";
}
return agentNamespace;
}
}
}
| 41.826087 | 99 | 0.549636 | [
"MIT"
] | agents-net/agents.net.designer | src/Agents.Net.Designer.Model/Agents/AutomaticMessageModelCreator.cs | 3,848 | C# |
namespace Develappers.BillomatNet.Types
{
public class InvoiceDocument : Document
{
public int InvoiceId { get; set; }
}
} | 20.428571 | 43 | 0.657343 | [
"MIT"
] | KuroSeongbae/BillomatNet | Develappers.BillomatNet/Types/InvoiceDocument.cs | 145 | C# |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2019 Tim Stair
//
// 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.Collections.Generic;
namespace CardMaker.Card.Translation
{
public interface ITranslatorFactory
{
TranslatorBase GetTranslator(Dictionary<string, int> dictionaryColumnNames,
Dictionary<string, string> dictionaryDefines,
Dictionary<string, Dictionary<string, int>> dictionaryElementOverrides, List<string> listColumnNames);
}
}
| 46.777778 | 114 | 0.683492 | [
"MIT"
] | rogues-gallery/cardmaker | CardMaker/Card/Translation/ITranslatorFactory.cs | 1,686 | C# |
namespace MassTransit.Containers.Tests.Scenarios
{
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Saga;
using Util;
public class SimpleSaga :
ISaga,
InitiatedBy<FirstSagaMessage>,
Orchestrates<SecondSagaMessage>,
Observes<ThirdSagaMessage, SimpleSaga>
{
readonly TaskCompletionSource<FirstSagaMessage> _first = TaskUtil.GetTask<FirstSagaMessage>();
readonly TaskCompletionSource<SecondSagaMessage> _second = TaskUtil.GetTask<SecondSagaMessage>();
readonly TaskCompletionSource<ThirdSagaMessage> _third = TaskUtil.GetTask<ThirdSagaMessage>();
public SimpleSaga(Guid correlationId)
{
CorrelationId = correlationId;
}
protected SimpleSaga()
{
}
public Task<FirstSagaMessage> First => _first.Task;
public Task<SecondSagaMessage> Second => _second.Task;
public Task<ThirdSagaMessage> Third => _third.Task;
public async Task Consume(ConsumeContext<FirstSagaMessage> context)
{
Console.WriteLine("SimpleSaga: First: {0}", context.Message.CorrelationId);
_first.TrySetResult(context.Message);
}
public Guid CorrelationId { get; set; }
public async Task Consume(ConsumeContext<ThirdSagaMessage> context)
{
Console.WriteLine("SimpleSaga: Third: {0}", context.Message.CorrelationId);
_third.TrySetResult(context.Message);
}
Expression<Func<SimpleSaga, ThirdSagaMessage, bool>> Observes<ThirdSagaMessage, SimpleSaga>.CorrelationExpression
{
get { return (saga, message) => saga.CorrelationId == message.CorrelationId; }
}
public async Task Consume(ConsumeContext<SecondSagaMessage> context)
{
Console.WriteLine("SimpleSaga: Second: {0}", context.Message.CorrelationId);
_second.TrySetResult(context.Message);
}
}
}
| 32.934426 | 121 | 0.661025 | [
"ECL-2.0",
"Apache-2.0"
] | MathiasZander/ServiceFabricPerfomanceTest | tests/MassTransit.Containers.Tests/Scenarios/SimpleSaga.cs | 2,009 | C# |
using System;
namespace Core4R.Data
{
public class Class1
{
}
}
| 8.666667 | 23 | 0.602564 | [
"Apache-2.0"
] | samuraitruong/core4r | Sources/Backend/Core4R.Data/Class1.cs | 80 | C# |
/* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. */
/******************************************************************************
*
* You may not use the identified files except in compliance with The MIT
* License (the "License.")
*
* You may obtain a copy of the License at
* https://github.com/oracle/Oracle.NET/blob/master/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
using System;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using System.Data.Common;
using System.Transactions;
class psfTxnScope
{
static void Main()
{
int retVal = 0;
string providerName = "Oracle.ManagedDataAccess.Client";
string constr =
@"User Id=scott;Password=tiger;Data Source=oracle;";
// Get the provider factory.
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
try
{
// Create a TransactionScope object, (It will start an ambient
// transaction automatically).
using (TransactionScope scope = new TransactionScope())
{
// Create first connection object.
using (DbConnection conn1 = factory.CreateConnection())
{
// Set connection string and open the connection. this connection
// will be automatically enlisted in a distributed transaction.
conn1.ConnectionString = constr;
conn1.Open();
// Create a command to execute the sql statement.
DbCommand cmd1 = factory.CreateCommand();
cmd1.Connection = conn1;
cmd1.CommandText = @"insert into dept (deptno, dname, loc)
values (99, 'st', 'lex')";
// Execute the SQL statement to insert one row in DB.
retVal = cmd1.ExecuteNonQuery();
Console.WriteLine("Rows to be affected by cmd1: {0}", retVal);
// Close the connection and dispose the command object.
conn1.Close();
conn1.Dispose();
cmd1.Dispose();
}
// The Complete method commits the transaction. If an exception has
// been thrown or Complete is not called then the transaction is
// rolled back.
scope.Complete();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
| 33.679012 | 80 | 0.605572 | [
"MIT"
] | 268sid255/dotnet-db-samples | samples/transaction/transaction-scope/psfTxnScope.cs | 2,728 | C# |
using System;
namespace Domain.UseCase.AppointmentService.Exceptions
{
[Serializable]
public class ValuesInvalidException : Exception
{
public ValuesInvalidException(string message) : base(message)
{
}
}
} | 19.923077 | 69 | 0.644788 | [
"MIT"
] | Micheler720/Localiza | Domain/UseCase/AppointmentService/Exceptions/ValuesInvalidException.cs | 259 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Codejam
{
class StandInLine
{
int[] Reconstruct(int[] left)
{
int[] final = left;
//Your code goes here
return final;
}
#region Testing code Do not change
public static void Main(String[] args)
{
String input = Console.ReadLine();
StandInLine standInLine = new StandInLine ();
do
{
int[] left = Array.ConvertAll<string, int>(input.Split(','), delegate(string s) { return Int32.Parse(s); });
Console.WriteLine(string.Join(",",Array.ConvertAll<int, string>(standInLine.Reconstruct(left), delegate(int s) { return s.ToString(); })));
input = Console.ReadLine();
} while (input != "-1");
}
#endregion
}
}
| 29.096774 | 155 | 0.537694 | [
"MIT"
] | tavisca-mrathore/TaviscaTraining | CodeJam/StandInLine/StandInLine.cs | 902 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior.
// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).
// https://github.com/angularsen/UnitsNet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Linq;
using JetBrains.Annotations;
using UnitsNet.Units;
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <summary>
/// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.
/// </summary>
// ReSharper disable once PartialTypeWithSinglePart
// Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components
// Public structures can't have any members other than public fields, and those fields must be value types or strings.
// Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic.
#if WINDOWS_UWP
public sealed partial class Permittivity : IQuantity
#else
public partial struct Permittivity : IQuantity, IComparable, IComparable<Permittivity>
#endif
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly PermittivityUnit? _unit;
/// <summary>
/// The unit this quantity was constructed with -or- <see cref="BaseUnit" /> if default ctor was used.
/// </summary>
public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit);
static Permittivity()
{
BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0);
}
/// <summary>
/// Creates the quantity with the given value in the base unit FaradPerMeter.
/// </summary>
[Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")]
public Permittivity(double faradspermeter)
{
_value = Convert.ToDouble(faradspermeter);
_unit = BaseUnit;
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="numericValue">Numeric value.</param>
/// <param name="unit">Unit representation.</param>
/// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks>
#if WINDOWS_UWP
private
#else
public
#endif
Permittivity(double numericValue, PermittivityUnit unit)
{
_value = numericValue;
_unit = unit;
}
// Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods
/// <summary>
/// Creates the quantity with the given value assuming the base unit FaradPerMeter.
/// </summary>
/// <param name="faradspermeter">Value assuming base unit FaradPerMeter.</param>
#if WINDOWS_UWP
private
#else
[Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")]
public
#endif
Permittivity(long faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { }
// Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods
// Windows Runtime Component does not support decimal type
/// <summary>
/// Creates the quantity with the given value assuming the base unit FaradPerMeter.
/// </summary>
/// <param name="faradspermeter">Value assuming base unit FaradPerMeter.</param>
#if WINDOWS_UWP
private
#else
[Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")]
public
#endif
Permittivity(decimal faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { }
#region Properties
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public static QuantityType QuantityType => QuantityType.Permittivity;
/// <summary>
/// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value.
/// </summary>
public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions
{
get;
}
/// <summary>
/// All units of measurement for the Permittivity quantity.
/// </summary>
public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast<PermittivityUnit>().ToArray();
/// <summary>
/// Get Permittivity in FaradsPerMeter.
/// </summary>
public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter);
#endregion
#region Static
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter.
/// </summary>
public static Permittivity Zero => new Permittivity(0, BaseUnit);
/// <summary>
/// Get Permittivity from FaradsPerMeter.
/// </summary>
#if WINDOWS_UWP
[Windows.Foundation.Metadata.DefaultOverload]
public static Permittivity FromFaradsPerMeter(double faradspermeter)
#else
public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter)
#endif
{
double value = (double) faradspermeter;
return new Permittivity(value, PermittivityUnit.FaradPerMeter);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="PermittivityUnit" /> to <see cref="Permittivity" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>Permittivity unit value.</returns>
#if WINDOWS_UWP
// Fix name conflict with parameter "value"
[return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")]
public static Permittivity From(double value, PermittivityUnit fromUnit)
#else
public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit)
#endif
{
return new Permittivity((double)value, fromUnit);
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
[UsedImplicitly]
public static string GetAbbreviation(PermittivityUnit unit)
{
return GetAbbreviation(unit, null);
}
#endregion
#region Equality / IComparable
public int CompareTo(object obj)
{
if(obj is null) throw new ArgumentNullException(nameof(obj));
if(!(obj is Permittivity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj));
return CompareTo((Permittivity)obj);
}
// Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods
#if WINDOWS_UWP
internal
#else
public
#endif
int CompareTo(Permittivity other)
{
return _value.CompareTo(other.AsBaseNumericType(this.Unit));
}
[Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals($quantityName, double, ComparisonType) to provide the max allowed absolute or relative error.")]
public override bool Equals(object obj)
{
if(obj is null || !(obj is Permittivity))
return false;
var objQuantity = (Permittivity)obj;
return _value.Equals(objQuantity.AsBaseNumericType(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another Permittivity within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </para>
/// </summary>
/// <param name="other">The other quantity to compare to.</param>
/// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name="comparisonType">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType)
{
if(tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0.");
double thisValue = (double)this.Value;
double otherValueInThisUnits = other.As(this.Unit);
return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType);
}
/// <summary>
/// Compare equality to another Permittivity by specifying a max allowed difference.
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </summary>
/// <param name="other">Other quantity to compare to.</param>
/// <param name="maxError">Max error allowed.</param>
/// <returns>True if the difference between the two values is not greater than the specified max.</returns>
[Obsolete("Please use the Equals(Permittivity, double, ComparisonType) overload. This method will be removed in a future version.")]
public bool Equals(Permittivity other, Permittivity maxError)
{
return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current Permittivity.</returns>
public override int GetHashCode()
{
return new { Value, Unit }.GetHashCode();
}
#endregion
#region Conversion
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(PermittivityUnit unit)
{
if(Unit == unit)
return Convert.ToDouble(Value);
var converted = AsBaseNumericType(unit);
return Convert.ToDouble(converted);
}
/// <summary>
/// Converts this Permittivity to another Permittivity with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A Permittivity with the specified unit.</returns>
public Permittivity ToUnit(PermittivityUnit unit)
{
var convertedValue = AsBaseNumericType(unit);
return new Permittivity(convertedValue, unit);
}
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double AsBaseUnit()
{
switch(Unit)
{
case PermittivityUnit.FaradPerMeter: return _value;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
private double AsBaseNumericType(PermittivityUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = AsBaseUnit();
switch(unit)
{
case PermittivityUnit.FaradPerMeter: return baseUnitValue;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
#region Parsing
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static Permittivity Parse(string str)
{
return Parse(str, null);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse([CanBeNull] string str, out Permittivity result)
{
return TryParse(str, null, out result);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static PermittivityUnit ParseUnit(string str)
{
return ParseUnit(str, (IFormatProvider)null);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="UnitSystem" />'s default culture.</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
[Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")]
public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName)
{
return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName));
}
#endregion
/// <summary>
/// Set the default unit used by ToString(). Default is FaradPerMeter
/// </summary>
[Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")]
public static PermittivityUnit ToStringDefaultUnit { get; set; } = PermittivityUnit.FaradPerMeter;
/// <summary>
/// Get default string representation of value and unit.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString()
{
return ToString(Unit);
}
/// <summary>
/// Get string representation of value and unit. Using current UI culture and two significant digits after radix.
/// </summary>
/// <param name="unit">Unit representation to use.</param>
/// <returns>String representation.</returns>
public string ToString(PermittivityUnit unit)
{
return ToString(unit, null, 2);
}
/// <summary>
/// Represents the largest possible value of Permittivity
/// </summary>
public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of Permittivity
/// </summary>
public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit);
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public QuantityType Type => Permittivity.QuantityType;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => Permittivity.BaseDimensions;
}
}
| 44.341223 | 311 | 0.621858 | [
"MIT"
] | Maradaehne/UnitsNet | Common/GeneratedCode/Quantities/Permittivity.Common.g.cs | 22,483 | C# |
using ChessCake.Commons;
using ChessCake.Engines.Contracts;
using ChessCake.Models.Boards.Cells.Contracts;
using ChessCake.Models.Boards.Contracts;
using ChessCake.Models.Pieces.Contracts;
using ChessCake.Models.Positions;
using ChessCake.Providers.Movements.Pieces.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace ChessCake.Providers.Movements.Pieces {
public class BishopMovement : BasePieceMovement {
public BishopMovement(IEngine engine, ICell source) : base(engine, source) { }
public override IList<ICell> GenerateLegalMoves() {
IList<ICell> legalMoves = new List<ICell>();
ICell referenceCell;
int referenceRow;
int referenceColumn;
// Northeast Direction:
referenceRow = Source.Position.Row - 1;
referenceColumn = Source.Position.Column + 1;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
while (ValidateReferenceCell(referenceCell)) {
if (!referenceCell.IsOccupied()) {
legalMoves.Add(referenceCell);
}
referenceRow--;
referenceColumn++;
if (!Position.IsValidCoordinates(referenceRow, referenceColumn)) break;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
}
if (ValidateBreakCell(referenceCell)) {
legalMoves.Add(referenceCell);
}
// Southeast Direction:
referenceRow = Source.Position.Row + 1;
referenceColumn = Source.Position.Column + 1;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
while (ValidateReferenceCell(referenceCell)) {
if (!referenceCell.IsOccupied()) {
legalMoves.Add(referenceCell);
}
referenceRow++;
referenceColumn++;
if (!Position.IsValidCoordinates(referenceRow, referenceColumn)) break;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
}
if (ValidateBreakCell(referenceCell)) {
legalMoves.Add(referenceCell);
}
// Southwest Direction:
referenceRow = Source.Position.Row + 1;
referenceColumn = Source.Position.Column - 1;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
while (ValidateReferenceCell(referenceCell)) {
if (!referenceCell.IsOccupied()) {
legalMoves.Add(referenceCell);
}
referenceRow++;
referenceColumn--;
if (!Position.IsValidCoordinates(referenceRow, referenceColumn)) break;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
}
if (ValidateBreakCell(referenceCell)) {
legalMoves.Add(referenceCell);
}
// Northwest Direction:
referenceRow = Source.Position.Row - 1;
referenceColumn = Source.Position.Column - 1;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
while (ValidateReferenceCell(referenceCell)) {
if (!referenceCell.IsOccupied()) {
legalMoves.Add(referenceCell);
}
referenceRow--;
referenceColumn--;
if (!Position.IsValidCoordinates(referenceRow, referenceColumn)) break;
referenceCell = LoadReferenceCell(referenceRow, referenceColumn);
}
if (ValidateBreakCell(referenceCell)) {
legalMoves.Add(referenceCell);
}
return legalMoves;
}
private ICell LoadReferenceCell(int referenceRow, int referenceColumn) {
if (!Position.IsValidCoordinates(referenceRow, referenceColumn)) return null;
ICell referenceCell = Engine.Board.GetCell(referenceRow, referenceColumn);
return referenceCell;
}
}
}
| 34.130081 | 89 | 0.599809 | [
"MIT"
] | gcleiton/chesscake | ChessCake/Providers/Movements/Pieces/BishopMovement.cs | 4,200 | 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 BenchmarkDotNet.Attributes;
using System.Buffers.Reader;
using System.Buffers.Text;
using System.Text;
namespace System.Buffers.Benchmarks
{
public class Reader
{
static byte[] s_array;
static ReadOnlySequence<byte> s_ros;
[GlobalSetup]
public void Setup()
{
var sections = 100000;
var section = "1234 ";
var builder = new StringBuilder(sections * section.Length);
for (int i = 0; i < sections; i++)
{
builder.Append(section);
}
s_array = Encoding.UTF8.GetBytes(builder.ToString());
s_ros = new ReadOnlySequence<byte>(s_array);
}
[Benchmark(Baseline = true)]
public void ParseInt32Utf8Parser()
{
var span = new ReadOnlySpan<byte>(s_array);
int totalConsumed = 0;
while (Utf8Parser.TryParse(span.Slice(totalConsumed), out int value, out int consumed))
{
totalConsumed += consumed + 1;
}
}
[Benchmark]
public void ParseInt32BufferReader()
{
var reader = BufferReader.Create(s_ros);
while (BufferReaderExtensions.TryParse(ref reader, out int value))
{
reader.Advance(1); // advance past the delimiter
}
}
[Benchmark]
public void ParseInt32BufferReaderRaw()
{
var reader = BufferReader.Create(s_ros);
while (Utf8Parser.TryParse(reader.CurrentSegment.Slice(reader.ConsumedBytes), out int value, out int consumed))
{
reader.Advance(consumed + 1);
}
}
}
}
| 29.378788 | 123 | 0.572976 | [
"MIT"
] | benaadams/corefxlab | tests/Benchmarks/System.Buffers/Reader.cs | 1,939 | 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 Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Lkadoxioapplicationtransferownershipv1modifiedby operations.
/// </summary>
public partial class Lkadoxioapplicationtransferownershipv1modifiedby : IServiceOperations<DynamicsClient>, ILkadoxioapplicationtransferownershipv1modifiedby
{
/// <summary>
/// Initializes a new instance of the Lkadoxioapplicationtransferownershipv1modifiedby class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Lkadoxioapplicationtransferownershipv1modifiedby(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get lk_adoxio_applicationtransferownershipv1_modifiedby from systemusers
/// </summary>
/// <param name='ownerid'>
/// key: ownerid of systemuser
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1Collection>> GetWithHttpMessagesAsync(string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (ownerid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ownerid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("ownerid", ownerid);
tracingParameters.Add("top", top);
tracingParameters.Add("skip", skip);
tracingParameters.Add("search", search);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "systemusers({ownerid})/lk_adoxio_applicationtransferownershipv1_modifiedby").ToString();
_url = _url.Replace("{ownerid}", System.Uri.EscapeDataString(ownerid));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (skip != null)
{
_queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1Collection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1Collection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get lk_adoxio_applicationtransferownershipv1_modifiedby from systemusers
/// </summary>
/// <param name='ownerid'>
/// key: ownerid of systemuser
/// </param>
/// <param name='businessprocessflowinstanceid'>
/// key: businessprocessflowinstanceid of adoxio_applicationtransferownershipv1
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1>> ModifiedbyByKeyWithHttpMessagesAsync(string ownerid, string businessprocessflowinstanceid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (ownerid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ownerid");
}
if (businessprocessflowinstanceid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "businessprocessflowinstanceid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("ownerid", ownerid);
tracingParameters.Add("businessprocessflowinstanceid", businessprocessflowinstanceid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ModifiedbyByKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "systemusers({ownerid})/lk_adoxio_applicationtransferownershipv1_modifiedby({businessprocessflowinstanceid})").ToString();
_url = _url.Replace("{ownerid}", System.Uri.EscapeDataString(ownerid));
_url = _url.Replace("{businessprocessflowinstanceid}", System.Uri.EscapeDataString(businessprocessflowinstanceid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationtransferownershipv1>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 45.52459 | 569 | 0.574309 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Lkadoxioapplicationtransferownershipv1modifiedby.cs | 19,439 | 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("VisionUtils")]
[assembly: AssemblyDescription("Assistive Context-Aware Toolkit (ACAT)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("http://01.org/acat")]
[assembly: AssemblyProduct("Assistive Context-Aware Toolkit (ACAT)")]
[assembly: AssemblyCopyright("Licensed and distributed under the Apache License v2.0 by Intel Corporation")]
[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("98f7820c-c8ba-40ce-9f81-c370ddb62273")]
// 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")]
| 40.447368 | 108 | 0.752115 | [
"Apache-2.0"
] | 125m125/acat | src/Extensions/Default/Actuators/Vision/VisionUtils/Properties/AssemblyInfo.cs | 1,539 | C# |
namespace JT809.Protocol
{
/// <summary>
/// 报文加密标识位 b: 0 表示报文不加密,1 表示报文加密。
/// </summary>
public enum JT809Header_Encrypt:byte
{
None = 0X00,
Common = 0X01,
}
}
| 16.916667 | 40 | 0.541872 | [
"MIT"
] | 786744873/JT809 | src/JT809.Protocol/JT809Header_Encrypt.cs | 249 | C# |
/*
* ORY Hydra
*
* Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here.
*
* The version of the OpenAPI document: v1.9.1
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using Ory.Hydra.Client.Client;
using Ory.Hydra.Client.Model;
namespace Ory.Hydra.Client.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IPublicApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout
/// </summary>
/// <remarks>
/// This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns></returns>
void DisconnectUser();
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout
/// </summary>
/// <remarks>
/// This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DisconnectUserWithHttpInfo();
/// <summary>
/// OpenID Connect Discovery
/// </summary>
/// <remarks>
/// The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraWellKnown</returns>
HydraWellKnown DiscoverOpenIDConfiguration();
/// <summary>
/// OpenID Connect Discovery
/// </summary>
/// <remarks>
/// The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraWellKnown</returns>
ApiResponse<HydraWellKnown> DiscoverOpenIDConfigurationWithHttpInfo();
/// <summary>
/// Check Readiness Status
/// </summary>
/// <remarks>
/// This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraHealthStatus</returns>
HydraHealthStatus IsInstanceReady();
/// <summary>
/// Check Readiness Status
/// </summary>
/// <remarks>
/// This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraHealthStatus</returns>
ApiResponse<HydraHealthStatus> IsInstanceReadyWithHttpInfo();
/// <summary>
/// The OAuth 2.0 Token Endpoint
/// </summary>
/// <remarks>
/// The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <returns>HydraOauth2TokenResponse</returns>
HydraOauth2TokenResponse Oauth2Token(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string));
/// <summary>
/// The OAuth 2.0 Token Endpoint
/// </summary>
/// <remarks>
/// The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <returns>ApiResponse of HydraOauth2TokenResponse</returns>
ApiResponse<HydraOauth2TokenResponse> Oauth2TokenWithHttpInfo(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string));
/// <summary>
/// The OAuth 2.0 Authorize Endpoint
/// </summary>
/// <remarks>
/// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns></returns>
void OauthAuth();
/// <summary>
/// The OAuth 2.0 Authorize Endpoint
/// </summary>
/// <remarks>
/// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> OauthAuthWithHttpInfo();
/// <summary>
/// Revoke OAuth2 Tokens
/// </summary>
/// <remarks>
/// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <returns></returns>
void RevokeOAuth2Token(string token);
/// <summary>
/// Revoke OAuth2 Tokens
/// </summary>
/// <remarks>
/// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> RevokeOAuth2TokenWithHttpInfo(string token);
/// <summary>
/// OpenID Connect Userinfo
/// </summary>
/// <remarks>
/// This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraUserinfoResponse</returns>
HydraUserinfoResponse Userinfo();
/// <summary>
/// OpenID Connect Userinfo
/// </summary>
/// <remarks>
/// This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraUserinfoResponse</returns>
ApiResponse<HydraUserinfoResponse> UserinfoWithHttpInfo();
/// <summary>
/// JSON Web Keys Discovery
/// </summary>
/// <remarks>
/// This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraJSONWebKeySet</returns>
HydraJSONWebKeySet WellKnown();
/// <summary>
/// JSON Web Keys Discovery
/// </summary>
/// <remarks>
/// This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraJSONWebKeySet</returns>
ApiResponse<HydraJSONWebKeySet> WellKnownWithHttpInfo();
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IPublicApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout
/// </summary>
/// <remarks>
/// This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DisconnectUserAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout
/// </summary>
/// <remarks>
/// This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DisconnectUserWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// OpenID Connect Discovery
/// </summary>
/// <remarks>
/// The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraWellKnown</returns>
System.Threading.Tasks.Task<HydraWellKnown> DiscoverOpenIDConfigurationAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// OpenID Connect Discovery
/// </summary>
/// <remarks>
/// The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraWellKnown)</returns>
System.Threading.Tasks.Task<ApiResponse<HydraWellKnown>> DiscoverOpenIDConfigurationWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Check Readiness Status
/// </summary>
/// <remarks>
/// This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraHealthStatus</returns>
System.Threading.Tasks.Task<HydraHealthStatus> IsInstanceReadyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Check Readiness Status
/// </summary>
/// <remarks>
/// This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraHealthStatus)</returns>
System.Threading.Tasks.Task<ApiResponse<HydraHealthStatus>> IsInstanceReadyWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// The OAuth 2.0 Token Endpoint
/// </summary>
/// <remarks>
/// The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraOauth2TokenResponse</returns>
System.Threading.Tasks.Task<HydraOauth2TokenResponse> Oauth2TokenAsync(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// The OAuth 2.0 Token Endpoint
/// </summary>
/// <remarks>
/// The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraOauth2TokenResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<HydraOauth2TokenResponse>> Oauth2TokenWithHttpInfoAsync(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// The OAuth 2.0 Authorize Endpoint
/// </summary>
/// <remarks>
/// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task OauthAuthAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// The OAuth 2.0 Authorize Endpoint
/// </summary>
/// <remarks>
/// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> OauthAuthWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Revoke OAuth2 Tokens
/// </summary>
/// <remarks>
/// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task RevokeOAuth2TokenAsync(string token, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Revoke OAuth2 Tokens
/// </summary>
/// <remarks>
/// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> RevokeOAuth2TokenWithHttpInfoAsync(string token, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// OpenID Connect Userinfo
/// </summary>
/// <remarks>
/// This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraUserinfoResponse</returns>
System.Threading.Tasks.Task<HydraUserinfoResponse> UserinfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// OpenID Connect Userinfo
/// </summary>
/// <remarks>
/// This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraUserinfoResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<HydraUserinfoResponse>> UserinfoWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// JSON Web Keys Discovery
/// </summary>
/// <remarks>
/// This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraJSONWebKeySet</returns>
System.Threading.Tasks.Task<HydraJSONWebKeySet> WellKnownAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// JSON Web Keys Discovery
/// </summary>
/// <remarks>
/// This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </remarks>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraJSONWebKeySet)</returns>
System.Threading.Tasks.Task<ApiResponse<HydraJSONWebKeySet>> WellKnownWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IPublicApi : IPublicApiSync, IPublicApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class PublicApi : IPublicApi
{
private Ory.Hydra.Client.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="PublicApi"/> class.
/// </summary>
/// <returns></returns>
public PublicApi() : this((string)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PublicApi"/> class.
/// </summary>
/// <returns></returns>
public PublicApi(String basePath)
{
this.Configuration = Ory.Hydra.Client.Client.Configuration.MergeConfigurations(
Ory.Hydra.Client.Client.GlobalConfiguration.Instance,
new Ory.Hydra.Client.Client.Configuration { BasePath = basePath }
);
this.Client = new Ory.Hydra.Client.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Ory.Hydra.Client.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = Ory.Hydra.Client.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="PublicApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public PublicApi(Ory.Hydra.Client.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = Ory.Hydra.Client.Client.Configuration.MergeConfigurations(
Ory.Hydra.Client.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new Ory.Hydra.Client.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Ory.Hydra.Client.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = Ory.Hydra.Client.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="PublicApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public PublicApi(Ory.Hydra.Client.Client.ISynchronousClient client, Ory.Hydra.Client.Client.IAsynchronousClient asyncClient, Ory.Hydra.Client.Client.IReadableConfiguration configuration)
{
if (client == null) throw new ArgumentNullException("client");
if (asyncClient == null) throw new ArgumentNullException("asyncClient");
if (configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = Ory.Hydra.Client.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public Ory.Hydra.Client.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public Ory.Hydra.Client.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Ory.Hydra.Client.Client.IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Ory.Hydra.Client.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns></returns>
public void DisconnectUser()
{
DisconnectUserWithHttpInfo();
}
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of Object(void)</returns>
public Ory.Hydra.Client.Client.ApiResponse<Object> DisconnectUserWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = this.Client.Get<Object>("/oauth2/sessions/logout", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DisconnectUser", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DisconnectUserAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await DisconnectUserWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// OpenID Connect Front-Backchannel Enabled Logout This endpoint initiates and completes user logout at ORY Hydra and initiates OpenID Connect Front-/Back-channel logout: https://openid.net/specs/openid-connect-frontchannel-1_0.html https://openid.net/specs/openid-connect-backchannel-1_0.html
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<Object>> DisconnectUserWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<Object>("/oauth2/sessions/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DisconnectUser", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// OpenID Connect Discovery The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraWellKnown</returns>
public HydraWellKnown DiscoverOpenIDConfiguration()
{
Ory.Hydra.Client.Client.ApiResponse<HydraWellKnown> localVarResponse = DiscoverOpenIDConfigurationWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// OpenID Connect Discovery The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraWellKnown</returns>
public Ory.Hydra.Client.Client.ApiResponse<HydraWellKnown> DiscoverOpenIDConfigurationWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = this.Client.Get<HydraWellKnown>("/.well-known/openid-configuration", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DiscoverOpenIDConfiguration", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// OpenID Connect Discovery The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraWellKnown</returns>
public async System.Threading.Tasks.Task<HydraWellKnown> DiscoverOpenIDConfigurationAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.ApiResponse<HydraWellKnown> localVarResponse = await DiscoverOpenIDConfigurationWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// OpenID Connect Discovery The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this flow at https://openid.net/specs/openid-connect-discovery-1_0.html . Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others. For a full list of clients go here: https://openid.net/developers/certified/
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraWellKnown)</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<HydraWellKnown>> DiscoverOpenIDConfigurationWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<HydraWellKnown>("/.well-known/openid-configuration", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DiscoverOpenIDConfiguration", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// Check Readiness Status This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraHealthStatus</returns>
public HydraHealthStatus IsInstanceReady()
{
Ory.Hydra.Client.Client.ApiResponse<HydraHealthStatus> localVarResponse = IsInstanceReadyWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// Check Readiness Status This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraHealthStatus</returns>
public Ory.Hydra.Client.Client.ApiResponse<HydraHealthStatus> IsInstanceReadyWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = this.Client.Get<HydraHealthStatus>("/health/ready", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("IsInstanceReady", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// Check Readiness Status This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraHealthStatus</returns>
public async System.Threading.Tasks.Task<HydraHealthStatus> IsInstanceReadyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.ApiResponse<HydraHealthStatus> localVarResponse = await IsInstanceReadyWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// Check Readiness Status This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraHealthStatus)</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<HydraHealthStatus>> IsInstanceReadyWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<HydraHealthStatus>("/health/ready", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("IsInstanceReady", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// The OAuth 2.0 Token Endpoint The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <returns>HydraOauth2TokenResponse</returns>
public HydraOauth2TokenResponse Oauth2Token(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string))
{
Ory.Hydra.Client.Client.ApiResponse<HydraOauth2TokenResponse> localVarResponse = Oauth2TokenWithHttpInfo(grantType, code, refreshToken, redirectUri, clientId);
return localVarResponse.Data;
}
/// <summary>
/// The OAuth 2.0 Token Endpoint The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <returns>ApiResponse of HydraOauth2TokenResponse</returns>
public Ory.Hydra.Client.Client.ApiResponse<HydraOauth2TokenResponse> Oauth2TokenWithHttpInfo(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string))
{
// verify the required parameter 'grantType' is set
if (grantType == null)
throw new Ory.Hydra.Client.Client.ApiException(400, "Missing required parameter 'grantType' when calling PublicApi->Oauth2Token");
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.FormParameters.Add("grant_type", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(grantType)); // form parameter
if (code != null)
{
localVarRequestOptions.FormParameters.Add("code", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(code)); // form parameter
}
if (refreshToken != null)
{
localVarRequestOptions.FormParameters.Add("refresh_token", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(refreshToken)); // form parameter
}
if (redirectUri != null)
{
localVarRequestOptions.FormParameters.Add("redirect_uri", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(redirectUri)); // form parameter
}
if (clientId != null)
{
localVarRequestOptions.FormParameters.Add("client_id", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(clientId)); // form parameter
}
// authentication (basic) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Ory.Hydra.Client.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Post<HydraOauth2TokenResponse>("/oauth2/token", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("Oauth2Token", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// The OAuth 2.0 Token Endpoint The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraOauth2TokenResponse</returns>
public async System.Threading.Tasks.Task<HydraOauth2TokenResponse> Oauth2TokenAsync(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.ApiResponse<HydraOauth2TokenResponse> localVarResponse = await Oauth2TokenWithHttpInfoAsync(grantType, code, refreshToken, redirectUri, clientId, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// The OAuth 2.0 Token Endpoint The client makes a request to the token endpoint by sending the following parameters using the \"application/x-www-form-urlencoded\" HTTP request entity-body. > Do not implement a client for this endpoint yourself. Use a library. There are many libraries > available for any programming language. You can find a list of libraries here: https://oauth.net/code/ > > Do note that Hydra SDK does not implement this endpoint properly. Use one of the libraries listed above!
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="grantType"></param>
/// <param name="code"> (optional)</param>
/// <param name="refreshToken"> (optional)</param>
/// <param name="redirectUri"> (optional)</param>
/// <param name="clientId"> (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraOauth2TokenResponse)</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<HydraOauth2TokenResponse>> Oauth2TokenWithHttpInfoAsync(string grantType, string code = default(string), string refreshToken = default(string), string redirectUri = default(string), string clientId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// verify the required parameter 'grantType' is set
if (grantType == null)
throw new Ory.Hydra.Client.Client.ApiException(400, "Missing required parameter 'grantType' when calling PublicApi->Oauth2Token");
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.FormParameters.Add("grant_type", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(grantType)); // form parameter
if (code != null)
{
localVarRequestOptions.FormParameters.Add("code", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(code)); // form parameter
}
if (refreshToken != null)
{
localVarRequestOptions.FormParameters.Add("refresh_token", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(refreshToken)); // form parameter
}
if (redirectUri != null)
{
localVarRequestOptions.FormParameters.Add("redirect_uri", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(redirectUri)); // form parameter
}
if (clientId != null)
{
localVarRequestOptions.FormParameters.Add("client_id", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(clientId)); // form parameter
}
// authentication (basic) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Ory.Hydra.Client.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<HydraOauth2TokenResponse>("/oauth2/token", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("Oauth2Token", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// The OAuth 2.0 Authorize Endpoint This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns></returns>
public void OauthAuth()
{
OauthAuthWithHttpInfo();
}
/// <summary>
/// The OAuth 2.0 Authorize Endpoint This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of Object(void)</returns>
public Ory.Hydra.Client.Client.ApiResponse<Object> OauthAuthWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = this.Client.Get<Object>("/oauth2/auth", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("OauthAuth", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// The OAuth 2.0 Authorize Endpoint This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task OauthAuthAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await OauthAuthWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The OAuth 2.0 Authorize Endpoint This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a library for your programming language will exists. To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<Object>> OauthAuthWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<Object>("/oauth2/auth", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("OauthAuth", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// Revoke OAuth2 Tokens Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <returns></returns>
public void RevokeOAuth2Token(string token)
{
RevokeOAuth2TokenWithHttpInfo(token);
}
/// <summary>
/// Revoke OAuth2 Tokens Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <returns>ApiResponse of Object(void)</returns>
public Ory.Hydra.Client.Client.ApiResponse<Object> RevokeOAuth2TokenWithHttpInfo(string token)
{
// verify the required parameter 'token' is set
if (token == null)
throw new Ory.Hydra.Client.Client.ApiException(400, "Missing required parameter 'token' when calling PublicApi->RevokeOAuth2Token");
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.FormParameters.Add("token", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(token)); // form parameter
// authentication (basic) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Ory.Hydra.Client.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/oauth2/revoke", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("RevokeOAuth2Token", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// Revoke OAuth2 Tokens Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task RevokeOAuth2TokenAsync(string token, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await RevokeOAuth2TokenWithHttpInfoAsync(token, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Revoke OAuth2 Tokens Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token. Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by the client the token was generated for.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="token"></param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<Object>> RevokeOAuth2TokenWithHttpInfoAsync(string token, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// verify the required parameter 'token' is set
if (token == null)
throw new Ory.Hydra.Client.Client.ApiException(400, "Missing required parameter 'token' when calling PublicApi->RevokeOAuth2Token");
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.FormParameters.Add("token", Ory.Hydra.Client.Client.ClientUtils.ParameterToString(token)); // form parameter
// authentication (basic) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Ory.Hydra.Client.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/oauth2/revoke", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("RevokeOAuth2Token", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// OpenID Connect Userinfo This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraUserinfoResponse</returns>
public HydraUserinfoResponse Userinfo()
{
Ory.Hydra.Client.Client.ApiResponse<HydraUserinfoResponse> localVarResponse = UserinfoWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// OpenID Connect Userinfo This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraUserinfoResponse</returns>
public Ory.Hydra.Client.Client.ApiResponse<HydraUserinfoResponse> UserinfoWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Get<HydraUserinfoResponse>("/userinfo", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("Userinfo", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// OpenID Connect Userinfo This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraUserinfoResponse</returns>
public async System.Threading.Tasks.Task<HydraUserinfoResponse> UserinfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.ApiResponse<HydraUserinfoResponse> localVarResponse = await UserinfoWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// OpenID Connect Userinfo This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 Access Token. For more information please [refer to the spec](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraUserinfoResponse)</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<HydraUserinfoResponse>> UserinfoWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<HydraUserinfoResponse>("/userinfo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("Userinfo", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// JSON Web Keys Discovery This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>HydraJSONWebKeySet</returns>
public HydraJSONWebKeySet WellKnown()
{
Ory.Hydra.Client.Client.ApiResponse<HydraJSONWebKeySet> localVarResponse = WellKnownWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// JSON Web Keys Discovery This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of HydraJSONWebKeySet</returns>
public Ory.Hydra.Client.Client.ApiResponse<HydraJSONWebKeySet> WellKnownWithHttpInfo()
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = this.Client.Get<HydraJSONWebKeySet>("/.well-known/jwks.json", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("WellKnown", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// JSON Web Keys Discovery This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of HydraJSONWebKeySet</returns>
public async System.Threading.Tasks.Task<HydraJSONWebKeySet> WellKnownAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.ApiResponse<HydraJSONWebKeySet> localVarResponse = await WellKnownWithHttpInfoAsync(cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// JSON Web Keys Discovery This endpoint returns JSON Web Keys to be used as public keys for verifying OpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This endpoint can be used with client libraries like [node-jwks-rsa](https://github.com/auth0/node-jwks-rsa) among others.
/// </summary>
/// <exception cref="Ory.Hydra.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (HydraJSONWebKeySet)</returns>
public async System.Threading.Tasks.Task<Ory.Hydra.Client.Client.ApiResponse<HydraJSONWebKeySet>> WellKnownWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Ory.Hydra.Client.Client.RequestOptions localVarRequestOptions = new Ory.Hydra.Client.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Ory.Hydra.Client.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<HydraJSONWebKeySet>("/.well-known/jwks.json", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("WellKnown", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
}
}
| 64.105263 | 532 | 0.684113 | [
"Apache-2.0"
] | UkonnRa/sdk | clients/hydra/dotnet/src/Ory.Hydra.Client/Api/PublicApi.cs | 92,568 | C# |
// Copyright (c) True Goodwill. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace FFT.SlottedTimers.Tests
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TimerTests
{
[TestMethod]
public async Task TimerWorks()
{
using var timer = new SlottedTimer(50);
using var cts = new CancellationTokenSource(2000);
var sw1 = Stopwatch.StartNew();
var sw2 = Stopwatch.StartNew();
var t1 = Task.Run(async () =>
{
await timer.WaitAsync(100, cts.Token);
sw1.Stop();
});
var t2 = Task.Run(async () =>
{
await timer.WaitAsync(1000, cts.Token);
sw2.Stop();
});
await Task.WhenAll(t1, t2);
Assert.IsTrue(sw1.ElapsedMilliseconds > 50 && sw1.ElapsedMilliseconds < 150);
Assert.IsTrue(sw2.ElapsedMilliseconds > 900 && sw1.ElapsedMilliseconds < 1100);
}
[TestMethod]
public async Task CancellationWorks()
{
using var timer = new SlottedTimer(50);
using var cts = new CancellationTokenSource(900);
await Assert.ThrowsExceptionAsync<OperationCanceledException>(() => Task.Run(async () => await timer.WaitAsync(1000, cts.Token)));
}
}
}
| 29.808511 | 136 | 0.657388 | [
"MIT"
] | FastFinTech/FFT.SlottedTimers | src/FFT.SlottedTimers.Tests/TimerTests.cs | 1,401 | C# |
using MBran.Core.Models;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
namespace MBran.Core
{
public class ContentHelper : IContentHelper
{
private readonly UmbracoHelper _umbracoHelper;
public ContentHelper(UmbracoHelper umbracoHelper)
{
_umbracoHelper = umbracoHelper;
}
public IEnumerable<T> GetDescendants<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return new List<T>();
}
var children = startNode.Descendants<T>()
.Where(c => c.Id > 0);
return children;
}
public IEnumerable<T> GetDescendantsOrSelf<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return new List<T>();
}
var children = startNode.DescendantsOrSelf<T>().ToList();
return children;
}
public T GetDescendant<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return default(T);
}
var descendant = startNode.Descendant<T>();
return descendant;
}
public T GetDescendantOrSelf<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return default(T);
}
var descendant = startNode.DescendantOrSelf<T>();
return descendant;
}
public IEnumerable<T> GetAncestors<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return new List<T>();
}
var children = startNode.Ancestors<T>()
.Where(c => c.Id > 0);
return children;
}
public IEnumerable<T> GetAncestorsOrSelf<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return new List<T>();
}
var children = startNode.AncestorsOrSelf<T>().ToList();
return children;
}
public T GetAncestor<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return default(T);
}
var ancestor = startNode.Ancestor<T>();
return ancestor;
}
public T GetAncestorOrSelf<T>(int startId) where T : class, IPublishedContent
{
var startNode = _umbracoHelper.TypedContent(startId);
if (startNode == null || startNode.Id <= 0)
{
return default(T);
}
var ancestor = startNode.Ancestor<T>();
return ancestor;
}
public T GetContent<T>(int nodeId) where T : PublishedContentModel
{
var node = _umbracoHelper.TypedContent(nodeId)?.As<T>();
return node;
}
public IPublishedContent GetRoot()
{
var root = _umbracoHelper.TypedContentAtRoot().First();
return root;
}
public IPublishedContent CurrentPage()
{
return _umbracoHelper.UmbracoContext.PublishedContentRequest.PublishedContent;
}
public T CurrentPage<T>() where T : PublishedContentModel
{
var currentPage = CurrentPage();
return currentPage.As<T>();
}
public int CurrentPageId()
{
return CurrentPage().Id;
}
}
}
| 29.655405 | 101 | 0.541353 | [
"MIT"
] | markglibres/umbraco-starter-kit | src/Core/MBran.Core/Helpers/ContentHelper.cs | 4,391 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the AWSMigrationHub-2017-05-31.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.MigrationHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MigrationHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// NotifyApplicationState Request Marshaller
/// </summary>
public class NotifyApplicationStateRequestMarshaller : IMarshaller<IRequest, NotifyApplicationStateRequest> , 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((NotifyApplicationStateRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(NotifyApplicationStateRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.MigrationHub");
string target = "AWSMigrationHub.NotifyApplicationState";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-05-31";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetApplicationId())
{
context.Writer.WritePropertyName("ApplicationId");
context.Writer.Write(publicRequest.ApplicationId);
}
if(publicRequest.IsSetDryRun())
{
context.Writer.WritePropertyName("DryRun");
context.Writer.Write(publicRequest.DryRun);
}
if(publicRequest.IsSetStatus())
{
context.Writer.WritePropertyName("Status");
context.Writer.Write(publicRequest.Status);
}
if(publicRequest.IsSetUpdateDateTime())
{
context.Writer.WritePropertyName("UpdateDateTime");
context.Writer.Write(publicRequest.UpdateDateTime);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static NotifyApplicationStateRequestMarshaller _instance = new NotifyApplicationStateRequestMarshaller();
internal static NotifyApplicationStateRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static NotifyApplicationStateRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.206612 | 159 | 0.619265 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/MigrationHub/Generated/Model/Internal/MarshallTransformations/NotifyApplicationStateRequestMarshaller.cs | 4,381 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("aliyun-ddns")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("aliyun-ddns")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("eeb8273b-daed-4bc8-bc3d-e01dcad71a9d")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.486486 | 56 | 0.712619 | [
"MIT"
] | hxulin/aliyun-ddns | aliyun-ddns/Properties/AssemblyInfo.cs | 1,284 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace TickTrader.BotTerminal
{
public class AutoColumnsGrid : UniformGrid
{
public static readonly DependencyProperty ColumnMinWidthProperty =
DependencyProperty.Register(nameof(MinColumnWidth), typeof(double), typeof(AutoColumnsGrid), new FrameworkPropertyMetadata(40.0));
public static readonly DependencyProperty MaxColumnsProperty =
DependencyProperty.Register(nameof(MaxColumns), typeof(int), typeof(AutoColumnsGrid), new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty MinColumnsProperty =
DependencyProperty.Register(nameof(MinColumns), typeof(int), typeof(AutoColumnsGrid), new FrameworkPropertyMetadata(0));
public double MinColumnWidth
{
get { return (double)GetValue(ColumnMinWidthProperty); }
set { SetValue(ColumnMinWidthProperty, value); }
}
public int MaxColumns
{
get { return (int)GetValue(MaxColumnsProperty); }
set { SetValue(MaxColumnsProperty, value); }
}
public int MinColumns
{
get { return (int)GetValue(MinColumnsProperty); }
set { SetValue(MinColumnsProperty, value); }
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
if (sizeInfo.WidthChanged)
RecalculateColumnsCount(sizeInfo.NewSize);
base.OnRenderSizeChanged(sizeInfo);
}
protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
{
RecalculateColumnsCount(RenderSize);
base.OnVisualChildrenChanged(visualAdded, visualRemoved);
}
private void RecalculateColumnsCount(Size areaSize)
{
var columnMinSize = MinColumnWidth;
var minCount = MinColumns > 0 ? MinColumns : 1;
if (columnMinSize > 0)
{
var newColumsCount = (int)Math.Floor(areaSize.Width / columnMinSize);
if (MaxColumns > 0 && newColumsCount > MaxColumns)
newColumsCount = MaxColumns;
if (newColumsCount <= minCount)
newColumsCount = minCount;
if (newColumsCount > VisualChildrenCount)
newColumsCount = VisualChildrenCount;
if (newColumsCount != Columns)
Columns = newColumsCount;
}
}
}
}
| 33.7875 | 142 | 0.63929 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SoftFx/TTAlgo | TickTrader.BotTerminal/Controls/AutoColumnsGrid.cs | 2,705 | C# |
using System.Threading.Tasks;
using Xunit;
namespace JikanDotNet.Tests
{
public class PersonExtendedTestClass
{
private readonly IJikan jikan;
public PersonExtendedTestClass()
{
jikan = new Jikan();
}
[Fact]
public async Task GetPersonPictures_WakamotoId_ShouldParseNorioWakamotoImages()
{
PersonPictures norioWakamoto = await jikan.GetPersonPictures(84);
Assert.Equal(4, norioWakamoto.Pictures.Count);
}
}
} | 19.173913 | 81 | 0.75737 | [
"MIT"
] | EZ1SGT/jikan.net | JikanDotNet.Test/PersonExtendedTestClass.cs | 443 | C# |
using System;
using System.Net.Http;
namespace Alpaca.Markets
{
/// <summary>
/// Encapsulates request parameters for <see cref="AlpacaTradingClient.ListCalendarAsync(CalendarRequest,System.Threading.CancellationToken)"/> call.
/// </summary>
public sealed class CalendarRequest : IRequestWithTimeInterval<IInclusiveTimeInterval>
{
/// <summary>
/// Gets inclusive date interval for filtering items in response.
/// </summary>
public IInclusiveTimeInterval TimeInterval { get; private set; } = Markets.TimeInterval.InclusiveEmpty;
/// <summary>
/// Gets start time for filtering (inclusive).
/// </summary>
[Obsolete("Use the TimeInterval.From property instead.", true)]
public DateTime? StartDateInclusive => TimeInterval?.From;
/// <summary>
/// Gets end time for filtering (inclusive).
/// </summary>
[Obsolete("Use the TimeInterval.Into property instead.", true)]
public DateTime? EndDateInclusive => TimeInterval?.Into;
/// <summary>
/// Sets exclusive time interval for request (start/end time included into interval if specified).
/// </summary>
/// <param name="start">Filtering interval start time.</param>
/// <param name="end">Filtering interval end time.</param>
/// <returns>Fluent interface method return same <see cref="CalendarRequest"/> instance.</returns>
[Obsolete("This method will be removed soon in favor of the extension method SetInclusiveTimeInterval.", true)]
public CalendarRequest SetInclusiveTimeIntervalWithNulls(
DateTime? start,
DateTime? end) =>
this.SetTimeInterval(Markets.TimeInterval.GetInclusive(start, end));
internal UriBuilder GetUriBuilder(
HttpClient httpClient) =>
new UriBuilder(httpClient.BaseAddress)
{
Path = "v2/calendar",
Query = new QueryBuilder()
.AddParameter("start", TimeInterval?.From, DateTimeHelper.DateFormat)
.AddParameter("end", TimeInterval?.Into, DateTimeHelper.DateFormat)
};
void IRequestWithTimeInterval<IInclusiveTimeInterval>.SetInterval(
IInclusiveTimeInterval value) => TimeInterval = value;
}
}
| 43.648148 | 153 | 0.645736 | [
"Apache-2.0"
] | darocha/alpaca-trade-api-csharp | Alpaca.Markets/Parameters/CalendarRequest.cs | 2,359 | C# |
using System.IO;
using CppSharp.AST;
using CppSharp.Generators;
using CppSharp.Passes;
using CppSharp.Utils;
namespace CppSharp.Tests
{
public class NamespacesDerivedTests : GeneratorTest
{
public NamespacesDerivedTests(GeneratorKind kind)
: base("NamespacesDerived", kind)
{
}
public override void Setup(Driver driver)
{
base.Setup(driver);
driver.Options.GenerateDefaultValuesForArguments = true;
driver.Options.Modules[1].IncludeDirs.Add(GetTestsDirectory("NamespacesDerived"));
var @base = "NamespacesBase";
var module = new Module();
module.IncludeDirs.Add(Path.GetFullPath(GetTestsDirectory(@base)));
module.Headers.Add(string.Format("{0}.h", @base));
module.OutputNamespace = @base;
module.SharedLibraryName = string.Format("{0}.Native", @base);
// Workaround for CLR which does not check for .dll if the name already has a dot
if (System.Type.GetType("Mono.Runtime") == null)
module.SharedLibraryName += ".dll";
module.LibraryName = @base;
driver.Options.Modules.Insert(1, module);
}
public override void Postprocess(Driver driver, ASTContext ctx)
{
driver.Generator.OnUnitGenerated += o =>
{
Block firstBlock = o.Outputs[0].RootBlock.Blocks[1];
firstBlock.WriteLine("using System.Runtime.CompilerServices;");
firstBlock.NewLine();
firstBlock.WriteLine("[assembly:InternalsVisibleTo(\"NamespacesDerived.CSharp\")]");
};
}
}
public class NamespacesDerived
{
public static void Main(string[] args)
{
ConsoleDriver.Run(new NamespacesDerivedTests(GeneratorKind.CSharp));
}
}
}
| 33.982143 | 100 | 0.605885 | [
"MIT"
] | JackWangCUMT/CppSharp | tests/NamespacesDerived/NamespacesDerived.cs | 1,903 | C# |
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using BlazingPizza.Client.Pages;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
namespace BlazingPizza.Client
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services
.AddHttpClient<OrdersClient>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped<OrderState>();
builder.Services.AddApiAuthorization<PizzaAuthenticationState>(options => {
options.AuthenticationPaths.LogOutSucceededPath = "";
});
await builder.Build().RunAsync();
}
}
}
| 37.28125 | 124 | 0.682313 | [
"MIT"
] | mikesigs/blazor-workshop | save-points/00-get-started/BlazingPizza.Client/Program.cs | 1,195 | 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 MediaPlayer.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;
}
}
}
}
| 34.387097 | 151 | 0.581614 | [
"Apache-2.0"
] | OmarMAshour/Fantaza | MediaPlayer/Properties/Settings.Designer.cs | 1,068 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x64.Instructions
{
/// <summary>
/// Sub32
/// </summary>
/// <seealso cref="Mosa.Platform.x64.X64Instruction" />
public sealed class Sub32 : X64Instruction
{
internal Sub32()
: base(1, 2)
{
}
public override bool ThreeTwoAddressConversion { get { return true; } }
public override bool IsZeroFlagModified { get { return true; } }
public override bool IsCarryFlagModified { get { return true; } }
public override bool IsSignFlagModified { get { return true; } }
public override bool IsOverflowFlagModified { get { return true; } }
public override bool IsParityFlagModified { get { return true; } }
public override void Emit(InstructionNode node, OpcodeEncoder opcodeEncoder)
{
System.Diagnostics.Debug.Assert(node.ResultCount == 1);
System.Diagnostics.Debug.Assert(node.OperandCount == 2);
System.Diagnostics.Debug.Assert(node.Result.IsCPURegister);
System.Diagnostics.Debug.Assert(node.Operand1.IsCPURegister);
System.Diagnostics.Debug.Assert(node.Result.Register == node.Operand1.Register);
if (node.Operand2.IsCPURegister)
{
opcodeEncoder.SuppressByte(0x40);
opcodeEncoder.Append4Bits(0b0100);
opcodeEncoder.Append1Bit(0b0);
opcodeEncoder.Append1Bit((node.Result.Register.RegisterCode >> 3) & 0x1);
opcodeEncoder.Append1Bit(0b0);
opcodeEncoder.Append1Bit((node.Operand2.Register.RegisterCode >> 3) & 0x1);
opcodeEncoder.Append8Bits(0x2B);
opcodeEncoder.Append2Bits(0b11);
opcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
opcodeEncoder.Append3Bits(node.Operand2.Register.RegisterCode);
return;
}
if (node.Operand2.IsConstant)
{
opcodeEncoder.SuppressByte(0x40);
opcodeEncoder.Append4Bits(0b0100);
opcodeEncoder.Append1Bit(0b0);
opcodeEncoder.Append1Bit((node.Result.Register.RegisterCode >> 3) & 0x1);
opcodeEncoder.Append1Bit(0b0);
opcodeEncoder.Append1Bit(0b0);
opcodeEncoder.Append8Bits(0x81);
opcodeEncoder.Append2Bits(0b11);
opcodeEncoder.Append3Bits(0b101);
opcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
opcodeEncoder.Append32BitImmediate(node.Operand2);
return;
}
throw new Compiler.Common.Exceptions.CompilerException("Invalid Opcode");
}
}
}
| 32.413333 | 83 | 0.739202 | [
"BSD-3-Clause"
] | AnErrupTion/MOSA-Project | Source/Mosa.Platform.x64/Instructions/Sub32.cs | 2,431 | C# |
using System.Collections.Generic;
using Negum.Core.Models.Palettes;
namespace Negum.Core.Models.Pcx
{
/// <summary>
/// Represents a general model of an image read from the PCX file.
/// </summary>
///
/// <author>
/// https://github.com/TheNegumProject/Negum.Core
/// </author>
public interface IPcxImage
{
byte Id { get; }
byte Version { get; }
byte Encoding { get; }
byte BitPerPixel { get; }
ushort X { get; }
ushort Y { get; }
ushort Width { get; }
ushort Height { get; }
ushort HRes { get; }
ushort VRes { get; }
IPalette ColorPalette { get; }
byte Reserved { get; }
byte NbPlanes { get; }
ushort BitesPerLine { get; }
ushort PaletteIndex { get; }
IPalette Palette { get; }
byte Signature { get; }
/// <summary>
/// Each pixel is build out of 4 bytes (RGBA).
/// </summary>
IEnumerable<byte> Pixels { get; }
}
/// <summary>
/// </summary>
///
/// <author>
/// https://github.com/TheNegumProject/Negum.Core
/// </author>
public class PcxImage : IPcxImage
{
public byte Id { get; internal set; }
public byte Version { get; internal set; }
public byte Encoding { get; internal set; }
public byte BitPerPixel { get; internal set; }
public ushort X { get; internal set; }
public ushort Y { get; internal set; }
public ushort Width { get; internal set; }
public ushort Height { get; internal set; }
public ushort HRes { get; internal set; }
public ushort VRes { get; internal set; }
public IPalette ColorPalette { get; internal set; }
public byte Reserved { get; internal set; }
public byte NbPlanes { get; internal set; }
public ushort BitesPerLine { get; internal set; }
public ushort PaletteIndex { get; internal set; }
public IPalette Palette { get; internal set; }
public byte Signature { get; internal set; }
public IEnumerable<byte> Pixels { get; internal set; }
}
} | 32.818182 | 70 | 0.569252 | [
"MIT"
] | TheNegumProject/Negum.Core | Negum.Core/Models/Pcx/IPcxImage.cs | 2,166 | C# |
namespace SharpTemplar;
public class Table : HTMLBodyElement
{
internal override string TagType => "table";
internal Table(HTMLBodyElement parent)
: base(parent) { }
}
public abstract partial class HTMLBodyElement : HTMLElement
{
public HTMLBodyElement AddTable()
{
var table = new Table(this);
AddElement(table);
return this;
}
public HTMLBodyElement AddTable(out HTMLBodyElement saveIn)
{
var table = new Table(this);
saveIn = table;
AddElement(table);
return this;
}
} | 21.296296 | 63 | 0.634783 | [
"MIT"
] | emiljapelt/SharpTemplar | src/Body/BodyElements/Table.cs | 575 | C# |
#if !NETSTANDARD13
/*
* 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 networkmanager-2019-07-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.NetworkManager.Model
{
/// <summary>
/// Base class for GetTransitGatewayConnectPeerAssociations paginators.
/// </summary>
internal sealed partial class GetTransitGatewayConnectPeerAssociationsPaginator : IPaginator<GetTransitGatewayConnectPeerAssociationsResponse>, IGetTransitGatewayConnectPeerAssociationsPaginator
{
private readonly IAmazonNetworkManager _client;
private readonly GetTransitGatewayConnectPeerAssociationsRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<GetTransitGatewayConnectPeerAssociationsResponse> Responses => new PaginatedResponse<GetTransitGatewayConnectPeerAssociationsResponse>(this);
/// <summary>
/// Enumerable containing all of the TransitGatewayConnectPeerAssociations
/// </summary>
public IPaginatedEnumerable<TransitGatewayConnectPeerAssociation> TransitGatewayConnectPeerAssociations =>
new PaginatedResultKeyResponse<GetTransitGatewayConnectPeerAssociationsResponse, TransitGatewayConnectPeerAssociation>(this, (i) => i.TransitGatewayConnectPeerAssociations);
internal GetTransitGatewayConnectPeerAssociationsPaginator(IAmazonNetworkManager client, GetTransitGatewayConnectPeerAssociationsRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<GetTransitGatewayConnectPeerAssociationsResponse> IPaginator<GetTransitGatewayConnectPeerAssociationsResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
GetTransitGatewayConnectPeerAssociationsResponse response;
do
{
_request.NextToken = nextToken;
response = _client.GetTransitGatewayConnectPeerAssociations(_request);
nextToken = response.NextToken;
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<GetTransitGatewayConnectPeerAssociationsResponse> IPaginator<GetTransitGatewayConnectPeerAssociationsResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
GetTransitGatewayConnectPeerAssociationsResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.GetTransitGatewayConnectPeerAssociationsAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
}
}
#endif | 46.181818 | 202 | 0.697507 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/NetworkManager/Generated/Model/_bcl45+netstandard/GetTransitGatewayConnectPeerAssociationsPaginator.cs | 4,572 | C# |
using System;
using System.Net;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;
using LiveCoreLibrary;
using LiveCoreLibrary.Client;
using LiveCoreLibrary.Commands;
using LiveCoreLibrary.Messages;
using UnityEngine;
namespace LiveClient
{
public class LiveNetwork
{
public bool IsConnected => _tcp is { IsConnected: true };
private static LiveNetwork _instance;
public static LiveNetwork Instance => _instance ??= new LiveNetwork();
private Tcp _tcp;
private Udp _udp;
private EndPointPacketHolder _p2PClients;
public event Action<ReceiveData> OnMessageReceivedTcp;
public event Action<IUdpCommand> OnMessageReceivedUdp;
public event Action OnConnected;
public event Action<Guid> OnJoin;
public event Action<Guid> OnLeave;
public event Action<EndPointPacketHolder> OnReceiveUsers;
public event Action OnClose;
private Guid _userId;
private SynchronizationContext _context;
public LiveNetwork()
{
_context = SynchronizationContext.Current;
}
/// <summary>
/// Udpホールパンチングにより、Portの開放を行う
/// </summary>
public async Task HolePunching()
{
IUdpCommand endPointPacket = new HolePunchingPacket(this._userId);
if(_udp != null) await _udp.SendServer(endPointPacket);
}
/// <summary>
/// Udp送信
/// </summary>
/// <param name="udpCommand"></param>
public async Task SendClients(IUdpCommand udpCommand)
{
if(_udp != null) await _udp.SendClients(udpCommand, _p2PClients);
}
/// <summary>
/// Tcp送信
/// </summary>
/// <param name="tcpCommand"></param>
public void Send(ITcpCommand tcpCommand)
{
_tcp.SendAsync(tcpCommand);
}
/// <summary>
/// ルームに入る
/// </summary>
/// <param name="userId"></param>
/// <param name="roomName"></param>
public void Join(Guid userId, string roomName)
{
this._userId = userId;
ITcpCommand join = new Join(userId, roomName);
_tcp.SendAsync(join);
}
/// <summary>
/// サーバー側未実装
/// </summary>
public void Leave()
{
ITcpCommand leave = new Leave(_userId);
_tcp.SendAsync(leave);
}
/// <summary>
/// サーバに接続する
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
public async Task<bool> ConnectTcp(string host, int port)
{
// Tcp
_tcp = new Tcp();
//イベント登録
_tcp.OnMessageReceived += OnMessageReceived;
_tcp.OnConnected += OnConnect;
_tcp.OnDisconnected += OnDisconnected;
_tcp.OnClose += OnClosed;
// 接続するまで待機
return await _tcp.ConnectAsync(host, port);
}
public void OnClosed()
{
_context.Post((e) => OnClose?.Invoke(), null);
}
/// <summary>
/// サーバーにUdp接続を行う
/// ConnectTcpとJoinメソッドによって,ルームへ入る必要がある
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
public async void ConnectUdp(string host, int port)
{
// Udp
_udp = new Udp(_userId, new IPEndPoint(IPAddress.Parse(host), port));
_udp.ReceiveLoop(10);
_udp.Process(10);
_udp.OnMessageReceived += OnMessageReceivedOfUdp;
await HolePunching();
}
/// <summary>
/// Close
/// </summary>
public void Close()
{
if (_udp != null) _udp.Close();
if (_tcp != null) _tcp.Close();
#if DEBUG
Console.WriteLine("終了します.");
#endif
}
private void OnMessageReceived(ReceiveData receiveData)
{
switch (receiveData.TcpCommand)
{
case JoinResult x:
_context.Post(e => OnJoin?.Invoke(x.UserId), null);
break;
case LeaveResult x:
_context.Post(e => OnLeave?.Invoke(x.UserId), null);
break;
case EndPointPacketHolder x:
_p2PClients = x;
_context.Post(e => OnReceiveUsers?.Invoke(x), null);
break;
}
_context.Post((e) => OnMessageReceivedTcp?.Invoke(receiveData), null);
// OnMessageReceivedTcp?.Invoke(receiveData);
}
private void OnMessageReceivedOfUdp(IUdpCommand command)
{
_context.Post((e) => OnMessageReceivedUdp?.Invoke(command), null);
}
private void OnConnect(IPEndPoint ipEndPoint)
{
//Log
Console.WriteLine($"[CLIENT]{ipEndPoint.Address}:[{ipEndPoint.Port.ToString()}] tcp connect");
//受信開始
_tcp.ReceiveStart(100);
_context.Post((e) => OnConnected?.Invoke(), null);
}
private void OnDisconnected()
{
if (_tcp != null && _udp != null)
{
//_tcp.Close(); // 一応
_udp.Close();
Console.WriteLine("一応Close");
}
Console.WriteLine($"[CLIENT]disconnect");
}
}
} | 29.963351 | 107 | 0.515813 | [
"MIT"
] | Taku3939/LiveCSharpForUnity | Assets/LiveCSharpForUnity/Client/LiveNetwork.cs | 5,927 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26
{
using HL7;
/// <summary>
/// MFN_M12 (Message) -
/// </summary>
public interface MFN_M12 :
HL7V26Layout
{
/// <summary>
/// MSH
/// </summary>
Segment<MSH> MSH { get; }
/// <summary>
/// SFT
/// </summary>
SegmentList<SFT> SFT { get; }
/// <summary>
/// UAC
/// </summary>
Segment<UAC> UAC { get; }
/// <summary>
/// MFI
/// </summary>
Segment<MFI> MFI { get; }
/// <summary>
/// MF_OBS_ATTRIBUTES
/// </summary>
LayoutList<MFN_M12_MF_OBS_ATTRIBUTES> MfObsAttributes { get; }
}
} | 23.358974 | 104 | 0.517014 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.HL7Schema/V26/Messages/MFN_M12.cs | 911 | C# |
using System;
using BCnEncoder.Shared;
namespace BCnEncoder.Encoder.Bc7
{
internal static class Bc7Mode3Encoder
{
public static Bc7Block EncodeBlock(RawBlock4X4Rgba32 block, int startingVariation, int bestPartition)
{
var output = new Bc7Block();
const Bc7BlockType type = Bc7BlockType.Type3;
var endpoints = new ColorRgba32[4];
var pBits = new byte[4];
ReadOnlySpan<int> partitionTable = Bc7Block.Subsets2PartitionTable[bestPartition];
var indices = new byte[16];
var anchorIndices = new int[] {
0,
Bc7Block.Subsets2AnchorIndices[bestPartition]
};
for (var subset = 0; subset < 2; subset++) {
Bc7EncodingHelpers.GetInitialUnscaledEndpointsForSubset(block, out var ep0, out var ep1,
partitionTable, subset);
var scaledEp0 =
Bc7EncodingHelpers.ScaleDownEndpoint(ep0, type, true, out var pBit0);
var scaledEp1 =
Bc7EncodingHelpers.ScaleDownEndpoint(ep1, type, true, out var pBit1);
Bc7EncodingHelpers.OptimizeSubsetEndpointsWithPBit(type, block, ref scaledEp0,
ref scaledEp1, ref pBit0, ref pBit1, startingVariation, partitionTable, subset, true, false);
ep0 = Bc7EncodingHelpers.ExpandEndpoint(type, scaledEp0, pBit0);
ep1 = Bc7EncodingHelpers.ExpandEndpoint(type, scaledEp1, pBit1);
Bc7EncodingHelpers.FillSubsetIndices(type, block,
ep0,
ep1,
partitionTable, subset, indices);
if ((indices[anchorIndices[subset]] & 0b10) > 0) //If anchor index most significant bit is 1, switch endpoints
{
var c = scaledEp0;
var p = pBit0;
scaledEp0 = scaledEp1;
pBit0 = pBit1;
scaledEp1 = c;
pBit1 = p;
//redo indices
ep0 = Bc7EncodingHelpers.ExpandEndpoint(type, scaledEp0, pBit0);
ep1 = Bc7EncodingHelpers.ExpandEndpoint(type, scaledEp1, pBit1);
Bc7EncodingHelpers.FillSubsetIndices(type, block,
ep0,
ep1,
partitionTable, subset, indices);
}
endpoints[subset * 2] = scaledEp0;
endpoints[subset * 2 + 1] = scaledEp1;
pBits[subset * 2] = pBit0;
pBits[subset * 2 + 1] = pBit1;
}
output.PackType3(bestPartition, new[]{
new byte[]{endpoints[0].r, endpoints[0].g, endpoints[0].b},
new byte[]{endpoints[1].r, endpoints[1].g, endpoints[1].b},
new byte[]{endpoints[2].r, endpoints[2].g, endpoints[2].b},
new byte[]{endpoints[3].r, endpoints[3].g, endpoints[3].b}
},
pBits,
indices);
return output;
}
}
}
| 29.829268 | 114 | 0.683565 | [
"MIT",
"Unlicense"
] | onepiecefreak3/BCnEncoder.NET | BCnEnc.Net/Encoder/Bc7/Bc7Mode3Encoder.cs | 2,448 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace B2C.Message.Core.Handlers
{
class MobileCodeEventHandler
{
}
}
| 14 | 35 | 0.733766 | [
"MIT"
] | shelldudu/never_application | src/message/B2C.Message.Core/Handlers/MobileCodeEventHandler.cs | 156 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="IChocolateyConfigurationProvider.cs">
// Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ChocolateyGui.Providers
{
public interface IChocolateyConfigurationProvider
{
string ChocolateyInstall { get; }
bool IsChocolateyExecutableBeingUsed { get; }
}
} | 43.933333 | 121 | 0.455235 | [
"Apache-2.0"
] | dhtdht020/ChocolateyGUI | Source/ChocolateyGui/Providers/IChocolateyConfigurationProvider.cs | 661 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.ViewModel;
namespace DotVVM.Samples.BasicSamples.ViewModels.FeatureSamples.MarkupControl
{
public class ComboBoxDataSourceBoundToStaticCollection : DotvvmViewModelBase
{
public int Value { get; set; }
}
}
| 23.928571 | 80 | 0.779104 | [
"Apache-2.0"
] | AMBULATUR/dotvvm | src/DotVVM.Samples.Common/ViewModels/FeatureSamples/MarkupControl/ComboBoxDataSourceBoundToStaticCollection.cs | 335 | C# |
using System.Collections.Generic;
using UsefulProteomicsDatabases;
using EngineLayer;
using Proteomics;
namespace TaskLayer
{
public class SearchParameters
{
public SearchParameters()
{
// default search task parameters
DisposeOfFileWhenDone = true;
DoParsimony = true;
NoOneHitWonders = false;
ModPeptidesAreDifferent = false;
DoQuantification = true;
QuantifyPpmTol = 5;
SearchTarget = true;
DecoyType = DecoyType.Reverse;
DoHistogramAnalysis = false;
HistogramBinTolInDaltons = 0.003;
DoLocalizationAnalysis = true;
WritePrunedDatabase = false;
KeepAllUniprotMods = true;
MassDiffAcceptorType = MassDiffAcceptorType.OneMM;
MaxFragmentSize = 30000.0;
WriteMzId = true;
WritePepXml = false;
ModsToWriteSelection = new Dictionary<string, int>
{
//Key is modification type.
//Value is integer 0, 1, 2 and 3 interpreted as:
// 0: Do not Write
// 1: Write if in DB and Observed
// 2: Write if in DB
// 3: Write if Observed
{"N-linked glycosylation", 3},
{"O-linked glycosylation", 3},
{"Other glycosylation", 3},
{"Common Biological", 3},
{"Less Common", 3},
{"Metal", 3},
{"2+ nucleotide substitution", 3},
{"1 nucleotide substitution", 3},
{"UniProt", 2},
};
WriteDecoys = true;
WriteContaminants = true;
WriteIndividualFiles = true;
LocalFdrCategories = new List<FdrCategory> { FdrCategory.FullySpecific };
}
public bool DisposeOfFileWhenDone { get; set; }
public bool DoParsimony { get; set; }
public bool ModPeptidesAreDifferent { get; set; }
public bool NoOneHitWonders { get; set; }
public bool MatchBetweenRuns { get; set; }
public bool Normalize { get; set; }
public double QuantifyPpmTol { get; set; }
public bool DoHistogramAnalysis { get; set; }
public bool SearchTarget { get; set; }
public DecoyType DecoyType { get; set; }
public MassDiffAcceptorType MassDiffAcceptorType { get; set; }
public bool WritePrunedDatabase { get; set; }
public bool KeepAllUniprotMods { get; set; }
public bool DoLocalizationAnalysis { get; set; }
public bool DoQuantification { get; set; }
public SearchType SearchType { get; set; }
public List<FdrCategory> LocalFdrCategories { get; set; }
public string CustomMdac { get; set; }
public double MaxFragmentSize { get; set; }
public double HistogramBinTolInDaltons { get; set; }
public Dictionary<string, int> ModsToWriteSelection { get; set; }
public double MaximumMassThatFragmentIonScoreIsDoubled { get; set; }
public bool WriteMzId { get; set; }
public bool WritePepXml { get; set; }
public bool WriteDecoys { get; set; }
public bool WriteContaminants { get; set; }
public bool WriteIndividualFiles { get; set; }
public bool CompressIndividualFiles { get; set; }
public List<SilacLabel> SilacLabels { get; set; }
public SilacLabel StartTurnoverLabel { get; set; } //used for SILAC turnover experiments
public SilacLabel EndTurnoverLabel { get; set; } //used for SILAC turnover experiments
}
} | 40.9 | 96 | 0.585982 | [
"MIT"
] | cameyer6/MetaMorpheus | TaskLayer/SearchTask/SearchParameters.cs | 3,681 | 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.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace System.Diagnostics
{
internal static partial class ProcessManager
{
/// <summary>Gets the IDs of all processes on the current machine.</summary>
public static int[] GetProcessIds()
{
return EnumerateProcessIds().ToArray();
}
/// <summary>Gets process infos for each process on the specified machine.</summary>
/// <param name="machineName">The target machine.</param>
/// <returns>An array of process infos, one per found process.</returns>
public static ProcessInfo[] GetProcessInfos(string machineName)
{
ThrowIfRemoteMachine(machineName);
int[] procIds = GetProcessIds(machineName);
// Iterate through all process IDs to load information about each process
var reusableReader = new ReusableTextReader();
var processes = new List<ProcessInfo>(procIds.Length);
foreach (int pid in procIds)
{
ProcessInfo pi = CreateProcessInfo(pid, reusableReader);
if (pi != null)
{
processes.Add(pi);
}
}
return processes.ToArray();
}
/// <summary>Gets an array of module infos for the specified process.</summary>
/// <param name="processId">The ID of the process whose modules should be enumerated.</param>
/// <returns>The array of modules.</returns>
internal static ProcessModuleCollection GetModules(int processId)
{
var modules = new ProcessModuleCollection(0);
// Process from the parsed maps file each entry representing a module
foreach (Interop.procfs.ParsedMapsModule entry in Interop.procfs.ParseMapsModules(processId))
{
int sizeOfImage = (int)(entry.AddressRange.Value - entry.AddressRange.Key);
// A single module may be split across multiple map entries; consolidate based on
// the name and address ranges of sequential entries.
if (modules.Count > 0)
{
ProcessModule module = modules[modules.Count - 1];
if (module.FileName == entry.FileName &&
((long)module.BaseAddress + module.ModuleMemorySize == entry.AddressRange.Key))
{
// Merge this entry with the previous one
module.ModuleMemorySize += sizeOfImage;
continue;
}
}
// It's not a continuation of a previous entry but a new one: add it.
unsafe
{
modules.Add(new ProcessModule()
{
FileName = entry.FileName,
ModuleName = Path.GetFileName(entry.FileName),
BaseAddress = new IntPtr(unchecked((void*)entry.AddressRange.Key)),
ModuleMemorySize = sizeOfImage,
EntryPointAddress = IntPtr.Zero // unknown
});
}
}
// Move the main executable module to be the first in the list if it's not already
string exePath = Process.GetExePath(processId);
for (int i = 0; i < modules.Count; i++)
{
ProcessModule module = modules[i];
if (module.FileName == exePath)
{
if (i > 0)
{
modules.RemoveAt(i);
modules.Insert(0, module);
}
break;
}
}
// Return the set of modules found
return modules;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// Creates a ProcessInfo from the specified process ID.
/// </summary>
internal static ProcessInfo CreateProcessInfo(int pid, ReusableTextReader reusableReader = null)
{
if (reusableReader == null)
{
reusableReader = new ReusableTextReader();
}
Interop.procfs.ParsedStat stat;
return Interop.procfs.TryReadStatFile(pid, out stat, reusableReader) ?
CreateProcessInfo(ref stat, reusableReader) :
null;
}
/// <summary>
/// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory.
/// </summary>
internal static ProcessInfo CreateProcessInfo(ref Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader, string processName = null)
{
int pid = procFsStat.pid;
var pi = new ProcessInfo()
{
ProcessId = pid,
ProcessName = processName ?? Process.GetUntruncatedProcessName(ref procFsStat) ?? string.Empty,
BasePriority = (int)procFsStat.nice,
VirtualBytes = (long)procFsStat.vsize,
WorkingSet = procFsStat.rss * Environment.SystemPageSize,
SessionId = procFsStat.session,
// We don't currently fill in the other values.
// A few of these could probably be filled in from getrusage,
// but only for the current process or its children, not for
// arbitrary other processes.
};
// Then read through /proc/pid/task/ to find each thread in the process...
string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid);
try
{
foreach (string taskDir in Directory.EnumerateDirectories(tasksDir))
{
// ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo
string dirName = Path.GetFileName(taskDir);
int tid;
Interop.procfs.ParsedStat stat;
if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) &&
Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader))
{
unsafe
{
pi._threadInfoList.Add(new ThreadInfo()
{
_processId = pid,
_threadId = (ulong)tid,
_basePriority = pi.BasePriority,
_currentPriority = (int)stat.nice,
_startAddress = IntPtr.Zero,
_threadState = ProcFsStateToThreadState(stat.state),
_threadWaitReason = ThreadWaitReason.Unknown
});
}
}
}
}
catch (IOException)
{
// Between the time that we get an ID and the time that we try to read the associated
// directories and files in procfs, the process could be gone.
}
// Finally return what we've built up
return pi;
}
// ----------------------------------
// ---- Unix PAL layer ends here ----
// ----------------------------------
/// <summary>Enumerates the IDs of all processes on the current machine.</summary>
internal static IEnumerable<int> EnumerateProcessIds()
{
// Parse /proc for any directory that's named with a number. Each such
// directory represents a process.
foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath))
{
string dirName = Path.GetFileName(procDir);
int pid;
if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid))
{
Debug.Assert(pid >= 0);
yield return pid;
}
}
}
/// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary>
/// <param name="c">The status field value.</param>
/// <returns></returns>
private static ThreadState ProcFsStateToThreadState(char c)
{
// Information on these in fs/proc/array.c
// `man proc` does not document them all
switch (c)
{
case 'R': // Running
return ThreadState.Running;
case 'D': // Waiting on disk
case 'P': // Parked
case 'S': // Sleeping in a wait
case 't': // Tracing/debugging
case 'T': // Stopped on a signal
return ThreadState.Wait;
case 'x': // dead
case 'X': // Dead
case 'Z': // Zombie
return ThreadState.Terminated;
case 'W': // Paging or waking
case 'K': // Wakekill
return ThreadState.Transition;
case 'I': // Idle
return ThreadState.Ready;
default:
Debug.Fail($"Unexpected status character: {c}");
return ThreadState.Unknown;
}
}
}
}
| 40.787755 | 157 | 0.511658 | [
"MIT"
] | 939481896/dotnet-corefx | src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs | 9,993 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CTA.Rules.Models;
using CTA.Rules.PortCore;
using Codelyzer.Analysis;
using Codelyzer.Analysis.Common;
using Codelyzer.Analysis.Model;
using Microsoft.Extensions.Logging;
using PortingAssistant.Client.Common.Utils;
using PortingAssistant.Client.Analysis.Utils;
using PortingAssistant.Client.Model;
using PortingAssistant.Client.NuGet;
using AnalyzerConfiguration = Codelyzer.Analysis.AnalyzerConfiguration;
using IDEProjectResult = Codelyzer.Analysis.Build.IDEProjectResult;
using PortingAssistant.Client.Common.Model;
namespace PortingAssistant.Client.Analysis
{
public class PortingAssistantAnalysisHandler : IPortingAssistantAnalysisHandler
{
private readonly ILogger<PortingAssistantAnalysisHandler> _logger;
private readonly IPortingAssistantNuGetHandler _handler;
private readonly IPortingAssistantRecommendationHandler _recommendationHandler;
private const string DEFAULT_TARGET = "netcoreapp3.1";
public PortingAssistantAnalysisHandler(ILogger<PortingAssistantAnalysisHandler> logger,
IPortingAssistantNuGetHandler handler, IPortingAssistantRecommendationHandler recommendationHandler)
{
_logger = logger;
_handler = handler;
_recommendationHandler = recommendationHandler;
}
private async Task<List<AnalyzerResult>> RunCoderlyzerAnalysis(string solutionFilename)
{
MemoryUtils.LogSystemInfo(_logger);
MemoryUtils.LogSolutiontSize(_logger, solutionFilename);
_logger.LogInformation("Memory usage before RunCoderlyzerAnalysis: ");
MemoryUtils.LogMemoryConsumption(_logger);
var configuration = GetAnalyzerConfiguration();
var analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);
var analyzerResults = await analyzer.AnalyzeSolution(solutionFilename);
_logger.LogInformation("Memory usage after RunCoderlyzerAnalysis: ");
MemoryUtils.LogMemoryConsumption(_logger);
return analyzerResults;
}
public async Task<List<SourceFileAnalysisResult>> AnalyzeFileIncremental(string filePath, string fileContent, string projectFile, string solutionFilePath, List<string> preportReferences
, List<string> currentReferences, RootNodes projectRules, ExternalReferences externalReferences, bool actionsOnly = false, bool compatibleOnly = false, string targetFramework = DEFAULT_TARGET)
{
try
{
List<SourceFileAnalysisResult> sourceFileAnalysisResults = new List<SourceFileAnalysisResult>();
var fileAnalysis = await AnalyzeProjectFiles(projectFile, fileContent, filePath, preportReferences, currentReferences);
var fileActions = AnalyzeFileActionsIncremental(projectFile, projectRules, targetFramework, solutionFilePath, filePath, fileAnalysis);
var sourceFileResult = fileAnalysis.RootNodes.FirstOrDefault();
Dictionary<string, List<CodeEntityDetails>> sourceFileToCodeEntityDetails = new Dictionary<string, List<CodeEntityDetails>>();
Dictionary<string, Task<RecommendationDetails>> recommendationResults = new Dictionary<string, Task<RecommendationDetails>>();
Dictionary<PackageVersionPair, Task<PackageDetails>> packageResults = new Dictionary<PackageVersionPair, Task<PackageDetails>>();
if (!actionsOnly)
{
var sourceFileToInvocations = new[] { SourceFileToCodeTokens(sourceFileResult) }.ToDictionary(result => result.Key, result => result.Value);
sourceFileToCodeEntityDetails = CodeEntityModelToCodeEntities.Convert(sourceFileToInvocations, externalReferences);
var namespaces = sourceFileToCodeEntityDetails.Aggregate(new HashSet<string>(), (agg, cur) =>
{
agg.UnionWith(cur.Value.Select(i => i.Namespace).Where(i => i != null));
return agg;
});
var nugetPackages = externalReferences?.NugetReferences?
.Select(r => CodeEntityModelToCodeEntities.ReferenceToPackageVersionPair(r))?
.ToHashSet();
var subDependencies = externalReferences?.NugetDependencies?
.Select(r => CodeEntityModelToCodeEntities.ReferenceToPackageVersionPair(r))
.ToHashSet();
var sdkPackages = namespaces.Select(n => new PackageVersionPair { PackageId = n, Version = "0.0.0", PackageSourceType = PackageSourceType.SDK });
var allPackages = nugetPackages
.Union(subDependencies)
.Union(sdkPackages)
.ToList();
packageResults = _handler.GetNugetPackages(allPackages, solutionFilePath, isIncremental: true, incrementalRefresh: false);
recommendationResults = _recommendationHandler.GetApiRecommendation(namespaces.ToList());
}
var portingActionResults = new Dictionary<string, List<RecommendedAction>>();
var recommendedActions = fileActions.Select(f => new RecommendedAction()
{
Description = f.Description,
RecommendedActionType = RecommendedActionType.ReplaceApi,
TextSpan = new Model.TextSpan()
{
StartCharPosition = f.TextSpan.StartCharPosition,
EndCharPosition = f.TextSpan.EndCharPosition,
StartLinePosition = f.TextSpan.StartLinePosition,
EndLinePosition = f.TextSpan.EndLinePosition
},
TextChanges = f.TextChanges
}).ToHashSet().ToList();
portingActionResults.Add(filePath, recommendedActions);
var sourceFileAnalysisResult = CodeEntityModelToCodeEntities.AnalyzeResults(
sourceFileToCodeEntityDetails, packageResults, recommendationResults, portingActionResults, targetFramework, compatibleOnly);
//In case actions only, result will be empty, so we populate with actions
if (actionsOnly)
{
sourceFileAnalysisResult.Add(new SourceFileAnalysisResult()
{
SourceFileName = Path.GetFileName(filePath),
SourceFilePath = filePath,
RecommendedActions = recommendedActions,
ApiAnalysisResults = new List<ApiAnalysisResult>()
});
}
sourceFileAnalysisResults.AddRange(sourceFileAnalysisResult);
return sourceFileAnalysisResults;
}
finally
{
CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeFileIncremental");
}
}
public async Task<List<SourceFileAnalysisResult>> AnalyzeFileIncremental(string filePath, string projectFile, string solutionFilePath, List<string> preportReferences
, List<string> currentReferences, RootNodes projectRules, ExternalReferences externalReferences, bool actionsOnly, bool compatibleOnly, string targetFramework = DEFAULT_TARGET)
{
var fileContent = File.ReadAllText(filePath);
return await AnalyzeFileIncremental(filePath, fileContent, projectFile, solutionFilePath, preportReferences, currentReferences, projectRules, externalReferences, actionsOnly, compatibleOnly, targetFramework);
}
public async Task<Dictionary<string, ProjectAnalysisResult>> AnalyzeSolutionIncremental(
string solutionFilename, List<string> projects, string targetFramework = DEFAULT_TARGET)
{
try
{
var analyzerResults = await RunCoderlyzerAnalysis(solutionFilename);
var analysisActions = AnalyzeActions(projects, targetFramework, analyzerResults, solutionFilename);
var solutionAnalysisResult = AnalyzeProjects(
solutionFilename, projects,
analyzerResults, analysisActions,
isIncremental: true, targetFramework);
var projectActions = projects
.Select((project) => new KeyValuePair<string, ProjectActions>
(project, analysisActions.FirstOrDefault(p => p.ProjectFile == project)?.ProjectActions ?? new ProjectActions()))
.Where(p => p.Value != null)
.ToDictionary(p => p.Key, p => p.Value);
return solutionAnalysisResult;
}
catch (OutOfMemoryException e)
{
_logger.LogError("Analyze solution {0} with error {1}", solutionFilename, e);
MemoryUtils.LogMemoryConsumption(_logger);
throw e;
}
finally
{
CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeSolutionIncremental");
}
}
private List<IDEFileActions> AnalyzeFileActionsIncremental(string project, RootNodes rootNodes, string targetFramework
, string pathToSolution, string filePath, IDEProjectResult projectResult)
{
List<PortCoreConfiguration> configs = new List<PortCoreConfiguration>();
PortCoreConfiguration projectConfiguration = new PortCoreConfiguration()
{
ProjectPath = project,
UseDefaultRules = true,
TargetVersions = new List<string> { targetFramework },
PortCode = false,
PortProject = false
};
projectResult.ProjectPath = project;
configs.Add(projectConfiguration);
var solutionPort = new SolutionPort(pathToSolution, projectResult, configs);
return solutionPort.RunIncremental(rootNodes, filePath);
}
private async Task<IDEProjectResult> AnalyzeProjectFiles(string projectPath, string fileContent, string filePath, List<string> preportReferences, List<string> currentReferences)
{
try
{
var configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
{
MetaDataSettings =
{
LiteralExpressions = true,
MethodInvocations = true,
ReferenceData = true,
Annotations = true,
DeclarationNodes = true,
LoadBuildData = true,
LocationData = true,
InterfaceDeclarations = true
}
};
var analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);
var ideProjectResult = await analyzer.AnalyzeFile(projectPath, filePath, fileContent, preportReferences, currentReferences);
return ideProjectResult;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while analyzing files");
}
finally
{
CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeFileIncremental");
}
return null;
}
public async Task<Dictionary<string, ProjectAnalysisResult>> AnalyzeSolution(
string solutionFilename, List<string> projects, string targetFramework = DEFAULT_TARGET)
{
try
{
var analyzerResults = await RunCoderlyzerAnalysis(solutionFilename);
var analysisActions = AnalyzeActions(projects, targetFramework, analyzerResults, solutionFilename);
var solutionAnalysisResult = AnalyzeProjects(
solutionFilename, projects,
analyzerResults, analysisActions,
isIncremental: false, targetFramework);
return solutionAnalysisResult;
}
catch (OutOfMemoryException e)
{
_logger.LogError("Analyze solution {0} with error {1}", solutionFilename, e);
MemoryUtils.LogMemoryConsumption(_logger);
throw e;
}
finally
{
CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeSolution");
}
}
private List<ProjectResult> AnalyzeActions(List<string> projects, string targetFramework, List<AnalyzerResult> analyzerResults, string pathToSolution)
{
_logger.LogInformation("Memory Consumption before AnalyzeActions: ");
MemoryUtils.LogMemoryConsumption(_logger);
List<PortCoreConfiguration> configs = new List<PortCoreConfiguration>();
var anaylyzedProjects = projects.Where(p =>
{
var project = analyzerResults.Find((a) => a.ProjectResult?.ProjectFilePath != null &&
a.ProjectResult.ProjectFilePath.Equals(p));
return project != null;
}).ToList();
foreach (var proj in anaylyzedProjects)
{
PortCoreConfiguration projectConfiguration = new PortCoreConfiguration()
{
ProjectPath = proj,
UseDefaultRules = true,
TargetVersions = new List<string> { targetFramework },
PortCode = false,
PortProject = false
};
configs.Add(projectConfiguration);
}
var solutionPort = new SolutionPort(pathToSolution, analyzerResults, configs, _logger);
var projectResults = solutionPort.Run().ProjectResults.ToList();
_logger.LogInformation("Memory Consumption after AnalyzeActions: ");
MemoryUtils.LogMemoryConsumption(_logger);
return projectResults;
}
private KeyValuePair<string, UstList<UstNode>> SourceFileToCodeTokens(RootUstNode sourceFile)
{
var allNodes = new UstList<UstNode>();
allNodes.AddRange(sourceFile.AllInvocationExpressions());
allNodes.AddRange(sourceFile.AllAnnotations());
allNodes.AddRange(sourceFile.AllDeclarationNodes());
allNodes.AddRange(sourceFile.AllStructDeclarations());
allNodes.AddRange(sourceFile.AllEnumDeclarations());
return KeyValuePair.Create(sourceFile.FileFullPath, allNodes);
}
private Dictionary<string, ProjectAnalysisResult> AnalyzeProjects(
string solutionFileName,
List<string> projects,
List<AnalyzerResult> analyzerResult,
List<ProjectResult> analysisActions,
bool isIncremental = false,
string targetFramework = DEFAULT_TARGET)
{
_logger.LogInformation("Memory Consumption before AnalyzeProjects: ");
MemoryUtils.LogMemoryConsumption(_logger);
var results = projects
.Select((project) => new KeyValuePair<string, ProjectAnalysisResult>(
project,
AnalyzeProject(
project, solutionFileName,
analyzerResult, analysisActions,
isIncremental, targetFramework)))
.Where(p => p.Value != null)
.ToDictionary(p => p.Key, p => p.Value);
_logger.LogInformation("Memory Consumption after AnalyzeProjects: ");
MemoryUtils.LogMemoryConsumption(_logger);
return results;
}
private ProjectAnalysisResult AnalyzeProject(
string project, string solutionFileName, List<AnalyzerResult> analyzers, List<ProjectResult> analysisActions, bool isIncremental = false, string targetFramework = DEFAULT_TARGET)
{
try
{
var analyzer = analyzers.Find((a) => a.ProjectResult?.ProjectFilePath != null &&
a.ProjectResult.ProjectFilePath.Equals(project));
var projectActions = analysisActions.FirstOrDefault(p => p.ProjectFile == project)?.ProjectActions ?? new ProjectActions();
if (analyzer == null || analyzer.ProjectResult == null)
{
_logger.LogError("Unable to build {0}.", project);
return null;
}
var sourceFileToCodeTokens = analyzer.ProjectResult.SourceFileResults.Select((sourceFile) =>
{
return SourceFileToCodeTokens(sourceFile);
}).ToDictionary(p => p.Key, p => p.Value);
var sourceFileToCodeEntityDetails = CodeEntityModelToCodeEntities.Convert(sourceFileToCodeTokens, analyzer);
var namespaces = sourceFileToCodeEntityDetails.Aggregate(new HashSet<string>(), (agg, cur) =>
{
agg.UnionWith(cur.Value.Select(i => i.Namespace).Where(i => i != null));
return agg;
});
var targetframeworks = analyzer.ProjectResult.TargetFrameworks.Count == 0 ?
new List<string> { analyzer.ProjectResult.TargetFramework } : analyzer.ProjectResult.TargetFrameworks;
var nugetPackages = analyzer.ProjectResult.ExternalReferences.NugetReferences
.Select(r => CodeEntityModelToCodeEntities.ReferenceToPackageVersionPair(r))
.ToHashSet();
var subDependencies = analyzer.ProjectResult.ExternalReferences.NugetDependencies
.Select(r => CodeEntityModelToCodeEntities.ReferenceToPackageVersionPair(r))
.ToHashSet();
var sdkPackages = namespaces.Select(n => new PackageVersionPair { PackageId = n, Version = "0.0.0", PackageSourceType = PackageSourceType.SDK });
var allPackages = nugetPackages
.Union(subDependencies)
.Union(sdkPackages)
.ToList();
Dictionary<PackageVersionPair, Task<PackageDetails>> packageResults;
if (isIncremental)
packageResults = _handler.GetNugetPackages(allPackages, solutionFileName, isIncremental: true, incrementalRefresh: true);
else
packageResults = _handler.GetNugetPackages(allPackages, null, isIncremental: false, incrementalRefresh: false);
var recommendationResults = _recommendationHandler.GetApiRecommendation(namespaces.ToList());
var packageAnalysisResults = nugetPackages.Select(package =>
{
var result = PackageCompatibility.IsCompatibleAsync(packageResults.GetValueOrDefault(package, null), package, _logger, targetFramework);
var packageAnalysisResult = PackageCompatibility.GetPackageAnalysisResult(result, package, targetFramework);
return new Tuple<PackageVersionPair, Task<PackageAnalysisResult>>(package, packageAnalysisResult);
}).ToDictionary(t => t.Item1, t => t.Item2);
var portingActionResults = ProjectActionsToRecommendedActions.Convert(projectActions);
var SourceFileAnalysisResults = CodeEntityModelToCodeEntities.AnalyzeResults(
sourceFileToCodeEntityDetails, packageResults, recommendationResults, portingActionResults, targetFramework);
var compatibilityResults = GenerateCompatibilityResults(SourceFileAnalysisResults, analyzer.ProjectResult.ProjectFilePath, analyzer.ProjectBuildResult?.PrePortCompilation != null);
return new ProjectAnalysisResult
{
ProjectName = analyzer.ProjectResult.ProjectName,
ProjectFilePath = analyzer.ProjectResult.ProjectFilePath,
TargetFrameworks = targetframeworks,
PackageReferences = nugetPackages.ToList(),
ProjectReferences = analyzer.ProjectResult.ExternalReferences.ProjectReferences.ConvertAll(p => new ProjectReference { ReferencePath = p.AssemblyLocation }),
PackageAnalysisResults = packageAnalysisResults,
IsBuildFailed = analyzer.ProjectResult.IsBuildFailed() || analyzer.ProjectBuildResult.IsSyntaxAnalysis,
Errors = analyzer.ProjectResult.BuildErrors,
ProjectGuid = analyzer.ProjectResult.ProjectGuid,
ProjectType = analyzer.ProjectResult.ProjectType,
SourceFileAnalysisResults = SourceFileAnalysisResults,
MetaReferences = analyzer.ProjectBuildResult.Project.MetadataReferences.Select(m => m.Display).ToList(),
PreportMetaReferences = analyzer.ProjectBuildResult.PreportReferences,
ProjectRules = projectActions.ProjectRules,
ExternalReferences = analyzer.ProjectResult.ExternalReferences,
ProjectCompatibilityResult = compatibilityResults
};
}
catch (Exception ex)
{
_logger.LogError("Error while analyzing {0}, {1}", project, ex);
return new ProjectAnalysisResult
{
ProjectName = Path.GetFileNameWithoutExtension(project),
ProjectFilePath = project,
TargetFrameworks = new List<string>(),
PackageReferences = new List<PackageVersionPair>(),
ProjectReferences = new List<ProjectReference>(),
PackageAnalysisResults = new Dictionary<PackageVersionPair, Task<PackageAnalysisResult>>(),
IsBuildFailed = true,
Errors = new List<string> { string.Format("Error while analyzing {0}, {1}", project, ex) },
ProjectGuid = null,
ProjectType = null,
SourceFileAnalysisResults = new List<SourceFileAnalysisResult>()
};
}
}
private ProjectCompatibilityResult GenerateCompatibilityResults(List<SourceFileAnalysisResult> sourceFileAnalysisResults, string projectPath, bool isPorted)
{
var projectCompatibilityResult = new ProjectCompatibilityResult() { IsPorted = isPorted, ProjectPath = projectPath };
sourceFileAnalysisResults.ForEach(SourceFileAnalysisResult => {
SourceFileAnalysisResult.ApiAnalysisResults.ForEach(apiAnalysisResult =>
{
var currentEntity = projectCompatibilityResult.CodeEntityCompatibilityResults.First(r => r.CodeEntityType == apiAnalysisResult.CodeEntityDetails.CodeEntityType);
var hasAction = SourceFileAnalysisResult.RecommendedActions.Any(ra => ra.TextSpan.Equals(apiAnalysisResult.CodeEntityDetails.TextSpan));
if (hasAction)
{
currentEntity.Actions++;
}
var compatibility = apiAnalysisResult.CompatibilityResults?.FirstOrDefault().Value?.Compatibility;
if (compatibility == Compatibility.COMPATIBLE)
{
currentEntity.Compatible++;
}
else if (compatibility == Compatibility.INCOMPATIBLE)
{
currentEntity.Incompatible++;
}
else if (compatibility == Compatibility.UNKNOWN)
{
currentEntity.Unknown++;
}
else if (compatibility == Compatibility.DEPRECATED)
{
currentEntity.Deprecated++;
}
else
{
currentEntity.Unknown++;
}
});
});
_logger.LogInformation($"{projectCompatibilityResult.ToString()}");
return projectCompatibilityResult;
}
private AnalyzerConfiguration GetAnalyzerConfiguration()
{
return new AnalyzerConfiguration(LanguageOptions.CSharp)
{
MetaDataSettings =
{
LiteralExpressions = true,
MethodInvocations = true,
ReferenceData = true,
Annotations = true,
DeclarationNodes = true,
LoadBuildData = true,
LocationData = true,
InterfaceDeclarations = true
},
ConcurrentThreads = 1
};
}
}
}
| 48.860153 | 220 | 0.608508 | [
"Apache-2.0"
] | birojnayak/porting-assistant-dotnet-client | src/PortingAssistant.Client.Analysis/AnalysisHandler.cs | 25,507 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoRest.AzureResourceSchema
{
[Flags]
public enum SchemaConfiguration
{
None = 0,
OmitExpressionRef = 1 << 0,
}
/// <summary>
/// An object representing a JSON schema. Each property of a JSON schema ($schema, title, and
/// description are metadata, not properties) is also a JSON schema, so the class is recursive.
/// </summary>
public class JsonSchema
{
private string resourceType;
/// <summary>
/// A reference to the location in the parent schema where this schema's definition can be
/// found.
/// </summary>
public string Ref { get; set; }
/// <summary>
/// The JSONSchema that will be applied to the elements of this schema, assuming this
/// schema is an array schema type.
/// </summary>
public JsonSchema Items { get; set; }
/// <summary>
/// The format of the value that matches this schema. This only applies to string values.
/// </summary>
public string Format { get; set; }
/// <summary>
/// The description metadata that describes this schema.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The type metadata of this schema that describes what type matching JSON values must be.
/// For example, this value will be either "object", "string", "array", "integer",
/// "number", or "boolean".
/// </summary>
public string JsonType { get; set; }
/// <summary>
/// Gets or sets the resource type of this JsonSchema.
/// </summary>
public string ResourceType
{
get
{
return resourceType;
}
set
{
resourceType = value;
if (Properties != null && Properties.ContainsKey("type"))
{
// update the value of the type enum. we have to be careful though that we don't
// stomp over some other enum that happens to have the name "type". this code path
// is typically hit when building a child resource definition from a cloned parent.
if (Properties["type"].Enum.Count > 1)
throw new InvalidOperationException("Attempt to update 'type' enum that contains more than one member (possible collision).");
if (!Properties["type"].Enum[0].EndsWith(value))
throw new InvalidOperationException($"The updated type value '{value}' is not a child of type value '{Properties["type"].Enum[0]}'");
Properties["type"].Enum[0] = value;
}
}
}
/// <summary>
/// The number that a numeric value matching this schema must be a multiple of
/// </summary>
public double? MultipleOf { get; set; }
/// <summary>
/// The minimum value that a numeric value matching this schema can have.
/// </summary>
public double? Minimum { get; set; }
/// <summary>
/// The maximum value that a numeric value matching this schema can have.
/// </summary>
public double? Maximum { get; set; }
/// <summary>
/// The regular expression pattern that a string value matching this schema must match.
/// </summary>
public string Pattern { get; set; }
/// <summary>
/// The minimum length that a string or an array matching this schema can have.
/// </summary>
public double? MinLength { get; set; }
/// <summary>
/// The maximum length that a string or an array matching this schema can have.
/// </summary>
public double? MaxLength { get; set; }
/// <summary>
/// The maximum length that a string or an array matching this schema can have.
/// </summary>
public string Default { get; set; }
/// <summary>
/// The schema that matches additional properties that have not been specified in the
/// Properties dictionary.
/// </summary>
public JsonSchema AdditionalProperties { get; set; }
/// <summary>
/// An enumeration of values that will match this JSON schema. Any value not in this
/// enumeration will not match this schema.
/// </summary>
public IList<string> Enum { get; private set;}
/// <summary>
/// The list of oneOf options that exist for this JSON schema.
/// </summary>
public IList<JsonSchema> OneOf { get; private set;}
/// <summary>
/// The list of anyOf options that exist for this JSON schema.
/// </summary>
public IList<JsonSchema> AnyOf { get; private set;}
/// <summary>
/// The list of allOf options that exist for this JSON schema.
/// </summary>
public IList<JsonSchema> AllOf { get; private set;}
/// <summary>
/// The schemas that describe the properties of a matching JSON value.
/// </summary>
public IDictionary<string, JsonSchema> Properties { get; private set; }
/// <summary>
/// The names of the properties that are required for a matching JSON value.
/// </summary>
public IList<string> Required { get; private set; }
/// <summary>
/// Configuration to override default schema serialization behavior.
/// </summary>
public SchemaConfiguration Configuration { get; set; }
public bool IsEmpty()
{
return Ref == null &&
Items == null &&
AdditionalProperties == null &&
MultipleOf == null &&
Minimum == null &&
Maximum == null &&
Pattern == null &&
MinLength == null &&
MaxLength == null &&
IsEmpty(Enum) &&
IsEmpty(Properties) &&
IsEmpty(Required) &&
IsEmpty(OneOf) &&
IsEmpty(AnyOf) &&
IsEmpty(AllOf);
}
private static bool IsEmpty<T>(IEnumerable<T> values)
{
return values == null || !values.Any();
}
/// <summary>
/// Add a new value (or values) to this JsonSchema's enum list. This JsonSchema (with the
/// new value(s)) is then returned so that additional changes can be chained together.
/// </summary>
/// <param name="enumValue"></param>
/// <param name="extraEnumValues"></param>
/// <returns></returns>
public JsonSchema AddEnum(string enumValue, params string[] extraEnumValues)
{
if (Enum == null)
{
Enum = new List<string>();
}
if (Enum.Contains(enumValue))
{
throw new ArgumentException("enumValue (" + enumValue + ") already exists in the list of allowed values.", "enumValue");
}
Enum.Add(enumValue);
if (extraEnumValues != null && extraEnumValues.Length > 0)
{
foreach (string extraEnumValue in extraEnumValues)
{
if (Enum.Contains(extraEnumValue))
{
throw new ArgumentException("extraEnumValue (" + extraEnumValue + ") already exists in the list of allowed values.", "extraEnumValues");
}
Enum.Add(extraEnumValue);
}
}
return this;
}
public JsonSchema AddPropertyWithOverwrite(string propertyName, JsonSchema propertyDefinition, bool isRequired)
{
if (Properties != null && Properties.ContainsKey(propertyName))
{
Properties.Remove(propertyName);
}
if (Required != null && Required.Contains(propertyName))
{
Required.Remove(propertyName);
}
AddProperty(propertyName, propertyDefinition, isRequired);
return this;
}
/// <summary>
/// Add a new property to this JsonSchema, and then return this JsonSchema so that
/// additional changes can be chained together.
/// </summary>
/// <param name="propertyName">The name of the property to add.</param>
/// <param name="propertyDefinition">The JsonSchema definition of the property to add.</param>
/// <param name="isRequired">Whether this property is required or not.</param>
/// <returns></returns>
public JsonSchema AddProperty(string propertyName, JsonSchema propertyDefinition, bool isRequired = false)
{
if (string.IsNullOrWhiteSpace(propertyName))
{
throw new ArgumentException("propertyName cannot be null or whitespace", "propertyName");
}
if (propertyDefinition == null)
{
throw new ArgumentNullException("propertyDefinition");
}
if (Properties == null)
{
Properties = new Dictionary<string, JsonSchema>();
}
if (Properties.ContainsKey(propertyName))
{
throw new ArgumentException("A property with the name \"" + propertyName + "\" already exists in this JSONSchema", "propertyName");
}
Properties[propertyName] = propertyDefinition;
if (isRequired)
{
AddRequired(propertyName);
}
return this;
}
/// <summary>
/// Add the provided required property names to this JSON schema's list of required property names.
/// </summary>
/// <param name="requiredPropertyName"></param>
/// <param name="extraRequiredPropertyNames"></param>
public JsonSchema AddRequired(string requiredPropertyName, params string[] extraRequiredPropertyNames)
{
if (Properties == null || !Properties.ContainsKey(requiredPropertyName))
{
throw new ArgumentException("No property exists with the provided requiredPropertyName (" + requiredPropertyName + ")", nameof(requiredPropertyName));
}
if (Required == null)
{
Required = new List<string>();
}
if (Required.Contains(requiredPropertyName))
{
throw new ArgumentException("'" + requiredPropertyName + "' is already a required property.", "requiredPropertyName");
}
Required.Add(requiredPropertyName);
if (extraRequiredPropertyNames != null)
{
foreach (string extraRequiredPropertyName in extraRequiredPropertyNames)
{
if (Properties == null || !Properties.ContainsKey(extraRequiredPropertyName))
{
throw new ArgumentException("No property exists with the provided extraRequiredPropertyName (" + extraRequiredPropertyName + ")", "extraRequiredPropertyNames");
}
if (Required.Contains(extraRequiredPropertyName))
{
throw new ArgumentException("'" + extraRequiredPropertyName + "' is already a required property.", "extraRequiredPropertyNames");
}
Required.Add(extraRequiredPropertyName);
}
}
return this;
}
/// <summary>
/// Add the provided JSON schema as an option for the anyOf property of this JSON schema.
/// </summary>
/// <param name="anyOfOption"></param>
/// <returns></returns>
public JsonSchema AddAnyOf(JsonSchema anyOfOption)
{
if (anyOfOption == null)
{
throw new ArgumentNullException(nameof(anyOfOption));
}
if (AnyOf == null)
{
AnyOf = new List<JsonSchema>();
}
AnyOf.Add(anyOfOption);
return this;
}
/// <summary>
/// Add the provided JSON schema as an option for the oneOf property of this JSON schema.
/// </summary>
/// <param name="oneOfOption"></param>
/// <returns></returns>
public JsonSchema AddOneOf(JsonSchema oneOfOption)
{
if (oneOfOption == null)
{
throw new ArgumentNullException(nameof(oneOfOption));
}
if (OneOf == null)
{
OneOf = new List<JsonSchema>();
}
OneOf.Add(oneOfOption);
return this;
}
/// <summary>
/// Add the provided JSON schema as an option for the allOf property of this JSON schema.
/// </summary>
/// <param name="allOfOption"></param>
/// <returns></returns>
public JsonSchema AddAllOf(JsonSchema allOfOption)
{
if (allOfOption == null)
{
throw new ArgumentNullException(nameof(allOfOption));
}
if (AllOf == null)
{
AllOf = new List<JsonSchema>();
}
AllOf.Add(allOfOption);
return this;
}
/// <summary>
/// Create a new JsonSchema that is an exact copy of this one.
/// </summary>
/// <returns></returns>
public JsonSchema Clone()
{
JsonSchema result = new JsonSchema();
result.Ref = Ref;
result.Items = Clone(Items);
result.Description = Description;
result.JsonType = JsonType;
result.AdditionalProperties = Clone(AdditionalProperties);
result.MultipleOf = MultipleOf;
result.Minimum = Minimum;
result.Maximum = Maximum;
result.Pattern = Pattern;
result.MinLength = MinLength;
result.MaxLength = MaxLength;
result.Default = Default;
result.Enum = Clone(Enum);
result.Properties = Clone(Properties);
result.Required = Clone(Required);
result.OneOf = Clone(OneOf);
result.AnyOf = Clone(AnyOf);
result.AllOf = Clone(AllOf);
result.Configuration = Configuration;
return result;
}
private static JsonSchema Clone(JsonSchema toClone)
=> toClone?.Clone();
private static IList<string> Clone(IList<string> toClone)
=> toClone?.Select(x => x).ToList();
private static IList<JsonSchema> Clone(IList<JsonSchema> toClone)
=> toClone?.Select(x => Clone(x)).ToList();
private static IDictionary<string, JsonSchema> Clone(IDictionary<string, JsonSchema> toClone)
=> toClone?.ToDictionary(kvp => kvp.Key, kvp => Clone(kvp.Value));
public static JsonSchema CreateSingleValuedEnum(string enumValue)
{
var result = new JsonSchema
{
JsonType = "string",
Configuration = SchemaConfiguration.OmitExpressionRef,
};
result.AddEnum(enumValue);
return result;
}
}
}
| 37.321839 | 185 | 0.529966 | [
"MIT"
] | anthony-c-martin/autorest.azureresourceschema | src/JsonSchema.cs | 16,237 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using ProtoBuf;
using System;
namespace GameMain
{
[Serializable, ProtoContract(Name = @"SCHeartBeat")]
public class SCHeartBeat : SCPacketBase
{
public SCHeartBeat()
{
}
public override int Id
{
get
{
return 2;
}
}
public override void Clear()
{
}
}
}
| 20.636364 | 63 | 0.441997 | [
"MIT"
] | suweitao8/BattleOfTheTwoCities | Assets/GameMain/Scripts/Network/Packet/SCHeartBeat.cs | 684 | 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("JonesClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JonesClient")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("72c86c0e-7320-4a24-bdf8-7479547034ba")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.744803 | [
"Apache-2.0"
] | mwhooker/jones | contrib/dotnet/JonesClient/Properties/AssemblyInfo.cs | 1,398 | C# |
using System.Globalization;
namespace FarsiLibrary.UnitTest.Helpers
{
public class DateTimeFormatWrapper
{
public static DateTimeFormatInfo GetFormatInfo()
{
return new DateTimeFormatInfo
{
DateSeparator = "-",
};
}
}
} | 22.733333 | 56 | 0.513196 | [
"MIT"
] | HEskandari/FarsiLibrary | FarsiLibrary.UnitTest/Helpers/DateTimeFormatWrapper.cs | 341 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CodeCommit.Model
{
///<summary>
/// CodeCommit exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class EncryptionKeyDisabledException : AmazonCodeCommitException
{
/// <summary>
/// Constructs a new EncryptionKeyDisabledException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public EncryptionKeyDisabledException(string message)
: base(message) {}
/// <summary>
/// Construct instance of EncryptionKeyDisabledException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public EncryptionKeyDisabledException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of EncryptionKeyDisabledException
/// </summary>
/// <param name="innerException"></param>
public EncryptionKeyDisabledException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of EncryptionKeyDisabledException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public EncryptionKeyDisabledException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of EncryptionKeyDisabledException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public EncryptionKeyDisabledException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the EncryptionKeyDisabledException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected EncryptionKeyDisabledException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 43.865979 | 178 | 0.655934 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/EncryptionKeyDisabledException.cs | 4,255 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.VisualScripting
{
public static class GraphsExceptionUtility
{
// Note: Checking hasDebugData here instead of enableDebug,
// because we always want exceptions to register, even if
// background debug is disabled.
private const string handledKey = "Bolt.Core.Handled";
public static Exception GetException(this IGraphElementWithDebugData element, GraphPointer pointer)
{
if (!pointer.hasDebugData)
{
return null;
}
var debugData = pointer.GetElementDebugData<IGraphElementDebugData>(element);
return debugData.runtimeException;
}
public static void SetException(this IGraphElementWithDebugData element, GraphPointer pointer, Exception ex)
{
if (!pointer.hasDebugData)
{
return;
}
var debugData = pointer.GetElementDebugData<IGraphElementDebugData>(element);
debugData.runtimeException = ex;
}
public static void HandleException(this IGraphElementWithDebugData element, GraphPointer pointer, Exception ex)
{
Ensure.That(nameof(ex)).IsNotNull(ex);
if (pointer == null)
{
Debug.LogError("Caught exception with null graph pointer (flow was likely disposed):\n" + ex);
return;
}
var reference = pointer.AsReference();
if (!ex.HandledIn(reference))
{
element.SetException(pointer, ex);
}
while (reference.isChild)
{
var parentElement = reference.parentElement;
reference = reference.ParentReference(true);
if (parentElement is IGraphElementWithDebugData debuggableParentElement)
{
if (!ex.HandledIn(reference))
{
debuggableParentElement.SetException(reference, ex);
}
}
}
}
private static bool HandledIn(this Exception ex, GraphReference reference)
{
Ensure.That(nameof(ex)).IsNotNull(ex);
if (!ex.Data.Contains(handledKey))
{
ex.Data.Add(handledKey, new HashSet<GraphReference>());
}
var handled = (HashSet<GraphReference>)ex.Data[handledKey];
if (handled.Contains(reference))
{
return true;
}
else
{
handled.Add(reference);
return false;
}
}
}
}
| 29.521277 | 119 | 0.54991 | [
"MIT"
] | 2PUEG-VRIK/UnityEscapeGame | 2P-UnityEscapeGame/Library/PackageCache/com.unity.visualscripting@1.6.1/Runtime/VisualScripting.Core/Graphs/GraphsExceptionUtility.cs | 2,775 | 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.Azure.Commands.Resources.Test.ScenarioTests
{
using ServiceManagement.Common.Models;
using WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Xunit.Abstractions;
public class MoveResourceTest : ResourceTestRunner
{
public MoveResourceTest(ITestOutputHelper output) : base(output)
{
}
[Fact(Skip = "Need to re-record test")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestMoveAzureResource()
{
TestRunner.RunTestScript("Test-MoveAzureResource");
}
}
}
| 39.742857 | 87 | 0.609633 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Resources/Resources.Test/ScenarioTests/MoveResourceTest.cs | 1,359 | C# |
using System;
using System.Windows.Input;
#nullable enable
namespace aemarcoCommons.WpfTools.Commands
{
public abstract class BaseCommand : ICommand
{
public abstract void Execute(object? parameter);
public virtual bool CanExecute(object? parameter)
{
return true;
}
public event EventHandler? CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
}
| 24 | 63 | 0.636364 | [
"Unlicense"
] | UltimateSeeSharp/aemarcoCommons | WpfTools/Commands/BaseCommand.cs | 530 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Horizon.Payment.Alipay.Domain;
namespace Horizon.Payment.Alipay.Response
{
/// <summary>
/// KoubeiRetailKbcodeQueryResponse.
/// </summary>
public class KoubeiRetailKbcodeQueryResponse : AlipayResponse
{
/// <summary>
/// 口碑码信息列表
/// </summary>
[JsonPropertyName("code_info_list")]
public List<RetailKbcodeQueryVo> CodeInfoList { get; set; }
/// <summary>
/// 口碑码总记录数
/// </summary>
[JsonPropertyName("total_count")]
public long TotalCount { get; set; }
}
}
| 25.76 | 67 | 0.624224 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Response/KoubeiRetailKbcodeQueryResponse.cs | 674 | C# |
using BizHawk.Common;
using System;
using BizHawk.Emulation.Cores.Components.LR35902;
namespace BizHawk.Emulation.Cores.Nintendo.GBHawk
{
// Sachen Bootleg Mapper
// NOTE: Normally, locked mode is disabled after 31 rises of A15
// this occurs when the Boot Rom is loading the nintendo logo into VRAM
// instead of tracking that in the main memory map where it will just slow things down for no reason
// we'll clear the 'locked' flag when the last byte of the logo is read
class MapperSachen2 : MapperBase
{
public int ROM_bank;
public bool locked, locked_GBC, finished;
public int ROM_mask;
public int ROM_bank_mask;
public int BASE_ROM_Bank;
public bool reg_access;
public ushort addr_last;
public int counter;
public override void Reset()
{
ROM_bank = 1;
ROM_mask = Core._rom.Length / 0x4000 - 1;
BASE_ROM_Bank = 0;
ROM_bank_mask = 0;
locked = true;
locked_GBC = false;
finished = false;
reg_access = false;
addr_last = 0;
counter = 0;
}
public override byte ReadMemory(ushort addr)
{
if (addr < 0x4000)
{
// header is scrambled
if ((addr >= 0x100) && (addr < 0x200))
{
int temp0 = (addr & 1);
int temp1 = (addr & 2);
int temp4 = (addr & 0x10);
int temp6 = (addr & 0x40);
temp0 = temp0 << 6;
temp1 = temp1 << 3;
temp4 = temp4 >> 3;
temp6 = temp6 >> 6;
addr &= 0x1AC;
addr |= (ushort)(temp0 | temp1 | temp4 | temp6);
}
if (locked_GBC) { addr |= 0x80; }
return Core._rom[addr + BASE_ROM_Bank * 0x4000];
}
else if (addr < 0x8000)
{
int temp_bank = (ROM_bank & ~ROM_bank_mask) | (ROM_bank_mask & BASE_ROM_Bank);
temp_bank &= ROM_mask;
return Core._rom[(addr - 0x4000) + temp_bank * 0x4000];
}
else
{
return 0xFF;
}
}
public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags)
{
if (addr < 0x4000)
{
// header is scrambled
if ((addr >= 0x100) && (addr < 0x200))
{
int temp0 = (addr & 1);
int temp1 = (addr & 2);
int temp4 = (addr & 0x10);
int temp6 = (addr & 0x40);
temp0 = temp0 << 6;
temp1 = temp1 << 3;
temp4 = temp4 >> 3;
temp6 = temp6 >> 6;
addr &= 0x1AC;
addr |= (ushort)(temp0 | temp1 | temp4 | temp6);
}
if (locked_GBC) { addr |= 0x80; }
SetCDLROM(flags, addr + BASE_ROM_Bank * 0x4000);
}
else if (addr < 0x8000)
{
int temp_bank = (ROM_bank & ~ROM_bank_mask) | (ROM_bank_mask & BASE_ROM_Bank);
temp_bank &= ROM_mask;
SetCDLROM(flags, (addr - 0x4000) + temp_bank * 0x4000);
}
else
{
return;
}
}
public override byte PeekMemory(ushort addr)
{
return ReadMemory(addr);
}
public override void WriteMemory(ushort addr, byte value)
{
if (addr < 0x2000)
{
if (reg_access)
{
BASE_ROM_Bank = value;
}
}
else if (addr < 0x4000)
{
ROM_bank = (value > 0) ? (value) : 1;
if ((value & 0x30) == 0x30)
{
reg_access = true;
}
else
{
reg_access = false;
}
}
else if (addr < 0x6000)
{
if (reg_access)
{
ROM_bank_mask = value;
}
}
}
public override void PokeMemory(ushort addr, byte value)
{
WriteMemory(addr, value);
}
public override void Mapper_Tick()
{
if (locked)
{
if (((Core.addr_access & 0x8000) == 0) && ((addr_last & 0x8000) > 0) && (Core.addr_access >= 0x100))
{
counter++;
}
if (Core.addr_access >= 0x100)
{
addr_last = Core.addr_access;
}
if (counter == 0x30)
{
locked = false;
locked_GBC = true;
counter = 0;
}
}
else if (locked_GBC)
{
if (((Core.addr_access & 0x8000) == 0) && ((addr_last & 0x8000) > 0) && (Core.addr_access >= 0x100))
{
counter++;
}
if (Core.addr_access >= 0x100)
{
addr_last = Core.addr_access;
}
if (counter == 0x30)
{
locked_GBC = false;
finished = true;
Console.WriteLine("Finished");
Console.WriteLine(Core.cpu.TotalExecutedCycles);
}
// The above condition seems to never be reached as described in the mapper notes
// so for now add this one
if ((Core.addr_access == 0x133) && (counter == 1))
{
locked_GBC = false;
finished = true;
Console.WriteLine("Unlocked");
}
}
}
public override void SyncState(Serializer ser)
{
ser.Sync(nameof(ROM_bank), ref ROM_bank);
ser.Sync(nameof(ROM_mask), ref ROM_mask);
ser.Sync(nameof(locked), ref locked);
ser.Sync(nameof(locked_GBC), ref locked_GBC);
ser.Sync(nameof(finished), ref finished);
ser.Sync(nameof(ROM_bank_mask), ref ROM_bank_mask);
ser.Sync(nameof(BASE_ROM_Bank), ref BASE_ROM_Bank);
ser.Sync(nameof(reg_access), ref reg_access);
ser.Sync(nameof(addr_last), ref addr_last);
ser.Sync(nameof(counter), ref counter);
}
}
} | 21.990991 | 104 | 0.600164 | [
"MIT"
] | Gorialis/BizHawk | BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC2.cs | 4,884 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Network" />
/// </summary>
public partial class NetworkTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Network"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Network" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Network" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Network" />.</param>
/// <returns>
/// an instance of <see cref="Network" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.INetwork ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.INetwork).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Network.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Network.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Network.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 50.56338 | 245 | 0.575348 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/Network.TypeConverter.cs | 7,039 | C# |
namespace Caliburn.Micro {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if WinRT81
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
using EventTrigger = Microsoft.Xaml.Interactions.Core.EventTriggerBehavior;
using Windows.UI.Xaml.Shapes;
#else
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Shapes;
using EventTrigger = System.Windows.Interactivity.EventTrigger;
#endif
#if !SILVERLIGHT && !WinRT
using System.Windows.Documents;
#endif
/// <summary>
/// Used to configure the conventions used by the framework to apply bindings and create actions.
/// </summary>
public static class ConventionManager {
static readonly ILog Log = LogManager.GetLog(typeof(ConventionManager));
/// <summary>
/// Converters <see cref="bool"/> to/from <see cref="Visibility"/>.
/// </summary>
public static IValueConverter BooleanToVisibilityConverter = new BooleanToVisibilityConverter();
/// <summary>
/// Indicates whether or not static properties should be included during convention name matching.
/// </summary>
/// <remarks>False by default.</remarks>
public static bool IncludeStaticProperties = false;
/// <summary>
/// Indicates whether or not the Content of ContentControls should be overwritten by conventional bindings.
/// </summary>
/// <remarks>False by default.</remarks>
public static bool OverwriteContent = false;
/// <summary>
/// The default DataTemplate used for ItemsControls when required.
/// </summary>
public static DataTemplate DefaultItemTemplate = (DataTemplate)
#if SILVERLIGHT || WinRT
XamlReader.Load(
#else
XamlReader.Parse(
#endif
#if WinRT
"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:cal='using:Caliburn.Micro'>" +
"<ContentControl cal:View.Model=\"{Binding}\" VerticalContentAlignment=\"Stretch\" HorizontalContentAlignment=\"Stretch\" IsTabStop=\"False\" />" +
"</DataTemplate>"
#else
"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:cal='clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro.Platform'> " +
"<ContentControl cal:View.Model=\"{Binding}\" VerticalContentAlignment=\"Stretch\" HorizontalContentAlignment=\"Stretch\" IsTabStop=\"False\" />" +
"</DataTemplate>"
#endif
);
/// <summary>
/// The default DataTemplate used for Headered controls when required.
/// </summary>
public static DataTemplate DefaultHeaderTemplate = (DataTemplate)
#if SILVERLIGHT || WinRT
XamlReader.Load(
#else
XamlReader.Parse(
#endif
"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'><TextBlock Text=\"{Binding DisplayName, Mode=TwoWay}\" /></DataTemplate>"
);
static readonly Dictionary<Type, ElementConvention> ElementConventions = new Dictionary<Type, ElementConvention>();
/// <summary>
/// Changes the provided word from a plural form to a singular form.
/// </summary>
public static Func<string, string> Singularize = original => {
return original.EndsWith("ies")
? original.TrimEnd('s').TrimEnd('e').TrimEnd('i') + "y"
: original.TrimEnd('s');
};
/// <summary>
/// Derives the SelectedItem property name.
/// </summary>
public static Func<string, IEnumerable<string>> DerivePotentialSelectionNames = name => {
var singular = Singularize(name);
return new[] {
"Active" + singular,
"Selected" + singular,
"Current" + singular
};
};
/// <summary>
/// Creates a binding and sets it on the element, applying the appropriate conventions.
/// </summary>
/// <param name="viewModelType"></param>
/// <param name="path"></param>
/// <param name="property"></param>
/// <param name="element"></param>
/// <param name="convention"></param>
/// <param name="bindableProperty"></param>
public static Action<Type, string, PropertyInfo, FrameworkElement, ElementConvention, DependencyProperty> SetBinding =
(viewModelType, path, property, element, convention, bindableProperty) => {
#if WinRT
var binding = new Binding { Path = new PropertyPath(path) };
#else
var binding = new Binding(path);
#endif
ApplyBindingMode(binding, property);
ApplyValueConverter(binding, bindableProperty, property);
ApplyStringFormat(binding, convention, property);
ApplyValidation(binding, viewModelType, property);
ApplyUpdateSourceTrigger(bindableProperty, element, binding, property);
BindingOperations.SetBinding(element, bindableProperty, binding);
};
/// <summary>
/// Applies the appropriate binding mode to the binding.
/// </summary>
public static Action<Binding, PropertyInfo> ApplyBindingMode = (binding, property) => {
#if WinRT
var setMethod = property.SetMethod;
binding.Mode = (property.CanWrite && setMethod != null && setMethod.IsPublic) ? BindingMode.TwoWay : BindingMode.OneWay;
#else
var setMethod = property.GetSetMethod();
binding.Mode = (property.CanWrite && setMethod != null && setMethod.IsPublic) ? BindingMode.TwoWay : BindingMode.OneWay;
#endif
};
/// <summary>
/// Determines whether or not and what type of validation to enable on the binding.
/// </summary>
public static Action<Binding, Type, PropertyInfo> ApplyValidation = (binding, viewModelType, property) => {
#if SILVERLIGHT || NET45
if (typeof(INotifyDataErrorInfo).IsAssignableFrom(viewModelType)) {
binding.ValidatesOnNotifyDataErrors = true;
binding.ValidatesOnExceptions = true;
}
#endif
#if !WinRT
if (typeof(IDataErrorInfo).IsAssignableFrom(viewModelType)) {
binding.ValidatesOnDataErrors = true;
binding.ValidatesOnExceptions = true;
}
#endif
};
/// <summary>
/// Determines whether a value converter is is needed and applies one to the binding.
/// </summary>
public static Action<Binding, DependencyProperty, PropertyInfo> ApplyValueConverter = (binding, bindableProperty, property) => {
if (bindableProperty == UIElement.VisibilityProperty && typeof(bool).IsAssignableFrom(property.PropertyType))
binding.Converter = BooleanToVisibilityConverter;
};
/// <summary>
/// Determines whether a custom string format is needed and applies it to the binding.
/// </summary>
public static Action<Binding, ElementConvention, PropertyInfo> ApplyStringFormat = (binding, convention, property) => {
#if !WinRT
if(typeof(DateTime).IsAssignableFrom(property.PropertyType))
binding.StringFormat = "{0:d}";
#endif
};
/// <summary>
/// Determines whether a custom update source trigger should be applied to the binding.
/// </summary>
public static Action<DependencyProperty, DependencyObject, Binding, PropertyInfo> ApplyUpdateSourceTrigger = (bindableProperty, element, binding, info) => {
#if SILVERLIGHT && !SL5
ApplySilverlightTriggers(
element,
bindableProperty,
x => x.GetBindingExpression(bindableProperty),
info,
binding
);
#elif WinRT81 || NET
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
#endif
};
static ConventionManager() {
#if WINDOWS_UWP
AddElementConvention<SplitView>(SplitView.ContentProperty, "IsPaneOpen", "PaneClosing").GetBindableProperty =
delegate (DependencyObject foundControl)
{
var element = (SplitView)foundControl;
if (!OverwriteContent)
return null;
Log.Info("ViewModel bound on {0}.", element.Name);
return View.ModelProperty;
};
#endif
#if !WINDOWS_PHONE && !WinRT
AddElementConvention<DatePicker>(DatePicker.SelectedDateProperty, "SelectedDate", "SelectedDateChanged");
#endif
#if WinRT81
AddElementConvention<DatePicker>(DatePicker.DateProperty, "Date", "DateChanged");
AddElementConvention<TimePicker>(TimePicker.TimeProperty, "Time", "TimeChanged");
AddElementConvention<Hub>(Hub.HeaderProperty, "Header", "Loaded");
AddElementConvention<HubSection>(HubSection.HeaderProperty, "Header", "SectionsInViewChanged");
AddElementConvention<MenuFlyoutItem>(MenuFlyoutItem.TextProperty, "Text", "Click");
AddElementConvention<ToggleMenuFlyoutItem>(ToggleMenuFlyoutItem.IsCheckedProperty, "IsChecked", "Click");
#endif
#if WinRT81 && !WP81
AddElementConvention<SearchBox>(SearchBox.QueryTextProperty, "QueryText", "QuerySubmitted");
#endif
#if WinRT
AddElementConvention<ToggleSwitch>(ToggleSwitch.IsOnProperty, "IsOn", "Toggled");
AddElementConvention<ProgressRing>(ProgressRing.IsActiveProperty, "IsActive", "Loaded");
AddElementConvention<Slider>(Slider.ValueProperty, "Value", "ValueChanged");
AddElementConvention<RichEditBox>(RichEditBox.DataContextProperty, "DataContext", "TextChanged");
#endif
#if WP81 || WINDOWS_UWP
AddElementConvention<Pivot>(Pivot.ItemsSourceProperty, "SelectedItem", "SelectionChanged")
.ApplyBinding = (viewModelType, path, property, element, convention) =>
{
if (!SetBindingWithoutBindingOrValueOverwrite(viewModelType, path, property, element, convention, ItemsControl.ItemsSourceProperty))
{
return false;
}
ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path);
ApplyItemTemplate((ItemsControl)element, property);
return true;
};
#endif
#if SILVERLIGHT || WinRT
AddElementConvention<HyperlinkButton>(HyperlinkButton.ContentProperty, "DataContext", "Click");
AddElementConvention<PasswordBox>(PasswordBox.PasswordProperty, "Password", "PasswordChanged");
#else
AddElementConvention<DocumentViewer>(DocumentViewer.DocumentProperty, "DataContext", "Loaded");
AddElementConvention<PasswordBox>(null, "Password", "PasswordChanged");
AddElementConvention<Hyperlink>(Hyperlink.DataContextProperty, "DataContext", "Click");
AddElementConvention<RichTextBox>(RichTextBox.DataContextProperty, "DataContext", "TextChanged");
AddElementConvention<Menu>(Menu.ItemsSourceProperty,"DataContext", "Click");
AddElementConvention<MenuItem>(MenuItem.ItemsSourceProperty, "DataContext", "Click");
AddElementConvention<Label>(Label.ContentProperty, "Content", "DataContextChanged");
AddElementConvention<Slider>(Slider.ValueProperty, "Value", "ValueChanged");
AddElementConvention<Expander>(Expander.IsExpandedProperty, "IsExpanded", "Expanded");
AddElementConvention<StatusBar>(StatusBar.ItemsSourceProperty, "DataContext", "Loaded");
AddElementConvention<ToolBar>(ToolBar.ItemsSourceProperty, "DataContext", "Loaded");
AddElementConvention<ToolBarTray>(ToolBarTray.VisibilityProperty, "DataContext", "Loaded");
AddElementConvention<TreeView>(TreeView.ItemsSourceProperty, "SelectedItem", "SelectedItemChanged");
AddElementConvention<TabControl>(TabControl.ItemsSourceProperty, "ItemsSource", "SelectionChanged")
.ApplyBinding = (viewModelType, path, property, element, convention) => {
var bindableProperty = convention.GetBindableProperty(element);
if(!SetBindingWithoutBindingOverwrite(viewModelType, path, property, element, convention, bindableProperty))
return false;
var tabControl = (TabControl)element;
if(tabControl.ContentTemplate == null
&& tabControl.ContentTemplateSelector == null
&& property.PropertyType.IsGenericType) {
var itemType = property.PropertyType.GetGenericArguments().First();
if(!itemType.IsValueType && !typeof(string).IsAssignableFrom(itemType)){
tabControl.ContentTemplate = DefaultItemTemplate;
Log.Info("ContentTemplate applied to {0}.", element.Name);
}
}
ConfigureSelectedItem(element, Selector.SelectedItemProperty, viewModelType, path);
if(string.IsNullOrEmpty(tabControl.DisplayMemberPath))
ApplyHeaderTemplate(tabControl, TabControl.ItemTemplateProperty, TabControl.ItemTemplateSelectorProperty, viewModelType);
return true;
};
AddElementConvention<TabItem>(TabItem.ContentProperty, "DataContext", "DataContextChanged");
AddElementConvention<Window>(Window.DataContextProperty, "DataContext", "Loaded");
#endif
AddElementConvention<UserControl>(UserControl.VisibilityProperty, "DataContext", "Loaded");
AddElementConvention<Image>(Image.SourceProperty, "Source", "Loaded");
AddElementConvention<ToggleButton>(ToggleButton.IsCheckedProperty, "IsChecked", "Click");
AddElementConvention<ButtonBase>(ButtonBase.ContentProperty, "DataContext", "Click");
AddElementConvention<TextBox>(TextBox.TextProperty, "Text", "TextChanged");
AddElementConvention<TextBlock>(TextBlock.TextProperty, "Text", "DataContextChanged");
AddElementConvention<ProgressBar>(ProgressBar.ValueProperty, "Value", "ValueChanged");
AddElementConvention<Selector>(Selector.ItemsSourceProperty, "SelectedItem", "SelectionChanged")
.ApplyBinding = (viewModelType, path, property, element, convention) => {
if (!SetBindingWithoutBindingOrValueOverwrite(viewModelType, path, property, element, convention, ItemsControl.ItemsSourceProperty)) {
return false;
}
ConfigureSelectedItem(element, Selector.SelectedItemProperty, viewModelType, path);
ApplyItemTemplate((ItemsControl)element, property);
return true;
};
AddElementConvention<ItemsControl>(ItemsControl.ItemsSourceProperty, "DataContext", "Loaded")
.ApplyBinding = (viewModelType, path, property, element, convention) => {
if (!SetBindingWithoutBindingOrValueOverwrite(viewModelType, path, property, element, convention, ItemsControl.ItemsSourceProperty)) {
return false;
}
ApplyItemTemplate((ItemsControl)element, property);
return true;
};
AddElementConvention<ContentControl>(ContentControl.ContentProperty, "DataContext", "Loaded").GetBindableProperty =
delegate(DependencyObject foundControl) {
var element = (ContentControl)foundControl;
if (element.Content is DependencyObject && !OverwriteContent)
return null;
#if SILVERLIGHT
var useViewModel = element.ContentTemplate == null;
#else
var useViewModel = element.ContentTemplate == null && element.ContentTemplateSelector == null;
#endif
if (useViewModel) {
Log.Info("ViewModel bound on {0}.", element.Name);
return View.ModelProperty;
}
Log.Info("Content bound on {0}. Template or content was present.", element.Name);
return ContentControl.ContentProperty;
};
AddElementConvention<Shape>(Shape.VisibilityProperty, "DataContext", "MouseLeftButtonUp");
AddElementConvention<FrameworkElement>(FrameworkElement.VisibilityProperty, "DataContext", "Loaded");
}
/// <summary>
/// Adds an element convention.
/// </summary>
/// <typeparam name="T">The type of element.</typeparam>
/// <param name="bindableProperty">The default property for binding conventions.</param>
/// <param name="parameterProperty">The default property for action parameters.</param>
/// <param name="eventName">The default event to trigger actions.</param>
public static ElementConvention AddElementConvention<T>(DependencyProperty bindableProperty, string parameterProperty, string eventName) {
return AddElementConvention(new ElementConvention {
ElementType = typeof(T),
GetBindableProperty = element => bindableProperty,
ParameterProperty = parameterProperty,
CreateTrigger = () => new EventTrigger { EventName = eventName }
});
}
/// <summary>
/// Adds an element convention.
/// </summary>
/// <param name="convention"></param>
public static ElementConvention AddElementConvention(ElementConvention convention) {
return ElementConventions[convention.ElementType] = convention;
}
/// <summary>
/// Gets an element convention for the provided element type.
/// </summary>
/// <param name="elementType">The type of element to locate the convention for.</param>
/// <returns>The convention if found, null otherwise.</returns>
/// <remarks>Searches the class hierarchy for conventions.</remarks>
public static ElementConvention GetElementConvention(Type elementType) {
if (elementType == null)
return null;
ElementConvention propertyConvention;
ElementConventions.TryGetValue(elementType, out propertyConvention);
#if WinRT
return propertyConvention ?? GetElementConvention(elementType.GetTypeInfo().BaseType);
#else
return propertyConvention ?? GetElementConvention(elementType.BaseType);
#endif
}
/// <summary>
/// Determines whether a particular dependency property already has a binding on the provided element.
/// </summary>
public static bool HasBinding(FrameworkElement element, DependencyProperty property) {
#if NET
return BindingOperations.GetBindingBase(element, property) != null;
#else
return element.GetBindingExpression(property) != null;
#endif
}
/// <summary>
/// Creates a binding and sets it on the element, guarding against pre-existing bindings.
/// </summary>
public static bool SetBindingWithoutBindingOverwrite(Type viewModelType, string path, PropertyInfo property,
FrameworkElement element, ElementConvention convention,
DependencyProperty bindableProperty) {
if (bindableProperty == null || HasBinding(element, bindableProperty)) {
return false;
}
SetBinding(viewModelType, path, property, element, convention, bindableProperty);
return true;
}
/// <summary>
/// Creates a binding and set it on the element, guarding against pre-existing bindings and pre-existing values.
/// </summary>
/// <param name="viewModelType"></param>
/// <param name="path"></param>
/// <param name="property"></param>
/// <param name="element"></param>
/// <param name="convention"></param>
/// <param name="bindableProperty"> </param>
/// <returns></returns>
public static bool SetBindingWithoutBindingOrValueOverwrite(Type viewModelType, string path,
PropertyInfo property, FrameworkElement element,
ElementConvention convention,
DependencyProperty bindableProperty) {
if (bindableProperty == null || HasBinding(element, bindableProperty)) {
return false;
}
if (element.GetValue(bindableProperty) != null) {
return false;
}
SetBinding(viewModelType, path, property, element, convention, bindableProperty);
return true;
}
/// <summary>
/// Attempts to apply the default item template to the items control.
/// </summary>
/// <param name="itemsControl">The items control.</param>
/// <param name="property">The collection property.</param>
public static void ApplyItemTemplate(ItemsControl itemsControl, PropertyInfo property) {
if (!string.IsNullOrEmpty(itemsControl.DisplayMemberPath)
|| HasBinding(itemsControl, ItemsControl.DisplayMemberPathProperty)
|| itemsControl.ItemTemplate != null) {
return;
}
#if !WinRT
if (property.PropertyType.IsGenericType) {
var itemType = property.PropertyType.GetGenericArguments().First();
if (itemType.IsValueType || typeof(string).IsAssignableFrom(itemType)) {
return;
}
}
#else
if (property.PropertyType.GetTypeInfo().IsGenericType) {
var itemType = property.PropertyType.GenericTypeArguments.First();
if (itemType.GetTypeInfo().IsValueType || typeof (string).IsAssignableFrom(itemType)) {
return;
}
}
#endif
#if !SILVERLIGHT
if (itemsControl.ItemTemplateSelector == null){
itemsControl.ItemTemplate = DefaultItemTemplate;
Log.Info("ItemTemplate applied to {0}.", itemsControl.Name);
}
#else
itemsControl.ItemTemplate = DefaultItemTemplate;
Log.Info("ItemTemplate applied to {0}.", itemsControl.Name);
#endif
}
/// <summary>
/// Configures the selected item convention.
/// </summary>
/// <param name="selector">The element that has a SelectedItem property.</param>
/// <param name="selectedItemProperty">The SelectedItem property.</param>
/// <param name="viewModelType">The view model type.</param>
/// <param name="path">The property path.</param>
public static Action<FrameworkElement, DependencyProperty, Type, string> ConfigureSelectedItem =
(selector, selectedItemProperty, viewModelType, path) => {
if (HasBinding(selector, selectedItemProperty)) {
return;
}
var index = path.LastIndexOf('.');
index = index == -1 ? 0 : index + 1;
var baseName = path.Substring(index);
foreach (var potentialName in DerivePotentialSelectionNames(baseName)) {
if (viewModelType.GetPropertyCaseInsensitive(potentialName) != null) {
var selectionPath = path.Replace(baseName, potentialName);
#if WinRT
var binding = new Binding { Mode = BindingMode.TwoWay, Path = new PropertyPath(selectionPath) };
#else
var binding = new Binding(selectionPath) { Mode = BindingMode.TwoWay };
#endif
var shouldApplyBinding = ConfigureSelectedItemBinding(selector, selectedItemProperty, viewModelType, selectionPath, binding);
if (shouldApplyBinding) {
BindingOperations.SetBinding(selector, selectedItemProperty, binding);
Log.Info("SelectedItem binding applied to {0}.", selector.Name);
return;
}
Log.Info("SelectedItem binding not applied to {0} due to 'ConfigureSelectedItemBinding' customization.", selector.Name);
}
}
};
/// <summary>
/// Configures the SelectedItem binding for matched selection path.
/// </summary>
/// <param name="selector">The element that has a SelectedItem property.</param>
/// <param name="selectedItemProperty">The SelectedItem property.</param>
/// <param name="viewModelType">The view model type.</param>
/// <param name="selectionPath">The property path.</param>
/// <param name="binding">The binding to configure.</param>
/// <returns>A bool indicating whether to apply binding</returns>
public static Func<FrameworkElement, DependencyProperty, Type, string, Binding, bool> ConfigureSelectedItemBinding =
(selector, selectedItemProperty, viewModelType, selectionPath, binding) => {
return true;
};
/// <summary>
/// Applies a header template based on <see cref="IHaveDisplayName"/>
/// </summary>
/// <param name="element"></param>
/// <param name="headerTemplateProperty"></param>
/// <param name="headerTemplateSelectorProperty"> </param>
/// <param name="viewModelType"></param>
public static void ApplyHeaderTemplate(FrameworkElement element, DependencyProperty headerTemplateProperty, DependencyProperty headerTemplateSelectorProperty, Type viewModelType) {
var template = element.GetValue(headerTemplateProperty);
var selector = headerTemplateSelectorProperty != null
? element.GetValue(headerTemplateSelectorProperty)
: null;
if (template != null || selector != null || !typeof(IHaveDisplayName).IsAssignableFrom(viewModelType)) {
return;
}
element.SetValue(headerTemplateProperty, DefaultHeaderTemplate);
Log.Info("Header template applied to {0}.", element.Name);
}
/// <summary>
/// Gets a property by name, ignoring case and searching all interfaces.
/// </summary>
/// <param name="type">The type to inspect.</param>
/// <param name="propertyName">The property to search for.</param>
/// <returns>The property or null if not found.</returns>
public static PropertyInfo GetPropertyCaseInsensitive(this Type type, string propertyName) {
#if WinRT
var typeInfo = type.GetTypeInfo();
var typeList = new List<Type> { type };
if (typeInfo.IsInterface) {
typeList.AddRange(typeInfo.ImplementedInterfaces);
}
return typeList
.Select(interfaceType => interfaceType.GetRuntimeProperty(propertyName))
.FirstOrDefault(property => property != null);
#else
var typeList = new List<Type> { type };
if (type.IsInterface) {
typeList.AddRange(type.GetInterfaces());
}
var flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
if (IncludeStaticProperties) {
flags = flags | BindingFlags.Static;
}
return typeList
.Select(interfaceType => interfaceType.GetProperty(propertyName, flags))
.FirstOrDefault(property => property != null);
#endif
}
#if (SILVERLIGHT && !SL5)
/// <summary>
/// Accounts for the lack of UpdateSourceTrigger in silverlight.
/// </summary>
/// <param name="element">The element to wire for change events on.</param>
/// <param name="dependencyProperty">The property that is being bound.</param>
/// <param name="expressionSource">Gets the the binding expression that needs to be updated.</param>
/// <param name="property">The property being bound to if available.</param>
/// <param name="binding">The binding if available.</param>
public static void ApplySilverlightTriggers(DependencyObject element, DependencyProperty dependencyProperty, Func<FrameworkElement, BindingExpression> expressionSource, PropertyInfo property, Binding binding){
var textBox = element as TextBox;
if (textBox != null && dependencyProperty == TextBox.TextProperty) {
if (property != null) {
var typeCode = Type.GetTypeCode(property.PropertyType);
if (typeCode == TypeCode.Single || typeCode == TypeCode.Double || typeCode == TypeCode.Decimal) {
binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
textBox.KeyUp += delegate {
var start = textBox.SelectionStart;
var text = textBox.Text;
expressionSource(textBox).UpdateSource();
textBox.Text = text;
textBox.SelectionStart = start;
};
return;
}
}
textBox.TextChanged += delegate { expressionSource(textBox).UpdateSource(); };
return;
}
var passwordBox = element as PasswordBox;
if (passwordBox != null && dependencyProperty == PasswordBox.PasswordProperty) {
passwordBox.PasswordChanged += delegate { expressionSource(passwordBox).UpdateSource(); };
}
}
#endif
}
}
| 49.148562 | 217 | 0.61631 | [
"MIT"
] | LTGKeithYang/CaliburnFrameworkStudy | src/Caliburn.Micro.Platform/ConventionManager.cs | 30,769 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public GameObject mainCam;
[Range(1f, 100f)]
public float moveSpeed;
void Start()
{
mainCam = this.gameObject;
}
// Update is called once per frame
void Update()
{
Vector2 moveDir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
// Debug.Log(moveDir);
mainCam.transform.position += (Vector3)moveDir * moveSpeed * Time.deltaTime;
}
}
| 23.333333 | 94 | 0.653571 | [
"MIT"
] | ARF-DEV/Graph-Search-Algo | Assets/CameraMovement.cs | 562 | C# |
using System.Reflection;
using Abp.Domain.Uow;
using Abp.Web.Models;
namespace Abp.AspNetCore.Configuration
{
public interface IAbpAspNetCoreConfiguration
{
WrapResultAttribute DefaultWrapResultAttribute { get; }
UnitOfWorkAttribute DefaultUnitOfWorkAttribute { get; }
/// <summary>
/// Default: true.
/// </summary>
bool IsValidationEnabledForControllers { get; set; }
/// <summary>
/// Default: true.
/// </summary>
bool SetNoCacheForAjaxResponses { get; set; }
void CreateControllersForAppServices(Assembly assembly, string moduleName = AbpServiceControllerSetting.DefaultServiceModuleName, bool useConventionalHttpVerbs = true);
}
}
| 28.576923 | 176 | 0.682369 | [
"MIT"
] | luyuxi14Linbaw/ZERO | src/Abp.AspNetCore/AspNetCore/Configuration/IAbpAspNetCoreConfiguration.cs | 745 | C# |
// Copyright (c) 2008 Vesa Tuomiaro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
using System;
namespace CloudMath
{
public static partial class Common
{
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified colors.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Color3"/>.</param>
/// <param name="value2">A <see cref="Color3"/>.</param>
/// <param name="value3">A <see cref="Color3"/>.</param>
/// <param name="value4">A <see cref="Color3"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Color3 result, ref Color3 value1, ref Color3 value2, ref Color3 value3, ref Color3 value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.R = 0.5f * (2 * value2.R + amount * (value3.R - value1.R) + amount2 * (2 * value1.R - 5 * value2.R + 4 * value3.R - value4.R) + amount3 * (value4.R - 3 * value3.R + 3 * value2.R - value1.R));
result.G = 0.5f * (2 * value2.G + amount * (value3.G - value1.G) + amount2 * (2 * value1.G - 5 * value2.G + 4 * value3.G - value4.G) + amount3 * (value4.G - 3 * value3.G + 3 * value2.G - value1.G));
result.B = 0.5f * (2 * value2.B + amount * (value3.B - value1.B) + amount2 * (2 * value1.B - 5 * value2.B + 4 * value3.B - value4.B) + amount3 * (value4.B - 3 * value3.B + 3 * value2.B - value1.B));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified colors.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Color4"/>.</param>
/// <param name="value2">A <see cref="Color4"/>.</param>
/// <param name="value3">A <see cref="Color4"/>.</param>
/// <param name="value4">A <see cref="Color4"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Color4 result, ref Color4 value1, ref Color4 value2, ref Color4 value3, ref Color4 value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.A = 0.5f * (2 * value2.A + amount * (value3.A - value1.A) + amount2 * (2 * value1.A - 5 * value2.A + 4 * value3.A - value4.A) + amount3 * (value4.A - 3 * value3.A + 3 * value2.A - value1.A));
result.R = 0.5f * (2 * value2.R + amount * (value3.R - value1.R) + amount2 * (2 * value1.R - 5 * value2.R + 4 * value3.R - value4.R) + amount3 * (value4.R - 3 * value3.R + 3 * value2.R - value1.R));
result.G = 0.5f * (2 * value2.G + amount * (value3.G - value1.G) + amount2 * (2 * value1.G - 5 * value2.G + 4 * value3.G - value4.G) + amount3 * (value4.G - 3 * value3.G + 3 * value2.G - value1.G));
result.B = 0.5f * (2 * value2.B + amount * (value3.B - value1.B) + amount2 * (2 * value1.B - 5 * value2.B + 4 * value3.B - value4.B) + amount3 * (value4.B - 3 * value3.B + 3 * value2.B - value1.B));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified values.
/// </summary>
/// <param name="value1">A <see cref="Single"/>.</param>
/// <param name="value2">A <see cref="Single"/>.</param>
/// <param name="value3">A <see cref="Single"/>.</param>
/// <param name="value4">A <see cref="Single"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
/// <returns>Interpolated value.</returns>
public static float CatmullRom(float value1, float value2, float value3, float value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
return 0.5f * (2 * value2 + amount * (value3 - value1) + amount2 * (2 * value1 - 5 * value2 + 4 * value3 - value4) + amount3 * (value4 - 3 * value3 + 3 * value2 - value1));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified vectors.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Vector2"/>.</param>
/// <param name="value2">A <see cref="Vector2"/>.</param>
/// <param name="value3">A <see cref="Vector2"/>.</param>
/// <param name="value4">A <see cref="Vector2"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Vector2 result, ref Vector2 value1, ref Vector2 value2, ref Vector2 value3, ref Vector2 value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.X = 0.5f * (2 * value2.X + amount * (value3.X - value1.X) + amount2 * (2 * value1.X - 5 * value2.X + 4 * value3.X - value4.X) + amount3 * (value4.X - 3 * value3.X + 3 * value2.X - value1.X));
result.Y = 0.5f * (2 * value2.Y + amount * (value3.Y - value1.Y) + amount2 * (2 * value1.Y - 5 * value2.Y + 4 * value3.Y - value4.Y) + amount3 * (value4.Y - 3 * value3.Y + 3 * value2.Y - value1.Y));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified vectors.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Vector3"/>.</param>
/// <param name="value2">A <see cref="Vector3"/>.</param>
/// <param name="value3">A <see cref="Vector3"/>.</param>
/// <param name="value4">A <see cref="Vector3"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Vector3 result, ref Vector3 value1, ref Vector3 value2, ref Vector3 value3, ref Vector3 value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.X = 0.5f * (2 * value2.X + amount * (value3.X - value1.X) + amount2 * (2 * value1.X - 5 * value2.X + 4 * value3.X - value4.X) + amount3 * (value4.X - 3 * value3.X + 3 * value2.X - value1.X));
result.Y = 0.5f * (2 * value2.Y + amount * (value3.Y - value1.Y) + amount2 * (2 * value1.Y - 5 * value2.Y + 4 * value3.Y - value4.Y) + amount3 * (value4.Y - 3 * value3.Y + 3 * value2.Y - value1.Y));
result.Z = 0.5f * (2 * value2.Z + amount * (value3.Z - value1.Z) + amount2 * (2 * value1.Z - 5 * value2.Z + 4 * value3.Z - value4.Z) + amount3 * (value4.Z - 3 * value3.Z + 3 * value2.Z - value1.Z));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified vectors.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Vector4"/>.</param>
/// <param name="value2">A <see cref="Vector4"/>.</param>
/// <param name="value3">A <see cref="Vector4"/>.</param>
/// <param name="value4">A <see cref="Vector4"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Vector4 result, ref Vector4 value1, ref Vector4 value2, ref Vector4 value3, ref Vector4 value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.X = 0.5f * (2 * value2.X + amount * (value3.X - value1.X) + amount2 * (2 * value1.X - 5 * value2.X + 4 * value3.X - value4.X) + amount3 * (value4.X - 3 * value3.X + 3 * value2.X - value1.X));
result.Y = 0.5f * (2 * value2.Y + amount * (value3.Y - value1.Y) + amount2 * (2 * value1.Y - 5 * value2.Y + 4 * value3.Y - value4.Y) + amount3 * (value4.Y - 3 * value3.Y + 3 * value2.Y - value1.Y));
result.Z = 0.5f * (2 * value2.Z + amount * (value3.Z - value1.Z) + amount2 * (2 * value1.Z - 5 * value2.Z + 4 * value3.Z - value4.Z) + amount3 * (value4.Z - 3 * value3.Z + 3 * value2.Z - value1.Z));
result.W = 0.5f * (2 * value2.W + amount * (value3.W - value1.W) + amount2 * (2 * value1.W - 5 * value2.W + 4 * value3.W - value4.W) + amount3 * (value4.W - 3 * value3.W + 3 * value2.W - value1.W));
}
/// <summary>
/// Performs a Catmull-Rom spline interpolation between the specified quaternions.
/// </summary>
/// <param name="result">Output variable for the result.</param>
/// <param name="value1">A <see cref="Quaternion"/>.</param>
/// <param name="value2">A <see cref="Quaternion"/>.</param>
/// <param name="value3">A <see cref="Quaternion"/>.</param>
/// <param name="value4">A <see cref="Quaternion"/>.</param>
/// <param name="amount">Interpolation value in range [0, 1].</param>
public static void CatmullRom(out Quaternion result, ref Quaternion value1, ref Quaternion value2, ref Quaternion value3, ref Quaternion value4, float amount)
{
float amount2 = amount * amount;
float amount3 = amount * amount2;
result.W = 0.5f * (2 * value2.W + amount * (value3.W - value1.W) + amount2 * (2 * value1.W - 5 * value2.W + 4 * value3.W - value4.W) + amount3 * (value4.W - 3 * value3.W + 3 * value2.W - value1.W));
result.I = 0.5f * (2 * value2.I + amount * (value3.I - value1.I) + amount2 * (2 * value1.I - 5 * value2.I + 4 * value3.I - value4.I) + amount3 * (value4.I - 3 * value3.I + 3 * value2.I - value1.I));
result.J = 0.5f * (2 * value2.J + amount * (value3.J - value1.J) + amount2 * (2 * value1.J - 5 * value2.J + 4 * value3.J - value4.J) + amount3 * (value4.J - 3 * value3.J + 3 * value2.J - value1.J));
result.K = 0.5f * (2 * value2.K + amount * (value3.K - value1.K) + amount2 * (2 * value1.K - 5 * value2.K + 4 * value3.K - value4.K) + amount3 * (value4.K - 3 * value3.K + 3 * value2.K - value1.K));
}
}
}
| 70.31875 | 210 | 0.583681 | [
"Apache-2.0"
] | MoysheBenRabi/setp | csharp/Examples/CloudDaemon/CloudMath/CatmullRom.cs | 11,253 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.CloudFormation
{
/// <summary>
/// Configuration for accessing Amazon CloudFormation service
/// </summary>
public partial class AmazonCloudFormationConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.11.18");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonCloudFormationConfig()
{
this.AuthenticationServiceName = "cloudformation";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "cloudformation";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2010-05-15";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.6375 | 112 | 0.595026 | [
"Apache-2.0"
] | InsiteVR/aws-sdk-net | sdk/src/Services/CloudFormation/Generated/AmazonCloudFormationConfig.cs | 2,131 | C# |
using NUnit.Framework;
using System.Collections.Generic;
using Wr.UmbracoPhoneManager.Models;
namespace Wr.UmbracoPhoneManager.Tests.Providers.Storage.XPath
{
[TestFixture]
public class XPathRepository_XPathNavigatorTest
{
[Test]
public void XPathRepository_GetXPathNavigator_CheckDefaultSettings_WithAllProperties_ReturnValid()
{
// Arrange
var dataModel = new PhoneManagerModel() { DefaultCampaignQueryStringKey = "fsource", DefaultPersistDurationInDays = 32 };
dataModel.PhoneManagerCampaignDetail = new List<PhoneManagerCampaignDetail>() { new PhoneManagerCampaignDetail() { Id = "1201", TelephoneNumber = "0800 123 4567", CampaignCode = "testcode" } };
var testPhoneManagerData = dataModel.ToXmlString();
var method = MockProviders.Repository(testPhoneManagerData);
// Act
var act = method.GetDefaultSettings();
// Assert
Assert.IsTrue(act.DefaultCampaignQueryStringKey == dataModel.DefaultCampaignQueryStringKey);
Assert.IsTrue(act.DefaultPersistDurationInDays == dataModel.DefaultPersistDurationInDays);
}
[Test]
public void XPathRepository_GetXPathNavigator_CheckDefaultSettings_WithDefaultValueForMissingPropertyDefaultPersistDurationInDays_ReturnValid()
{
// Arrange
var dataModel = new PhoneManagerModel() { DefaultCampaignQueryStringKey = "fsource", DefaultPersistDurationInDays = 0 };
dataModel.PhoneManagerCampaignDetail = new List<PhoneManagerCampaignDetail>() { new PhoneManagerCampaignDetail() { Id = "1201", TelephoneNumber = "0800 123 4567", CampaignCode = "testcode" } };
var testPhoneManagerData = dataModel.ToXmlString();
var method = MockProviders.Repository(testPhoneManagerData);
// Act
var act = method.GetDefaultSettings();
// Assert
Assert.IsTrue(act.DefaultCampaignQueryStringKey == dataModel.DefaultCampaignQueryStringKey);
Assert.IsTrue(act.DefaultPersistDurationInDays == 30);
}
[Test]
public void XPathRepository_GetXPathNavigator_ListAllCampaignDetailRecords_ReturnAllRecords()
{
// Arrange
var dataModel = new PhoneManagerModel() { DefaultCampaignQueryStringKey = "fsource", DefaultPersistDurationInDays = 0 };
dataModel.PhoneManagerCampaignDetail = new List<PhoneManagerCampaignDetail>()
{
new PhoneManagerCampaignDetail() { Id = "1201", TelephoneNumber = "0800 123 4567", CampaignCode = "testcode" },
new PhoneManagerCampaignDetail() { Id = "1202", TelephoneNumber = "0800 000 4567", CampaignCode = "testcode2" }
};
var testPhoneManagerData = dataModel.ToXmlString();
var method = MockProviders.Repository(testPhoneManagerData);
// Act
var act = method.ListAllCampaignDetailRecords();
// Assert
Assert.IsTrue(act.Count == 2);
}
[Test]
public void XPathRepository_GetXPathNavigator_GetCampaignDetailById_WithMatchingRecord_ReturnValid()
{
// Arrange
var dataModel = new PhoneManagerModel() { DefaultCampaignQueryStringKey = "fsource", DefaultPersistDurationInDays = 0 };
dataModel.PhoneManagerCampaignDetail = new List<PhoneManagerCampaignDetail>()
{
new PhoneManagerCampaignDetail() { Id = "1201", TelephoneNumber = "0800 123 4567", CampaignCode = "testcode" },
new PhoneManagerCampaignDetail() { Id = "1202", TelephoneNumber = "0800 000 4567", CampaignCode = "testcode2" }
};
var testPhoneManagerData = dataModel.ToXmlString();
var method = MockProviders.Repository(testPhoneManagerData);
// Act
var act = method.GetCampaignDetailById("1202");
// Assert
Assert.AreEqual("1202", act.Id);
}
[Test]
public void XPathRepository_GetXPathNavigator_GetCampaignDetailById_WithNoMatchingRecord_ReturnNull()
{
// Arrange
var dataModel = new PhoneManagerModel() { DefaultCampaignQueryStringKey = "fsource", DefaultPersistDurationInDays = 0 };
dataModel.PhoneManagerCampaignDetail = new List<PhoneManagerCampaignDetail>()
{
new PhoneManagerCampaignDetail() { Id = "1201", TelephoneNumber = "0800 123 4567", CampaignCode = "testcode" },
new PhoneManagerCampaignDetail() { Id = "1202", TelephoneNumber = "0800 000 4567", CampaignCode = "testcode2" }
};
var testPhoneManagerData = dataModel.ToXmlString();
var method = MockProviders.Repository(testPhoneManagerData);
// Act
var act = method.GetCampaignDetailById("1203");
// Assert
Assert.IsNull(act);
}
}
}
| 43.655172 | 205 | 0.647907 | [
"MIT"
] | bifter/Wr.Umbraco.CampaignPhoneManager | Wr.UmbracoPhoneManager.Tests/Providers/Storage/XPath/XPathRepository_XPathNavigatorTest.cs | 5,066 | C# |
using BusinessLogic;
using System;
using System.Collections.Generic;
using System.Text;
namespace MuzeyServer
{
public class ACADCSingleReqDto
{
public string id { get; set; }
public string workShop { get; set; }
[MuzeyReqType]
public string productionNumber { get; set; }
}
}
| 20.1875 | 52 | 0.659443 | [
"MIT"
] | muzeyc/MuzeyWebForNetCore | src/MuzeyAngular.Application/AC/ACADCSingle/Dto/ACADCSingleReqDto.cs | 325 | C# |
using Newtonsoft.Json;
using System.Runtime.Serialization;
namespace com.freeclimb
{
/// <summary>
/// Account Status enumeration with a default value of NONE.
/// </summary>
[JsonConverter(typeof(EnumConverter))]
public enum EAccountStatus
{
#pragma warning disable 1591 // XML comment compiler warning
[EnumMember(Value = "")]
NONE = 0,
[EnumMember(Value = "active")]
Active,
[EnumMember(Value = "suspended")]
Suspended,
[EnumMember(Value = "closed")]
Closed
#pragma warning restore 1591
}
}
| 21.178571 | 64 | 0.620573 | [
"MIT"
] | Anedumgottil/csharp-sdk | freeclimb-cs-sdk/EAccountStatus.cs | 595 | 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 Aliyun.Acs.Core;
namespace Aliyun.Acs.Yundun_ds.Model.V20190103
{
public class ValidateConnectorResponse : AcsResponse
{
private string requestId;
private bool? connected;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Connected
{
get
{
return connected;
}
set
{
connected = value;
}
}
}
}
| 22.736842 | 63 | 0.689815 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-yundun-ds/Yundun_ds/Model/V20190103/ValidateConnectorResponse.cs | 1,296 | C# |
namespace YaBlewItCP.Logic;
public interface IChooseColorProcesses
{
Task ColorChosenAsync(EnumColors color);
} | 23.2 | 44 | 0.818966 | [
"MIT"
] | musictopia2/GamingPackXV3 | CP/Games/YaBlewItCP/Logic/IChooseColorProcesses.cs | 118 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.TestCommon;
using Moq;
public class HubControllerOfTTest
{
[Fact]
public void HubContext_ReturnsContextResolvedFromConnectionManager()
{
DefaultContextController controller = new DefaultContextController();
controller.Configuration = new HttpConfiguration();
Mock<IConnectionManager> mockConnectionManager = new Mock<IConnectionManager>();
IHubContext context = new Mock<IHubContext>().Object;
mockConnectionManager.Setup(mock => mock.GetHubContext<MyHub>()).Returns(context);
Mock<System.Web.Http.Dependencies.IDependencyResolver> mockDependencyResolver = new Mock<System.Web.Http.Dependencies.IDependencyResolver>();
mockDependencyResolver.Setup(mock => mock.GetService(typeof(IConnectionManager))).Returns(mockConnectionManager.Object);
controller.Configuration.DependencyResolver = mockDependencyResolver.Object;
Assert.Same(context, controller.GetHubContext());
}
public class DefaultContextController : HubController<MyHub>
{
public IHubContext GetHubContext()
{
return HubContext;
}
public IConnectionManager GetConnectionManager()
{
return ConnectionManager;
}
}
public class MyHub : Hub
{
}
} | 36.738095 | 149 | 0.725859 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | test/System.Web.Http.SignalR.Test/HubControllerOfTHubTest.cs | 1,545 | C# |
using MediatorPatternExemple.Infraestrutura;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace MediatorPatternExemplo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IRepositorioCliente, RepositorioCliente>();
services.AddMediatR(typeof(Startup));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
| 32.219512 | 109 | 0.687358 | [
"MIT"
] | alexandredorea/MediatorPatternExemplo | MediatorPatternExemplo/Startup.cs | 1,323 | C# |
using Mono.Reflection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cvl.VirtualMachine.Instructions.Conditional
{
/// <summary>
/// Transfers control to a target instruction (short form) when two unsigned integer values or unordered float values are not equal.
/// https://docs.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.bne_un_s
/// </summary>
public class Bne : InstructionBase
{
public override void Wykonaj()
{
var value2 = PopObject();
var value1 = PopObject();
if (value2 != value1)
{
var op = Instruction.Operand as Instruction;
var nextOffset = op.Offset;
WykonajSkok(nextOffset);
}
else
{
WykonajNastepnaInstrukcje();
}
}
}
}
| 28.15625 | 136 | 0.580466 | [
"MIT"
] | cv-lang/virtual-machine | Cvl.VirtualMachine/Cvl.VirtualMachine.Standard/Instructions/Conditional/Bne.cs | 903 | C# |
namespace WWTWebservices
{
public partial class WWTToursDataset {
}
} | 15.6 | 42 | 0.717949 | [
"MIT"
] | Carifio24/wwt-website | src/WWTWebservices/WWTToursDataset.cs | 80 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class textAnimationController : MonoBehaviour
{
private Animator anim;
int q = 0;
public string[] texts;
public Text outText;
public float delay;
private bool isShow = false;
void Start()
{
anim = gameObject.GetComponent<Animator>();
outText.text = texts[q];
InvokeRepeating("writeText", 1f, delay);
}
void writeText(){
if(q < texts.Length){
if(isShow){
anim.Play("fadeOutTextAnimation");
}else{
outText.text = texts[q];
anim.Play("TextAnimation");
q++;
}
isShow = !isShow;
}
}
void Update()
{
if (Input.GetKeyDown("space"))
{
anim.Play("fadeOutTextAnimation");
}
}
}
| 21.369565 | 63 | 0.505595 | [
"MIT"
] | Team-on/GGJ20 | GGJ/Assets/Scripts/Video/textAnimationController.cs | 985 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using EFCoreApp.Data;
namespace EFCoreApp.Data.Migrations
{
[DbContext(typeof(EFCoreDbContext))]
[Migration("20200505225252_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.6");
modelBuilder.Entity("EFCoreApp.Model.Cliente", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Apellidos");
b.Property<string>("Direccion");
b.Property<int>("Dni");
b.Property<string>("Nombres");
b.HasKey("Id");
b.ToTable("Clientes");
});
}
}
}
| 26.538462 | 75 | 0.565217 | [
"MIT"
] | gustavogavancho/EFCoreApp | EFCoreApp.Data/Migrations/20200505225252_Init.Designer.cs | 1,037 | C# |
using Microsoft.Extensions.Configuration;
using Tests.Models;
using Tortuga.Chain;
using Tortuga.Chain.AuditRules;
using Tortuga.Chain.DataSources;
using Tortuga.Chain.SqlServer;
namespace Tests;
public abstract partial class TestBase
{
public const string EmployeeTableName = "HR.Employee";
public const string EmployeeViewName = "HR.EmployeeWithManager";
internal static readonly Dictionary<string, SqlServerDataSource> s_DataSources = new Dictionary<string, SqlServerDataSource>();
internal static SqlServerDataSource s_PrimaryDataSource;
public static string CustomerTableName { get { return "Sales.Customer"; } }
public static string EmployeeTableName_Trigger { get { return "HR.EmployeeWithTrigger"; } }
public string MultiResultSetProc1Name { get { return "Sales.CustomerWithOrdersByState"; } }
public string ScalarFunction1Name { get { return "HR.EmployeeCount"; } }
public string TableFunction1Name { get { return "Sales.CustomersByState"; } }
public string TableFunction2Name { get { return "Sales.CustomersByStateInline"; } }
public SqlServerDataSource AttachRules(SqlServerDataSource source)
{
return source.WithRules(
new DateTimeRule("CreatedDate", DateTimeKind.Local, OperationTypes.Insert),
new DateTimeRule("UpdatedDate", DateTimeKind.Local, OperationTypes.InsertOrUpdate),
new UserDataRule("CreatedByKey", "EmployeeKey", OperationTypes.Insert),
new UserDataRule("UpdatedByKey", "EmployeeKey", OperationTypes.InsertOrUpdate),
new ValidateWithValidatable(OperationTypes.InsertOrUpdate)
);
}
public SqlServerDataSource AttachSoftDeleteRulesWithUser(SqlServerDataSource source)
{
var currentUser1 = source.From(EmployeeTableName).WithLimits(1).ToObject<Employee>().Execute();
return source.WithRules(
new SoftDeleteRule("DeletedFlag", true),
new UserDataRule("DeletedByKey", "EmployeeKey", OperationTypes.Delete),
new DateTimeRule("DeletedDate", DateTimeKind.Local, OperationTypes.Delete)
).WithUser(currentUser1);
}
public SqlServerDataSource DataSource(string name, [CallerMemberName] string caller = null)
{
//WriteLine($"{caller} requested Data Source {name}");
return AttachTracers(s_DataSources[name]);
}
public SqlServerDataSourceBase DataSource(string name, DataSourceType mode, [CallerMemberName] string caller = null)
{
//WriteLine($"{caller} requested Data Source {name} with mode {mode}");
var ds = s_DataSources[name];
switch (mode)
{
case DataSourceType.Normal: return AttachTracers(ds);
case DataSourceType.Strict: return AttachTracers(ds).WithSettings(new SqlServerDataSourceSettings() { StrictMode = true });
case DataSourceType.SequentialAccess: return AttachTracers(ds).WithSettings(new SqlServerDataSourceSettings() { SequentialAccessMode = true });
case DataSourceType.Transactional: return AttachTracers(ds.BeginTransaction());
case DataSourceType.Open:
var root = (IRootDataSource)ds;
return AttachTracers((SqlServerDataSourceBase)root.CreateOpenDataSource(root.CreateConnection(), null));
}
throw new ArgumentException($"Unknown mode {mode}");
}
public async Task<SqlServerDataSourceBase> DataSourceAsync(string name, DataSourceType mode, [CallerMemberName] string caller = null)
{
//WriteLine($"{caller} requested Data Source {name} with mode {mode}");
var ds = s_DataSources[name];
switch (mode)
{
case DataSourceType.Normal: return AttachTracers(ds);
case DataSourceType.Strict: return AttachTracers(ds).WithSettings(new SqlServerDataSourceSettings() { StrictMode = true });
case DataSourceType.SequentialAccess: return AttachTracers(ds).WithSettings(new SqlServerDataSourceSettings() { SequentialAccessMode = true });
case DataSourceType.Transactional: return AttachTracers(await ds.BeginTransactionAsync());
case DataSourceType.Open:
var root = (IRootDataSource)ds;
return AttachTracers((SqlServerDataSourceBase)root.CreateOpenDataSource(await root.CreateConnectionAsync(), null));
}
throw new ArgumentException($"Unknown mode {mode}");
}
internal static void SetupTestBase()
{
if (s_PrimaryDataSource != null)
return; //run once check
var configuration = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json").Build();
foreach (var con in configuration.GetSection("ConnectionStrings").GetChildren())
{
var ds = new SqlServerDataSource(con.Key, con.Value);
s_DataSources.Add(con.Key, ds);
if (s_PrimaryDataSource == null) s_PrimaryDataSource = ds;
}
BuildEmployeeSearchKey1000(s_PrimaryDataSource);
}
void WriteDetails(ExecutionEventArgs e)
{
if (e.ExecutionDetails is SqlServerCommandExecutionToken)
{
WriteLine("");
WriteLine("Command text: ");
WriteLine(e.ExecutionDetails.CommandText);
//Indent();
foreach (var item in ((SqlServerCommandExecutionToken)e.ExecutionDetails).Parameters)
WriteLine(item.ParameterName + ": " + (item.Value == null || item.Value == DBNull.Value ? "<NULL>" : item.Value) + " [" + item.SqlDbType + "]");
//Unindent();
WriteLine("******");
WriteLine("");
}
}
}
| 40.428571 | 148 | 0.764821 | [
"MIT"
] | TortugaResearch/Chain | Tortuga.Chain/Tortuga.Chain.SqlServer.MDS.Tests/TestBase.cs | 5,094 | C# |
using System;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PSHandHistoryManager.Setup
{
public partial class ArchiveForm : HandManagerForm
{
public ArchiveForm(HandManagerForm prevForm)
{
InitializeComponent();
base.initializeHandManagerForm(prevForm);
}
private void button1_Click(object sender, EventArgs e)
{
base.showPreviousForm();
}
private void button3_Click(object sender, EventArgs e)
{
base.setConfigValue("ArchiveUnprocessedHands", "1");
string workingDir = ConfigurationManager.AppSettings["WorkingDirectory"];
string archiveDir = Directory.GetParent(workingDir) + "\\archive\\";
if(Directory.Exists(archiveDir) == false)
{
Directory.CreateDirectory(archiveDir);
}
base.setConfigValue("ArchiveHandsFolder", archiveDir);
StorageForm f = new StorageForm(this);
f.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
base.setConfigValue("ArchiveUnprocessedHands", "0");
StorageForm f = new StorageForm(this);
f.Show();
this.Hide();
}
}
}
| 30.137255 | 86 | 0.595966 | [
"MIT"
] | Husky110/PSHandHistoryManager | PSHandHistoryManager/Setup/ArchiveForm.cs | 1,539 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CarUI : MonoBehaviour
{
NewCarController newCarController;
public Text txtMode;
public Text txtVelocity;
public Text txtRPM;
public Text txtGear;
public Text txtNowDistance;
public Text txtTime;
// Start is called before the first frame update
void Start()
{
newCarController = FindObjectOfType<NewCarController>();
}
// Update is called once per frame
void Update()
{
txtMode.text = "" + newCarController.car.Mode;
txtVelocity.text = "" + (int)(newCarController.car.GetVx() * 3.6);
txtRPM.text = "" + (int)newCarController.car.OmegaE;
txtGear.text = "" + (int)newCarController.car.GearNumber;
txtNowDistance.text = "" + (int)newCarController.car.GetX();
txtTime.text = "" + (float)newCarController.car.GetTime();
}
}
| 28 | 74 | 0.665966 | [
"MIT"
] | hhj3258/GamePhysics_RealisticCarPhysics | CarSimulatorProject/Assets/Script/CarUI.cs | 952 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.