content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections.Generic;
using System.Text.Json;
namespace Localizer.Net.Json
{
public static class JsonLocaleHelpers
{
public static void FlattenObject(string pathSeparator, JsonProperty jsonProperty, Dictionary<string, string> valuePairs, string keyPrefix = "")
{
switch (jsonProperty.Value.ValueKind)
{
case JsonValueKind.String:
if (keyPrefix == "")
valuePairs[keyPrefix + jsonProperty.Name] = jsonProperty.Value.GetString();
else
valuePairs[string.Concat(keyPrefix + pathSeparator + jsonProperty.Name)] = jsonProperty.Value.GetString();
break;
case JsonValueKind.Object:
foreach (var innerProperty in jsonProperty.Value.EnumerateObject())
FlattenObject(pathSeparator, innerProperty, valuePairs, keyPrefix + jsonProperty.Name);
break;
}
}
}
}
| 34.566667 | 151 | 0.585342 | [
"MIT"
] | trinitrotoluene/Localizer.Net | src/Localizer.Net.Json/JsonLocaleHelpers.cs | 1,037 | C# |
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Common;
using mesoBoard.Data;
using Ninject;
using Ninject.Infrastructure;
namespace mesoBoard.Web.Helpers
{
public static partial class mesoBoardHtmlHelpers
{
public static IHtmlString PluginConfigValue(this HtmlHelper html, string Name)
{
var PluginConfigRep = ((IHaveKernel)html.ViewContext.RequestContext.HttpContext.ApplicationInstance).Kernel.Get<IRepository<PluginConfig>>();
return new HtmlString(PluginConfigRep.First(item => item.Name.Equals(Name)).Value);
}
public static IHtmlString GetMessages(this HtmlHelper html)
{
string output = GenerateMessage(ViewDataKeys.GlobalMessages.Success, html);
output += GenerateMessage(ViewDataKeys.GlobalMessages.Notice, html);
output += GenerateMessage(ViewDataKeys.GlobalMessages.Error, html);
return new HtmlString(output);
}
private static string GenerateMessage(string messageType, HtmlHelper html)
{
string message = (string)html.ViewContext.TempData[messageType] ?? (string)html.ViewData[messageType] ?? string.Empty;
if (string.IsNullOrWhiteSpace(message))
return string.Empty;
string cssClass = string.Empty;
if (messageType == ViewDataKeys.GlobalMessages.Error)
cssClass = "error";
else if (messageType == ViewDataKeys.GlobalMessages.Notice)
cssClass = "notice";
else if (messageType == ViewDataKeys.GlobalMessages.Success)
cssClass = "success";
TagBuilder tag = new TagBuilder("div");
tag.AddCssClass(cssClass);
tag.AddCssClass("global_message");
tag.InnerHtml = message;
return tag.ToString();
}
public static IHtmlString PageTitle(this HtmlHelper html)
{
var ConfigRep = ((IHaveKernel)html.ViewContext.RequestContext.HttpContext.ApplicationInstance).Kernel.Get<IRepository<Config>>();
string breadCrumb = html.ViewData[ViewDataKeys.BreadCrumb] as string;
if (!string.IsNullOrWhiteSpace(breadCrumb))
{
string TheCrumb = html.ViewData[ViewDataKeys.BreadCrumb].ToString();
string[] seperators = { " | " };
string[] Split = TheCrumb.Split(seperators, StringSplitOptions.RemoveEmptyEntries);
return new HtmlString(Split.Last() + ConfigRep.First(item => item.Name.Equals("PageTitlePhrase")).Value);
}
else
{
Config boardName = ConfigRep.First(item => item.Name.Equals("BoardName"));
Config titlePhrase = ConfigRep.First(item => item.Name.Equals("PageTitlePhrase"));
return new HtmlString(string.Format("{0} {1}", boardName.Value, titlePhrase.Value));
}
}
}
} | 41.410959 | 153 | 0.63083 | [
"BSD-3-Clause"
] | craigmoliver/mesoBoard | mesoBoard.Web.Helpers/HtmlHelpers/Messages.cs | 3,025 | 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 lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Container for the parameters to the GetDisk operation.
/// Returns information about a specific block storage disk.
/// </summary>
public partial class GetDiskRequest : AmazonLightsailRequest
{
private string _diskName;
/// <summary>
/// Gets and sets the property DiskName.
/// <para>
/// The name of the disk (e.g., <code>my-disk</code>).
/// </para>
/// </summary>
public string DiskName
{
get { return this._diskName; }
set { this._diskName = value; }
}
// Check to see if DiskName property is set
internal bool IsSetDiskName()
{
return this._diskName != null;
}
}
} | 29.438596 | 107 | 0.651371 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/GetDiskRequest.cs | 1,678 | C# |
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using ksqlDB.Api.Client.Samples.Models.Sensors;
using ksqlDB.RestApi.Client.KSql.Linq.PullQueries;
using ksqlDB.RestApi.Client.KSql.Linq.Statements;
using ksqlDB.RestApi.Client.KSql.Query.Context;
using ksqlDB.RestApi.Client.KSql.Query.Context.Options;
using ksqlDB.RestApi.Client.KSql.Query.Functions;
using ksqlDB.RestApi.Client.KSql.Query.Windows;
using ksqlDB.RestApi.Client.KSql.RestApi;
using ksqlDB.RestApi.Client.KSql.RestApi.Http;
using ksqlDB.RestApi.Client.KSql.RestApi.Statements;
namespace ksqlDB.Api.Client.Samples.PullQuery
{
public class PullQueryExample
{
IKSqlDbRestApiClient restApiClient;
public async Task ExecuteAsync()
{
string ksqlDbUrl = @"http:\\localhost:8088";
var contextOptions = new KSqlDbContextOptionsBuilder()
.UseKSqlDb(ksqlDbUrl)
.SetBasicAuthCredentials("fred", "letmein")
.Options;
await using var context = new KSqlDBContext(contextOptions);
var httpClientFactory = new HttpClientFactory(new Uri(ksqlDbUrl));
restApiClient = new KSqlDbRestApiClient(httpClientFactory)
.SetCredentials(new BasicAuthCredentials("fred", "letmein"));
await CreateOrReplaceStreamAsync();
var statement = context.CreateTableStatement(MaterializedViewName)
.As<IoTSensor>("sensor_values")
.GroupBy(c => c.SensorId)
.WindowedBy(new TimeWindows(Duration.OfSeconds(5)).WithGracePeriod(Duration.OfHours(2)))
.Select(c => new { SensorId = c.Key, AvgValue = c.Avg(g => g.Value) });
var query = statement.ToStatementString();
var response = await statement.ExecuteStatementAsync();
response = await InsertAsync(new IoTSensor { SensorId = "sensor-1", Value = 11 });
await PullSensor(context);
}
private static async Task PullSensor(KSqlDBContext context)
{
string windowStart = "2019-10-03T21:31:16";
string windowEnd = "2025-10-03T21:31:16";
var pullQuery = context.CreatePullQuery<IoTSensorStats>(MaterializedViewName)
.Where(c => c.SensorId == "sensor-1")
.Where(c => Bounds.WindowStart > windowStart && Bounds.WindowEnd <= windowEnd);
var sql = pullQuery.ToQueryString();
await foreach(var item in pullQuery.GetManyAsync().OrderBy(c => c.SensorId).ConfigureAwait(false))
Console.WriteLine($"Pull query - GetMany result => Id: {item?.SensorId} - Avg Value: {item?.AvgValue} - Window Start {item?.WindowStart}");
var list = await pullQuery.GetManyAsync().OrderBy(c => c.SensorId).ToListAsync();
string ksql = "SELECT * FROM avg_sensor_values WHERE SensorId = 'sensor-1';";
var result2 = await context.ExecutePullQuery<IoTSensorStats>(ksql);
}
private static async Task GetAsync(IPullable<IoTSensorStats> pullQuery)
{
var result = await pullQuery
.FirstOrDefaultAsync();
Console.WriteLine(
$"Pull query GetAsync result => Id: {result?.SensorId} - Avg Value: {result?.AvgValue} - Window Start {result?.WindowStart}");
Console.WriteLine();
}
const string MaterializedViewName = "avg_sensor_values";
async Task<HttpResponseMessage> CreateOrReplaceStreamAsync()
{
const string createOrReplaceStream =
@"CREATE STREAM sensor_values (
SensorId VARCHAR KEY,
Value INT
) WITH (
kafka_topic = 'sensor_values',
partitions = 2,
value_format = 'json'
);";
return await ExecuteAsync(createOrReplaceStream);
}
async Task<HttpResponseMessage> InsertAsync(IoTSensor sensor)
{
string insert =
$"INSERT INTO sensor_values (SensorId, Value) VALUES ('{sensor.SensorId}', {sensor.Value});";
return await ExecuteAsync(insert);
}
async Task<HttpResponseMessage> ExecuteAsync(string statement)
{
KSqlDbStatement ksqlDbStatement = new(statement);
var httpResponseMessage = await restApiClient.ExecuteStatementAsync(ksqlDbStatement)
.ConfigureAwait(false);
string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
return httpResponseMessage;
}
}
} | 34.073171 | 147 | 0.704844 | [
"MIT"
] | tomasfabian/Kafka.DotNet.ksqlDB | Samples/ksqlDB.RestApi.Client.Sample/PullQuery/PullQueryExample.cs | 4,193 | C# |
using hass_workstation_service.Domain.Sensors;
using System;
namespace hass_workstation_service.Data
{
public class ConfiguredCommand
{
public string Type { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public string Command { get; set; }
public byte KeyCode { get; set; }
}
} | 25.5 | 46 | 0.638655 | [
"Apache-2.0"
] | AdamCLarsen/hass-workstation-service | hass-workstation-service/Data/ConfiguredCommand.cs | 357 | C# |
#region Header
//
// Copyright 2003-2018 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#endregion // Header
using System;
namespace RevitLookup.Snoop.Data
{
/// <summary>
/// Snoop.Data class to hold and format a Exception value.
/// </summary>
public class Exception : Data
{
protected System.Exception m_val;
public Exception(string label, System.Exception val)
: base(label)
{
m_val = val;
}
public override string StrValue()
{
return m_val.Message;
}
public override bool IsError
{
get { return true; }
}
}
}
| 29.792453 | 73 | 0.664345 | [
"MIT"
] | OpenAIM/OpenRFA-RevitLookup | CS/Snoop/Data/Exception.cs | 1,579 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.235
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebExample.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WebExample.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Reason PersonalThanks
///"Had a big impact on refining the SPARCet app.
///- Was instrumental in producing many of the pre-prod refinements that are key in a software release.
///- Played a key role in usability testing.
///- Owned several features (including feedback system)." I really have appreciated all of the brainstorming, push for excellence, encouragement, and hard work. It's been great having you on-board.
///Eric helped with the funding of the server for SPARCet! Eric, thank you so much for your help with [rest of string was truncated]";.
/// </summary>
internal static string TagCloudInput {
get {
return ResourceManager.GetString("TagCloudInput", resourceCulture);
}
}
}
}
| 47.153846 | 216 | 0.621533 | [
"Unlicense",
"MIT"
] | chrisdavies/Sparc.TagCloud | Examples/WebExample/Properties/Resources.Designer.cs | 3,680 | C# |
namespace Be.Stateless.BizTalk.Schemas.Sql.Procedures.Batch {
using Microsoft.XLANGs.BaseTypes;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.BizTalk.Schema.Compiler", "3.0.1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[SchemaType(SchemaTypeEnum.Document)]
[Schema(@"http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo",@"usp_batch_QueueControlledRelease")]
[System.SerializableAttribute()]
[SchemaRoots(new string[] {@"usp_batch_QueueControlledRelease"})]
public sealed class QueueControlledRelease : Microsoft.XLANGs.BaseTypes.SchemaBase {
[System.NonSerializedAttribute()]
private static object _rawSchema;
[System.NonSerializedAttribute()]
private const string _strSchema = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" elementFormDefault=""qualified"" targetNamespace=""http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo"" version=""1.0"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:annotation>
<xs:documentation><![CDATA[
Copyright © 2012 - 2021 François Chabot
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.
]]></xs:documentation>
<xs:appinfo>
<fileNameHint xmlns=""http://schemas.microsoft.com/servicemodel/adapters/metadata/xsd"">QueueControlledRelease</fileNameHint>
</xs:appinfo>
</xs:annotation>
<xs:element name=""usp_batch_QueueControlledRelease"">
<xs:annotation>
<xs:documentation>
<doc:action xmlns:doc=""http://schemas.microsoft.com/servicemodel/adapters/metadata/documentation"">XmlProcedure/dbo/usp_batch_QueueControlledRelease</doc:action>
</xs:documentation>
<xs:appinfo>
<b:recordInfo rootTypeName=""Request"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" />
</xs:appinfo>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""envelopeSpecName"" nillable=""true"">
<xs:simpleType>
<xs:restriction base=""xs:string"">
<xs:maxLength value=""256"" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""environmentTag"" nillable=""true"">
<xs:simpleType>
<xs:restriction base=""xs:string"">
<xs:maxLength value=""256"" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""partition"" nillable=""true"">
<xs:simpleType>
<xs:restriction base=""xs:string"">
<xs:maxLength value=""128"" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""processActivityId"">
<xs:simpleType>
<xs:restriction base=""xs:string"">
<xs:length value=""32"" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
public QueueControlledRelease() {
}
public override string XmlContent {
get {
return _strSchema;
}
}
public override string[] RootNodes {
get {
string[] _RootElements = new string [1];
_RootElements[0] = "usp_batch_QueueControlledRelease";
return _RootElements;
}
}
protected override object RawSchema {
get {
return _rawSchema;
}
set {
_rawSchema = value;
}
}
}
}
| 39.612613 | 241 | 0.622015 | [
"Apache-2.0"
] | emmanuelbenitez/Be.Stateless.BizTalk.Factory.Batching.Application | src/Be.Stateless.BizTalk.Batching.Schemas/Schemas/Sql/Procedures/Batch/QueueControlledRelease.xsd.cs | 4,399 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pattern.Adapter
{
interface IAdvancedMediaPlayer
{
void PlayVlc(string fileName);
void PlayMp4(string fileName);
}
}
| 18.2 | 38 | 0.721612 | [
"MIT"
] | PUPA42/Pattern | Pattern/Adapter/IAdvancedMediaPlayer.cs | 275 | C# |
namespace MGU.Core.Tests.Extensions
{
using Core.Extensions.Is;
using Xunit;
public class IsExtensionsTests
{
[Fact]
public void Should_Return_True_When_Source_And_Other_Are_Equal()
{
var source = new object();
var other = source;
Assert.True(source.Is(other));
Assert.True(5.Is(5));
}
[Fact]
public void Should_Return_False_When_Source_And_Other_Are_Not_Equal()
{
var source = new object();
var other = new object();
Assert.False(source.Is(other));
Assert.False(5.Is(42));
}
}
} | 23.714286 | 77 | 0.552711 | [
"MIT"
] | mrGarvin90/MGU | MGU/Tests/MGU.Core.Tests/Extensions/IsExtensionsTests.cs | 666 | 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("CircleAreaAndPer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("CircleAreaAndPer")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2019")]
[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("39286b7b-a25e-49c7-b769-df1edc40eaf2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.216216 | 84 | 0.748939 | [
"MIT"
] | Martin-Stamenkov/Csharp-SoftUni | Programmig Basics/Simple Calculations/CircleAreaAndPer/Properties/AssemblyInfo.cs | 1,417 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190801
{
/// <summary>
/// FirewallPolicy Resource.
/// </summary>
public partial class FirewallPolicy : Pulumi.CustomResource
{
/// <summary>
/// The parent firewall policy from which rules are inherited.
/// </summary>
[Output("basePolicy")]
public Output<Outputs.SubResourceResponse?> BasePolicy { get; private set; } = null!;
/// <summary>
/// List of references to Child Firewall Policies.
/// </summary>
[Output("childPolicies")]
public Output<ImmutableArray<Outputs.SubResourceResponse>> ChildPolicies { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// List of references to Azure Firewalls that this Firewall Policy is associated with.
/// </summary>
[Output("firewalls")]
public Output<ImmutableArray<Outputs.SubResourceResponse>> Firewalls { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the firewall policy resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// List of references to FirewallPolicyRuleGroups.
/// </summary>
[Output("ruleGroups")]
public Output<ImmutableArray<Outputs.SubResourceResponse>> RuleGroups { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The operation mode for Threat Intelligence.
/// </summary>
[Output("threatIntelMode")]
public Output<string?> ThreatIntelMode { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a FirewallPolicy resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public FirewallPolicy(string name, FirewallPolicyArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190801:FirewallPolicy", name, args ?? new FirewallPolicyArgs(), MakeResourceOptions(options, ""))
{
}
private FirewallPolicy(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190801:FirewallPolicy", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/latest:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:FirewallPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:FirewallPolicy"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing FirewallPolicy resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static FirewallPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new FirewallPolicy(name, id, options);
}
}
public sealed class FirewallPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The parent firewall policy from which rules are inherited.
/// </summary>
[Input("basePolicy")]
public Input<Inputs.SubResourceArgs>? BasePolicy { get; set; }
/// <summary>
/// The name of the Firewall Policy.
/// </summary>
[Input("firewallPolicyName", required: true)]
public Input<string> FirewallPolicyName { get; set; } = null!;
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// The operation mode for Threat Intelligence.
/// </summary>
[Input("threatIntelMode")]
public Input<string>? ThreatIntelMode { get; set; }
public FirewallPolicyArgs()
{
}
}
}
| 39.405128 | 142 | 0.585632 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20190801/FirewallPolicy.cs | 7,684 | C# |
// <auto-generated />
using System;
using ArvidsonFoto.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ArvidsonFoto.Migrations
{
[DbContext(typeof(ArvidsonFotoDbContext))]
[Migration("20210208214305_SkapatTabeller")]
partial class SkapatTabeller
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:Collation", "Finnish_Swedish_CI_AS")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.2");
modelBuilder.Entity("ArvidsonFoto.Models.TblGb", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID")
.UseIdentityColumn();
b.Property<DateTime?>("GbDate")
.HasColumnType("smalldatetime")
.HasColumnName("GB_date");
b.Property<string>("GbEmail")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)")
.HasColumnName("GB_email");
b.Property<string>("GbHomepage")
.HasMaxLength(255)
.HasColumnType("nvarchar(255)")
.HasColumnName("GB_homepage");
b.Property<int>("GbId")
.HasColumnType("int")
.HasColumnName("GB_ID");
b.Property<string>("GbIp")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("GB_IP");
b.Property<string>("GbName")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)")
.HasColumnName("GB_name");
b.Property<bool?>("GbReadPost")
.HasColumnType("bit")
.HasColumnName("GB_ReadPost");
b.Property<string>("GbText")
.HasColumnType("nvarchar(max)")
.HasColumnName("GB_text");
b.HasKey("Id");
b.ToTable("tbl_gb");
});
modelBuilder.Entity("ArvidsonFoto.Models.TblImage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID")
.UseIdentityColumn();
b.Property<int>("ImageArt")
.HasColumnType("int")
.HasColumnName("image_art");
b.Property<DateTime?>("ImageDate")
.HasColumnType("smalldatetime")
.HasColumnName("image_date");
b.Property<string>("ImageDescription")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)")
.HasColumnName("image_description");
b.Property<int?>("ImageFamilj")
.HasColumnType("int")
.HasColumnName("image_familj");
b.Property<int?>("ImageHuvudfamilj")
.HasColumnType("int")
.HasColumnName("image_huvudfamilj");
b.Property<int>("ImageId")
.HasColumnType("int")
.HasColumnName("image_ID");
b.Property<DateTime>("ImageUpdate")
.HasColumnType("datetime")
.HasColumnName("image_update");
b.Property<string>("ImageUrl")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("image_URL");
b.HasKey("Id");
b.ToTable("tbl_images");
});
modelBuilder.Entity("ArvidsonFoto.Models.TblMenu", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID")
.UseIdentityColumn();
b.Property<int>("MenuId")
.HasColumnType("int")
.HasColumnName("menu_ID");
b.Property<DateTime?>("MenuLastshowdate")
.HasColumnType("datetime")
.HasColumnName("menu_lastshowdate");
b.Property<int?>("MenuMainId")
.HasColumnType("int")
.HasColumnName("menu_mainID");
b.Property<int?>("MenuPagecounter")
.HasColumnType("int")
.HasColumnName("menu_pagecounter");
b.Property<string>("MenuText")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("menu_text");
b.Property<string>("MenuUrltext")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("menu_URLtext");
b.HasKey("Id");
b.ToTable("tbl_menu");
});
modelBuilder.Entity("ArvidsonFoto.Models.TblPageCounter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("PageCounter_ID")
.UseIdentityColumn();
b.Property<DateTime>("LastShowDate")
.HasColumnType("datetime")
.HasColumnName("PageCounter_LastShowDate");
b.Property<string>("MonthViewed")
.HasMaxLength(20)
.HasColumnType("nvarchar(20)")
.HasColumnName("PageCounter_MonthViewed");
b.Property<string>("PageName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("PageCounter_Name");
b.Property<int>("PageViews")
.HasColumnType("int")
.HasColumnName("PageCounter_Views");
b.HasKey("Id");
b.ToTable("tbl_PageCounter");
});
#pragma warning restore 612, 618
}
}
}
| 37.056701 | 79 | 0.449158 | [
"MIT"
] | pownas/ArvidsonFoto-MVC-NET5 | ArvidsonFoto/Migrations/20210208214305_SkapatTabeller.Designer.cs | 7,191 | C# |
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Test
{
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public enum TestEnum
{
EnumVal1,
EnumVal2,
EnumVal3,
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public partial class Simple
{
[global::Bond.Id(0)]
public int someInt;
[global::Bond.Id(1)]
public int anotherInt;
[global::Bond.Id(2), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string someString = "";
public Simple(
int someInt,
int anotherInt,
string someString)
{
this.someInt = someInt;
this.anotherInt = anotherInt;
this.someString = someString;
}
public Simple()
{
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public partial class Foo
{
[global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string someText = "BaseText1";
public Foo(
string someText)
{
this.someText = someText;
}
public Foo()
{
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public partial class Bar
: Foo
{
[global::Bond.Id(0)]
public TestEnum testEnum = TestEnum.Val2;
[global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
new public string someText = "DerivedText1";
[global::Bond.Id(2)]
public int someInt;
[global::Bond.Id(3), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string moreText = "";
[global::Bond.Id(4), global::Bond.Type(typeof(List<Simple>))]
public IList<Simple> someList = new List<Simple>();
[global::Bond.Id(5), global::Bond.Type(typeof(Dictionary<global::Bond.Tag.wstring, double>))]
public IDictionary<string, double> someMap = new Dictionary<string, double>();
[global::Bond.Id(6), global::Bond.Type(typeof(HashSet<global::Bond.Tag.wstring>))]
public ISet<string> someSet = new HashSet<string>();
public Bar(
// Base class parameters
string someText,
// This class parameters
TestEnum testEnum,
string someText0,
int someInt,
string moreText,
IList<Simple> someList,
IDictionary<string, double> someMap,
ISet<string> someSet
) : base(
someText)
{
this.testEnum = testEnum;
this.someText = someText0;
this.someInt = someInt;
this.moreText = moreText;
this.someList = someList;
this.someMap = someMap;
this.someSet = someSet;
}
public Bar()
{
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public partial class Baz
: Bar
{
[global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
new public string someText = "";
[global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string evenMoreText = "";
[global::Bond.Id(2), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string someText1 = "";
public Baz(
// Base class parameters
string someText,
TestEnum testEnum,
string someText0,
int someInt,
string moreText,
IList<Simple> someList,
IDictionary<string, double> someMap,
ISet<string> someSet,
// This class parameters
string someText1,
string evenMoreText,
string someText10
) : base(
someText,
testEnum,
someText0,
someInt,
moreText,
someList,
someMap,
someSet)
{
this.someText = someText1;
this.evenMoreText = evenMoreText;
this.someText1 = someText10;
}
public Baz()
{
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.3")]
public partial class DerivedEmpty
: Foo
{
public DerivedEmpty(
// Base class parameters
string someText
) : base(
someText)
{
}
public DerivedEmpty()
{
}
}
} // Test
| 25.77451 | 101 | 0.54108 | [
"MIT"
] | YanlongLi/bond | compiler/tests/generated/constructor-parameters_fields/collection-interfaces/complex_inheritance_types.cs | 5,258 | C# |
/*
Copyright 2019 James Craig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using BigBook;
using Enlighten.SentenceDetection;
using Enlighten.Tokenizer.Enums;
using Enlighten.Tokenizer.Interfaces;
using Enlighten.Tokenizer.Utils;
using Microsoft.Extensions.ObjectPool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Enlighten.Tokenizer
{
/// <summary>
/// Default tokenizer
/// </summary>
/// <seealso cref="ITokenizer"/>
public class DefaultTokenizer : ITokenizer
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTokenizer"/> class.
/// </summary>
/// <param name="languages">The languages.</param>
/// <param name="objectPool">The object pool.</param>
public DefaultTokenizer(IEnumerable<ITokenizerLanguage> languages, ObjectPool<StringBuilder> objectPool)
{
Languages = languages.Where(x => x.GetType().Assembly != typeof(DefaultTokenizer).Assembly).ToDictionary(x => x.ISOCode);
foreach (var Language in languages.Where(x => x.GetType().Assembly == typeof(DefaultTokenizer).Assembly
&& !Languages.ContainsKey(x.ISOCode)))
{
Languages.Add(Language.ISOCode, Language);
}
ObjectPool = objectPool;
}
/// <summary>
/// Gets the languages.
/// </summary>
/// <value>The languages.</value>
public Dictionary<string, ITokenizerLanguage> Languages { get; }
/// <summary>
/// Gets the object pool.
/// </summary>
/// <value>The object pool.</value>
private ObjectPool<StringBuilder> ObjectPool { get; }
/// <summary>
/// Detokenizes the specified tokens.
/// </summary>
/// <param name="tokens">The tokens.</param>
/// <param name="language">The language.</param>
/// <returns>The resulting text.</returns>
public string Detokenize(Token[] tokens, TokenizerLanguage language)
{
if (!Languages.TryGetValue(language, out var Tokenizer) || tokens is null || tokens.Length == 0)
return string.Empty;
return Tokenizer.Detokenize(tokens);
}
/// <summary>
/// Detokenizes the specified sentences.
/// </summary>
/// <param name="sentences">The sentences.</param>
/// <param name="language">The language.</param>
/// <returns>The resulting text.</returns>
public string Detokenize(Sentence[] sentences, TokenizerLanguage language)
{
if (!Languages.TryGetValue(language, out var Tokenizer) || sentences is null || sentences.Length == 0)
return string.Empty;
var Builder = ObjectPool.Get();
Builder.Append(Tokenizer.Detokenize(sentences[0].Tokens));
for (int x = 1; x < sentences.Length; ++x)
{
Builder.Append(" ").Append(Tokenizer.Detokenize(sentences[x].Tokens));
}
var ReturnValue = Builder.ToString();
ObjectPool.Return(Builder);
return ReturnValue;
}
/// <summary>
/// Tokenizes the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="language">The language.</param>
/// <returns>The tokens found.</returns>
public Token[] Tokenize(string text, TokenizerLanguage language)
{
if (!Languages.TryGetValue(language, out var Tokenizer))
return Array.Empty<Token>();
var Stream = new TokenizableStream<char>(text?.ToCharArray() ?? Array.Empty<char>());
return Tokenizer.Tokenize(Stream);
}
}
} | 39.267857 | 134 | 0.602092 | [
"Apache-2.0"
] | JaCraig/Enlighten | Enlighten/Tokenizer/DefaultTokenizer.cs | 4,400 | C# |
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Elsa.Activities.Http.Services;
namespace Elsa.Activities.Http.Parsers
{
public class DefaultHttpResponseBodyParser : IHttpResponseBodyParser
{
public int Priority => -1;
public IEnumerable<string?> SupportedContentTypes => new[] { "", default };
public async Task<object> ParseAsync(HttpResponseMessage response, CancellationToken cancellationToken) => await response.Content.ReadAsStringAsync();
}
} | 37 | 158 | 0.758559 | [
"BSD-3-Clause"
] | JohnZhaoXiaoHu/elsa-core | src/activities/Elsa.Activities.Http/Parsers/DefaultHttpResponseBodyParser.cs | 557 | C# |
using System;
namespace Stylet.Logging
{
/// <summary>
/// Logger used by Stylet for internal logging
/// </summary>
public interface ILogger
{
/// <summary>
/// Log the message as info
/// </summary>
/// <param name="format">A formatted message</param>
/// <param name="args">format parameters</param>
void Info(string format, params object[] args);
/// <summary>
/// Log the message as a warning
/// </summary>
/// <param name="format">A formatted message</param>
/// <param name="args">format parameters</param>
void Warn(string format, params object[] args);
/// <summary>
/// Log an exception as an error
/// </summary>
/// <param name="exception">Exception to log</param>
/// <param name="message">Additional message to add to the exception</param>
void Error(Exception exception, string message = null);
}
}
| 31.8125 | 85 | 0.554028 | [
"MIT"
] | DotNetUz/Stylet | Stylet/Logging/ILogger.cs | 989 | C# |
// Copyright 2004-2017 Castle Project - http://www.castleproject.org/
//
// 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 Castle.Windsor
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.MicroKernel.SubSystems.Resource;
using Castle.Windsor.Configuration;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Windsor.Diagnostics;
using Castle.Windsor.Installer;
using Castle.Windsor.Proxy;
/// <summary>
/// Implementation of <see cref = "IWindsorContainer" />
/// which delegates to <see cref = "IKernel" /> implementation.
/// </summary>
[Serializable]
[DebuggerDisplay("{name,nq}")]
[DebuggerTypeProxy(typeof(KernelDebuggerProxy))]
public partial class WindsorContainer :
#if FEATURE_REMOTING
MarshalByRefObject,
#endif
IWindsorContainer
{
private const string CastleUnicode = "\uD83C\uDFF0";
private static int instanceCount = 0;
private readonly IKernel kernel;
private readonly string name;
private readonly IComponentsInstaller installer;
private IWindsorContainer parent;
private readonly Dictionary<string, IWindsorContainer> childContainers = new Dictionary<string, IWindsorContainer>(StringComparer.OrdinalIgnoreCase);
private readonly object childContainersLocker = new object();
/// <summary>
/// Constructs a container without any external
/// configuration reference
/// </summary>
public WindsorContainer() : this(new DefaultKernel(), new DefaultComponentInstaller())
{
}
/// <summary>
/// Constructs a container using the specified
/// <see cref = "IConfigurationStore" /> implementation.
/// </summary>
/// <param name = "store">The instance of an <see cref = "IConfigurationStore" /> implementation.</param>
public WindsorContainer(IConfigurationStore store) : this()
{
kernel.ConfigurationStore = store;
RunInstaller();
}
/// <summary>
/// Constructs a container using the specified
/// <see cref = "IConfigurationInterpreter" /> implementation.
/// </summary>
/// <param name = "interpreter">The instance of an <see cref = "IConfigurationInterpreter" /> implementation.</param>
public WindsorContainer(IConfigurationInterpreter interpreter) : this()
{
if (interpreter == null)
{
throw new ArgumentNullException("interpreter");
}
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore, kernel);
RunInstaller();
}
/// <summary>
/// Initializes a new instance of the <see cref = "WindsorContainer" /> class.
/// </summary>
/// <param name = "interpreter">The interpreter.</param>
/// <param name = "environmentInfo">The environment info.</param>
public WindsorContainer(IConfigurationInterpreter interpreter, IEnvironmentInfo environmentInfo) : this()
{
if (interpreter == null)
{
throw new ArgumentNullException("interpreter");
}
if (environmentInfo == null)
{
throw new ArgumentNullException("environmentInfo");
}
interpreter.EnvironmentName = environmentInfo.GetEnvironmentName();
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore, kernel);
RunInstaller();
}
/// <summary>
/// Initializes a new instance of the <see cref = "WindsorContainer" /> class using a
/// resource pointed to by the parameter. That may be a file, an assembly embedded resource, a UNC path or a config file section.
/// <para>
/// Equivalent to the use of <c>new WindsorContainer(new XmlInterpreter(configurationUri))</c>
/// </para>
/// </summary>
/// <param name = "configurationUri">The XML file.</param>
public WindsorContainer(String configurationUri) : this()
{
if (configurationUri == null)
{
throw new ArgumentNullException("configurationUri");
}
var interpreter = GetInterpreter(configurationUri);
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore, kernel);
RunInstaller();
}
/// <summary>
/// Constructs a container using the specified <see cref = "IKernel" />
/// implementation. Rarely used.
/// </summary>
/// <remarks>
/// This constructs sets the Kernel.ProxyFactory property to
/// <c>Proxy.DefaultProxyFactory</c>
/// </remarks>
/// <param name = "kernel">Kernel instance</param>
/// <param name = "installer">Installer instance</param>
public WindsorContainer(IKernel kernel, IComponentsInstaller installer) : this(MakeUniqueName(), kernel, installer)
{
}
/// <summary>
/// Constructs a container using the specified <see cref = "IKernel" />
/// implementation. Rarely used.
/// </summary>
/// <remarks>
/// This constructs sets the Kernel.ProxyFactory property to
/// <c>Proxy.DefaultProxyFactory</c>
/// </remarks>
/// <param name = "name">Container's name</param>
/// <param name = "kernel">Kernel instance</param>
/// <param name = "installer">Installer instance</param>
public WindsorContainer(String name, IKernel kernel, IComponentsInstaller installer)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (kernel == null)
{
throw new ArgumentNullException("kernel");
}
if (installer == null)
{
throw new ArgumentNullException("installer");
}
this.name = name;
this.kernel = kernel;
this.kernel.ProxyFactory = new DefaultProxyFactory();
this.installer = installer;
}
/// <summary>
/// Constructs with a given <see cref = "IProxyFactory" />.
/// </summary>
/// <param name = "proxyFactory">A instance of an <see cref = "IProxyFactory" />.</param>
public WindsorContainer(IProxyFactory proxyFactory)
{
if (proxyFactory == null)
{
throw new ArgumentNullException("proxyFactory");
}
kernel = new DefaultKernel(proxyFactory);
installer = new DefaultComponentInstaller();
}
/// <summary>
/// Constructs a container assigning a parent container
/// before starting the dependency resolution.
/// </summary>
/// <param name = "parent">The instance of an <see cref = "IWindsorContainer" /></param>
/// <param name = "interpreter">The instance of an <see cref = "IConfigurationInterpreter" /> implementation</param>
public WindsorContainer(IWindsorContainer parent, IConfigurationInterpreter interpreter) : this()
{
if (parent == null)
{
throw new ArgumentNullException("parent");
}
if (interpreter == null)
{
throw new ArgumentNullException("interpreter");
}
parent.AddChildContainer(this);
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore, kernel);
RunInstaller();
}
/// <summary>
/// Initializes a new instance of the <see cref = "WindsorContainer" /> class.
/// </summary>
/// <param name = "name">The container's name.</param>
/// <param name = "parent">The parent.</param>
/// <param name = "interpreter">The interpreter.</param>
public WindsorContainer(string name, IWindsorContainer parent, IConfigurationInterpreter interpreter) : this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (parent == null)
{
throw new ArgumentNullException("parent");
}
if (interpreter == null)
{
throw new ArgumentNullException("interpreter");
}
this.name = name;
parent.AddChildContainer(this);
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore, kernel);
RunInstaller();
}
public IComponentsInstaller Installer
{
get { return installer; }
}
/// <summary>
/// Returns the inner instance of the MicroKernel
/// </summary>
public virtual IKernel Kernel
{
get { return kernel; }
}
/// <summary>
/// Gets the container's name
/// </summary>
/// <remarks>
/// Only useful when child containers are being used
/// </remarks>
/// <value>The container's name.</value>
public string Name
{
get { return name; }
}
/// <summary>
/// Gets or sets the parent container if this instance
/// is a sub container.
/// </summary>
public virtual IWindsorContainer Parent
{
get { return parent; }
set
{
if (value == null)
{
if (parent != null)
{
parent.RemoveChildContainer(this);
parent = null;
}
}
else
{
if (value != parent)
{
parent = value;
parent.AddChildContainer(this);
}
}
}
}
protected virtual void RunInstaller()
{
if (installer != null)
{
installer.SetUp(this, kernel.ConfigurationStore);
}
}
private void Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope)
{
using (var store = new PartialConfigurationStore((IKernelInternal)kernel))
{
foreach (var windsorInstaller in installers)
{
windsorInstaller.Install(this, store);
}
scope.SetUp(this, store);
}
}
/// <summary>
/// Executes Dispose on underlying <see cref = "IKernel" />
/// </summary>
public virtual void Dispose()
{
Parent = null;
childContainers.Clear();
kernel.Dispose();
}
/// <summary>
/// Registers a subcontainer. The components exposed
/// by this container will be accessible from subcontainers.
/// </summary>
/// <param name = "childContainer"></param>
public virtual void AddChildContainer(IWindsorContainer childContainer)
{
if (childContainer == null)
{
throw new ArgumentNullException("childContainer");
}
if (!childContainers.ContainsKey(childContainer.Name))
{
lock (childContainersLocker)
{
if (!childContainers.ContainsKey(childContainer.Name))
{
kernel.AddChildKernel(childContainer.Kernel);
childContainers.Add(childContainer.Name, childContainer);
childContainer.Parent = this;
}
}
}
}
/// <summary>
/// Registers a facility within the container.
/// </summary>
/// <param name = "facility"></param>
public IWindsorContainer AddFacility(IFacility facility)
{
kernel.AddFacility(facility);
return this;
}
/// <summary>
/// Creates and adds an <see cref = "IFacility" /> facility to the container.
/// </summary>
/// <typeparam name = "T">The facility type.</typeparam>
/// <returns></returns>
public IWindsorContainer AddFacility<T>() where T : IFacility, new()
{
kernel.AddFacility<T>();
return this;
}
/// <summary>
/// Creates and adds an <see cref = "IFacility" /> facility to the container.
/// </summary>
/// <typeparam name = "T">The facility type.</typeparam>
/// <param name = "onCreate">The callback for creation.</param>
/// <returns></returns>
public IWindsorContainer AddFacility<T>(Action<T> onCreate)
where T : IFacility, new()
{
kernel.AddFacility(onCreate);
return this;
}
/// <summary>
/// Gets a child container instance by name.
/// </summary>
/// <param name = "name">The container's name.</param>
/// <returns>The child container instance or null</returns>
public IWindsorContainer GetChildContainer(string name)
{
lock (childContainersLocker)
{
IWindsorContainer windsorContainer;
childContainers.TryGetValue(name, out windsorContainer);
return windsorContainer;
}
}
/// <summary>
/// Runs the <paramref name = "installers" /> so that they can register components in the container. For details see the documentation at http://j.mp/WindsorInstall
/// </summary>
/// <remarks>
/// In addition to instantiating and passing every installer inline you can use helper methods on <see
/// cref = "FromAssembly" /> class to automatically instantiate and run your installers.
/// You can also use <see cref = "Configuration" /> class to install components and/or run aditional installers specofied in a configuration file.
/// </remarks>
/// <returns>The container.</returns>
/// <example>
/// <code>
/// container.Install(new YourInstaller1(), new YourInstaller2(), new YourInstaller3());
/// </code>
/// </example>
/// <example>
/// <code>
/// container.Install(FromAssembly.This(), Configuration.FromAppConfig(), new SomeOtherInstaller());
/// </code>
/// </example>
public IWindsorContainer Install(params IWindsorInstaller[] installers)
{
if (installers == null)
{
throw new ArgumentNullException("installers");
}
if (installers.Length == 0)
{
return this;
}
var scope = new DefaultComponentInstaller();
var internalKernel = kernel as IKernelInternal;
if (internalKernel == null)
{
Install(installers, scope);
}
else
{
var token = internalKernel.OptimizeDependencyResolution();
Install(installers, scope);
if (token != null)
{
token.Dispose();
}
}
return this;
}
/// <summary>
/// Registers the components with the <see cref = "IWindsorContainer" />. The instances of <see cref = "IRegistration" /> are produced by fluent registration API.
/// Most common entry points are <see cref = "Component.For{TService}" /> method to register a single type or (recommended in most cases)
/// <see cref = "Classes.FromAssembly(Assembly)" />.
/// Let the Intellisense drive you through the fluent API past those entry points. For details see the documentation at http://j.mp/WindsorApi
/// </summary>
/// <example>
/// <code>
/// container.Register(Component.For<IService>().ImplementedBy<DefaultService>().LifestyleTransient());
/// </code>
/// </example>
/// <example>
/// <code>
/// container.Register(Classes.FromThisAssembly().BasedOn<IService>().WithServiceDefaultInterfaces().Configure(c => c.LifestyleTransient()));
/// </code>
/// </example>
/// <param name = "registrations">The component registrations created by <see cref = "Component.For{TService}" />, <see
/// cref = "Classes.FromAssembly(Assembly)" /> or different entry method to the fluent API.</param>
/// <returns>The container.</returns>
public IWindsorContainer Register(params IRegistration[] registrations)
{
Kernel.Register(registrations);
return this;
}
/// <summary>
/// Releases a component instance
/// </summary>
/// <param name = "instance"></param>
public virtual void Release(object instance)
{
kernel.ReleaseComponent(instance);
}
/// <summary>
/// Removes (unregisters) a subcontainer. The components exposed by this container
/// will no longer be accessible to the child container.
/// </summary>
/// <param name = "childContainer"></param>
public virtual void RemoveChildContainer(IWindsorContainer childContainer)
{
if (childContainer == null)
{
throw new ArgumentNullException("childContainer");
}
if (childContainers.ContainsKey(childContainer.Name))
{
lock (childContainersLocker)
{
if (childContainers.ContainsKey(childContainer.Name))
{
kernel.RemoveChildKernel(childContainer.Kernel);
childContainers.Remove(childContainer.Name);
childContainer.Parent = null;
}
}
}
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <param name = "service"></param>
/// <param name = "arguments"></param>
/// <returns></returns>
public virtual object Resolve(Type service, IDictionary arguments)
{
return kernel.Resolve(service, arguments);
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <param name = "service"></param>
/// <param name = "argumentsAsAnonymousType"></param>
/// <returns></returns>
public virtual object Resolve(Type service, object argumentsAsAnonymousType)
{
return Resolve(service, new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <param name = "service"></param>
/// <returns></returns>
public virtual object Resolve(Type service)
{
return kernel.Resolve(service, arguments: null);
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <param name = "service"></param>
/// <returns></returns>
public virtual object Resolve(String key, Type service)
{
return kernel.Resolve(key, service, arguments: null);
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <param name = "service"></param>
/// <param name = "arguments"></param>
/// <returns></returns>
public virtual object Resolve(String key, Type service, IDictionary arguments)
{
return kernel.Resolve(key, service, arguments);
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <param name = "service"></param>
/// <param name = "argumentsAsAnonymousType"></param>
/// <returns></returns>
public virtual object Resolve(String key, Type service, object argumentsAsAnonymousType)
{
return kernel.Resolve(key, service, new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "arguments"></param>
/// <returns></returns>
public T Resolve<T>(IDictionary arguments)
{
return (T)kernel.Resolve(typeof(T), arguments);
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "argumentsAsAnonymousType"></param>
/// <returns></returns>
public T Resolve<T>(object argumentsAsAnonymousType)
{
return (T)kernel.Resolve(typeof(T), new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <param name = "arguments"></param>
/// <returns></returns>
public virtual T Resolve<T>(String key, IDictionary arguments)
{
return (T)kernel.Resolve(key, typeof(T), arguments);
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <param name = "argumentsAsAnonymousType"></param>
/// <returns></returns>
public virtual T Resolve<T>(String key, object argumentsAsAnonymousType)
{
return (T)kernel.Resolve(key, typeof(T), new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
/// <summary>
/// Returns a component instance by the service
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <returns></returns>
public T Resolve<T>()
{
return (T)kernel.Resolve(typeof(T), arguments: null);
}
/// <summary>
/// Returns a component instance by the key
/// </summary>
/// <param name = "key"></param>
/// <returns></returns>
public virtual T Resolve<T>(String key)
{
return (T)kernel.Resolve(key, typeof(T), arguments: null);
}
/// <summary>
/// Resolve all valid components that match this type.
/// </summary>
/// <typeparam name = "T">The service type</typeparam>
public T[] ResolveAll<T>()
{
return (T[])ResolveAll(typeof(T));
}
public Array ResolveAll(Type service)
{
return kernel.ResolveAll(service);
}
public Array ResolveAll(Type service, IDictionary arguments)
{
return kernel.ResolveAll(service, arguments);
}
public Array ResolveAll(Type service, object argumentsAsAnonymousType)
{
return ResolveAll(service, new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
/// <summary>
/// Resolve all valid components that match this type.
/// <typeparam name = "T">The service type</typeparam>
/// <param name = "arguments">Arguments to resolve the service</param>
/// </summary>
public T[] ResolveAll<T>(IDictionary arguments)
{
return (T[])ResolveAll(typeof(T), arguments);
}
/// <summary>
/// Resolve all valid components that match this type.
/// <typeparam name = "T">The service type</typeparam>
/// <param name = "argumentsAsAnonymousType">Arguments to resolve the service</param>
/// </summary>
public T[] ResolveAll<T>(object argumentsAsAnonymousType)
{
return ResolveAll<T>(new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType));
}
private XmlInterpreter GetInterpreter(string configurationUri)
{
try
{
var resources = (IResourceSubSystem)Kernel.GetSubSystem(SubSystemConstants.ResourceKey);
var resource = resources.CreateResource(configurationUri);
return new XmlInterpreter(resource);
}
catch (Exception)
{
// We fallback to the old behavior
return new XmlInterpreter(configurationUri);
}
}
private static string MakeUniqueName()
{
var sb = new StringBuilder();
#if FEATURE_APPDOMAIN
sb.Append(AppDomain.CurrentDomain.FriendlyName);
sb.Append(" ");
#endif
sb.Append(CastleUnicode);
sb.Append(" ");
sb.Append(Interlocked.Increment(ref instanceCount));
return sb.ToString();
}
}
} | 29.938187 | 168 | 0.673411 | [
"Apache-2.0"
] | LouisFei/Windsor | src/Castle.Windsor/Windsor/WindsorContainer.cs | 21,795 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Umbraco.Web.UI.ContentApps.Changes.Models
{
public class ValueChange
{
public string Culture { get; set; }
public object EditedValue { get; set; }
public object PublishedValue { get; set; }
}
}
| 21.8 | 51 | 0.678899 | [
"MIT"
] | NovawareNL/Changes | ContentApps/Changes/Models/ValueChange.cs | 329 | C# |
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Stryker.Core.Mutants.NodeOrchestrators
{
internal class StaticFieldDeclarationOrchestrator: NodeSpecificOrchestrator<FieldDeclarationSyntax, BaseFieldDeclarationSyntax>
{
protected override bool CanHandle(FieldDeclarationSyntax t)
{
return t.Modifiers.Any(x => x.Kind() == SyntaxKind.StaticKeyword);
}
protected override BaseFieldDeclarationSyntax OrchestrateChildrenMutation(FieldDeclarationSyntax node, MutationContext context)
{
using var newContext = context.EnterStatic();
// we need to signal we are in a static field
return base.OrchestrateChildrenMutation(node, newContext);
}
public StaticFieldDeclarationOrchestrator(CsharpMutantOrchestrator mutantOrchestrator) : base(mutantOrchestrator)
{
}
}
} | 38.08 | 135 | 0.72584 | [
"Apache-2.0"
] | 0xced/stryker-net | src/Stryker.Core/Stryker.Core/Mutants/NodeOrchestrators/StaticFieldDeclarationOrchestrator.cs | 954 | C# |
using System.ComponentModel.DataAnnotations;
namespace WebsiteCreatorMVC.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ManageUserViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class MoneyViewModel
{
[Display(Name = "AsMoney account")]
public string AsMoneyAccount { get; set; }
[Display(Name = "Bitcoin address")]
public string BitcoinAddress { get; set; }
[Display(Name = "Litecoin address")]
public string LitecoinAddress { get; set; }
[Display(Name = "PerfectMoney account")]
public string PerfectMoney { get; set; }
} // MoneyViewModel
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "AsMoney account")]
public string AsMoneyAccount { get; set; }
[Display(Name = "Bitcoin address")]
public string BitcoinAddress { get; set; }
[Display(Name = "Litecoin address")]
public string LitecoinAddress { get; set; }
[Display(Name = "PerfectMoney account")]
public string PerfectMoney { get; set; }
}
}
| 30.182796 | 110 | 0.598504 | [
"MIT"
] | managerwar/managerwar | WebsiteCreatorMVC/Models/AccountViewModels.cs | 2,809 | 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 lambda-2015-03-31.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.Lambda.Model
{
/// <summary>
/// The code for the Lambda function. You can specify either an object in Amazon S3, upload
/// a .zip file archive deployment package directly, or specify the URI of a container
/// image.
/// </summary>
public partial class FunctionCode
{
private string _imageUri;
private string _s3Bucket;
private string _s3Key;
private string _s3ObjectVersion;
private MemoryStream _zipFile;
/// <summary>
/// Gets and sets the property ImageUri.
/// <para>
/// URI of a container image in the Amazon ECR registry.
/// </para>
/// </summary>
public string ImageUri
{
get { return this._imageUri; }
set { this._imageUri = value; }
}
// Check to see if ImageUri property is set
internal bool IsSetImageUri()
{
return this._imageUri != null;
}
/// <summary>
/// Gets and sets the property S3Bucket.
/// <para>
/// An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in
/// a different AWS account.
/// </para>
/// </summary>
[AWSProperty(Min=3, Max=63)]
public string S3Bucket
{
get { return this._s3Bucket; }
set { this._s3Bucket = value; }
}
// Check to see if S3Bucket property is set
internal bool IsSetS3Bucket()
{
return this._s3Bucket != null;
}
/// <summary>
/// Gets and sets the property S3Key.
/// <para>
/// The Amazon S3 key of the deployment package.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string S3Key
{
get { return this._s3Key; }
set { this._s3Key = value; }
}
// Check to see if S3Key property is set
internal bool IsSetS3Key()
{
return this._s3Key != null;
}
/// <summary>
/// Gets and sets the property S3ObjectVersion.
/// <para>
/// For versioned objects, the version of the deployment package object to use.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string S3ObjectVersion
{
get { return this._s3ObjectVersion; }
set { this._s3ObjectVersion = value; }
}
// Check to see if S3ObjectVersion property is set
internal bool IsSetS3ObjectVersion()
{
return this._s3ObjectVersion != null;
}
/// <summary>
/// Gets and sets the property ZipFile.
/// <para>
/// The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients
/// handle the encoding for you.
/// </para>
/// </summary>
public MemoryStream ZipFile
{
get { return this._zipFile; }
set { this._zipFile = value; }
}
// Check to see if ZipFile property is set
internal bool IsSetZipFile()
{
return this._zipFile != null;
}
}
} | 30.535714 | 105 | 0.554854 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Lambda/Generated/Model/FunctionCode.cs | 4,275 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Docker.Tests
{
public class DockerHelper
{
public static string DockerOS => GetDockerOS();
public static string DockerArchitecture => GetDockerArch();
public static string ContainerWorkDir => IsLinuxContainerModeEnabled ? "/sandbox" : "c:\\sandbox";
public static bool IsLinuxContainerModeEnabled => string.Equals(DockerOS, "linux", StringComparison.OrdinalIgnoreCase);
public static string TestArtifactsDir { get; } = Path.Combine(Directory.GetCurrentDirectory(), "TestAppArtifacts");
private ITestOutputHelper OutputHelper { get; set; }
public DockerHelper(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}
public void Build(
string tag,
string dockerfile = null,
string target = null,
string contextDir = ".",
bool pull = false,
params string[] buildArgs)
{
string buildArgsOption = string.Empty;
if (buildArgs != null)
{
foreach (string arg in buildArgs)
{
buildArgsOption += $" --build-arg {arg}";
}
}
string targetArg = target == null ? string.Empty : $" --target {target}";
string dockerfileArg = dockerfile == null ? string.Empty : $" -f {dockerfile}";
string pullArg = pull ? " --pull" : string.Empty;
ExecuteWithLogging($"build -t {tag}{targetArg}{buildArgsOption}{dockerfileArg}{pullArg} {contextDir}");
}
/// <summary>
/// Builds a helper image intended to test distroless scenarios.
/// </summary>
/// <remarks>
/// Because distroless containers do not contain a shell, and potentially other packages necessary for testing,
/// this helper image adds the necessary packages to a distroless image.
/// </remarks>
public string BuildDistrolessHelper(DotNetImageType imageType, ProductImageData imageData, params string[] requiredPackages)
{
string dockerfile;
if (imageData.OS.Contains("mariner"))
{
dockerfile = Path.Combine(TestArtifactsDir, "Dockerfile.cbl-mariner-distroless");
}
else
{
throw new NotImplementedException($"Distroless helper not implemented for OS '{imageData.OS}'");
}
string baseImageTag = imageData.GetImage(imageType, this);
string installerImageTag = baseImageTag.Replace("-distroless", string.Empty);
string tag = imageData.GetIdentifier("distroless-helper");
Build(tag, dockerfile, null, TestArtifactsDir, false,
$"installer_image={installerImageTag}",
$"base_image={baseImageTag}",
$"\"required_packages={string.Join(" ", requiredPackages)}\"",
$"os_version={imageData.OsVersion}");
return tag;
}
public static bool ContainerExists(string name) => ResourceExists("container", $"-f \"name={name}\"");
public void Copy(string src, string dest) => ExecuteWithLogging($"cp {src} {dest}");
public void DeleteContainer(string container, bool captureLogs = false)
{
if (ContainerExists(container))
{
if (captureLogs)
{
ExecuteWithLogging($"logs {container}", ignoreErrors: true);
}
ExecuteWithLogging($"container rm -f {container}");
}
}
public void DeleteImage(string tag)
{
if (ImageExists(tag))
{
ExecuteWithLogging($"image rm -f {tag}");
}
}
private static string Execute(
string args, bool ignoreErrors = false, bool autoRetry = false, ITestOutputHelper outputHelper = null)
{
(Process Process, string StdOut, string StdErr) result;
if (autoRetry)
{
result = ExecuteWithRetry(args, outputHelper, ExecuteProcess);
}
else
{
result = ExecuteProcess(args, outputHelper);
}
if (!ignoreErrors && result.Process.ExitCode != 0)
{
ProcessStartInfo startInfo = result.Process.StartInfo;
string msg = $"Failed to execute {startInfo.FileName} {startInfo.Arguments}" +
$"{Environment.NewLine}Exit code: {result.Process.ExitCode}" +
$"{Environment.NewLine}Standard Error: {result.StdErr}";
throw new InvalidOperationException(msg);
}
return result.StdOut;
}
private static (Process Process, string StdOut, string StdErr) ExecuteProcess(
string args, ITestOutputHelper outputHelper) => ExecuteHelper.ExecuteProcess("docker", args, outputHelper);
private string ExecuteWithLogging(string args, bool ignoreErrors = false, bool autoRetry = false)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
OutputHelper.WriteLine($"Executing: docker {args}");
string result = Execute(args, outputHelper: OutputHelper, ignoreErrors: ignoreErrors, autoRetry: autoRetry);
stopwatch.Stop();
OutputHelper.WriteLine($"Execution Elapsed Time: {stopwatch.Elapsed}");
return result;
}
private static (Process Process, string StdOut, string StdErr) ExecuteWithRetry(
string args,
ITestOutputHelper outputHelper,
Func<string, ITestOutputHelper, (Process Process, string StdOut, string StdErr)> executor)
{
const int maxRetries = 5;
const int waitFactor = 5;
int retryCount = 0;
(Process Process, string StdOut, string StdErr) result = executor(args, outputHelper);
while (result.Process.ExitCode != 0)
{
retryCount++;
if (retryCount >= maxRetries)
{
break;
}
int waitTime = Convert.ToInt32(Math.Pow(waitFactor, retryCount - 1));
if (outputHelper != null)
{
outputHelper.WriteLine($"Retry {retryCount}/{maxRetries}, retrying in {waitTime} seconds...");
}
Thread.Sleep(waitTime * 1000);
result = executor(args, outputHelper);
}
return result;
}
private static string GetDockerOS() => Execute("version -f \"{{ .Server.Os }}\"");
private static string GetDockerArch() => Execute("version -f \"{{ .Server.Arch }}\"");
public string GetContainerAddress(string container)
{
string containerAddress = ExecuteWithLogging("inspect -f \"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}\" " + container);
if (String.IsNullOrWhiteSpace(containerAddress)){
containerAddress = ExecuteWithLogging("inspect -f \"{{.NetworkSettings.Networks.nat.IPAddress }}\" " + container);
}
return containerAddress;
}
public string GetContainerHostPort(string container, int containerPort = 80) =>
ExecuteWithLogging(
$"inspect -f \"{{{{(index (index .NetworkSettings.Ports \\\"{containerPort}/tcp\\\") 0).HostPort}}}}\" {container}");
public string GetContainerWorkPath(string relativePath)
{
string separator = IsLinuxContainerModeEnabled ? "/" : "\\";
return $"{ContainerWorkDir}{separator}{relativePath}";
}
public static bool ImageExists(string tag) => ResourceExists("image", tag);
public void Pull(string image) => ExecuteWithLogging($"pull {image}", autoRetry: true);
private static bool ResourceExists(string type, string filterArg)
{
string output = Execute($"{type} ls -a -q {filterArg}", true);
return output != "";
}
public string Run(
string image,
string name,
string command = null,
string workdir = null,
string optionalRunArgs = null,
bool detach = false,
string runAsUser = null,
bool skipAutoCleanup = false)
{
string cleanupArg = skipAutoCleanup ? string.Empty : " --rm";
string detachArg = detach ? " -d -t" : string.Empty;
string userArg = runAsUser != null ? $" -u {runAsUser}" : string.Empty;
string workdirArg = workdir == null ? string.Empty : $" -w {workdir}";
return ExecuteWithLogging(
$"run --name {name}{cleanupArg}{workdirArg}{userArg}{detachArg} {optionalRunArgs} {image} {command}");
}
public string CreateVolume(string name)
{
return ExecuteWithLogging($"volume create {name}");
}
public string DeleteVolume(string name)
{
return ExecuteWithLogging($"volume remove {name}");
}
}
}
| 39.247967 | 145 | 0.579389 | [
"MIT"
] | NET1211/dotnet-awesome | tests/Microsoft.DotNet.Docker.Tests/DockerHelper.cs | 9,655 | C# |
using AirCC.Portal.Domain.DomainServices.Abstract;
using AirCC.Portal.DomainServices.Abstract;
using BCI.Extensions.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace AirCC.Portal.Domain.DomainServices
{
public class UserService : IUserService
{
private readonly IRepository<User, string> repository;
private readonly ICryptoHasher cryptoHasher;
public UserService(IRepository<User, string> repository, ICryptoHasher cryptoHasher)
{
this.repository = repository;
this.cryptoHasher = cryptoHasher;
}
public async Task Create(string username, string password, UserRole role)
{
var isDuplicate = (await repository.GetListAsync(u => u.Username.Trim().ToLower() == username.Trim().ToLower())).Any();
if (isDuplicate) throw new ApplicationException($"{username} already exists!");
var hashedPassword = cryptoHasher.HashPassword(password);
var user = User.Create(username, hashedPassword, role);
await repository.InsertAsync(user);
}
/// <summary>
/// validate
/// </summary>
/// <param name="username">admin/admin</param>
/// <param name="password"></param>
/// <returns></returns>
public async Task<User> ValidateUser(string username, string password)
{
var user = (await repository.GetListAsync(u => u.Username.Trim().ToLower() == username.Trim().ToLower())).FirstOrDefault();
if (user == null) throw new ApplicationException("Username error!");
if (!cryptoHasher.VerifyHashedPassword(user.Password, password))
throw new ApplicationException("Password error!");
return user;
}
}
}
| 38.770833 | 135 | 0.649113 | [
"MIT"
] | ellefry/AirCC | src/AirCC.Portal.Domain/DomainServices/UserService.cs | 1,863 | C# |
namespace HealthHub.Services.Data.Tests.UseInMemoryDatabase
{
using System.Linq;
using System.Threading.Tasks;
using HealthHub.Data.Models;
using HealthHub.Web.ViewModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public class ServicesServiceTests : BaseServiceTests
{
private IServicesService Service => this.ServiceProvider.GetRequiredService<IServicesService>();
/* IEnumerable<T> GetAllServices<T>(); - done
*/
[Fact]
public async Task GetAllServicesShouldReturnTheCorrectModelCollection()
{
var service1 = await this.CreateServiceAsync("My service");
var serviceId1 = service1.Id;
var model1 = new ServicesViewModel()
{
Id = serviceId1,
Name = service1.Name,
};
var service2 = await this.CreateServiceAsync("Your service");
var serviceId2 = service2.Id;
var model2 = new ServicesViewModel()
{
Id = serviceId2,
Name = service2.Name,
};
var resultModelCollection = this.Service.GetAllServices<ServicesViewModel>();
Assert.Equal(model1.Id, resultModelCollection.First().Id);
Assert.Equal(model1.Name, resultModelCollection.First().Name);
Assert.Equal(model2.Id, resultModelCollection.Last().Id);
Assert.Equal(model2.Name, resultModelCollection.Last().Name);
}
private async Task<Service> CreateServiceAsync(string name)
{
var service = new Service()
{
Name = name,
Description = new NLipsum.Core.Sentence().ToString(),
};
await this.DbContext.Services.AddAsync(service);
await this.DbContext.SaveChangesAsync();
this.DbContext.Entry<Service>(service).State = EntityState.Detached;
return service;
}
}
}
| 34.183333 | 104 | 0.605558 | [
"MIT"
] | DenitsaDey/My-Projects | HealthHub 3.0/Tests/HealthHub.Services.Data.Tests/UseInMemoryDatabase/ServicesServiceTests.cs | 2,053 | C# |
namespace UglyToad.PdfPig.AcroForms.Fields
{
using Core;
using Tokens;
/// <inheritdoc />
/// <summary>
/// A push button responds immediately to user input without storing any state.
/// </summary>
public class AcroPushButtonField : AcroFieldBase
{
/// <summary>
/// The <see cref="AcroButtonFieldFlags"/> which define the behaviour of this button type.
/// </summary>
public AcroButtonFieldFlags Flags { get; }
/// <inheritdoc />
/// <summary>
/// Create a new <see cref="AcroPushButtonField"/>.
/// </summary>
public AcroPushButtonField(DictionaryToken dictionary, string fieldType,
AcroButtonFieldFlags fieldFlags,
AcroFieldCommonInformation information,
int? pageNumber,
PdfRectangle? bounds) :
base(dictionary, fieldType, (uint)fieldFlags, AcroFieldType.PushButton, information, pageNumber, bounds)
{
Flags = fieldFlags;
}
}
} | 33.354839 | 116 | 0.609284 | [
"Apache-2.0"
] | BobLd/PdfP | src/UglyToad.PdfPig/AcroForms/Fields/AcroPushButtonField.cs | 1,036 | C# |
#pragma checksum "C:\Users\asalah.BCT\source\repos\1\1\CardsViewSample\CardsViewSample.UWP\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "5694B18B1414A31DB918B8C655599694"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CardsViewSample.UWP
{
#if !DISABLE_XAML_GENERATED_MAIN
/// <summary>
/// Program class
/// </summary>
public static class Program
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.16.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
static void Main(string[] args)
{
global::Windows.UI.Xaml.Application.Start((p) => new App());
}
}
#endif
partial class App : global::Windows.UI.Xaml.Application
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.16.0")]
private bool _contentLoaded;
/// <summary>
/// InitializeComponent()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.16.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
#if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
DebugSettings.BindingFailed += (sender, args) =>
{
global::System.Diagnostics.Debug.WriteLine(args.Message);
};
#endif
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
}
}
| 36.3 | 177 | 0.594123 | [
"MIT"
] | AhmedSalahKhodair/CardsViewSample | CardsViewSample/CardsViewSample.UWP/obj/x86/Debug/App.g.i.cs | 2,180 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.TestPlatform.Build.UnitTests
{
using System.Linq;
using Microsoft.TestPlatform.Build.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class VsTestTaskTests
{
[TestMethod]
public void CreateArgumentShouldAddDoubleQuotesForCLIRunSettings()
{
const string arg1 = "RunConfiguration.ResultsDirectory=Path having Space";
const string arg2 = "MSTest.DeploymentEnabled";
var vstestTask = new VSTestTask { VSTestCLIRunSettings = new string[2] };
vstestTask.VSTestCLIRunSettings[0] = arg1;
vstestTask.VSTestCLIRunSettings[1] = arg2;
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var result = vstestTask.CreateArgument().ToArray();
// First, second and third args would be --framework:abc, testfilepath and -- respectively.
Assert.AreEqual($"\"{arg1}\"", result[3]);
Assert.AreEqual($"\"{arg2}\"", result[4]);
}
[TestMethod]
public void CreateArgumentShouldPassResultsDirectoryCorrectly()
{
const string resultsDirectoryValue = @"C:\tmp\ResultsDirectory";
var vstestTask = new VSTestTask { VSTestResultsDirectory = resultsDirectoryValue };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var result = vstestTask.CreateArgument().ToArray();
Assert.AreEqual($"--resultsDirectory:\"{resultsDirectoryValue}\"", result[1]);
}
[TestMethod]
public void CreateArgumentShouldNotSetConsoleLoggerVerbosityIfConsoleLoggerIsGivenInArgs()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "diag" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
vstestTask.VSTestLogger = "Console;Verbosity=quiet";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=quiet")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsn()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "n" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsnormal()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "normal" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsd()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "d" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsdetailed()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "detailed" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsdiag()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "diag" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsdiagnostic()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "diagnostic" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=normal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsq()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "q" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=quiet")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsquiet()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "quiet" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=quiet")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToMinimalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsm()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "m" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=minimal")));
}
[TestMethod]
public void CreateArgumentShouldSetConsoleLoggerVerbosityToMinimalIfConsoleLoggerIsNotGivenInArgsAndVerbosityIsminimal()
{
var vstestTask = new VSTestTask { VSTestVerbosity = "minimal" };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--logger:Console;Verbosity=minimal")));
}
[TestMethod]
public void CreateArgumentShouldAddOneCollectArgumentForEachCollect()
{
var vstestTask = new VSTestTask { VSTestCollect = new string[2] };
// Add values for required properties.
vstestTask.TestFileFullPath = "abc";
vstestTask.VSTestFramework = "abc";
vstestTask.VSTestCollect[0] = "name1";
vstestTask.VSTestCollect[1] = "name2";
var allArguments = vstestTask.CreateArgument().ToArray();
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--collect:name1")));
Assert.IsNotNull(allArguments.FirstOrDefault(arg => arg.Contains("--collect:name2")));
}
}
}
| 40.515695 | 130 | 0.652684 | [
"MIT"
] | eerhardt/vstest | test/Microsoft.TestPlatform.Build.UnitTests/VsTestTaskTests.cs | 9,035 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Input;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Cursor;
using osu.Game.Online.API;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Play.BreaksOverlay;
using osu.Game.Screens.Ranking;
using osu.Game.Storyboards.Drawables;
using OpenTK;
namespace osu.Game.Screens.Play
{
public class Player : OsuScreen, IProvideCursor
{
protected override BackgroundScreen CreateBackground() => new BackgroundScreenBeatmap(Beatmap);
public override bool ShowOverlaysOnEnter => false;
public Action RestartRequested;
public override bool AllowBeatmapRulesetChange => false;
public bool HasFailed { get; private set; }
public bool AllowPause { get; set; } = true;
public bool AllowLeadIn { get; set; } = true;
public bool AllowResults { get; set; } = true;
public int RestartCount;
public CursorContainer Cursor => RulesetContainer.Cursor;
public bool ProvidingUserCursor => RulesetContainer?.Cursor != null && !RulesetContainer.HasReplayLoaded.Value;
private IAdjustableClock adjustableSourceClock;
private FramedOffsetClock offsetClock;
private DecoupleableInterpolatingFramedClock decoupledClock;
private PauseContainer pauseContainer;
private RulesetInfo ruleset;
private APIAccess api;
private ScoreProcessor scoreProcessor;
protected RulesetContainer RulesetContainer;
#region User Settings
private Bindable<double> dimLevel;
private Bindable<double> blurLevel;
private Bindable<bool> showStoryboard;
private Bindable<bool> mouseWheelDisabled;
private Bindable<double> userAudioOffset;
private SampleChannel sampleRestart;
#endregion
private Container storyboardContainer;
private DrawableStoryboard storyboard;
private HUDOverlay hudOverlay;
private FailOverlay failOverlay;
private bool loadedSuccessfully => RulesetContainer?.Objects.Any() == true;
[BackgroundDependencyLoader]
private void load(AudioManager audio, OsuConfigManager config, APIAccess api)
{
this.api = api;
dimLevel = config.GetBindable<double>(OsuSetting.DimLevel);
blurLevel = config.GetBindable<double>(OsuSetting.BlurLevel);
showStoryboard = config.GetBindable<bool>(OsuSetting.ShowStoryboard);
mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
sampleRestart = audio.Sample.Get(@"Gameplay/restart");
WorkingBeatmap working = Beatmap.Value;
Beatmap beatmap;
try
{
beatmap = working.Beatmap;
if (beatmap == null)
throw new InvalidOperationException("Beatmap was not loaded");
ruleset = Ruleset.Value ?? beatmap.BeatmapInfo.Ruleset;
var rulesetInstance = ruleset.CreateInstance();
try
{
RulesetContainer = rulesetInstance.CreateRulesetContainerWith(working, ruleset.ID == beatmap.BeatmapInfo.Ruleset.ID);
}
catch (BeatmapInvalidForRulesetException)
{
// we may fail to create a RulesetContainer if the beatmap cannot be loaded with the user's preferred ruleset
// let's try again forcing the beatmap's ruleset.
ruleset = beatmap.BeatmapInfo.Ruleset;
rulesetInstance = ruleset.CreateInstance();
RulesetContainer = rulesetInstance.CreateRulesetContainerWith(Beatmap, true);
}
if (!RulesetContainer.Objects.Any())
throw new InvalidOperationException("Beatmap contains no hit objects!");
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap sucessfully!");
//couldn't load, hard abort!
Exit();
return;
}
adjustableSourceClock = (IAdjustableClock)working.Track ?? new StopwatchClock();
decoupledClock = new DecoupleableInterpolatingFramedClock { IsCoupled = false };
var firstObjectTime = RulesetContainer.Objects.First().StartTime;
decoupledClock.Seek(AllowLeadIn
? Math.Min(0, firstObjectTime - Math.Max(beatmap.ControlPointInfo.TimingPointAt(firstObjectTime).BeatLength * 4, beatmap.BeatmapInfo.AudioLeadIn))
: firstObjectTime);
decoupledClock.ProcessFrame();
offsetClock = new FramedOffsetClock(decoupledClock);
userAudioOffset = config.GetBindable<double>(OsuSetting.AudioOffset);
userAudioOffset.ValueChanged += v => offsetClock.Offset = v;
userAudioOffset.TriggerChange();
scoreProcessor = RulesetContainer.CreateScoreProcessor();
Children = new Drawable[]
{
storyboardContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Clock = offsetClock,
Alpha = 0,
},
pauseContainer = new PauseContainer
{
AudioClock = decoupledClock,
FramedClock = offsetClock,
OnRetry = Restart,
OnQuit = Exit,
CheckCanPause = () => AllowPause && ValidForResume && !HasFailed && !RulesetContainer.HasReplayLoaded,
OnPause = () =>
{
pauseContainer.Retries = RestartCount;
hudOverlay.KeyCounter.IsCounting = pauseContainer.IsPaused;
},
OnResume = () => hudOverlay.KeyCounter.IsCounting = true,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Clock = offsetClock,
Child = RulesetContainer,
},
new SkipButton(firstObjectTime) { AudioClock = decoupledClock },
hudOverlay = new HUDOverlay(scoreProcessor, RulesetContainer, decoupledClock, working, adjustableSourceClock)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
},
new BreakOverlay(beatmap.BeatmapInfo.LetterboxInBreaks, scoreProcessor)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Clock = decoupledClock,
Breaks = beatmap.Breaks
}
}
},
failOverlay = new FailOverlay
{
OnRetry = Restart,
OnQuit = Exit,
},
new HotkeyRetryOverlay
{
Action = () =>
{
if (!IsCurrentScreen) return;
//we want to hide the hitrenderer immediately (looks better).
//we may be able to remove this once the mouse cursor trail is improved.
RulesetContainer?.Hide();
Restart();
},
}
};
if (showStoryboard)
initializeStoryboard(false);
// Bind ScoreProcessor to ourselves
scoreProcessor.AllJudged += onCompletion;
scoreProcessor.Failed += onFail;
foreach (var mod in Beatmap.Value.Mods.Value.OfType<IApplicableToScoreProcessor>())
mod.ApplyToScoreProcessor(scoreProcessor);
}
private void applyRateFromMods()
{
if (adjustableSourceClock == null) return;
adjustableSourceClock.Rate = 1;
foreach (var mod in Beatmap.Value.Mods.Value.OfType<IApplicableToClock>())
mod.ApplyToClock(adjustableSourceClock);
}
private void initializeStoryboard(bool asyncLoad)
{
var beatmap = Beatmap.Value;
storyboard = beatmap.Storyboard.CreateDrawable(Beatmap.Value);
storyboard.Masking = true;
if (asyncLoad)
LoadComponentAsync(storyboard, storyboardContainer.Add);
else
storyboardContainer.Add(storyboard);
}
public void Restart()
{
sampleRestart?.Play();
ValidForResume = false;
RestartRequested?.Invoke();
Exit();
}
private ScheduledDelegate onCompletionEvent;
private void onCompletion()
{
// Only show the completion screen if the player hasn't failed
if (scoreProcessor.HasFailed || onCompletionEvent != null)
return;
ValidForResume = false;
if (!AllowResults) return;
using (BeginDelayedSequence(1000))
{
onCompletionEvent = Schedule(delegate
{
if (!IsCurrentScreen) return;
var score = new Score
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = ruleset
};
scoreProcessor.PopulateScore(score);
score.User = RulesetContainer.Replay?.User ?? api.LocalUser.Value;
Push(new Results(score));
});
}
}
private bool onFail()
{
if (Beatmap.Value.Mods.Value.OfType<IApplicableFailOverride>().Any(m => !m.AllowFail))
return false;
decoupledClock.Stop();
HasFailed = true;
failOverlay.Retries = RestartCount;
failOverlay.Show();
return true;
}
protected override void OnEntering(Screen last)
{
base.OnEntering(last);
if (!loadedSuccessfully)
return;
dimLevel.ValueChanged += _ => updateBackgroundElements();
blurLevel.ValueChanged += _ => updateBackgroundElements();
showStoryboard.ValueChanged += _ => updateBackgroundElements();
updateBackgroundElements();
Content.Alpha = 0;
Content
.ScaleTo(0.7f)
.ScaleTo(1, 750, Easing.OutQuint)
.Delay(250)
.FadeIn(250);
Task.Run(() =>
{
adjustableSourceClock.Reset();
Schedule(() =>
{
decoupledClock.ChangeSource(adjustableSourceClock);
applyRateFromMods();
this.Delay(750).Schedule(() =>
{
if (!pauseContainer.IsPaused)
decoupledClock.Start();
});
});
});
pauseContainer.Alpha = 0;
pauseContainer.FadeIn(750, Easing.OutQuint);
}
protected override void OnSuspending(Screen next)
{
fadeOut();
base.OnSuspending(next);
}
protected override bool OnExiting(Screen next)
{
if ((!AllowPause || HasFailed || !ValidForResume || pauseContainer?.IsPaused != false || RulesetContainer?.HasReplayLoaded != false) && (!pauseContainer?.IsResuming ?? false))
{
// In the case of replays, we may have changed the playback rate.
applyRateFromMods();
fadeOut();
return base.OnExiting(next);
}
if (loadedSuccessfully)
{
pauseContainer?.Pause();
}
return true;
}
private void updateBackgroundElements()
{
if (!IsCurrentScreen) return;
const float duration = 800;
var opacity = 1 - (float)dimLevel;
if (showStoryboard && storyboard == null)
initializeStoryboard(true);
var beatmap = Beatmap.Value;
var storyboardVisible = showStoryboard && beatmap.Storyboard.HasDrawable;
storyboardContainer
.FadeColour(OsuColour.Gray(opacity), duration, Easing.OutQuint)
.FadeTo(storyboardVisible && opacity > 0 ? 1 : 0, duration, Easing.OutQuint);
(Background as BackgroundScreenBeatmap)?.BlurTo(new Vector2((float)blurLevel.Value * 25), duration, Easing.OutQuint);
Background?.FadeTo(beatmap.Background != null && (!storyboardVisible || !beatmap.Storyboard.ReplacesBackground) ? opacity : 0, duration, Easing.OutQuint);
}
private void fadeOut()
{
const float fade_out_duration = 250;
RulesetContainer?.FadeOut(fade_out_duration);
Content.FadeOut(fade_out_duration);
hudOverlay?.ScaleTo(0.7f, fade_out_duration * 3, Easing.In);
Background?.FadeTo(1f, fade_out_duration);
}
protected override bool OnWheel(InputState state) => mouseWheelDisabled.Value && !pauseContainer.IsPaused;
}
}
| 36.254902 | 188 | 0.54516 | [
"MIT"
] | acinonyx-esports/osu | osu.Game/Screens/Play/Player.cs | 14,794 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQ_3.Sum__Min__Max__Average
{
public class Program
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var list = new List<int>();
for (int i = 0; i < n; i++)
{
int numbers = int.Parse(Console.ReadLine());
list.Add(numbers);
}
Console.WriteLine("Sum = {0}", list.Sum());
Console.WriteLine("Min = {0}", list.Min());
Console.WriteLine("Max = {0}", list.Max());
Console.WriteLine("Average = {0}", list.Average());
}
}
}
| 25.586207 | 63 | 0.522911 | [
"MIT"
] | StefanDimitrov97/Technologies-Programming-Fundamentals | softuni fundamental January Kenov/Dictionaries, Lambda and LINQ - Lab/LINQ 3. Sum, Min, Max, Average/LINQ 3. Sum, Min, Max, Average/Program.cs | 744 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Epiphany.Examples.Messaging.Models;
using Microsoft.Extensions.Configuration;
namespace Epiphany.Examples.Messaging.ModelGeneration
{
public class MessageGenerator : IMessageGenerator
{
private readonly ISerializer _serializer;
private readonly int _modelsNumber;
private readonly int _parametersNumber;
private readonly bool _produceInfinitely;
public MessageGenerator(IConfiguration configuration, ISerializer serializer)
{
_serializer = serializer;
_parametersNumber = int.Parse(configuration["PARAM_NUMBER"]);
_modelsNumber = int.Parse(configuration["MODELS_NUMBER"]);
_produceInfinitely = configuration["PRODUCE_INFINITELY"] == "1";
}
public IEnumerable<string> Generate(string prefixName)
{
while (true)
{
yield return GetMessage(prefixName);
if (!_produceInfinitely)
{
break;
}
}
}
private string GetMessage(string prefixName)
{
var models = new List<FakeModel>();
for (var i = 0; i < _modelsNumber; i++)
{
models.Add(new FakeModel($"{prefixName}{i}")
{
DateTime = DateTime.UtcNow,
Parameters = Enumerable.Range(0, _parametersNumber).Select(x => new FakeParameter($"Param00{x}")).ToList()
});
}
return _serializer.Serialize(models);
}
}
}
| 33.313725 | 127 | 0.567393 | [
"Apache-2.0"
] | ar3ndt/epiphany | examples/dotnet/Messaging/Epiphany.Examples.Messaging/ModelGeneration/MessageGenerator.cs | 1,699 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Ateo
{
public class GazeClickWarning : EditorWindow{
void OnGUI (){
EditorGUILayout.LabelField("Warning!", EditorStyles.boldLabel);
EditorGUILayout.LabelField ("\n \nYou are using the newest version of GoogleVR. \nThis version MAY not be supported by GazeClick yet. \nThis could possibly lead to errors. " +
"\nIf needed you can find older Versions of GoogleVR here: \nhttps://github.com/googlevr/gvr-unity-sdk " +
"\nIgnore this message, if everything is working.", EditorStyles.wordWrappedLabel);
GUILayout.Space (50);
if (GUILayout.Button ("OK"))
this.Close ();
}
}
}
| 29.833333 | 179 | 0.73324 | [
"MIT"
] | PieterQLovesu/UnityVREscapeRoom | Assets/GazeClick/Editor/GazeClickWarning.cs | 718 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhatsNewInCSharp7.D_PatternMatching
{
public class PatternMatchingExamples
{
public int DiceSum(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
if (item is int val)
sum += val;
else if (item is IEnumerable<object> subList)
sum += DiceSum(subList);
}
return sum;
}
public int DiceSum2(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
case 0:
break;
case int val:
sum += val;
break;
case IEnumerable<object> subList when subList.Any():
sum += DiceSum2(subList);
break;
case IEnumerable<object> subList:
break;
case var i when i is string:
break;
case null:
break;
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
}
}
| 26.836364 | 81 | 0.411924 | [
"BSD-3-Clause"
] | Manishkr117/DesignPattern | CSharp/WhatsNewInCSharp7/WhatsNewInCSharp7/D_PatternMatching/PatternMatchingExamples.cs | 1,478 | C# |
namespace CloudFoundry.VisualStudio
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using CloudFoundry.CloudController.V2.Client.Data;
public class XmlUri : IXmlSerializable
{
private Uri value;
public XmlUri()
{
}
public XmlUri(Uri source)
{
this.value = source;
}
public static implicit operator Uri(XmlUri uriInfo)
{
return uriInfo == null ? null : uriInfo.value;
}
public static implicit operator XmlUri(Uri uriInfo)
{
return uriInfo == null ? null : new XmlUri(uriInfo);
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
if (reader != null)
{
this.value = new Uri(reader.ReadElementContentAsString());
}
else
{
throw new InvalidOperationException("Xml reader cannot be null");
}
}
public void WriteXml(XmlWriter writer)
{
if (writer != null)
{
writer.WriteValue(this.value.ToString());
}
else
{
throw new InvalidOperationException("Xml writer cannot be null");
}
}
public override string ToString()
{
return this.value.ToString();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Validated")]
public override bool Equals(object obj)
{
if (this == null && obj == null)
{
return true;
}
return this.ToString() == obj.ToString();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| 24.770115 | 170 | 0.521578 | [
"Apache-2.0"
] | amd989/cf-vs-extension | src/CloudFoundry.VisualStudio/XmlUri.cs | 2,157 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace SolToBoogie
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BoogieAST;
using SolidityAST;
public class GhostVarAndAxiomGenerator
{
// require the ContractDefintions member is populated
private TranslatorContext context;
private BoogieCtorType contractType = new BoogieCtorType("ContractName");
public GhostVarAndAxiomGenerator(TranslatorContext context)
{
this.context = context;
}
public void Generate()
{
GenerateTypes();
GenerateConstants();
GenerateFunctions();
GenerateGlobalVariables();
GenerateGlobalImplementations();
GenerateAxioms();
}
private void GenerateFunctions()
{
context.Program.AddDeclaration(GenerateConstToRefFunction());
context.Program.AddDeclaration(GenerateModFunction());
context.Program.AddDeclaration(GenerateKeccakFunction());
context.Program.AddDeclaration(GenerateAbiEncodedFunctionOneArg());
context.Program.AddDeclaration(GenerateVeriSolSumFunction());
context.Program.AddDeclaration(GenerateAbiEncodedFunctionTwoArgs());
context.Program.AddDeclaration(GenerateAbiEncodedFunctionOneArgRef());
context.Program.AddDeclaration(GenerateAbiEncodedFunctionTwoArgsOneRef());
}
private BoogieFunction GenerateKeccakFunction()
{
//function for Int to Ref
var inVar = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"keccak256",
new List<BoogieVariable>() { inVar },
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateAbiEncodedFunctionOneArg()
{
//function for Int to Int
var inVar1 = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"abiEncodePacked1",
new List<BoogieVariable>() { inVar1},
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateAbiEncodedFunctionTwoArgs()
{
//function for Int*Int to Int
var inVar1 = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Int));
var inVar2 = new BoogieFormalParam(new BoogieTypedIdent("y", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"abiEncodePacked2",
new List<BoogieVariable>() { inVar1, inVar2 },
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateAbiEncodedFunctionOneArgRef()
{
//function for Int to Int
var inVar1 = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Ref));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"abiEncodePacked1R",
new List<BoogieVariable>() { inVar1 },
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateAbiEncodedFunctionTwoArgsOneRef()
{
//function for Int*Int to Int
var inVar1 = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Ref));
var inVar2 = new BoogieFormalParam(new BoogieTypedIdent("y", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"abiEncodePacked2R",
new List<BoogieVariable>() { inVar1, inVar2 },
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateConstToRefFunction()
{
//function for Int to Ref
var inVar = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Ref));
return new BoogieFunction(
"ConstantToRef",
new List<BoogieVariable>() { inVar },
new List<BoogieVariable>() { outVar },
null);
}
private BoogieFunction GenerateModFunction()
{
//function for arithmetic "modulo" operation for unsigned integers
string functionName = "modBpl";
var inVar1 = new BoogieFormalParam(new BoogieTypedIdent("x", BoogieType.Int));
var inVar2 = new BoogieFormalParam(new BoogieTypedIdent("y", BoogieType.Int));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
functionName,
new List<BoogieVariable>() { inVar1, inVar2 },
new List<BoogieVariable>() { outVar },
new List<BoogieAttribute> { new BoogieAttribute("bvbuiltin", "\"" + "mod" + "\"") });
}
private BoogieFunction GenerateVeriSolSumFunction()
{
//function for [Ref]int to int
var inVar = new BoogieFormalParam(new BoogieTypedIdent("x", new BoogieMapType(BoogieType.Ref, BoogieType.Int)));
var outVar = new BoogieFormalParam(new BoogieTypedIdent("ret", BoogieType.Int));
return new BoogieFunction(
"_SumMapping_VeriSol",
new List<BoogieVariable>() { inVar },
new List<BoogieVariable>() { outVar },
null);
}
private void GenerateTypes()
{
context.Program.AddDeclaration(new BoogieTypeCtorDecl("Ref"));
context.Program.AddDeclaration(new BoogieTypeCtorDecl("ContractName"));
}
private void GenerateConstants()
{
BoogieConstant nullConstant = new BoogieConstant(new BoogieTypedIdent("null", BoogieType.Ref), true);
context.Program.AddDeclaration(nullConstant);
// constants for contract names
BoogieCtorType tnameType = new BoogieCtorType("ContractName");
foreach (ContractDefinition contract in context.ContractDefinitions)
{
BoogieTypedIdent typedIdent = new BoogieTypedIdent(contract.Name, tnameType);
BoogieConstant contractNameConstant = new BoogieConstant(typedIdent, true);
context.Program.AddDeclaration(contractNameConstant);
foreach(var node in contract.Nodes)
{
if (node is StructDefinition structDefn)
{
var structTypedIdent = new BoogieTypedIdent(structDefn.CanonicalName, tnameType);
context.Program.AddDeclaration(new BoogieConstant(structTypedIdent, true));
}
}
}
}
private void GenerateGlobalVariables()
{
BoogieTypedIdent balanceId = new BoogieTypedIdent("Balance", new BoogieMapType(BoogieType.Ref, BoogieType.Int));
BoogieGlobalVariable balanceVar = new BoogieGlobalVariable(balanceId);
context.Program.AddDeclaration(balanceVar);
BoogieTypedIdent dtypeId = new BoogieTypedIdent("DType", new BoogieMapType(BoogieType.Ref, contractType));
BoogieGlobalVariable dtype = new BoogieGlobalVariable(dtypeId);
context.Program.AddDeclaration(dtype);
BoogieTypedIdent allocId = new BoogieTypedIdent("Alloc", new BoogieMapType(BoogieType.Ref, BoogieType.Bool));
BoogieGlobalVariable alloc = new BoogieGlobalVariable(allocId);
context.Program.AddDeclaration(alloc);
BoogieTypedIdent addrBalanceId = new BoogieTypedIdent("balance_ADDR", new BoogieMapType(BoogieType.Ref, BoogieType.Int));
BoogieGlobalVariable addrBalance = new BoogieGlobalVariable(addrBalanceId);
context.Program.AddDeclaration(addrBalance);
// generate global variables for each array/mapping type to model memory
GenerateMemoryVariables();
BoogieMapType type = new BoogieMapType(BoogieType.Ref, BoogieType.Int);
BoogieTypedIdent arrayLengthId = new BoogieTypedIdent("Length", type);
BoogieGlobalVariable arrayLength = new BoogieGlobalVariable(arrayLengthId);
context.Program.AddDeclaration(arrayLength);
if (context.TranslateFlags.ModelReverts)
{
BoogieTypedIdent revertId = new BoogieTypedIdent("revert", BoogieType.Bool);
BoogieGlobalVariable revert = new BoogieGlobalVariable(revertId);
context.Program.AddDeclaration(revert);
}
if (context.TranslateFlags.InstrumentGas)
{
BoogieTypedIdent gasId = new BoogieTypedIdent("gas", BoogieType.Int);
BoogieGlobalVariable gas = new BoogieGlobalVariable(gasId);
context.Program.AddDeclaration(gas);
}
}
private void GenerateGlobalImplementations()
{
GenerateGlobalProcedureFresh();
GenerateGlobalProcedureAllocMany();
GenerateBoogieRecord("int", BoogieType.Int);
GenerateBoogieRecord("ref", BoogieType.Ref);
GenerateBoogieRecord("bool", BoogieType.Bool);
GenerateStructConstructors();
}
private void GenerateStructConstructors()
{
foreach (ContractDefinition contract in context.ContractDefinitions)
{
foreach (var node in contract.Nodes)
{
if (node is StructDefinition structDefn)
{
GenerateStructConstructors(contract, structDefn);
}
}
}
}
private void GenerateStructConstructors(ContractDefinition contract, StructDefinition structDefn)
{
// generate the internal one without base constructors
string procName = structDefn.CanonicalName + "_ctor";
List<BoogieVariable> inParams = new List<BoogieVariable>();
inParams.AddRange(TransUtils.GetDefaultInParams());
foreach(var member in structDefn.Members)
{
Debug.Assert(!member.TypeDescriptions.IsStruct(), "Do no handle nested structs yet!");
var formalType = TransUtils.GetBoogieTypeFromSolidityTypeName(member.TypeName);
var formalName = member.Name;
inParams.Add(new BoogieFormalParam(new BoogieTypedIdent(formalName, formalType)));
}
List<BoogieVariable> outParams = new List<BoogieVariable>();
List<BoogieAttribute> attributes = new List<BoogieAttribute>()
{
new BoogieAttribute("inline", 1),
};
BoogieProcedure procedure = new BoogieProcedure(procName, inParams, outParams, attributes);
context.Program.AddDeclaration(procedure);
List<BoogieVariable> localVars = new List<BoogieVariable>();
BoogieStmtList procBody = new BoogieStmtList();
foreach (var member in structDefn.Members)
{
//f[this] = f_arg
Debug.Assert(!member.TypeDescriptions.IsStruct(), "Do no handle nested structs yet!");
var mapName = member.Name + "_" + structDefn.CanonicalName;
var formalName = member.Name;
var mapSelectExpr = new BoogieMapSelect(new BoogieIdentifierExpr(mapName), new BoogieIdentifierExpr("this"));
procBody.AddStatement(new BoogieAssignCmd(mapSelectExpr, new BoogieIdentifierExpr(member.Name)));
}
BoogieImplementation implementation = new BoogieImplementation(procName, inParams, outParams, localVars, procBody);
context.Program.AddDeclaration(implementation);
}
private void GenerateBoogieRecord(string typeName, BoogieType btype)
{
// generate the internal one without base constructors
string procName = "boogie_si_record_sol2Bpl_" + typeName;
var inVar = new BoogieFormalParam(new BoogieTypedIdent("x", btype));
List<BoogieVariable> inParams = new List<BoogieVariable>() { inVar };
List<BoogieVariable> outParams = new List<BoogieVariable>();
BoogieProcedure procedure = new BoogieProcedure(procName, inParams, outParams, null);
context.Program.AddDeclaration(procedure);
}
private void GenerateGlobalProcedureFresh()
{
// generate the internal one without base constructors
string procName = "FreshRefGenerator";
List<BoogieVariable> inParams = new List<BoogieVariable>();
var outVar = new BoogieFormalParam(new BoogieTypedIdent("newRef", BoogieType.Ref));
List<BoogieVariable> outParams = new List<BoogieVariable>()
{
outVar
};
List<BoogieAttribute> attributes = new List<BoogieAttribute>()
{
new BoogieAttribute("inline", 1),
};
BoogieProcedure procedure = new BoogieProcedure(procName, inParams, outParams, attributes);
context.Program.AddDeclaration(procedure);
List<BoogieVariable> localVars = new List<BoogieVariable>();
BoogieStmtList procBody = new BoogieStmtList();
var outVarIdentifier = new BoogieIdentifierExpr("newRef");
BoogieIdentifierExpr allocIdentExpr = new BoogieIdentifierExpr("Alloc");
// havoc tmp;
procBody.AddStatement(new BoogieHavocCmd(outVarIdentifier));
// assume Alloc[tmp] == false;
BoogieMapSelect allocMapSelect = new BoogieMapSelect(allocIdentExpr, outVarIdentifier);
BoogieExpr allocAssumeExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, allocMapSelect, new BoogieLiteralExpr(false));
procBody.AddStatement(new BoogieAssumeCmd(allocAssumeExpr));
// Alloc[tmp] := true;
procBody.AddStatement(new BoogieAssignCmd(allocMapSelect, new BoogieLiteralExpr(true)));
// assume tmp != null
procBody.AddStatement(new BoogieAssumeCmd(
new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, outVarIdentifier, new BoogieIdentifierExpr("null"))));
BoogieImplementation implementation = new BoogieImplementation(procName, inParams, outParams, localVars, procBody);
context.Program.AddDeclaration(implementation);
}
private void GenerateGlobalProcedureAllocMany()
{
// generate the internal one without base constructors
string procName = "HavocAllocMany";
List<BoogieVariable> inParams = new List<BoogieVariable>();
List<BoogieVariable> outParams = new List<BoogieVariable>();
List<BoogieAttribute> attributes = new List<BoogieAttribute>()
{
new BoogieAttribute("inline", 1),
};
BoogieProcedure procedure = new BoogieProcedure(procName, inParams, outParams, attributes);
context.Program.AddDeclaration(procedure);
var oldAlloc = new BoogieLocalVariable(new BoogieTypedIdent("oldAlloc", new BoogieMapType(BoogieType.Ref, BoogieType.Bool)));
List<BoogieVariable> localVars = new List<BoogieVariable>() {oldAlloc};
BoogieStmtList procBody = new BoogieStmtList();
BoogieIdentifierExpr oldAllocIdentExpr = new BoogieIdentifierExpr("oldAlloc");
BoogieIdentifierExpr allocIdentExpr = new BoogieIdentifierExpr("Alloc");
// oldAlloc = Alloc
procBody.AddStatement(new BoogieAssignCmd(oldAllocIdentExpr, allocIdentExpr));
// havoc Alloc
procBody.AddStatement(new BoogieHavocCmd(allocIdentExpr));
// assume forall i:ref oldAlloc[i] ==> alloc[i]
var qVar = QVarGenerator.NewQVar(0, 0);
BoogieMapSelect allocMapSelect = new BoogieMapSelect(allocIdentExpr, qVar);
BoogieMapSelect oldAllocMapSelect = new BoogieMapSelect(oldAllocIdentExpr, qVar);
BoogieExpr allocAssumeExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.IMP, oldAllocMapSelect, allocMapSelect);
procBody.AddStatement(new BoogieAssumeCmd(new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() {qVar}, new List<BoogieType>() { BoogieType.Ref }, allocAssumeExpr)));
BoogieImplementation implementation = new BoogieImplementation(procName, inParams, outParams, localVars, procBody);
context.Program.AddDeclaration(implementation);
}
private void GenerateAxioms()
{
if (context.TranslateFlags.NoAxiomsFlag)
return;
context.Program.AddDeclaration(GenerateConstToRefAxiom());
context.Program.AddDeclaration(GenerateKeccakAxiom());
context.Program.AddDeclaration(GenerateAbiEncodePackedAxiomOneArg());
GenerateVeriSolSumAxioms().ForEach(x => context.Program.AddDeclaration(x));
context.Program.AddDeclaration(GenerateAbiEncodePackedAxiomTwoArgs());
context.Program.AddDeclaration(GenerateAbiEncodePackedAxiomOneArgRef());
context.Program.AddDeclaration(GenerateAbiEncodePackedAxiomTwoArgsOneRef());
}
private BoogieAxiom GenerateConstToRefAxiom()
{
var qVar1 = QVarGenerator.NewQVar(0, 0);
var qVar2 = QVarGenerator.NewQVar(0, 1);
var eqVar12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar1, qVar2);
var qVar1Func = new BoogieFuncCallExpr("ConstantToRef", new List<BoogieExpr>() { qVar1 });
var qVar2Func = new BoogieFuncCallExpr("ConstantToRef", new List<BoogieExpr>() { qVar2 });
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqVar12, eqFunc12);
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
// forall q1:int, q2:int :: q1 == q2 || ConstantToRef(q1) != ConstantToRef(q2)
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar1, qVar2 }, new List<BoogieType>() { BoogieType.Int, BoogieType.Int }, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private BoogieAxiom GenerateKeccakAxiom()
{
var qVar1 = QVarGenerator.NewQVar(0, 0);
var qVar2 = QVarGenerator.NewQVar(0, 1);
var eqVar12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar1, qVar2);
var qVar1Func = new BoogieFuncCallExpr("keccak256", new List<BoogieExpr>() { qVar1 });
var qVar2Func = new BoogieFuncCallExpr("keccak256", new List<BoogieExpr>() { qVar2 });
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqVar12, eqFunc12);
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
// forall q1:int, q2:int :: q1 == q2 || keccak256(q1) != keccak256(q2)
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar1, qVar2 }, new List<BoogieType>() { BoogieType.Int, BoogieType.Int }, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private BoogieAxiom GenerateAbiEncodePackedAxiomOneArg()
{
var qVar1 = QVarGenerator.NewQVar(0, 0);
var qVar2 = QVarGenerator.NewQVar(0, 1);
var eqVar12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar1, qVar2);
var qVar1Func = new BoogieFuncCallExpr("abiEncodePacked1", new List<BoogieExpr>() { qVar1 });
var qVar2Func = new BoogieFuncCallExpr("abiEncodePacked1", new List<BoogieExpr>() { qVar2 });
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqVar12, eqFunc12);
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
// forall q1:int, q2:int :: q1 == q2 || abiEncodePacked(q1) != abiEncodePacked(q2)
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar1, qVar2 }, new List<BoogieType>() { BoogieType.Int, BoogieType.Int }, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private BoogieAxiom GenerateAbiEncodePackedAxiomTwoArgs()
{
var qVar11 = QVarGenerator.NewQVar(0, 0);
var qVar12 = QVarGenerator.NewQVar(0, 1);
var qVar21 = QVarGenerator.NewQVar(1, 0);
var qVar22 = QVarGenerator.NewQVar(1, 1);
var eqVar1 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar11, qVar12);
var eqVar2 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar21, qVar22);
var qVar1Func = new BoogieFuncCallExpr("abiEncodePacked2", new List<BoogieExpr>() { qVar11, qVar21 });
var qVar2Func = new BoogieFuncCallExpr("abiEncodePacked2", new List<BoogieExpr>() { qVar12, qVar22 });
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var eqArgs = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.AND, eqVar1, eqVar2);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqArgs, eqFunc12);
// forall q1:int, q2:int, q1', q2' :: (q1 == q1' && q2 == q2') || abiEncodePacked(q1, q2) != abiEncodePacked(q1', q2')
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar11, qVar12, qVar21, qVar22 },
new List<BoogieType>() { BoogieType.Int, BoogieType.Int, BoogieType.Int, BoogieType.Int }, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private BoogieAxiom GenerateAbiEncodePackedAxiomOneArgRef()
{
var qVar1 = QVarGenerator.NewQVar(0, 0);
var qVar2 = QVarGenerator.NewQVar(0, 1);
var eqVar12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar1, qVar2);
var qVar1Func = new BoogieFuncCallExpr("abiEncodePacked1R", new List<BoogieExpr>() { qVar1 });
var qVar2Func = new BoogieFuncCallExpr("abiEncodePacked1R", new List<BoogieExpr>() { qVar2 });
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqVar12, eqFunc12);
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
// forall q1:int, q2:int :: q1 == q2 || abiEncodePacked(q1) != abiEncodePacked(q2)
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar1, qVar2 }, new List<BoogieType>() { BoogieType.Ref, BoogieType.Ref}, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private List<BoogieAxiom> GenerateVeriSolSumAxioms()
{
// axiom(forall m:[Ref]int :: (exists _a: Ref::m[_a] != 0) || _SumMapping_VeriSol(m) == 0);
var qVar1 = QVarGenerator.NewQVar(0, 0);
var qVar2 = QVarGenerator.NewQVar(0, 1);
var ma = new BoogieMapSelect(qVar1, qVar2);
var maEq0 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, ma, new BoogieLiteralExpr(System.Numerics.BigInteger.Zero));
var existsMaNeq0 = new BoogieQuantifiedExpr(false,
new List<BoogieIdentifierExpr>() { qVar2 },
new List<BoogieType>() { BoogieType.Ref },
maEq0,
null);
var sumM = new BoogieFuncCallExpr("_SumMapping_VeriSol", new List<BoogieExpr>() { qVar1 });
var sumMEq0 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, sumM, new BoogieLiteralExpr(System.Numerics.BigInteger.Zero));
var maEq0SumEq0 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, existsMaNeq0, sumMEq0);
var axiom1 = new BoogieQuantifiedExpr(true,
new List<BoogieIdentifierExpr>() { qVar1},
new List<BoogieType>() { new BoogieMapType(BoogieType.Ref, BoogieType.Int)},
maEq0SumEq0,
null);
// axiom(forall m:[Ref]int, _a: Ref, _b: int :: _SumMapping_VeriSol(m[_a:= _b]) == _SumMapping_VeriSol(m) - m[_a] + _b);
var qVar3 = QVarGenerator.NewQVar(0, 2);
var subExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.SUB, sumM, ma);
var addExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.ADD, subExpr, qVar3);
var updExpr = new BoogieMapUpdate(qVar1, qVar2, qVar3);
var sumUpdExpr = new BoogieFuncCallExpr("_SumMapping_VeriSol", new List<BoogieExpr>() {updExpr});
var sumUpdEqExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, sumUpdExpr, addExpr);
var axiom2 = new BoogieQuantifiedExpr(true,
new List<BoogieIdentifierExpr>() { qVar1, qVar2, qVar3 },
new List<BoogieType>() { new BoogieMapType(BoogieType.Ref, BoogieType.Int), BoogieType.Ref, BoogieType.Int },
sumUpdEqExpr,
null);
return new List<BoogieAxiom>() { new BoogieAxiom(axiom1), new BoogieAxiom(axiom2) };
}
private BoogieAxiom GenerateAbiEncodePackedAxiomTwoArgsOneRef()
{
var qVar11 = QVarGenerator.NewQVar(0, 0);
var qVar12 = QVarGenerator.NewQVar(0, 1);
var qVar21 = QVarGenerator.NewQVar(1, 0);
var qVar22 = QVarGenerator.NewQVar(1, 1);
var eqVar1 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar11, qVar12);
var eqVar2 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, qVar21, qVar22);
var qVar1Func = new BoogieFuncCallExpr("abiEncodePacked2R", new List<BoogieExpr>() { qVar11, qVar21 });
var qVar2Func = new BoogieFuncCallExpr("abiEncodePacked2R", new List<BoogieExpr>() { qVar12, qVar22 });
var triggers = new List<BoogieExpr>() { qVar1Func, qVar2Func };
var eqFunc12 = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.NEQ, qVar1Func, qVar2Func);
var eqArgs = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.AND, eqVar1, eqVar2);
var bodyExpr = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.OR, eqArgs, eqFunc12);
// forall q1:int, q2:int, q1', q2' :: (q1 == q1' && q2 == q2') || abiEncodePacked(q1, q2) != abiEncodePacked(q1', q2')
var qExpr = new BoogieQuantifiedExpr(true, new List<BoogieIdentifierExpr>() { qVar11, qVar12, qVar21, qVar22 },
new List<BoogieType>() { BoogieType.Ref, BoogieType.Ref, BoogieType.Int, BoogieType.Int }, bodyExpr, triggers);
return new BoogieAxiom(qExpr);
}
private void GenerateMemoryVariables()
{
HashSet<KeyValuePair<BoogieType, BoogieType>> generatedTypes = new HashSet<KeyValuePair<BoogieType, BoogieType>>();
// mappings
foreach (ContractDefinition contract in context.ContractToMappingsMap.Keys)
{
foreach (VariableDeclaration varDecl in context.ContractToMappingsMap[contract])
{
Debug.Assert(varDecl.TypeName is Mapping);
Mapping mapping = varDecl.TypeName as Mapping;
GenerateMemoryVariablesForMapping(mapping, generatedTypes);
}
}
// arrays
foreach (ContractDefinition contract in context.ContractToArraysMap.Keys)
{
foreach (VariableDeclaration varDecl in context.ContractToArraysMap[contract])
{
Debug.Assert(varDecl.TypeName is ArrayTypeName);
ArrayTypeName array = varDecl.TypeName as ArrayTypeName;
GenerateMemoryVariablesForArray(array, generatedTypes);
}
}
}
private void GenerateMemoryVariablesForMapping(Mapping mapping, HashSet<KeyValuePair<BoogieType, BoogieType>> generatedTypes)
{
BoogieType boogieKeyType = TransUtils.GetBoogieTypeFromSolidityTypeName(mapping.KeyType);
BoogieType boogieValType = null;
if (mapping.ValueType is Mapping submapping)
{
boogieValType = BoogieType.Ref;
GenerateMemoryVariablesForMapping(submapping, generatedTypes);
}
else if (mapping.ValueType is ArrayTypeName array)
{
boogieValType = BoogieType.Ref;
GenerateMemoryVariablesForArray(array, generatedTypes);
}
else
{
boogieValType = TransUtils.GetBoogieTypeFromSolidityTypeName(mapping.ValueType);
}
KeyValuePair<BoogieType, BoogieType> pair = new KeyValuePair<BoogieType,BoogieType>(boogieKeyType, boogieValType);
if (!generatedTypes.Contains(pair))
{
generatedTypes.Add(pair);
GenerateSingleMemoryVariable(boogieKeyType, boogieValType);
}
}
private void GenerateMemoryVariablesForArray(ArrayTypeName array, HashSet<KeyValuePair<BoogieType, BoogieType>> generatedTypes)
{
BoogieType boogieKeyType = BoogieType.Int;
BoogieType boogieValType = null;
if (array.BaseType is ArrayTypeName subarray)
{
boogieValType = BoogieType.Ref;
GenerateMemoryVariablesForArray(subarray, generatedTypes);
}
else if (array.BaseType is Mapping mapping)
{
boogieValType = BoogieType.Ref;
GenerateMemoryVariablesForMapping(mapping, generatedTypes);
}
else
{
boogieValType = TransUtils.GetBoogieTypeFromSolidityTypeName(array.BaseType);
}
KeyValuePair<BoogieType, BoogieType> pair = new KeyValuePair<BoogieType, BoogieType>(boogieKeyType, boogieValType);
if (!generatedTypes.Contains(pair))
{
generatedTypes.Add(pair);
GenerateSingleMemoryVariable(boogieKeyType, boogieValType);
}
}
private void GenerateSingleMemoryVariable(BoogieType keyType, BoogieType valType)
{
BoogieMapType map = new BoogieMapType(keyType, valType);
map = new BoogieMapType(BoogieType.Ref, map);
string name = MapArrayHelper.GetMemoryMapName(keyType, valType);
context.Program.AddDeclaration(new BoogieGlobalVariable(new BoogieTypedIdent(name, map)));
}
}
}
| 52.4375 | 189 | 0.623269 | [
"MIT"
] | shenshan/VeriSol | Sources/SolToBoogie/GhostVarAndAxiomGenerator.cs | 32,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shamisen.Filters.BiQuad.Cascaded
{
/// <summary>
/// Filters audio signal with multiple Digital BiQuad Filter.
/// </summary>
public sealed partial class CascadedBiQuadFilter : ISampleFilter
{
private bool disposedValue;
/// <summary>
/// Initializes a new instance of <see cref="CascadedBiQuadFilter"/>.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="parameters">The filters for all channels.</param>
/// <exception cref="ArgumentNullException"></exception>
public CascadedBiQuadFilter(IReadableAudioSource<float, SampleFormat> source, BiQuadParameter[] parameters)
{
int channels = source.Format.Channels;
Source = source;
}
/// <summary>
/// Initializes a new instance of <see cref="CascadedBiQuadFilter"/>.
/// </summary>
/// <param name="source"></param>
/// <param name="parameters"></param>
/// <exception cref="ArgumentNullException"></exception>
public CascadedBiQuadFilter(IReadableAudioSource<float, SampleFormat> source, CascadedBiQuadParameters parameters)
{
if (parameters.Channels != source.Format.Channels) throw new ArgumentException("", nameof(parameters));
Source = source;
}
/// <inheritdoc/>
public IReadableAudioSource<float, SampleFormat> Source { get; }
/// <inheritdoc/>
public SampleFormat Format { get; }
/// <inheritdoc/>
public ulong? Length { get; }
/// <inheritdoc/>
public ulong? TotalLength { get; }
/// <inheritdoc/>
public ulong? Position { get; }
/// <inheritdoc/>
public ISkipSupport? SkipSupport { get; }
/// <inheritdoc/>
public ISeekSupport? SeekSupport { get; }
/// <inheritdoc/>
public ReadResult Read(Span<float> buffer) => throw new NotImplementedException();
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
//
}
disposedValue = true;
}
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
| 31.271605 | 122 | 0.571654 | [
"Apache-2.0"
] | MineCake147E/MonoAudio | Shamisen/Filters/BiQuad/Cascaded/CascadedBiQuadFilter.cs | 2,535 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460/blob/master/LICENSE
*
*/
#endregion
using ComponentFactory.Krypton.Toolkit;
using KryptonExtendedToolkit.ExtendedToolkit.UI;
using System;
using System.Windows.Forms;
namespace KryptonExtendedToolkit.Base.ButtonSpec
{
/// <summary>
/// Implementation for the fixed maximize button for krypton form.
/// </summary>
public class ButtonSpecFormWindowMax : ButtonSpecFormFixed
{
#region Identity
/// <summary>
/// Initialize a new instance of the ButtonSpecFormWindowMax class.
/// </summary>
/// <param name="form">Reference to owning krypton form instance.</param>
public ButtonSpecFormWindowMax(KryptonFormWithDropShadow form)
: base(form, PaletteButtonSpecStyle.FormMax)
{
}
#endregion
#region IButtonSpecValues
/// <summary>
/// Gets the button visible value.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button visibiliy.</returns>
public override bool GetVisible(IPalette palette)
{
// We do not show if the custom chrome is combined with composition,
// in which case the form buttons are handled by the composition
if (KryptonForm.ApplyComposition && KryptonForm.ApplyCustomChrome)
{
return false;
}
// The maximize button is never present on tool windows
switch (KryptonForm.FormBorderStyle)
{
case FormBorderStyle.FixedToolWindow:
case FormBorderStyle.SizableToolWindow:
return false;
}
// Have all buttons been turned off?
if (!KryptonForm.ControlBox)
{
return false;
}
// Has the minimize/maximize buttons been turned off?
return KryptonForm.MinimizeBox || KryptonForm.MaximizeBox;
}
/// <summary>
/// Gets the button enabled state.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button enabled state.</returns>
public override ButtonEnabled GetEnabled(IPalette palette)
{
// Has the maximize buttons been turned off?
return !KryptonForm.MaximizeBox ? ButtonEnabled.False : ButtonEnabled.True;
}
/// <summary>
/// Gets the button checked state.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button checked state.</returns>
public override ButtonCheckState GetChecked(IPalette palette)
{
// Close button is never shown as checked
return ButtonCheckState.NotCheckButton;
}
#endregion
#region Protected Overrides
/// <summary>
/// Raises the Click event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnClick(EventArgs e)
{
// Only if associated view is enabled to we perform an action
if (GetViewEnabled())
{
// If we do not provide an inert form
if (!KryptonForm.InertForm)
{
// Only if the mouse is still within the button bounds do we perform action
MouseEventArgs mea = (MouseEventArgs)e;
if (GetView().ClientRectangle.Contains(mea.Location))
{
// Toggle between maximized and restored
//KryptonForm.SendSysCommand(KryptonForm.WindowState == FormWindowState.Maximized
// ? PI.SC_RESTORE
// : PI.SC_MAXIMIZE);
// Let base class fire any other attached events
base.OnClick(e);
}
}
}
}
#endregion
}
} | 36.294118 | 105 | 0.572818 | [
"BSD-3-Clause"
] | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460 | Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/Base/ButtonSpec/ButtonSpecFormWindowMax.cs | 4,321 | C# |
using FluentAssertions.Execution;
using Xunit;
namespace FluentAssertions.Specs.Execution;
/// <content>
/// The chaining API specs.
/// </content>
public partial class AssertionScopeSpecs
{
[Fact]
public void Get_value_when_key_is_present()
{
// Arrange
var scope = new AssertionScope();
scope.AddNonReportable("SomeKey", "SomeValue");
scope.AddNonReportable("SomeOtherKey", "SomeOtherValue");
// Act
var value = scope.Get<string>("SomeKey");
// Assert
value.Should().Be("SomeValue");
}
[Fact]
public void Get_default_value_when_key_is_not_present()
{
// Arrange
var scope = new AssertionScope();
// Act
var value = scope.Get<int>("SomeKey");
// Assert
value.Should().Be(0);
}
[Fact]
public void Get_default_value_when_nullable_value_is_null()
{
// Arrange
var scope = new AssertionScope();
#pragma warning disable IDE0004 // Remove Unnecessary Cast
scope.AddNonReportable("SomeKey", (int?)null);
#pragma warning restore IDE0004 // Remove Unnecessary Cast
// Act
var value = scope.Get<int>("SomeKey");
// Assert
value.Should().Be(0);
}
[Fact]
public void Value_should_be_of_requested_type()
{
// Arrange
var scope = new AssertionScope();
scope.AddNonReportable("SomeKey", "SomeValue");
// Act
var value = scope.Get<string>("SomeKey");
// Assert
value.Should().BeOfType<string>();
}
}
| 23 | 65 | 0.601134 | [
"Apache-2.0"
] | IT-VBFK/fluentassertions | Tests/FluentAssertions.Specs/Execution/AssertionScope.ContextDataSpecs.cs | 1,589 | 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.
// This RegexWriter class is internal to the Regex package.
// It builds a block of regular expression codes (RegexCode)
// from a RegexTree parse tree.
// Implementation notes:
//
// This step is as simple as walking the tree and emitting
// sequences of codes.
//
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal sealed class RegexWriter
{
private int[] _intStack;
private int _depth;
private int[] _emitted;
private int _curpos;
private readonly Dictionary<string, int> _stringhash;
private readonly List<String> _stringtable;
private bool _counting;
private int _count;
private int _trackcount;
private Hashtable _caps;
private const int BeforeChild = 64;
private const int AfterChild = 128;
/// <summary>
/// This is the only function that should be called from outside.
/// It takes a RegexTree and creates a corresponding RegexCode.
/// </summary>
internal static RegexCode Write(RegexTree t)
{
RegexWriter w = new RegexWriter();
RegexCode retval = w.RegexCodeFromRegexTree(t);
#if DEBUG
if (t.Debug)
{
t.Dump();
retval.Dump();
}
#endif
return retval;
}
// Private constructor; can't be created outside
private RegexWriter()
{
_intStack = new int[32];
_emitted = new int[32];
_stringhash = new Dictionary<string, int>();
_stringtable = new List<String>();
}
/// <summary>
/// To avoid recursion, we use a simple integer stack.
/// This is the push.
/// </summary>
private void PushInt(int i)
{
if (_depth >= _intStack.Length)
{
int[] expanded = new int[_depth * 2];
Array.Copy(_intStack, 0, expanded, 0, _depth);
_intStack = expanded;
}
_intStack[_depth++] = i;
}
/// <summary>
/// <c>true</c> if the stack is empty.
/// </summary>
private bool EmptyStack()
{
return _depth == 0;
}
/// <summary>
/// This is the pop.
/// </summary>
private int PopInt()
{
return _intStack[--_depth];
}
/// <summary>
/// Returns the current position in the emitted code.
/// </summary>
private int CurPos()
{
return _curpos;
}
/// <summary>
/// Fixes up a jump instruction at the specified offset
/// so that it jumps to the specified jumpDest.
/// </summary>
private void PatchJump(int offset, int jumpDest)
{
_emitted[offset + 1] = jumpDest;
}
/// <summary>
/// Emits a zero-argument operation. Note that the emit
/// functions all run in two modes: they can emit code, or
/// they can just count the size of the code.
/// </summary>
private void Emit(int op)
{
if (_counting)
{
_count += 1;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
}
/// <summary>
/// Emits a one-argument operation.
/// </summary>
private void Emit(int op, int opd1)
{
if (_counting)
{
_count += 2;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
_emitted[_curpos++] = opd1;
}
/// <summary>
/// Emits a two-argument operation.
/// </summary>
private void Emit(int op, int opd1, int opd2)
{
if (_counting)
{
_count += 3;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
_emitted[_curpos++] = opd1;
_emitted[_curpos++] = opd2;
}
/// <summary>
/// Returns an index in the string table for a string;
/// uses a hashtable to eliminate duplicates.
/// </summary>
private int StringCode(String str)
{
if (_counting)
return 0;
if (str == null)
str = String.Empty;
Int32 i;
if (!_stringhash.TryGetValue(str, out i))
{
i = _stringtable.Count;
_stringhash[str] = i;
_stringtable.Add(str);
}
return i;
}
/// <summary>
/// When generating code on a regex that uses a sparse set
/// of capture slots, we hash them to a dense set of indices
/// for an array of capture slots. Instead of doing the hash
/// at match time, it's done at compile time, here.
/// </summary>
private int MapCapnum(int capnum)
{
if (capnum == -1)
return -1;
if (_caps != null)
return (int)_caps[capnum];
else
return capnum;
}
/// <summary>
/// The top level RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
///
/// It runs two passes, first to count the size of the generated
/// code, and second to generate the code.
///
/// We should time it against the alternative, which is
/// to just generate the code and grow the array as we go.
/// </summary>
private RegexCode RegexCodeFromRegexTree(RegexTree tree)
{
RegexNode curNode;
int curChild;
int capsize;
RegexPrefix fcPrefix;
RegexPrefix prefix;
int anchors;
RegexBoyerMoore bmPrefix;
bool rtl;
// construct sparse capnum mapping if some numbers are unused
if (tree._capnumlist == null || tree._captop == tree._capnumlist.Length)
{
capsize = tree._captop;
_caps = null;
}
else
{
capsize = tree._capnumlist.Length;
_caps = tree._caps;
for (int i = 0; i < tree._capnumlist.Length; i++)
_caps[tree._capnumlist[i]] = i;
}
_counting = true;
for (; ;)
{
if (!_counting)
_emitted = new int[_count];
curNode = tree._root;
curChild = 0;
Emit(RegexCode.Lazybranch, 0);
for (; ;)
{
if (curNode._children == null)
{
EmitFragment(curNode._type, curNode, 0);
}
else if (curChild < curNode._children.Count)
{
EmitFragment(curNode._type | BeforeChild, curNode, curChild);
curNode = (RegexNode)curNode._children[curChild];
PushInt(curChild);
curChild = 0;
continue;
}
if (EmptyStack())
break;
curChild = PopInt();
curNode = curNode._next;
EmitFragment(curNode._type | AfterChild, curNode, curChild);
curChild++;
}
PatchJump(0, CurPos());
Emit(RegexCode.Stop);
if (!_counting)
break;
_counting = false;
}
fcPrefix = RegexFCD.FirstChars(tree);
prefix = RegexFCD.Prefix(tree);
rtl = ((tree._options & RegexOptions.RightToLeft) != 0);
CultureInfo culture = (tree._options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
if (prefix != null && prefix.Prefix.Length > 0)
bmPrefix = new RegexBoyerMoore(prefix.Prefix, prefix.CaseInsensitive, rtl, culture);
else
bmPrefix = null;
anchors = RegexFCD.Anchors(tree);
return new RegexCode(_emitted, _stringtable, _trackcount, _caps, capsize, bmPrefix, fcPrefix, anchors, rtl);
}
/// <summary>
/// The main RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
/// </summary>
private void EmitFragment(int nodetype, RegexNode node, int curIndex)
{
int bits = 0;
if (nodetype <= RegexNode.Ref)
{
if (node.UseOptionR())
bits |= RegexCode.Rtl;
if ((node._options & RegexOptions.IgnoreCase) != 0)
bits |= RegexCode.Ci;
}
switch (nodetype)
{
case RegexNode.Concatenate | BeforeChild:
case RegexNode.Concatenate | AfterChild:
case RegexNode.Empty:
break;
case RegexNode.Alternate | BeforeChild:
if (curIndex < node._children.Count - 1)
{
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
}
break;
case RegexNode.Alternate | AfterChild:
{
if (curIndex < node._children.Count - 1)
{
int LBPos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(LBPos, CurPos());
}
else
{
int I;
for (I = 0; I < curIndex; I++)
{
PatchJump(PopInt(), CurPos());
}
}
break;
}
case RegexNode.Testref | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
Emit(RegexCode.Testref, MapCapnum(node._m));
Emit(RegexCode.Forejump);
break;
}
break;
case RegexNode.Testref | AfterChild:
switch (curIndex)
{
case 0:
{
int Branchpos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, CurPos());
Emit(RegexCode.Forejump);
if (node._children.Count > 1)
break;
// else fallthrough
goto case 1;
}
case 1:
PatchJump(PopInt(), CurPos());
break;
}
break;
case RegexNode.Testgroup | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
break;
}
break;
case RegexNode.Testgroup | AfterChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
break;
case 1:
int Branchpos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, CurPos());
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
if (node._children.Count > 2)
break;
// else fallthrough
goto case 2;
case 2:
PatchJump(PopInt(), CurPos());
break;
}
break;
case RegexNode.Loop | BeforeChild:
case RegexNode.Lazyloop | BeforeChild:
if (node._n < Int32.MaxValue || node._m > 1)
Emit(node._m == 0 ? RegexCode.Nullcount : RegexCode.Setcount, node._m == 0 ? 0 : 1 - node._m);
else
Emit(node._m == 0 ? RegexCode.Nullmark : RegexCode.Setmark);
if (node._m == 0)
{
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
}
PushInt(CurPos());
break;
case RegexNode.Loop | AfterChild:
case RegexNode.Lazyloop | AfterChild:
{
int StartJumpPos = CurPos();
int Lazy = (nodetype - (RegexNode.Loop | AfterChild));
if (node._n < Int32.MaxValue || node._m > 1)
Emit(RegexCode.Branchcount + Lazy, PopInt(), node._n == Int32.MaxValue ? Int32.MaxValue : node._n - node._m);
else
Emit(RegexCode.Branchmark + Lazy, PopInt());
if (node._m == 0)
PatchJump(PopInt(), StartJumpPos);
}
break;
case RegexNode.Group | BeforeChild:
case RegexNode.Group | AfterChild:
break;
case RegexNode.Capture | BeforeChild:
Emit(RegexCode.Setmark);
break;
case RegexNode.Capture | AfterChild:
Emit(RegexCode.Capturemark, MapCapnum(node._m), MapCapnum(node._n));
break;
case RegexNode.Require | BeforeChild:
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
break;
case RegexNode.Require | AfterChild:
Emit(RegexCode.Getmark);
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Forejump);
break;
case RegexNode.Prevent | BeforeChild:
Emit(RegexCode.Setjump);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
break;
case RegexNode.Prevent | AfterChild:
Emit(RegexCode.Backjump);
PatchJump(PopInt(), CurPos());
Emit(RegexCode.Forejump);
break;
case RegexNode.Greedy | BeforeChild:
Emit(RegexCode.Setjump);
break;
case RegexNode.Greedy | AfterChild:
Emit(RegexCode.Forejump);
break;
case RegexNode.One:
case RegexNode.Notone:
Emit(node._type | bits, (int)node._ch);
break;
case RegexNode.Notoneloop:
case RegexNode.Notonelazy:
case RegexNode.Oneloop:
case RegexNode.Onelazy:
if (node._m > 0)
Emit(((node._type == RegexNode.Oneloop || node._type == RegexNode.Onelazy) ?
RegexCode.Onerep : RegexCode.Notonerep) | bits, (int)node._ch, node._m);
if (node._n > node._m)
Emit(node._type | bits, (int)node._ch, node._n == Int32.MaxValue ?
Int32.MaxValue : node._n - node._m);
break;
case RegexNode.Setloop:
case RegexNode.Setlazy:
if (node._m > 0)
Emit(RegexCode.Setrep | bits, StringCode(node._str), node._m);
if (node._n > node._m)
Emit(node._type | bits, StringCode(node._str),
(node._n == Int32.MaxValue) ? Int32.MaxValue : node._n - node._m);
break;
case RegexNode.Multi:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Set:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Ref:
Emit(node._type | bits, MapCapnum(node._m));
break;
case RegexNode.Nothing:
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.Nonboundary:
case RegexNode.ECMABoundary:
case RegexNode.NonECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
Emit(node._type);
break;
default:
throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString(CultureInfo.CurrentCulture)));
}
}
}
}
| 34.114437 | 147 | 0.439955 | [
"MIT"
] | OlliSaarikivi/sre | Core/NetRegexParser/RegexWriter.cs | 19,377 | C# |
using System;
namespace SocketPacket.Network {
[Serializable]
public class StringPacket : Packet {
public string[] data;
public StringPacket() { }
public StringPacket(string[] data) {
this.data = data;
}
}
}
| 19.071429 | 44 | 0.576779 | [
"MIT"
] | skyneton/SocketPacket | SocketPacket/SocketPacket/Network/StringPacket.cs | 269 | C# |
using System.Collections.Generic;
using UnityEngine;
using Jotunn.Entities;
namespace Jotunn.Configs
{
/// <summary>
/// Configuration class for adding custom recipes.
/// </summary>
public class RecipeConfig
{
/// <summary>
/// The unique name for your recipe.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// The name of the item prefab that this recipe should create.
/// </summary>
public string Item { get; set; } = string.Empty;
/// <summary>
/// The amount of <see cref="Item"/> that will be created from this Recipe. Defaults to <c>1</c>.
/// </summary>
public int Amount { get; set; } = 1;
/// <summary>
/// Whether this recipe is craftable or not. Defaults to true.
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// The name of the crafting station prefab where this recipe can be crafted.
/// <br/>
/// Can be set to <c>null</c> to have the recipe be craftable without a crafting station.
/// </summary>
public string CraftingStation { get; set; } = string.Empty;
/// <summary>
/// The name of the crafting station prefab where this item can be repaired.
/// <br/>
/// Can be set to <c>null</c> to have the recipe be repairable without a crafting station.
/// </summary>
public string RepairStation { get; set; } = string.Empty;
/// <summary>
/// The minimum required level for the crafting station. Defaults to <c>0</c>.
/// </summary>
public int MinStationLevel { get; set; } = 0;
/// <summary>
/// Array of <see cref="RequirementConfig"/>s for all crafting materials it takes to craft the recipe.
/// </summary>
public RequirementConfig[] Requirements { get; set; } = new RequirementConfig[0];
/// <summary>
/// Converts the RequirementConfigs to Valheim style Piece.Requirements
/// </summary>
/// <returns>The Valheim Piece.Requirement array</returns>
public Piece.Requirement[] GetRequirements()
{
Piece.Requirement[] reqs = new Piece.Requirement[Requirements.Length];
for (int i = 0; i < reqs.Length; i++)
{
reqs[i] = Requirements[i].GetRequirement();
}
return reqs;
}
/// <summary>
/// Converts the RecipeConfig to a Valheim style Recipe.
/// </summary>
/// <returns>The Valheim recipe</returns>
public Recipe GetRecipe()
{
if (Item == null)
{
Logger.LogError($"No item set in recipe config");
return null;
}
var recipe = ScriptableObject.CreateInstance<Recipe>();
var name = Name;
if (string.IsNullOrEmpty(name))
{
name = "Recipe_" + Item;
}
recipe.name = name;
recipe.m_item = Mock<ItemDrop>.Create(Item);
recipe.m_amount = Amount;
recipe.m_enabled = Enabled;
if (!string.IsNullOrEmpty(CraftingStation))
{
recipe.m_craftingStation = Mock<CraftingStation>.Create(CraftingStation);
}
if (!string.IsNullOrEmpty(RepairStation))
{
recipe.m_repairStation = Mock<CraftingStation>.Create(RepairStation);
}
recipe.m_minStationLevel = MinStationLevel;
recipe.m_resources = GetRequirements();
return recipe;
}
/// <summary>
/// Loads a single RecipeConfig from a JSON string.
/// </summary>
/// <param name="json">JSON text</param>
/// <returns>Loaded RecipeConfig</returns>
public static RecipeConfig FromJson(string json)
{
return SimpleJson.SimpleJson.DeserializeObject<RecipeConfig>(json);
}
/// <summary>
/// Loads a list of RecipeConfigs from a JSON string.
/// </summary>
/// <param name="json">JSON text</param>
/// <returns>Loaded list of RecipeConfigs</returns>
public static List<RecipeConfig> ListFromJson(string json)
{
return SimpleJson.SimpleJson.DeserializeObject<List<RecipeConfig>>(json);
}
}
}
| 33.748148 | 114 | 0.546532 | [
"MIT"
] | Dominowood371/Jotunn | JotunnLib/Configs/RecipeConfig.cs | 4,558 | C# |
#region
using System;
using System.Reflection;
using System.Runtime.Serialization;
#endregion
namespace CoreLib.CORE.Helpers.AssemblyHelpers
{
/// <summary>
/// <see cref="SerializationBinder"/> that uses <see cref="SearchTypeHelper"/> to search the type of object
/// </summary>
public sealed class SearchAssembliesBinder : SerializationBinder
{
private readonly SearchTypeHelper _searchTypeHelper;
/// <summary>
/// <see cref="SerializationBinder"/> that uses <see cref="SearchTypeHelper"/> to search the type of object
/// </summary>
/// <param name="currentAssembly">Current assembly</param>
/// <param name="searchInDlls">Enable search in dependent assemblies</param>
public SearchAssembliesBinder(Assembly currentAssembly, bool searchInDlls)
{
_searchTypeHelper = new SearchTypeHelper(currentAssembly, searchInDlls);
}
public override Type BindToType(string assemblyName, string typeName)
{
return _searchTypeHelper.GetTypeToDeserialize(typeName);
}
}
} | 33.606061 | 115 | 0.683499 | [
"MIT"
] | ExLuzZziVo/CoreLib | CoreLib.CORE/Helpers/AssemblyHelpers/SearchAssembliesBinder.cs | 1,111 | C# |
using System.Collections;
using System.Management.Automation;
using Cognifide.PowerShell.Commandlets.Interactive.Messages;
using Sitecore;
using Sitecore.Jobs.AsyncUI;
using Sitecore.Text;
using Sitecore.Web;
namespace Cognifide.PowerShell.Commandlets.Interactive
{
[Cmdlet(VerbsCommon.Show, "ModalDialog")]
[OutputType(typeof (string))]
public class ShowModalDialogCommand : BaseFormCommand
{
[Parameter(Mandatory = true, ParameterSetName = "Dialog from control name")]
public string Control { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Dialog from Url")]
public string Url { get; set; }
[Parameter(ParameterSetName = "Dialog from control name")]
public Hashtable Parameters { get; set; }
[Parameter]
public Hashtable HandleParameters { get; set; }
protected override void ProcessRecord()
{
LogErrors(() =>
{
if (!CheckSessionCanDoInteractiveAction())
{
WriteObject("error");
return;
}
string response = null;
if (!string.IsNullOrEmpty(Url))
{
response = JobContext.ShowModalDialog(Url, WidthString, HeightString);
}
else if (!string.IsNullOrEmpty(Control))
{
UrlString url = new UrlString(UIUtil.GetUri("control:" + Control));
url["te"] = Title ?? "Sitecore";
if (Parameters != null)
{
foreach (string key in Parameters.Keys)
{
url.Add(key, WebUtil.SafeEncode(Parameters[key].ToString()));
}
}
var message = new ShowModalDialogPsMessage(url.ToString(), WidthString, HeightString, HandleParameters);
PutMessage(message);
response = (string) message.GetResult();
}
WriteObject(response);
});
}
}
} | 33.828125 | 124 | 0.534873 | [
"MIT"
] | Krusen/Console | Cognifide.PowerShell/Commandlets/Interactive/ShowModalDialogCommand.cs | 2,167 | C# |
using UnityEngine;
using UnityEngine.UI;
public class ToggleController : MonoBehaviour {
private void Start()
{
if(GridManager.Instance.CanDiagonalMove)
{
GetComponent<Toggle>().isOn = GridManager.Instance.CanDiagonalMove;
}
}
public void SetDiagonalMove(bool isCan)
{
GridManager.Instance.CanDiagonalMove = isCan;
}
}
| 19.6 | 79 | 0.65051 | [
"MIT"
] | scolia/A-star-demo | Assets/Scripts/ToggleController.cs | 394 | C# |
using System;
using System.IO;
using NUnit.Framework;
using SharpNose.SDK;
namespace SharpNose.Tests
{
public abstract class TestFrameworkTestBase
{
[TestFixtureSetUp]
public void SetUp()
{
if (Directory.Exists(SimpleAssemblyPath) == false)
{
Directory.CreateDirectory(SimpleAssemblyPath);
}
File.Copy(@".\" + NunitSimpleAssemblyName, NunitSimpleAssemblyFullName, true);
File.Copy(@".\" + MsTestSimpleAssemblyName, MsTestSimpleAssemblyFullName, true);
if (Directory.Exists(MultipleAssemblyPath) == false)
{
Directory.CreateDirectory(MultipleAssemblyPath);
}
File.Copy(@".\" + NunitSimpleAssemblyName, MultipleAssemblyPath + "\\" + NunitSimpleAssemblyName, true);
File.Copy(@".\" + NunitSimpleAssembly2Name, MultipleAssemblyPath + "\\" + NunitSimpleAssembly2Name, true);
File.Copy(@".\" + MsTestSimpleAssemblyName, MultipleAssemblyPath + "\\" + MsTestSimpleAssemblyName, true);
File.Copy(@".\" + MsTestSimpleAssembly2Name, MultipleAssemblyPath + "\\" + MsTestSimpleAssembly2Name, true);
}
[TestFixtureTearDown]
public void TearDown()
{
if (Directory.Exists(SimpleAssemblyPath))
{
try
{
Directory.Delete(SimpleAssemblyPath, true);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
if (Directory.Exists(MultipleAssemblyPath))
{
try
{
Directory.Delete(MultipleAssemblyPath, true);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
internal ValidDotNetAssemblies GetValidDotNetAssembliesFromPath(string path)
{
return
new ValidDotNetAssemblies(
new ValidAssemblyDiscovery(
new ArgumentParser(
new[] {path})
)
);
}
internal string NunitSimpleAssemblyName
{
get
{
return "SharpNose.Tests.Classes.dll";
}
}
internal string MsTestSimpleAssemblyName
{
get
{
return "SharpNose.Tests.MsTest.Classes.dll";
}
}
internal string NunitSimpleAssembly2Name
{
get
{
return "SharpNose.Tests.Classes2.dll";
}
}
internal string MsTestSimpleAssembly2Name
{
get
{
return "SharpNose.Tests.MsTest.Classes2.dll";
}
}
internal string SimpleAssemblyPath
{
get
{
return Path.GetTempPath() + @"\TestClasses";
}
}
internal string MultipleAssemblyPath
{
get
{
return Path.GetTempPath() + @"\TestClasses2";
}
}
internal string NunitSimpleAssemblyFullName
{
get
{
return SimpleAssemblyPath + "\\" + NunitSimpleAssemblyName;
}
}
internal string MsTestSimpleAssemblyFullName
{
get
{
return SimpleAssemblyPath + "\\" + MsTestSimpleAssemblyName;
}
}
}
}
| 28.61194 | 121 | 0.467397 | [
"MIT"
] | dhelper/SharpNose | SharpNose.Tests/TestFrameworkTestBase.cs | 3,834 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class PrivateImplementationBClass : PrivateImplementationAClass, IPrivateImplementationB, IPrivateOverriddenImplementation
{
[JsonIgnore]
public string PropertyB { get; set; }
[JsonProperty("PropertyB")]
string IPrivateImplementationB.PropertyB
{
get { return this.PropertyB; }
set { this.PropertyB = value; }
}
[JsonProperty("OverriddenProperty")]
private string OverriddenPropertyString
{
get { return this.OverriddenProperty.ToString(); }
set { this.OverriddenProperty = value; }
}
[JsonIgnore]
public object OverriddenProperty { get; set; }
[JsonIgnore]
object IPrivateOverriddenImplementation.OverriddenProperty
{
get { return this.OverriddenProperty; }
set { this.OverriddenProperty = value; }
}
}
} | 35.45614 | 131 | 0.73429 | [
"MIT"
] | Chimpaneez/LiveSplit | LiveSplit/Libs/JSON.Net/Source/Src/Newtonsoft.Json.Tests/TestObjects/PrivateImplementationBClass.cs | 2,023 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Confuser.Core;
using Confuser.Core.Helpers;
using Confuser.DynCipher;
using Confuser.DynCipher.AST;
using Confuser.DynCipher.Generation;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
namespace Confuser.Protections.Constants {
internal class DynamicMode : IEncodeMode {
private Action<uint[], uint[]> encryptFunc;
public IEnumerable<Instruction> EmitDecrypt(MethodDef init, CEContext ctx, Local block, Local key) {
StatementBlock encrypt, decrypt;
ctx.DynCipher.GenerateCipherPair(ctx.Random, out encrypt, out decrypt);
var ret = new List<Instruction>();
var codeGen = new CodeGen(block, key, init, ret);
codeGen.GenerateCIL(decrypt);
codeGen.Commit(init.Body);
var dmCodeGen = new DMCodeGen(typeof (void), new[] {
Tuple.Create("{BUFFER}", typeof (uint[])),
Tuple.Create("{KEY}", typeof (uint[]))
});
dmCodeGen.GenerateCIL(encrypt);
encryptFunc = dmCodeGen.Compile<Action<uint[], uint[]>>();
return ret;
}
public uint[] Encrypt(uint[] data, int offset, uint[] key) {
var ret = new uint[key.Length];
Buffer.BlockCopy(data, offset * sizeof (uint), ret, 0, key.Length * sizeof (uint));
encryptFunc(ret, key);
return ret;
}
public object CreateDecoder(MethodDef decoder, CEContext ctx) {
uint k1 = ctx.Random.NextUInt32() | 1;
uint k2 = ctx.Random.NextUInt32();
MutationHelper.ReplacePlaceholder(decoder, arg => {
var repl = new List<Instruction>();
repl.AddRange(arg);
repl.Add(Instruction.Create(OpCodes.Ldc_I4, (int)MathsUtils.modInv(k1)));
repl.Add(Instruction.Create(OpCodes.Mul));
repl.Add(Instruction.Create(OpCodes.Ldc_I4, (int)k2));
repl.Add(Instruction.Create(OpCodes.Xor));
return repl.ToArray();
});
return Tuple.Create(k1, k2);
}
public uint Encode(object data, CEContext ctx, uint id) {
var key = (Tuple<uint, uint>)data;
uint ret = (id ^ key.Item2) * key.Item1;
Debug.Assert(((ret * MathsUtils.modInv(key.Item1)) ^ key.Item2) == id);
return ret;
}
private class CodeGen : CILCodeGen {
private readonly Local block;
private readonly Local key;
public CodeGen(Local block, Local key, MethodDef init, IList<Instruction> instrs)
: base(init, instrs) {
this.block = block;
this.key = key;
}
protected override Local Var(Variable var) {
if (var.Name == "{BUFFER}")
return block;
if (var.Name == "{KEY}")
return key;
return base.Var(var);
}
}
}
} | 30.409639 | 102 | 0.685024 | [
"MIT"
] | ambyte/ConfuserEx | Confuser.Protections/Constants/DynamicMode.cs | 2,526 | C# |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Security.Cryptography.Ciphers;
using Renci.SshNet.Security.Cryptography.Ciphers.Paddings;
using Renci.SshNet.Tests.Common;
namespace Renci.SshNet.Tests.Classes.Security.Cryptography
{
[TestClass]
public class BlockCipherTest : TestBase
{
[TestMethod]
public void EncryptShouldTakeIntoAccountPaddingForLengthOfOutputBufferPassedToEncryptBlock()
{
var input = new byte[] { 0x2c, 0x1a, 0x05, 0x00, 0x68 };
var output = new byte[] { 0x0a, 0x00, 0x03, 0x02, 0x06, 0x08, 0x07, 0x05 };
var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
var blockCipher = new BlockCipherStub(key, 8, null, new PKCS5Padding())
{
EncryptBlockDelegate = (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset) =>
{
Assert.AreEqual(8, outputBuffer.Length);
Buffer.BlockCopy(output, 0, outputBuffer, 0, output.Length);
return inputBuffer.Length;
}
};
var actual = blockCipher.Encrypt(input);
Assert.IsTrue(output.SequenceEqual(actual));
}
[TestMethod]
public void DecryptShouldTakeIntoAccountPaddingForLengthOfOutputBufferPassedToDecryptBlock()
{
var input = new byte[] { 0x2c, 0x1a, 0x05, 0x00, 0x68 };
var output = new byte[] { 0x0a, 0x00, 0x03, 0x02, 0x06, 0x08, 0x07, 0x05 };
var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
var blockCipher = new BlockCipherStub(key, 8, null, new PKCS5Padding())
{
DecryptBlockDelegate = (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset) =>
{
Assert.AreEqual(8, outputBuffer.Length);
Buffer.BlockCopy(output, 0, outputBuffer, 0, output.Length);
return inputBuffer.Length;
}
};
var actual = blockCipher.Decrypt(input);
Assert.IsTrue(output.SequenceEqual(actual));
}
private class BlockCipherStub : BlockCipher
{
public Func<byte[], int, int, byte[], int, int> EncryptBlockDelegate;
public Func<byte[], int, int, byte[], int, int> DecryptBlockDelegate;
public BlockCipherStub(byte[] key, byte blockSize, CipherMode mode, CipherPadding padding) : base(key, blockSize, mode, padding)
{
}
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
return EncryptBlockDelegate(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
return DecryptBlockDelegate(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
}
}
}
| 44.307692 | 140 | 0.594329 | [
"MIT"
] | 0xced/SSH.NET | src/Renci.SshNet.Tests/Classes/Security/Cryptography/BlockCipherTest.cs | 3,458 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrewItem : Item
{
public override void Fix()
{
if (itemHealth >= maxItemHealth)
{
itemState = STATE_PERFECT;
animator.SetBool("Sick", false);
AfterFix();
}
if (itemHealth <= maxItemHealth) itemHealth++;
}
internal override void Broke()
{
itemHealth = 0;
itemState = STATE_BROKEN;
animator.SetBool("Sick", true);
}
}
| 19.740741 | 54 | 0.572233 | [
"MIT"
] | enoble2009/GGJ2020-UNITY | Assets/Scripts/Items/CrewItem.cs | 535 | C# |
using FileServer.Common.Extensions;
using FileServer.FileProvider;
using Microsoft.Extensions.Options;
using Minio;
using Minio.Exceptions;
using System;
using System.IO;
using System.Threading.Tasks;
namespace FileServer.Minio
{
public class MinioProvider : FileProviderHandler
{
protected IFilePathCalculator MinioBlobNameCalculator { get; }
private readonly MinioOptions Options;
public MinioProvider(IFilePathCalculator minioBlobNameCalculator, IOptions<MinioOptions> options)
{
MinioBlobNameCalculator = minioBlobNameCalculator;
Options = options?.Value;
}
public override async Task SaveAsync(BlobProviderSaveArgs args)
{
var blobName = MinioBlobNameCalculator.Calculate(args);
var client = GetMinioClient(args);
var containerName = GetContainerName();
if (!args.OverrideExisting && await BlobExistsAsync(client, containerName, blobName))
{
throw new Exception($"Saving BLOB '{args.BlobName}' does already exists in the container '{containerName}'! Set {nameof(args.OverrideExisting)} if it should be overwritten.");
}
if (Options.CreateBucketIfNotExists)
{
await CreateBucketIfNotExists(client, containerName);
}
await client.PutObjectAsync(containerName, blobName, args.BlobStream, args.BlobStream.Length);
}
public override async Task<bool> DeleteAsync(BlobProviderDeleteArgs args)
{
var blobName = MinioBlobNameCalculator.Calculate(args);
var client = GetMinioClient(args);
var containerName = GetContainerName();
if (await BlobExistsAsync(client, containerName, blobName))
{
await client.RemoveObjectAsync(containerName, blobName);
return true;
}
return false;
}
public override async Task<bool> ExistsAsync(BlobProviderExistsArgs args)
{
var blobName = MinioBlobNameCalculator.Calculate(args);
var client = GetMinioClient(args);
var containerName = GetContainerName();
return await BlobExistsAsync(client, containerName, blobName);
}
public override async Task<Stream> GetOrNullAsync(BlobProviderGetArgs args)
{
var blobName = MinioBlobNameCalculator.Calculate(args);
var client = GetMinioClient(args);
var containerName = GetContainerName();
if (!await BlobExistsAsync(client, containerName, blobName))
{
return null;
}
var memoryStream = new MemoryStream();
await client.GetObjectAsync(containerName, blobName, (stream) =>
{
if (stream != null)
{
stream.CopyTo(memoryStream);
}
else
{
memoryStream = null;
}
});
//必须将流的当前位置置0,否则将引发异常
//如果不设置为0,则流的当前位置在流的末端1629,然后读流就会从索引1629开始读取,实际上流的最大索引是1628,就会引发无效操作异常System.InvalidOperationException
//System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 1628)
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
public virtual MinioClient GetMinioClient(BlobProviderArgs args)
{
var client = new MinioClient(Options.EndPoint, Options.AccessKey, Options.SecretKey);
if (Options.WithSSL)
{
client.WithSSL();
}
return client;
}
public virtual async Task CreateBucketIfNotExists(MinioClient client, string containerName)
{
if (!await client.BucketExistsAsync(containerName))
{
await client.MakeBucketAsync(containerName);
}
}
public virtual async Task<bool> BlobExistsAsync(MinioClient client, string containerName, string blobName)
{
// Make sure Blob Container exists.
if (await client.BucketExistsAsync(containerName))
{
try
{
await client.StatObjectAsync(containerName, blobName);
}
catch (Exception e)
{
if (e is ObjectNotFoundException)
{
return false;
}
throw;
}
return true;
}
return false;
}
public override Task<Stream> GetAsync(BlobProviderGetArgs args)
{
throw new NotImplementedException();
}
protected virtual string GetContainerName()
{
return Options.BucketName.IsNullOrWhiteSpace()
? MinioDefaults.BucketName : Options.BucketName;
}
}
}
| 33.103896 | 191 | 0.580228 | [
"Apache-2.0"
] | jinjupeng/FileServer | src/FileServer.Minio/MinioProvider.cs | 5,246 | C# |
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using Franson.BlueTools;
namespace SimpleService
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button bAdvertise;
private System.Windows.Forms.Button bDeadvertise;
private System.Windows.Forms.Label lServiceStatus;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtWriteData;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtRead;
private System.Windows.Forms.Button bWrite;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox listSessions;
private System.Windows.Forms.Label lStackID;
private System.Windows.Forms.MainMenu mainMenu1;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
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.mainMenu1 = new System.Windows.Forms.MainMenu();
this.bAdvertise = new System.Windows.Forms.Button();
this.bDeadvertise = new System.Windows.Forms.Button();
this.lServiceStatus = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtWriteData = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtRead = new System.Windows.Forms.TextBox();
this.bWrite = new System.Windows.Forms.Button();
this.listSessions = new System.Windows.Forms.ListBox();
this.label3 = new System.Windows.Forms.Label();
this.lStackID = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// bAdvertise
//
this.bAdvertise.Location = new System.Drawing.Point(16, 16);
this.bAdvertise.Name = "bAdvertise";
this.bAdvertise.Size = new System.Drawing.Size(80, 24);
this.bAdvertise.TabIndex = 10;
this.bAdvertise.Text = "Advertise";
this.bAdvertise.Click += new System.EventHandler(this.bAdvertise_Click);
//
// bDeadvertise
//
this.bDeadvertise.Location = new System.Drawing.Point(112, 16);
this.bDeadvertise.Name = "bDeadvertise";
this.bDeadvertise.Size = new System.Drawing.Size(80, 24);
this.bDeadvertise.TabIndex = 9;
this.bDeadvertise.Text = "Deadvertise";
this.bDeadvertise.Click += new System.EventHandler(this.bDeadvertise_Click);
//
// lServiceStatus
//
this.lServiceStatus.Location = new System.Drawing.Point(16, 48);
this.lServiceStatus.Name = "lServiceStatus";
this.lServiceStatus.Size = new System.Drawing.Size(176, 16);
this.lServiceStatus.Text = "Service not active";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 88);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 16);
this.label1.Text = "Data to client";
//
// txtWriteData
//
this.txtWriteData.Location = new System.Drawing.Point(16, 104);
this.txtWriteData.Name = "txtWriteData";
this.txtWriteData.Size = new System.Drawing.Size(160, 21);
this.txtWriteData.TabIndex = 6;
this.txtWriteData.Text = "some data";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 128);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(152, 16);
this.label2.Text = "Datat from Client";
//
// txtRead
//
this.txtRead.Location = new System.Drawing.Point(16, 144);
this.txtRead.Name = "txtRead";
this.txtRead.Size = new System.Drawing.Size(160, 21);
this.txtRead.TabIndex = 4;
//
// bWrite
//
this.bWrite.Location = new System.Drawing.Point(184, 104);
this.bWrite.Name = "bWrite";
this.bWrite.Size = new System.Drawing.Size(48, 24);
this.bWrite.TabIndex = 3;
this.bWrite.Text = "Write";
this.bWrite.Click += new System.EventHandler(this.bWrite_Click);
//
// listSessions
//
this.listSessions.Location = new System.Drawing.Point(16, 192);
this.listSessions.Name = "listSessions";
this.listSessions.Size = new System.Drawing.Size(136, 44);
this.listSessions.TabIndex = 2;
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 176);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(96, 16);
this.label3.Text = "Sessions";
//
// lStackID
//
this.lStackID.Location = new System.Drawing.Point(16, 248);
this.lStackID.Name = "lStackID";
this.lStackID.Size = new System.Drawing.Size(144, 16);
this.lStackID.Text = "No stack found";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(240, 268);
this.Controls.Add(this.lStackID);
this.Controls.Add(this.label3);
this.Controls.Add(this.listSessions);
this.Controls.Add(this.bWrite);
this.Controls.Add(this.txtRead);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtWriteData);
this.Controls.Add(this.label1);
this.Controls.Add(this.lServiceStatus);
this.Controls.Add(this.bDeadvertise);
this.Controls.Add(this.bAdvertise);
this.Menu = this.mainMenu1;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "SimpleService";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
Manager m_manager = null;
Network m_network = null;
LocalService m_service = null;
private void Form1_Load(object sender, System.EventArgs e)
{
// You can get a valid evaluation key for BlueTools at
// http://franson.com/bluetools/
// That key will be valid for 14 days. Just cut and paste that key into the statement below.
// To get a key that do not expire you need to purchase a license
Franson.BlueTools.License license = new Franson.BlueTools.License();
license.LicenseKey = "HU5UZeq122KOJWA8lhmhOlVRYvv0PRKbHXEZ";
try
{
m_manager = Manager.GetManager();
switch(Manager.StackID)
{
case StackID.STACK_MICROSOFT:
lStackID.Text = "Microsoft stack";
break;
case StackID.STACK_WIDCOMM:
lStackID.Text = "WidComm stack";
break;
}
// Call events in GUI thread
m_manager.Parent = this;
// Call events in new thread (multi-threading)
// manager.Parent = null
// Get first netowrk (BlueTools 1.0 only supports one network == one dongle)
m_network = m_manager.Networks[0];
// Create local service
m_service = new LocalService(ServiceType.SerialPort, "SimpleService", "Sample");
// Called when client connected to service
m_service.ClientConnected += new BlueToolsEventHandler(m_service_ClientConnected);
// Called when client disconnected from service
m_service.ClientDisconnected += new BlueToolsEventHandler(m_service_ClientDisconnected);
// Called when service successfully is advertised to server
m_service.Advertised += new BlueToolsEventHandler(m_service_Advertised);
// Called when all connection to service closed, and service removed from server
m_service.Deadvertised += new BlueToolsEventHandler(m_service_Deadvertised);
// Clean up when form closes
this.Closing += new System.ComponentModel.CancelEventHandler(Form1_Closing);
// Buttons
bAdvertise.Enabled = true;
bDeadvertise.Enabled = false;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void m_service_ClientConnected(object sender, BlueToolsEventArgs eventArgs)
{
ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs;
Session connectedSession = connectionEvent.Session;
// Add new session to list
listSessions.Items.Add(connectedSession);
// Read data from stream
System.IO.Stream connectedStream = connectedSession.Stream;
byte[] buffer = new byte[20];
connectedStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), connectedStream);
lServiceStatus.Text = "Client connected";
}
private void m_service_ClientDisconnected(object sender, BlueToolsEventArgs eventArgs)
{
ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs;
// Remove session from list
listSessions.Items.Remove(connectionEvent.Session);
lServiceStatus.Text = "Client disconnected";
}
private void bAdvertise_Click(object sender, System.EventArgs e)
{
try
{
m_network.Server.Advertise(m_service);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void bDeadvertise_Click(object sender, System.EventArgs e)
{
try
{
m_network.Server.Deadvertise(m_service);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void m_service_Advertised(object sender, BlueToolsEventArgs eventArgs)
{
lServiceStatus.Text = "Service advertised";
// Buttons
bAdvertise.Enabled = false;
bDeadvertise.Enabled = true;
}
private void m_service_Deadvertised(object sender, BlueToolsEventArgs eventArgs)
{
lServiceStatus.Text = "Service not active";
// Buttons
bAdvertise.Enabled = true;
bDeadvertise.Enabled = false;
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Dispose must be called for the application to exit!
Manager.GetManager().Dispose();
}
private void bWrite_Click(object sender, System.EventArgs e)
{
Session selectedSession = (Session) listSessions.SelectedItem;
if(selectedSession != null)
{
System.IO.Stream selectedStream = selectedSession.Stream;
char[] charWrite = txtWriteData.Text.ToCharArray();
byte[] byteWrite = new byte[charWrite.Length];
for(int inx = 0; inx < charWrite.Length; inx++)
{
byteWrite[inx] = (byte) charWrite[inx];
}
selectedStream.BeginWrite(byteWrite, 0, byteWrite.Length, new AsyncCallback(writeCallback), selectedStream);
}
else
{
MessageBox.Show("Select a session first");
}
}
private void writeCallback(IAsyncResult result)
{
System.IO.Stream selectedStream = (System.IO.Stream) result.AsyncState;
try
{
// EndWrite() must always be called if BeginWrite() was used!
selectedStream.EndWrite(result);
}
catch(ObjectDisposedException ex)
{
// Thrown if stream has been closed.
lServiceStatus.Text = ex.Message;
}
}
private void readCallback(IAsyncResult result)
{
// Receives data from all connected devices!
// IAsyncResult argument is of type BlueToolsAsyncResult
BlueToolsAsyncResult blueResults = (BlueToolsAsyncResult) result;
System.IO.Stream currentStream = (System.IO.Stream) blueResults.AsyncState;
byte[] buffer = blueResults.Buffer;
try
{
// EndRead() must always be called!
int len = currentStream.EndRead(result);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(buffer, 0, len);
txtRead.Text = str;
// Start new async read
currentStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), currentStream);
}
catch(ObjectDisposedException ex)
{
// Thrown if stream has been closed.
lServiceStatus.Text = ex.Message;
}
}
}
}
| 33.994911 | 113 | 0.625973 | [
"MIT"
] | johanlantz/headsetpresenter | HeadsetPresenter_Bluetools/HeadsetPresenter/Bluetools/BlueTools SDK v1.2/dotNetCF200/C#/SimpleService/Form1.cs | 13,360 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Wheatech.Modulize.Properties;
namespace Wheatech.Modulize
{
public class ModuleDiscoverCollection : ICollection<IModuleDiscover>
{
private readonly List<IModuleDiscover> _discovers;
#region Constructors
public ModuleDiscoverCollection()
{
_discovers = new List<IModuleDiscover>();
}
public ModuleDiscoverCollection(IEnumerable<IModuleDiscover> discovers)
{
_discovers = new List<IModuleDiscover>(discovers);
}
public ModuleDiscoverCollection(int capacity)
{
_discovers = new List<IModuleDiscover>(capacity);
}
public ModuleDiscoverCollection(params IModuleDiscover[] discovers)
: this((IEnumerable<IModuleDiscover>)discovers)
{
}
#endregion
public IEnumerator<IModuleDiscover> GetEnumerator()
{
return _discovers.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal void SetReadOnly(bool isReadOnly)
{
IsReadOnly = isReadOnly;
}
private void ValidateReadOnly()
{
if (IsReadOnly)
{
throw new InvalidOperationException(Strings.Collection_ReadOnly);
}
}
public void Add(IModuleDiscover item)
{
ValidateReadOnly();
if (item == null) throw new ArgumentNullException(nameof(item));
_discovers.Add(item);
}
public void Clear()
{
ValidateReadOnly();
_discovers.Clear();
}
public bool Contains(IModuleDiscover item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
return _discovers.Contains(item);
}
public void CopyTo(IModuleDiscover[] array, int arrayIndex)
{
_discovers.CopyTo(array, arrayIndex);
}
public bool Remove(IModuleDiscover item)
{
ValidateReadOnly();
return _discovers.Remove(item);
}
public int Count => _discovers.Count;
public bool IsReadOnly { get; private set; }
public IModuleDiscover this[int index]
{
get { return _discovers[index]; }
set
{
ValidateReadOnly();
_discovers[index] = value;
}
}
}
}
| 25.096154 | 81 | 0.563218 | [
"MIT"
] | edwardmeng/Wheatech.Modulize | src/Wheatech.Modulize/Discover/ModuleDiscoverCollection.cs | 2,612 | C# |
using System;
namespace AlgoSdk
{
/// <summary>
/// A wrapper class around compiled teal bytes.
/// </summary>
[Serializable]
[AlgoApiFormatter(typeof(CompiledTealFormatter))]
public struct CompiledTeal
: IEquatable<CompiledTeal>
, IEquatable<byte[]>
{
public byte[] Bytes;
public bool Equals(CompiledTeal other)
{
return ArrayComparer.Equals(Bytes, other.Bytes);
}
public bool Equals(byte[] other)
{
return ArrayComparer.Equals(Bytes, other);
}
public static implicit operator byte[](CompiledTeal compiledTeal)
{
return compiledTeal.Bytes;
}
public static implicit operator CompiledTeal(byte[] bytes)
{
return new CompiledTeal { Bytes = bytes };
}
}
}
| 23.189189 | 73 | 0.581585 | [
"MIT"
] | CareBoo/Algorand.SDK.Unity | Packages/com.careboo.unity-algorand-sdk/CareBoo.AlgoSdk/AlgoApi/Shared/Models/CompiledTeal.cs | 858 | C# |
using System.Linq;
public partial class ModuleWeaver
{
public bool InjectOnPropertyNameChanged =true;
public void ResolveOnPropertyNameChangedConfig()
{
var value = Config?.Attributes("InjectOnPropertyNameChanged").FirstOrDefault();
if (value != null)
{
InjectOnPropertyNameChanged = bool.Parse((string) value);
}
}
} | 23.75 | 87 | 0.665789 | [
"MIT"
] | MoaidHathot/KnownTypes.Fody | PropertyChanged/PropertyChanged.Fody/InjectOnPropertyNameChangedConfig.cs | 380 | C# |
namespace PatrynSolutions.Utilities.Monad.LocalTesting
{
using PatrynSolutions.Utilities.Monad;
public class Program
{
public static void Main(string[] args)
{
var val = "something";
var maybe = val.ToMaybe<string>();
//Maybe<string> nulM = null;
var hasValue = maybe.HasValue;
var value = maybe.Value;
//var test = nulM.Value();
}
}
}
| 22.6 | 55 | 0.548673 | [
"Apache-2.0"
] | TeturactsWill/PatrynSolutions.Utilities | src/PatrynSolutions.Utilities.Monad.LocalTesting/Program.cs | 454 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace Microsoft.EntityFrameworkCore.ValueGeneration.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class TemporaryDateTimeValueGenerator : ValueGenerator<DateTime>
{
private long _current;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override DateTime Next(EntityEntry entry) => new DateTime(Interlocked.Increment(ref _current));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool GeneratesTemporaryValues => true;
}
}
| 52.771429 | 113 | 0.703303 | [
"Apache-2.0"
] | BionStt/EntityFrameworkCore | src/EFCore/ValueGeneration/Internal/TemporaryDateTimeValueGenerator.cs | 1,847 | C# |
using NUnit.Framework;
using Underscore.Extensions;
namespace Underscore.Test.Collection
{
[TestFixture]
public class CompareTest
{
[Test]
public void Collection_Compare_IsSorted_StringArguments_SortedInput()
{
string[] input = { "a", "b", "c", "d", "e", "f" };
Assert.IsTrue(_.Collection.IsSorted(input));
}
[Test]
public void Collection_Compare_IsSorted_StringArguments_UnsortedInput()
{
string[] input = { "a", "b", "c", "z", "y", "x" };
Assert.IsFalse(_.Collection.IsSorted(input));
}
[Test]
public void Collection_Compare_IsSorted_IntArguments_SortedInput()
{
int[] input = { 1, 2, 3, 4, 5, 6 };
Assert.IsTrue(_.Collection.IsSorted(input));
}
[Test]
public void Collection_Compare_IsSorted_IntArguments_UnsortedInput()
{
int[] input = { 1, 2, 3, 6, 5, 4 };
Assert.IsFalse(_.Collection.IsSorted(input));
}
[Test]
public void Collection_Compare_IsSorted_Descending_SortedInput()
{
int[] input = { 6, 5, 4, 3, 2, 1 };
Assert.IsTrue(_.Collection.IsSorted(input, true));
}
[Test]
public void Collection_Compare_IsSorted_Descending_UnsortedInput()
{
int[] input = { 1, 2, 3, 6, 5, 4 };
Assert.IsFalse(_.Collection.IsSorted(input, true));
}
[Test]
public void CollectionExtensions_Compare_IsSorted_StringArguments_SortedInput()
{
string[] input = { "a", "b", "c", "d", "e", "f" };
Assert.IsTrue(input.IsSorted());
}
[Test]
public void CollectionExtensions_Compare_IsSorted_StringArguments_UnsortedInput()
{
string[] input = { "a", "b", "c", "z", "y", "x" };
Assert.IsFalse(input.IsSorted());
}
[Test]
public void CollectionExtensions_Compare_IsSorted_IntArguments_SortedInput()
{
int[] input = { 1, 2, 3, 4, 5, 6 };
Assert.IsTrue(input.IsSorted());
}
[Test]
public void CollectionExtensions_Compare_IsSorted_IntArguments_UnsortedInput()
{
int[] input = { 1, 2, 3, 6, 5, 4 };
Assert.IsFalse(input.IsSorted());
}
[Test]
public void CollectionExtensions_Compare_IsSorted_Descending_SortedInput()
{
int[] input = { 6, 5, 4, 3, 2, 1 };
Assert.IsTrue(input.IsSorted(true));
}
[Test]
public void CollectionExtensions_Compare_IsSorted_Descending_UnsortedInput()
{
int[] input = { 1, 2, 3, 6, 5, 4 };
Assert.IsFalse(input.IsSorted(true));
}
}
}
| 27.382979 | 89 | 0.600622 | [
"MIT"
] | konkked/Underscore.cs | Underscore.Test/Collection/CompareTest.cs | 2,576 | C# |
#region copyright
/// GladNet Copyright (C) 2014 Andrew Blakely
/// andrew.blakely@ymail.com
/// GitHub: HeIIoKitty
/// Unity3D: Glader
/// Please refer to the repo License file for licensing information
/// If this source code has been distributed without a copy of the original license file then this is an illegal copy and you should delete it
#endregion
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: InternalsVisibleTo("GladNet.Server", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Client", AllInternalsVisible=true)]
[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[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("481704a9-ce5f-4a82-b9f7-3ca5e62f2752")]
// 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.170213 | 142 | 0.752648 | [
"BSD-2-Clause"
] | HelloKitty/GladNet | Common/Properties/AssemblyInfo.cs | 1,891 | 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.
#if WIN32
namespace CommunityToolkit.WinUI.Notifications
{
/// <summary>
/// Event triggered when a notification is clicked.
/// </summary>
/// <param name="e">Arguments that specify what action was taken and the user inputs.</param>
public delegate void OnActivated(ToastNotificationActivatedEventArgsCompat e);
}
#endif | 34.1875 | 97 | 0.740402 | [
"MIT"
] | ehtick/Uno.WindowsCommunityToolkit | CommunityToolkit.WinUI.Notifications/Toasts/Compat/Desktop/OnActivated.cs | 547 | 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("StringCalculator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StringCalculator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0e727bd8-8df2-4260-852b-87e1ac9da538")]
// 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.972973 | 84 | 0.746619 | [
"MIT"
] | nyluntu/kata-string-calculator | StringCalculator/Properties/AssemblyInfo.cs | 1,408 | C# |
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow
{
internal static class InteractiveContentTypeDefinitions
{
[Export, Name(PredefinedInteractiveContentTypes.InteractiveContentTypeName), BaseDefinition("text"), BaseDefinition("projection")]
internal static readonly ContentTypeDefinition InteractiveContentTypeDefinition;
[Export, Name(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName), BaseDefinition("text")]
internal static readonly ContentTypeDefinition InteractiveOutputContentTypeDefinition;
}
} | 46.285714 | 138 | 0.817901 | [
"Apache-2.0"
] | DavidKarlas/roslyn | src/InteractiveWindow/Editor/InteractiveContentTypeDefinitions.cs | 650 | C# |
// <copyright file="Mediator.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace AsyncIO.ProducerConsumer
{
using System;
using System.Collections.Generic;
using AsyncIO.ProducerConsumer.Factories;
using AsyncIO.ProducerConsumer.Models;
using AsyncIO.ProducerConsumer.Roles;
using Microsoft.Extensions.Logging;
/// <summary>
/// Mediator that handles all communications between producers and consumers.
/// </summary>
public class Mediator
{
private readonly Scheduler scheduler;
/// <summary>
/// Initializes a new instance of the <see cref="Mediator"/> class.
/// </summary>
/// <param name="producerFactory">Producer factory that creates producers.</param>
/// <param name="consumerFactory">Consumer factory that creates consumers.</param>
/// <param name="logger">Injectable logger.</param>
public Mediator(IProducerFactory producerFactory, IConsumerFactory consumerFactory, ILogger logger = null)
{
producerFactory = producerFactory ?? throw new ArgumentNullException(nameof(producerFactory));
consumerFactory = consumerFactory ?? throw new ArgumentNullException(nameof(consumerFactory));
this.scheduler = new Scheduler(producerFactory, consumerFactory, logger);
this.scheduler.OnCompleted += this.Scheduler_OnCompleted;
}
/// <summary>
/// Initializes a new instance of the <see cref="Mediator"/> class.
/// </summary>
/// <param name="producers">Producers.</param>
/// <param name="consumers">Consumers.</param>
/// <param name="logger">Injectable logger.</param>
public Mediator(IEnumerable<IProducer> producers, IEnumerable<IConsumer> consumers, ILogger logger = null)
{
producers = producers ?? throw new ArgumentNullException(nameof(producers));
consumers = consumers ?? throw new ArgumentNullException(nameof(consumers));
this.scheduler = new Scheduler(producers, consumers, logger);
this.scheduler.OnCompleted += this.Scheduler_OnCompleted;
}
/// <summary>
/// Event that fires when producers consumers completed.
/// </summary>
public event EventHandler OnCompleted;
/// <summary>
/// Gets configuration.
/// </summary>
public Configuration Configuration => this.scheduler.Configuration;
/// <summary>
/// Starts processing.
/// </summary>
public void Start()
{
this.scheduler.Start();
}
/// <summary>
/// Stops processing.
/// </summary>
public void Stop()
{
this.scheduler.Stop();
}
private void Scheduler_OnCompleted(object sender, EventArgs e)
{
this.OnCompleted?.Invoke(this, e);
}
}
}
| 36.13253 | 114 | 0.628876 | [
"MIT"
] | Ritor42/AsyncIO.ProducerConsumer | AsyncIO.ProducerConsumer/Mediator.cs | 3,001 | C# |
using System.Collections.Generic;
using System.Linq;
using FubuCore;
using FubuCore.Binding;
using FubuCore.Binding.InMemory;
using FubuCore.Descriptions;
using FubuMVC.Core.Http;
using FubuMVC.Core.Resources.Conneg;
namespace FubuMVC.Bender
{
public class BindingReaderOptions
{
public BindingReaderOptions()
{
BindingSources = new List<RequestDataSource> { RequestDataSource.Route };
}
public List<RequestDataSource> BindingSources { get; private set; }
}
public class BindingReader
{
public const string DescriptionFormat = "Reading with {0}.";
public const string DescriptionChildKey = "Formatter";
}
public class BindingReader<T, TFormatter> : BindingReader,
IReader<T>, DescribesItself where TFormatter : IFormatter
{
private readonly TFormatter _formatter;
private readonly BindingReaderOptions _options;
private readonly IObjectResolver _objectResolver;
private readonly IRequestData _requestData;
private readonly IServiceLocator _serviceLocator;
public BindingReader(TFormatter formatter,
BindingReaderOptions options,
IObjectResolver objectResolver,
IRequestData requestData,
IServiceLocator serviceLocator)
{
_formatter = formatter;
_options = options;
_objectResolver = objectResolver;
_requestData = requestData;
_serviceLocator = serviceLocator;
}
public T Read(string mimeType)
{
var model = _formatter.Read<T>();
var requestData = !_options.BindingSources.Any() ? _requestData :
new RequestData(_options.BindingSources.Distinct()
.Select(x => _requestData.ValuesFor(x)));
_objectResolver.BindProperties(typeof(T), model,
new BindingContext(requestData, _serviceLocator, new NulloBindingLogger()));
return model;
}
public IEnumerable<string> Mimetypes
{
get { return _formatter.MatchingMimetypes; }
}
public void Describe(Description description)
{
var formatter = Description.For(_formatter);
description.Title = DescriptionFormat.ToFormat(formatter.Title);
description.Children["Formatter"] = formatter;
}
}
}
| 33.891892 | 93 | 0.628788 | [
"MIT"
] | mikeobrien/FubuMVC.Bender | src/FubuMVC.Bender/BindingReader.cs | 2,510 | C# |
using OpenTK;
namespace pingine.Game.State
{
public static partial class EntityBehaviours
{
public static void TestMoving(Entity entity)
{
entity.Position = Vector2.Add(entity.Position, new Vector2(1, 1));
}
}
}
| 20.153846 | 78 | 0.625954 | [
"MIT"
] | HapaxL/pingine | pingine/Game/State/EntityBehaviours.cs | 264 | C# |
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using LanguageExt.TypeClasses;
namespace LanguageExt.ClassInstances
{
/// <summary>
/// Equality class instance for all record types
/// </summary>
/// <typeparam name="A">Record type</typeparam>
public struct EqRecord<A> : Eq<A> where A : Record<A>
{
[Pure]
public bool Equals(A x, A y) =>
RecordType<A>.EqualityTyped(x, y);
[Pure]
public int GetHashCode(A x) =>
default(HashableRecord<A>).GetHashCode(x);
[Pure]
public Task<bool> EqualsAsync(A x, A y) =>
Equals(x, y).AsTask();
[Pure]
public Task<int> GetHashCodeAsync(A x) =>
GetHashCode(x).AsTask();
}
}
| 25.9 | 57 | 0.577864 | [
"MIT"
] | Bagoum/language-ext | LanguageExt.Core/ClassInstances/Eq/EqRecord.cs | 779 | C# |
/**
* Copyright (c) 2019-2021 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using System;
using System.Linq;
using UnityEngine;
using UnityEditor;
using Simulator.Map;
[CustomEditor(typeof(MapParkingSpace)), CanEditMultipleObjects]
public class MapParkingSpaceEditor : Editor
{
private float targetWidth = 3;
private float targetLength = 6;
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MapParkingSpace mapParkingSpace = (MapParkingSpace)target;
GUILayout.Label("Length: " + mapParkingSpace.Length);
GUILayout.Label("Width: " + mapParkingSpace.Width);
GUILayout.BeginHorizontal();
if (GUILayout.Button("Force right angle by moving right side"))
{
MakeEdit(space =>
{
var forward = space.mapWorldPositions[2] - space.mapWorldPositions[1];
var right = Quaternion.AngleAxis(90, Vector3.up) * forward.normalized;
var fixed0 = space.mapWorldPositions[1] +
Vector3.Dot(space.mapWorldPositions[0] - space.mapWorldPositions[1],
right) * right;
var fixed3 = space.mapWorldPositions[2] +
Vector3.Dot(space.mapWorldPositions[3] - space.mapWorldPositions[2],
right) * right;
space.mapLocalPositions[0] = space.transform.InverseTransformPoint(fixed0);
space.mapLocalPositions[3] = space.transform.InverseTransformPoint(fixed3);
SceneView.RepaintAll();
}, "Force right angle by moving right side");
}
if (GUILayout.Button("Force right angle by moving left side"))
{
MakeEdit(space =>
{
var forward = space.mapWorldPositions[3] - space.mapWorldPositions[0];
var right = Quaternion.AngleAxis(90, Vector3.up) * forward.normalized;
var fixed2 = space.mapWorldPositions[3] -
Vector3.Dot(space.mapWorldPositions[0] - space.mapWorldPositions[1],
right) * right;
var fixed1 = space.mapWorldPositions[0] -
Vector3.Dot(space.mapWorldPositions[3] - space.mapWorldPositions[2],
right) * right;
space.mapLocalPositions[2] = space.transform.InverseTransformPoint(fixed2);
space.mapLocalPositions[1] = space.transform.InverseTransformPoint(fixed1);
SceneView.RepaintAll();
}, "Force right angle by moving left side");
}
GUILayout.EndHorizontal();
if (GUILayout.Button("Make right side parallel to the left side"))
{
MakeEdit(space =>
{
var offset = 0.5f * ((space.mapWorldPositions[0] - space.mapWorldPositions[1]) + (space.mapWorldPositions[3] - space.mapWorldPositions[2]));
space.mapLocalPositions[0] = space.transform.InverseTransformPoint(space.mapWorldPositions[1] + offset);
space.mapLocalPositions[3] = space.transform.InverseTransformPoint(space.mapWorldPositions[2] + offset);
}, "Make right side parallel to the left side");
}
GUILayout.BeginHorizontal();
targetWidth = EditorGUILayout.FloatField("Set width to (only with right angle)", targetWidth);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("By moving left side"))
{
MakeEdit(space =>
{
space.mapLocalPositions[2] = space.transform.InverseTransformPoint(space.mapWorldPositions[3] + (space.mapWorldPositions[2] - space.mapWorldPositions[3]).normalized * targetWidth);
space.mapLocalPositions[1] = space.transform.InverseTransformPoint(space.mapWorldPositions[0] + (space.mapWorldPositions[1] - space.mapWorldPositions[0]).normalized * targetWidth);
}, "Set width left");
}
if (GUILayout.Button("By moving right side"))
{
MakeEdit(space =>
{
space.mapLocalPositions[3] = space.transform.InverseTransformPoint(space.mapWorldPositions[2] + (space.mapWorldPositions[3] - space.mapWorldPositions[2]).normalized * targetWidth);
space.mapLocalPositions[0] = space.transform.InverseTransformPoint(space.mapWorldPositions[1] + (space.mapWorldPositions[0] - space.mapWorldPositions[1]).normalized * targetWidth);
}, "Set width right");
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
targetLength = EditorGUILayout.FloatField("Set length to", targetLength);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("By moving front"))
{
MakeEdit(space =>
{
var offset = (space.MiddleExit - space.MiddleEnter).normalized * targetLength;
space.mapLocalPositions[2] = space.transform.InverseTransformPoint(space.mapWorldPositions[1] + offset);
space.mapLocalPositions[3] = space.transform.InverseTransformPoint(space.mapWorldPositions[0] + offset);
}, "By moving front");
}
if (GUILayout.Button("By moving back"))
{
MakeEdit(space =>
{
var offset = (space.MiddleExit - space.MiddleEnter).normalized * targetLength;
space.mapLocalPositions[0] =
space.transform.InverseTransformPoint(space.mapWorldPositions[3] - offset);
space.mapLocalPositions[1] =
space.transform.InverseTransformPoint(space.mapWorldPositions[2] - offset);
}, "Set length back");
}
GUILayout.EndHorizontal();
if (GUILayout.Button("Fix Y"))
{
MakeEdit(space =>
{
for (int i = 0; i < space.mapWorldPositions.Count; i++)
{
Ray ray = new Ray(space.mapWorldPositions[i] + Vector3.up * 2, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 4))
{
space.mapLocalPositions[i] = space.transform.InverseTransformPoint(hit.point);
}
}
}, "Fix Y");
}
}
private void MakeEdit(Action<MapParkingSpace> action, string actionName)
{
Undo.RecordObjects(targets, actionName);
foreach (MapParkingSpace space in targets)
{
space.RefreshWorldPositions();
action(space);
}
SceneView.RepaintAll();
}
protected virtual void OnSceneGUI()
{
MapParkingSpace vmMapParkingSpace = (MapParkingSpace)target;
if (vmMapParkingSpace.mapLocalPositions.Count < 1)
return;
if (vmMapParkingSpace.DisplayHandles)
{
for (int i = 0; i < vmMapParkingSpace.mapLocalPositions.Count; i++)
{
Vector3 oldWorld = vmMapParkingSpace.transform.TransformPoint(vmMapParkingSpace.mapLocalPositions[i]);
Vector3 newTargetPosition = Handles.PositionHandle(oldWorld, Quaternion.identity);
if (oldWorld != newTargetPosition)
{
Undo.RecordObject(vmMapParkingSpace, "Speed Bump points change");
vmMapParkingSpace.mapLocalPositions[i] = vmMapParkingSpace.transform.InverseTransformPoint(newTargetPosition);
}
}
}
if (vmMapParkingSpace.DisplayHandles)
{
for (int i = 0; i < vmMapParkingSpace.mapLocalPositions.Count; i++)
{
int iPlus1 = (i + 1) % vmMapParkingSpace.mapLocalPositions.Count;
var iWorld = vmMapParkingSpace.transform.TransformPoint(vmMapParkingSpace.mapLocalPositions[i]);
var iPlus1World = vmMapParkingSpace.transform.TransformPoint(vmMapParkingSpace.mapLocalPositions[iPlus1]);
var oldMiddleWorld = 0.5f * (iWorld + iPlus1World);
Vector3 newTargetPosition = Handles.PositionHandle(oldMiddleWorld, Quaternion.identity);
if (oldMiddleWorld != newTargetPosition)
{
var diff = newTargetPosition - oldMiddleWorld;
Undo.RecordObject(vmMapParkingSpace, "Speed Bump points change");
vmMapParkingSpace.mapLocalPositions[i] = vmMapParkingSpace.transform.InverseTransformPoint(iWorld + diff);
vmMapParkingSpace.mapLocalPositions[iPlus1] = vmMapParkingSpace.transform.InverseTransformPoint(iPlus1World + diff);
}
}
}
}
}
| 47.047619 | 196 | 0.599978 | [
"Apache-2.0",
"BSD-3-Clause"
] | HaoruXue/simulator | Assets/Scripts/Editor/Map/MapParkingSpaceEditor.cs | 8,892 | 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("02.Animals")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.Animals")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9a76daef-ef75-4a01-9fdd-63e81edba8b9")]
// 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.513514 | 84 | 0.745677 | [
"MIT"
] | mdamyanova/C-Sharp-Web-Development | 08.C# Fundamentals/08.02.C# OOP Basics/07.Polymorphism/02.Animals/Properties/AssemblyInfo.cs | 1,391 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using EDO.Core.ViewModel;
using EDO.Core.Model;
using System.Diagnostics;
namespace EDO.SamplingCategory.SamplingForm
{
public class SamplingNumberVM :BaseVM, IEditableObject
{
private SamplingNumber samplingNumber;
private SamplingNumber bakSamplingNumber;
public SamplingNumberVM()
: this(new SamplingNumber())
{
}
public SamplingNumberVM(SamplingNumber samplingNumber)
{
this.samplingNumber = samplingNumber;
this.bakSamplingNumber = null;
}
#region Property
public SamplingNumber SamplingNumber { get { return samplingNumber; } }
public override object Model { get { return samplingNumber; } }
public string SampleSize
{
get
{
return samplingNumber.SampleSize;
}
set
{
if (samplingNumber.SampleSize != value)
{
samplingNumber.SampleSize = value;
NotifyPropertyChanged("SampleSize");
}
}
}
public string NumberOfResponses
{
get
{
return samplingNumber.NumberOfResponses;
}
set
{
if (samplingNumber.NumberOfResponses != value)
{
samplingNumber.NumberOfResponses = value;
NotifyPropertyChanged("NumberOfResponses");
}
}
}
public string ResponseRate
{
get
{
return samplingNumber.ResponseRate;
}
set
{
if (samplingNumber.ResponseRate != value)
{
samplingNumber.ResponseRate = value;
NotifyPropertyChanged("ResponseRate");
}
}
}
public string Description
{
get
{
return samplingNumber.Description;
}
set
{
if (samplingNumber.Description != value)
{
samplingNumber.Description = value;
NotifyPropertyChanged("Description");
}
}
}
#endregion
#region IEditableObject Member
public bool InEdit { get { return inEdit; } }
private bool inEdit;
public void BeginEdit()
{
if (inEdit)
{
return;
}
inEdit = true;
bakSamplingNumber = samplingNumber.Clone() as SamplingNumber;
}
public void CancelEdit()
{
if (!inEdit)
{
return;
}
inEdit = false;
this.SampleSize = bakSamplingNumber.SampleSize;
this.NumberOfResponses = bakSamplingNumber.NumberOfResponses;
this.ResponseRate = bakSamplingNumber.ResponseRate;
this.Description = bakSamplingNumber.Description;
}
public void EndEdit()
{
if (!inEdit)
{
return;
}
inEdit = false;
bakSamplingNumber = null;
Memorize();
}
protected override void PrepareValidation()
{
if (string.IsNullOrEmpty(SampleSize))
{
this.SampleSize = "0";
}
}
#endregion
}
}
| 24.453947 | 79 | 0.485069 | [
"Apache-2.0"
] | ssjda-ddi/EDO | EDO/SamplingCategory/SamplingForm/SamplingNumberVM.cs | 3,719 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace Microsoft.DotNet.Tests.EndToEnd
{
public class GivenDotNetUsesMSBuild : TestBase
{
[Fact]
public void ItCanNewRestoreBuildRunCleanMSBuildProject()
{
using (DisposableDirectory directory = Temp.CreateDirectory())
{
string projectDirectory = directory.Path;
string newArgs = "console -f netcoreapp2.1 --debug:ephemeral-hive --no-restore";
new NewCommandShim()
.WithWorkingDirectory(projectDirectory)
.Execute(newArgs)
.Should().Pass();
new RestoreCommand()
.WithWorkingDirectory(projectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
var binDirectory = new DirectoryInfo(projectDirectory).Sub("bin");
binDirectory.Should().HaveFilesMatching("*.dll", SearchOption.AllDirectories);
new CleanCommand()
.WithWorkingDirectory(projectDirectory)
.Execute()
.Should().Pass();
binDirectory.Should().NotHaveFilesMatching("*.dll", SearchOption.AllDirectories);
}
}
[Fact]
public void ItCanRunToolsInACSProj()
{
var testInstance = TestAssets.Get("MSBuildTestApp")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root;
new DotnetCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput("portable")
.Should()
.Pass()
.And
.HaveStdOutContaining("Hello Portable World!");;
}
[Fact(Skip="https://github.com/dotnet/cli/issues/9688")]
public void ItCanRunToolsThatPrefersTheCliRuntimeEvenWhenTheToolItselfDeclaresADifferentRuntime()
{
var testInstance = TestAssets.Get("MSBuildTestApp")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root;
new DotnetCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput("prefercliruntime")
.Should().Pass()
.And.HaveStdOutContaining("Hello I prefer the cli runtime World!");;
}
[Fact(Skip="https://github.com/dotnet/cli/issues/9688")]
public void ItCanRunAToolThatInvokesADependencyToolInACSProj()
{
var repoDirectoriesProvider = new RepoDirectoriesProvider();
var testInstance = TestAssets.Get("TestAppWithProjDepTool")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var configuration = "Debug";
var testProjectDirectory = testInstance.Root;
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute($"-c {configuration} ")
.Should()
.Pass();
new DotnetCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput(
$"-d dependency-tool-invoker -c {configuration} -f netcoreapp2.2 portable")
.Should().Pass()
.And.HaveStdOutContaining("Hello Portable World!");;
}
}
}
| 37.942149 | 105 | 0.534524 | [
"MIT"
] | APiZFiBlockChain4/cli | test/EndToEnd/GivenDotNetUsesMSBuild.cs | 4,593 | C# |
// SPDX-FileCopyrightText: © 2021-2022 MONAI Consortium
// SPDX-License-Identifier: Apache License 2.0
using System;
using System.IO;
using Crayon;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Monai.Deploy.InformaticsGateway.CLI.Test
{
public class ConsoleLoggerTest
{
[Fact(DisplayName = "BeginScope is not supported")]
public void BeingScope_IsNotSupported()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Information
});
var data = "test";
Assert.Null(logger.BeginScope(data));
}
[Fact(DisplayName = "IsEnabled")]
public void IsEnabled()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Information
});
Assert.False(logger.IsEnabled(LogLevel.Trace));
Assert.False(logger.IsEnabled(LogLevel.Debug));
Assert.True(logger.IsEnabled(LogLevel.Information));
Assert.True(logger.IsEnabled(LogLevel.Warning));
Assert.True(logger.IsEnabled(LogLevel.Error));
Assert.True(logger.IsEnabled(LogLevel.Critical));
}
[Fact(DisplayName = "Log ignored")]
public void Log_Ignored()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Error
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
logger.Log(LogLevel.Trace, message);
var result = sw.ToString();
Assert.Equal(string.Empty, result);
}
}
[Fact(DisplayName = "Log trace")]
public void Log_Trace()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Trace
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
logger.Log(LogLevel.Trace, message);
var result = sw.ToString();
Assert.Equal($"{Output.Bright.Black("trce: ")}{message}{Environment.NewLine}", result);
}
}
[Fact(DisplayName = "Log debug")]
public void Log_Debug()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Trace
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
logger.Log(LogLevel.Debug, message);
var result = sw.ToString();
Assert.Equal($"{Output.Bright.Black("dbug: ")}{message}{Environment.NewLine}", result);
}
}
[Fact(DisplayName = "Log information")]
public void Log_Information()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Trace
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
logger.Log(LogLevel.Information, message);
var result = sw.ToString();
Assert.Equal($"{Output.Bright.White("info: ")}{message}{Environment.NewLine}", result);
}
}
[Fact(DisplayName = "Log warning")]
public void Log_Warning()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Warning
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
Console.SetError(sw);
logger.Log(LogLevel.Warning, message);
sw.Flush();
var result = sw.ToString();
Assert.Equal($"{Output.Bright.Yellow("warn: ")}{Output.Bright.Yellow(message)}{Environment.NewLine}", result);
}
}
[Fact(DisplayName = "Log with exception")]
public void Log_WithException()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Error
});
using (var sw = new StringWriter())
{
var exception = new Exception("error");
var message = "Hello";
Console.SetOut(sw);
Console.SetError(sw);
logger.Log(LogLevel.Error, exception, message);
var result = sw.ToString();
Assert.Equal($"{Output.Bright.Red("fail: ")}{Output.Bright.Red(message + Environment.NewLine + exception.ToString())}{Environment.NewLine}", result);
}
}
[Fact(DisplayName = "Log Critical")]
public void Log_Critical()
{
var logger = new ConsoleLogger("test", new ConsoleLoggerConfiguration
{
MinimumLogLevel = LogLevel.Warning
});
using (var sw = new StringWriter())
{
var message = "Hello";
Console.SetOut(sw);
Console.SetError(sw);
logger.Log(LogLevel.Critical, message);
sw.Flush();
var result = sw.ToString();
Assert.Equal($"{Output.Bright.Red("crit: ")}{Output.Bright.Red(message)}{Environment.NewLine}", result);
}
}
}
}
| 35.35119 | 165 | 0.522142 | [
"Apache-2.0"
] | Project-MONAI/monai-deploy-informatics-gateway | src/CLI/Test/ConsoleLoggerTest.cs | 5,942 | C# |
using System.Collections.Immutable;
namespace Elevator.Agent.Models
{
public class BuildTaskResult
{
public ImmutableList<string> Logs { get; set; }
public TaskStatus Status { get; set; }
}
public enum TaskStatus
{
InProgress,
Success,
Failed
}
}
| 16.578947 | 55 | 0.606349 | [
"MIT"
] | Elevator-CI/elevator-agent | Elevator.Agent/Models/BuildTaskResult.cs | 317 | C# |
/*
* Portions Copyright 2019-2021, Fyfe Software Inc. and the SanteSuite Contributors (See NOTICE)
*
* 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.
*
* User: fyfej (Justin Fyfe)
* Date: 2021-8-5
*/
using RestSrvr.Attributes;
using SanteDB.Core;
using SanteDB.Core.Diagnostics;
using SanteDB.Core.Extensions;
using SanteDB.Core.Model;
using SanteDB.Core.Model.Acts;
using SanteDB.Core.Model.Collection;
using SanteDB.Core.Model.Constants;
using SanteDB.Core.Model.DataTypes;
using SanteDB.Core.Model.Entities;
using SanteDB.Core.Security;
using SanteDB.Core.Services;
using SanteDB.Messaging.GS1.Configuration;
using SanteDB.Messaging.GS1.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace SanteDB.Messaging.GS1.Rest
{
/// <summary>
/// GS1 BMS 3.3
/// </summary>
/// <remarks>The SanteDB server implementation of the GS1 BMS 3.3 interface over REST</remarks>
[ServiceBehavior(Name = "GS1BMS", InstanceMode = ServiceInstanceMode.PerCall)]
public class StockServiceBehavior : IStockService
{
// Configuration
private Gs1ConfigurationSection m_configuration = ApplicationServiceContext.Current.GetService<IConfigurationManager>().GetSection<Gs1ConfigurationSection>();
// Act repository
private IRepositoryService<Act> m_actRepository;
// Material repository
private IRepositoryService<Material> m_materialRepository;
// Manufactured materials
private IRepositoryService<ManufacturedMaterial> m_manufMaterialRepository;
// Place repository
private IRepositoryService<Place> m_placeRepository;
// Stock service
private IStockManagementRepositoryService m_stockService;
// GS1 Utility
private Gs1Util m_gs1Util;
// Tracer
private Tracer m_tracer = new Tracer(Gs1Constants.TraceSourceName);
// Localization Service
private readonly ILocalizationService m_localizationService;
/// <summary>
/// Default ctor setting services
/// </summary>
public StockServiceBehavior()
{
this.m_actRepository = ApplicationServiceContext.Current.GetService<IRepositoryService<Act>>();
this.m_materialRepository = ApplicationServiceContext.Current.GetService<IRepositoryService<Material>>();
this.m_placeRepository = ApplicationServiceContext.Current.GetService<IRepositoryService<Place>>();
this.m_stockService = ApplicationServiceContext.Current.GetService<IStockManagementRepositoryService>();
this.m_manufMaterialRepository = ApplicationServiceContext.Current.GetService<IRepositoryService<ManufacturedMaterial>>();
this.m_gs1Util = new Gs1Util();
this.m_localizationService = ApplicationServiceContext.Current.GetService<ILocalizationService>();
}
// HDSI Trace host
private readonly Tracer traceSource = new Tracer(Gs1Constants.TraceSourceName);
/// <summary>
/// The issue despactch advice message will insert a new shipped order into the TImR system.
/// </summary>
public void IssueDespatchAdvice(DespatchAdviceMessageType advice)
{
if (advice == null || advice.despatchAdvice == null)
{
this.m_tracer.TraceError("Invalid message sent");
throw new InvalidOperationException(this.m_localizationService.GetString("error.messaging.gs1.invalidMessage"));
}
// TODO: Validate the standard header
// Loop
Bundle orderTransaction = new Bundle();
foreach (var adv in advice.despatchAdvice)
{
// Has this already been created?
Place sourceLocation = this.m_gs1Util.GetLocation(adv.shipper),
destinationLocation = this.m_gs1Util.GetLocation(adv.receiver);
if (sourceLocation == null)
{
this.m_tracer.TraceError($"Shipper location not found");
throw new KeyNotFoundException(this.m_localizationService.FormatString("error.messaging.gs1.locationNotFound", new
{
param = "Shipper"
}));
}
else if (destinationLocation == null)
{
this.m_tracer.TraceError($"Shipper location not found");
throw new KeyNotFoundException(this.m_localizationService.FormatString("error.messaging.gs1.locationNotFound", new
{
param = "Receiver"
}));
}
// Find the original order which this despatch advice is fulfilling
Act orderRequestAct = null;
if (adv.orderResponse != null || adv.purchaseOrder != null)
{
orderRequestAct = this.m_gs1Util.GetOrder(adv.orderResponse ?? adv.purchaseOrder, ActMoodKeys.Request);
if (orderRequestAct != null) // Orderless despatch!
{
// If the original order request is not comlete, then complete it
orderRequestAct.StatusConceptKey = StatusKeys.Completed;
orderTransaction.Add(orderRequestAct);
}
}
// Find the author of the shipment
var oidService = ApplicationServiceContext.Current.GetService<IAssigningAuthorityRepositoryService>();
var gln = oidService.Get("GLN");
AssigningAuthority issuingAuthority = null;
if(adv.despatchAdviceIdentification.contentOwner != null)
issuingAuthority = oidService.Find(o=>o.Oid == $"{gln.Oid}.{adv.despatchAdviceIdentification.contentOwner.gln}").FirstOrDefault();
if (issuingAuthority == null)
issuingAuthority = oidService.Get(this.m_configuration.DefaultContentOwnerAssigningAuthority);
if (issuingAuthority == null)
{
this.m_tracer.TraceError("Could not find default issuing authority for advice identification. Please configure a valid OID");
throw new KeyNotFoundException(this.m_localizationService.GetString("error.messaging.gs1.issuingAuthority"));
}
int tr = 0;
var existing = this.m_actRepository.Find(o => o.Identifiers.Any(i => i.AuthorityKey == issuingAuthority.Key && i.Value == adv.despatchAdviceIdentification.entityIdentification), 0, 1, out tr);
if (existing.Any())
{
this.m_tracer.TraceWarning("Duplicate despatch {0} will be ignored", adv.despatchAdviceIdentification.entityIdentification);
continue;
}
// Now we want to create a new Supply act which that fulfills the old act
Act fulfillAct = new Act()
{
CreationTime = DateTimeOffset.Now,
MoodConceptKey = ActMoodKeys.Eventoccurrence,
ClassConceptKey = ActClassKeys.Supply,
StatusConceptKey = StatusKeys.Active,
TypeConceptKey = Guid.Parse("14d69b32-f6c4-4a49-a527-a74893dbcf4a"), // Order
ActTime = adv.despatchInformation.despatchDateTimeSpecified ? adv.despatchInformation.despatchDateTime : DateTime.Now,
Extensions = new List<ActExtension>()
{
new ActExtension(Gs1ModelExtensions.ActualShipmentDate, typeof(DateExtensionHandler), adv.despatchInformation.actualShipDateTime),
new ActExtension(Gs1ModelExtensions.ExpectedDeliveryDate, typeof(DateExtensionHandler), adv.despatchInformation.estimatedDeliveryDateTime)
},
Tags = new List<ActTag>()
{
new ActTag("orderNumber", adv.despatchAdviceIdentification.entityIdentification),
new ActTag("orderStatus", "shipped"),
new ActTag("http://santedb.org/tags/contrib/importedData", "true")
},
Identifiers = new List<ActIdentifier>()
{
new ActIdentifier(issuingAuthority, adv.despatchAdviceIdentification.entityIdentification)
},
Participations = new List<ActParticipation>()
{
// TODO: Author
// TODO: Performer
new ActParticipation(ActParticipationKey.Location, sourceLocation.Key),
new ActParticipation(ActParticipationKey.Destination, destinationLocation.Key)
}
};
orderTransaction.Add(fulfillAct);
// Fullfillment
if (orderRequestAct != null)
fulfillAct.Relationships = new List<ActRelationship>()
{
new ActRelationship(ActRelationshipTypeKeys.Fulfills, orderRequestAct.Key)
};
// Now add participations for each material in the despatch
foreach (var dal in adv.despatchAdviceLogisticUnit)
{
foreach (var line in dal.despatchAdviceLineItem)
{
if (line.despatchedQuantity.measurementUnitCode != "dose" &&
line.despatchedQuantity.measurementUnitCode != "unit")
{
this.m_tracer.TraceError("Despatched quantity must be reported in units or doses");
throw new InvalidOperationException(this.m_localizationService.GetString("error.messaging.gs1.despatchedQuantity"));
}
var material = this.m_gs1Util.GetManufacturedMaterial(line.transactionalTradeItem, this.m_configuration.AutoCreateMaterials);
// Add a participation
fulfillAct.Participations.Add(new ActParticipation(ActParticipationKey.Consumable, material.Key)
{
Quantity = (int)line.despatchedQuantity.Value
});
}
}
}
// insert transaction
if (orderTransaction.Item.Count > 0)
try
{
ApplicationServiceContext.Current.GetService<IRepositoryService<Bundle>>().Insert(orderTransaction);
}
catch (Exception e)
{
this.m_tracer.TraceError("Error issuing despatch advice: {0}", e);
throw new Exception(this.m_localizationService.FormatString("error.messaging.gs1.errorIssuing", new
{
param = e.Message
}), e);
}
}
/// <summary>
/// Requests the issuance of a BMS1 inventory report request
/// </summary>
public LogisticsInventoryReportMessageType IssueInventoryReportRequest(LogisticsInventoryReportRequestMessageType parameters)
{
// Status
LogisticsInventoryReportMessageType retVal = new LogisticsInventoryReportMessageType()
{
StandardBusinessDocumentHeader = this.m_gs1Util.CreateDocumentHeader("logisticsInventoryReport", null)
};
// Date / time of report
DateTime? reportFrom = parameters.logisticsInventoryReportRequest.First().reportingPeriod?.beginDate ?? DateTime.MinValue,
reportTo = parameters.logisticsInventoryReportRequest.First().reportingPeriod?.endDate ?? DateTime.Now;
// return value
LogisticsInventoryReportType report = new LogisticsInventoryReportType()
{
creationDateTime = DateTime.Now,
documentStatusCode = DocumentStatusEnumerationType.ORIGINAL,
documentActionCode = DocumentActionEnumerationType.CHANGE_BY_REFRESH,
logisticsInventoryReportIdentification = new Ecom_EntityIdentificationType() { entityIdentification = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0).ToString("X") },
structureTypeCode = new StructureTypeCodeType() { Value = "LOCATION_BY_ITEM" },
documentActionCodeSpecified = true
};
var locationStockStatuses = new List<LogisticsInventoryReportInventoryLocationType>();
// Next, we want to know which facilities for which we're getting the inventory report
List<Place> filterPlaces = null;
if (parameters.logisticsInventoryReportRequest.First().logisticsInventoryRequestLocation != null &&
parameters.logisticsInventoryReportRequest.First().logisticsInventoryRequestLocation.Length > 0)
{
foreach (var filter in parameters.logisticsInventoryReportRequest.First().logisticsInventoryRequestLocation)
{
int tc = 0;
var id = filter.inventoryLocation.gln ?? filter.inventoryLocation.additionalPartyIdentification?.FirstOrDefault()?.Value;
var place = this.m_placeRepository.Find(o => o.Identifiers.Any(i => i.Value == id), 0, 1, out tc).FirstOrDefault();
if (place == null)
{
Guid uuid = Guid.Empty;
if (Guid.TryParse(id, out uuid))
place = this.m_placeRepository.Get(uuid, Guid.Empty);
if(place == null)
{
this.m_tracer.TraceError($"Place {filter.inventoryLocation.gln} not found");
throw new FileNotFoundException(this.m_localizationService.FormatString("error.messaging.gs1.placeNotFound",
new
{
param = filter.inventoryLocation.gln
}));
}
}
if (filterPlaces == null)
filterPlaces = new List<Place>() { place };
else
filterPlaces.Add(place);
}
}
else
filterPlaces = this.m_placeRepository.Find(o => o.ClassConceptKey == EntityClassKeys.ServiceDeliveryLocation).ToList();
// Get the GLN AA data
var oidService = ApplicationServiceContext.Current.GetService<IAssigningAuthorityRepositoryService>();
var gln = oidService.Get("GLN");
var gtin = oidService.Get("GTIN");
if (gln == null || gln.Oid == null)
{
this.m_tracer.TraceError("GLN configuration must carry OID and be named GLN in repository");
throw new InvalidOperationException(this.m_localizationService.FormatString("error.messaging.gs1.configuration", new
{
param = "GLN",
}));
}
if (gtin == null || gtin.Oid == null)
{
this.m_tracer.TraceError("GTIN configuration must carry OID and be named GTIN in repository");
throw new InvalidOperationException(this.m_localizationService.FormatString("error.messaging.gs1.configuration", new
{
param = "GTIN"
}));
}
var masterAuthContext = AuthenticationContext.Current.Principal;
// Create the inventory report
filterPlaces.AsParallel().ForAll(place =>
{
using (AuthenticationContext.EnterContext(masterAuthContext))
{
try
{
var locationStockStatus = new LogisticsInventoryReportInventoryLocationType();
lock (locationStockStatuses)
locationStockStatuses.Add(locationStockStatus);
// TODO: Store the GLN configuration domain name
locationStockStatus.inventoryLocation = this.m_gs1Util.CreateLocation(place);
var tradeItemStatuses = new List<TradeItemInventoryStatusType>();
// What are the relationships of held entities
var persistenceService = ApplicationServiceContext.Current.GetService<IDataPersistenceService<EntityRelationship>>();
var relationships = persistenceService.Query(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.OwnedEntity && o.SourceEntityKey == place.Key.Value, AuthenticationContext.Current.Principal);
relationships.AsParallel().ForAll(rel =>
{
using (AuthenticationContext.EnterContext(masterAuthContext))
{
if (!(rel.TargetEntity is ManufacturedMaterial))
{
var matl = this.m_manufMaterialRepository.Get(rel.TargetEntityKey.Value, Guid.Empty);
if (matl == null)
{
Trace.TraceWarning("It looks like {0} owns {1} but {1} is not a mmat!?!?!", place.Key, rel.TargetEntityKey);
return;
}
else
rel.TargetEntity = matl;
}
var mmat = rel.TargetEntity as ManufacturedMaterial;
if (!(mmat is ManufacturedMaterial))
return;
var mat = this.m_materialRepository.Find(o => o.Relationships.Where(r => r.RelationshipType.Mnemonic == "Instance").Any(r => r.TargetEntity.Key == mmat.Key)).FirstOrDefault();
var instanceData = mat.LoadCollection<EntityRelationship>("Relationships").FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.Instance);
decimal balanceOH = rel.Quantity ?? 0;
// get the adjustments the adjustment acts are allocations and transfers
var adjustments = this.m_stockService.FindAdjustments(mmat.Key.Value, place.Key.Value, reportFrom, reportTo);
// We want to roll back to the start time and re-calc balance oh at time?
if (reportTo.Value.Date < DateTime.Now.Date)
{
var consumed = this.m_stockService.GetConsumed(mmat.Key.Value, place.Key.Value, reportTo, DateTime.Now);
balanceOH -= (decimal)consumed.Sum(o => o.Quantity ?? 0);
if (balanceOH == 0 && this.m_stockService.GetConsumed(mmat.Key.Value, place.Key.Value, reportFrom, reportTo).Count() == 0)
return;
}
ReferenceTerm cvx = null;
if (mat.TypeConceptKey.HasValue)
cvx = ApplicationServiceContext.Current.GetService<IConceptRepositoryService>().GetConceptReferenceTerm(mat.TypeConceptKey.Value, "CVX");
var typeItemCode = new ItemTypeCodeType()
{
Value = cvx?.Mnemonic ?? mmat.TypeConcept?.Mnemonic ?? mat.Key.Value.ToString(),
codeListVersion = cvx?.LoadProperty<CodeSystem>("CodeSystem")?.Authority ?? "SanteDB-MaterialType"
};
// First we need the GTIN for on-hand balance
lock (tradeItemStatuses)
tradeItemStatuses.Add(new TradeItemInventoryStatusType()
{
gtin = mmat.Identifiers.FirstOrDefault(o => o.Authority.DomainName == "GTIN")?.Value,
itemTypeCode = typeItemCode,
additionalTradeItemIdentification = mmat.Identifiers.Where(o => o.Authority.DomainName != "GTIN").Select(o => new AdditionalTradeItemIdentificationType()
{
additionalTradeItemIdentificationTypeCode = o.Authority.DomainName,
Value = o.Value
}).ToArray(),
tradeItemDescription = mmat.Names.Select(o => new Description200Type() { Value = o.Component.FirstOrDefault()?.Value }).FirstOrDefault(),
tradeItemClassification = new TradeItemClassificationType()
{
additionalTradeItemClassificationCode = mat.Identifiers.Where(o => o.Authority.Oid != gtin.Oid).Select(o => new AdditionalTradeItemClassificationCodeType()
{
codeListVersion = o.Authority.DomainName,
Value = o.Value
}).ToArray()
},
inventoryDateTime = DateTime.Now,
inventoryDispositionCode = new InventoryDispositionCodeType() { Value = "ON_HAND" },
transactionalItemData = new TransactionalItemDataType[]
{
new TransactionalItemDataType()
{
tradeItemQuantity = new QuantityType()
{
measurementUnitCode = (mmat.QuantityConcept ?? mat?.QuantityConcept)?.ReferenceTerms.Select(o => new AdditionalLogisticUnitIdentificationType()
{
additionalLogisticUnitIdentificationTypeCode = o.ReferenceTerm.CodeSystem.Name,
Value = o.ReferenceTerm.Mnemonic
}).FirstOrDefault()?.Value,
Value = balanceOH
},
batchNumber = mmat.LotNumber,
itemExpirationDate = mmat.ExpiryDate.Value,
itemExpirationDateSpecified = true
}
}
});
foreach (var adjgrp in adjustments.GroupBy(o => o.ReasonConceptKey))
{
var reasonConcept = ApplicationServiceContext.Current.GetService<IConceptRepositoryService>().GetConceptReferenceTerm(adjgrp.Key.Value, "GS1_STOCK_STATUS")?.Mnemonic;
if (reasonConcept == null)
reasonConcept = (ApplicationServiceContext.Current.GetService<IConceptRepositoryService>().Get(adjgrp.Key.Value, Guid.Empty) as Concept)?.Mnemonic;
// Broken vials?
lock (tradeItemStatuses)
tradeItemStatuses.Add(new TradeItemInventoryStatusType()
{
gtin = mmat.Identifiers.FirstOrDefault(o => o.Authority.DomainName == "GTIN")?.Value,
itemTypeCode = typeItemCode,
additionalTradeItemIdentification = mmat.Identifiers.Where(o => o.Authority.DomainName != "GTIN").Select(o => new AdditionalTradeItemIdentificationType()
{
additionalTradeItemIdentificationTypeCode = o.Authority.DomainName,
Value = o.Value
}).ToArray(),
tradeItemClassification = new TradeItemClassificationType()
{
additionalTradeItemClassificationCode = mat.Identifiers.Where(o => o.Authority.Oid != gtin.Oid).Select(o => new AdditionalTradeItemClassificationCodeType()
{
codeListVersion = o.Authority.DomainName,
Value = o.Value
}).ToArray()
},
tradeItemDescription = mmat.Names.Select(o => new Description200Type() { Value = o.Component.FirstOrDefault()?.Value }).FirstOrDefault(),
inventoryDateTime = DateTime.Now,
inventoryDispositionCode = new InventoryDispositionCodeType() { Value = reasonConcept },
transactionalItemData = new TransactionalItemDataType[]
{
new TransactionalItemDataType()
{
transactionalItemLogisticUnitInformation = instanceData == null ? null : new TransactionalItemLogisticUnitInformationType()
{
numberOfLayers = "1",
numberOfUnitsPerLayer = instanceData.Quantity.ToString(),
packageTypeCode = new PackageTypeCodeType() { Value = mat.LoadCollection<EntityExtension>("Extensions").FirstOrDefault(o=>o.ExtensionTypeKey == Gs1ModelExtensions.PackagingUnit)?.ExtensionValue?.ToString() ?? "CONT" }
},
tradeItemQuantity = new QuantityType()
{
measurementUnitCode = (mmat.QuantityConcept ?? mat?.QuantityConcept)?.ReferenceTerms.Select(o => new AdditionalLogisticUnitIdentificationType()
{
additionalLogisticUnitIdentificationTypeCode = o.ReferenceTerm.CodeSystem.Name,
Value = o.ReferenceTerm.Mnemonic
}).FirstOrDefault()?.Value,
Value = Math.Abs(adjgrp.Sum(o => o.Participations.First(p => p.ParticipationRoleKey == ActParticipationKey.Consumable && p.PlayerEntityKey == mmat.Key).Quantity.Value))
},
batchNumber = mmat.LotNumber,
itemExpirationDate = mmat.ExpiryDate.Value,
itemExpirationDateSpecified = true
}
}
});
}
}
});
// Reduce
locationStockStatus.tradeItemInventoryStatus = tradeItemStatuses.ToArray();
}
catch (Exception e)
{
traceSource.TraceError("Error fetching stock data : {0}", e);
}
}
// TODO: Reduce and Group by GTIN
});
report.logisticsInventoryReportInventoryLocation = locationStockStatuses.ToArray();
retVal.logisticsInventoryReport = new LogisticsInventoryReportType[] { report };
return retVal;
}
/// <summary>
/// Issues the order response message which will mark the requested order as underway
/// </summary>
public void IssueOrderResponse(OrderResponseMessageType orderResponse)
{
// TODO: Validate the standard header
Bundle orderTransaction = new Bundle();
// Loop
foreach (var resp in orderResponse.orderResponse)
{
// Find the original order which this despatch advice is fulfilling
Act orderRequestAct = this.m_gs1Util.GetOrder(resp.originalOrder, ActMoodKeys.Request);
if (orderRequestAct == null)
{
this.m_tracer.TraceError("Could not find originalOrder");
throw new KeyNotFoundException(this.m_localizationService.GetString("error.messaging.gs1.originalOrder"));
}
// Update the supplier if it exists
Place sourceLocation = this.m_gs1Util.GetLocation(resp.seller);
if (sourceLocation != null && !orderRequestAct.Participations.Any(o => o.ParticipationRoleKey == ActParticipationKey.Distributor))
{
// Add participation
orderRequestAct.Participations.Add(new ActParticipation()
{
ActKey = orderRequestAct.Key,
PlayerEntityKey = sourceLocation.Key,
ParticipationRoleKey = ActParticipationKey.Distributor
});
}
else if (resp.seller != null && sourceLocation == null)
{
this.m_tracer.TraceError($"Could not find seller id with {resp.seller?.additionalPartyIdentification?.FirstOrDefault()?.Value ?? resp.seller.gln}");
throw new KeyNotFoundException(this.m_localizationService.FormatString("error.messaging.gs1.seller", new
{
param = resp.seller?.additionalPartyIdentification?.FirstOrDefault()?.Value ?? resp.seller.gln
}));
}
var oidService = ApplicationServiceContext.Current.GetService<IAssigningAuthorityRepositoryService>();
var gln = oidService.Get("GLN");
var issuingAuthority = oidService.Find(o=>o.Oid == $"{gln.Oid}.{resp.orderResponseIdentification.contentOwner.gln}").FirstOrDefault();
if (issuingAuthority == null)
issuingAuthority = oidService.Get(this.m_configuration.DefaultContentOwnerAssigningAuthority);
if (issuingAuthority == null)
{
this.m_tracer.TraceError("Could not find default issuing authority for advice identification. Please configure a valid OID");
throw new KeyNotFoundException(this.m_localizationService.GetString("error.messaging.gs1.issuingAuthority"));
}
orderRequestAct.Identifiers.Add(new ActIdentifier(issuingAuthority, resp.orderResponseIdentification.entityIdentification));
// If the original order request is not comlete, then complete it
var existingTag = orderRequestAct.Tags.FirstOrDefault(o => o.TagKey == "orderStatus");
if (existingTag == null)
{
existingTag = new ActTag("orderStatus", "");
orderRequestAct.Tags.Add(existingTag);
}
// Accepted or not
if (resp.responseStatusCode?.Value == "ACCEPTED")
existingTag.Value = "accepted";
else if (resp.responseStatusCode?.Value == "REJECTED")
existingTag.Value = "rejected";
orderTransaction.Add(orderRequestAct);
}
// insert transaction
try
{
ApplicationServiceContext.Current.GetService<IRepositoryService<Bundle>>().Insert(orderTransaction);
}
catch (Exception e)
{
this.m_tracer.TraceError("Error issuing despatch advice: {0}", e);
throw new Exception(this.m_localizationService.FormatString("error.messaging.gs1.errorIssuing", new
{
param = e.Message
}), e);
}
}
}
} | 56.278418 | 263 | 0.532361 | [
"Apache-2.0"
] | santedb/santedb-gs1 | SanteDB.Messaging.GS1/Rest/StockServiceBehavior.cs | 34,163 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using SerializationTypes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using Xunit;
public static partial class XmlSerializerTests
{
#if ReflectionOnly|| XMLSERIALIZERGENERATORTESTS
private static readonly string SerializationModeSetterName = "set_Mode";
static XmlSerializerTests()
{
MethodInfo method = typeof(XmlSerializer).GetMethod(SerializationModeSetterName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(method != null, $"No method named {SerializationModeSetterName}");
#if ReflectionOnly
method.Invoke(null, new object[] { 1 });
#endif
#if XMLSERIALIZERGENERATORTESTS
method.Invoke(null, new object[] { 3 });
#endif
}
#endif
private static bool IsTimeSpanSerializationAvailable => true;
[Fact]
public static void Xml_TypeWithDateTimePropertyAsXmlTime()
{
DateTime localTime = new DateTime(549269870000L, DateTimeKind.Local);
TypeWithDateTimePropertyAsXmlTime localTimeOjbect = new TypeWithDateTimePropertyAsXmlTime()
{
Value = localTime
};
// This is how we convert DateTime from time to string.
var localTimeDateTime = DateTime.MinValue + localTime.TimeOfDay;
string localTimeString = localTimeDateTime.ToString("HH:mm:ss.fffffffzzzzzz", DateTimeFormatInfo.InvariantInfo);
TypeWithDateTimePropertyAsXmlTime localTimeOjbectRoundTrip = SerializeAndDeserialize(localTimeOjbect,
string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
<TypeWithDateTimePropertyAsXmlTime xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">{0}</TypeWithDateTimePropertyAsXmlTime>", localTimeString));
Assert.StrictEqual(localTimeOjbect.Value, localTimeOjbectRoundTrip.Value);
TypeWithDateTimePropertyAsXmlTime utcTimeOjbect = new TypeWithDateTimePropertyAsXmlTime()
{
Value = new DateTime(549269870000L, DateTimeKind.Utc)
};
if (IsTimeSpanSerializationAvailable)
{
TypeWithDateTimePropertyAsXmlTime utcTimeRoundTrip = SerializeAndDeserialize(utcTimeOjbect,
@"<?xml version=""1.0"" encoding=""utf-8""?>
<TypeWithDateTimePropertyAsXmlTime xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">15:15:26.9870000Z</TypeWithDateTimePropertyAsXmlTime>");
Assert.StrictEqual(utcTimeOjbect.Value, utcTimeRoundTrip.Value);
}
}
[Fact]
public static void Xml_ArrayAsGetSet()
{
TypeWithGetSetArrayMembers x = new TypeWithGetSetArrayMembers
{
F1 = new SimpleType[] { new SimpleType { P1 = "ab", P2 = 1 }, new SimpleType { P1 = "cd", P2 = 2 } },
F2 = new int[] { -1, 3 },
P1 = new SimpleType[] { new SimpleType { P1 = "ef", P2 = 5 }, new SimpleType { P1 = "gh", P2 = 7 } },
P2 = new int[] { 11, 12 }
};
TypeWithGetSetArrayMembers y = SerializeAndDeserialize<TypeWithGetSetArrayMembers>(x,
@"<?xml version=""1.0""?>
<TypeWithGetSetArrayMembers xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<F1>
<SimpleType>
<P1>ab</P1>
<P2>1</P2>
</SimpleType>
<SimpleType>
<P1>cd</P1>
<P2>2</P2>
</SimpleType>
</F1>
<F2>
<int>-1</int>
<int>3</int>
</F2>
<P1>
<SimpleType>
<P1>ef</P1>
<P2>5</P2>
</SimpleType>
<SimpleType>
<P1>gh</P1>
<P2>7</P2>
</SimpleType>
</P1>
<P2>
<int>11</int>
<int>12</int>
</P2>
</TypeWithGetSetArrayMembers>");
Assert.NotNull(y);
Utils.Equal<SimpleType>(x.F1, y.F1, (a, b) => { return SimpleType.AreEqual(a, b); });
Assert.Equal(x.F2, y.F2);
Utils.Equal<SimpleType>(x.P1, y.P1, (a, b) => { return SimpleType.AreEqual(a, b); });
Assert.Equal(x.P2, y.P2);
}
[Fact]
public static void Xml_ArrayAsGetOnly()
{
TypeWithGetOnlyArrayProperties x = new TypeWithGetOnlyArrayProperties();
x.P1[0] = new SimpleType { P1 = "ab", P2 = 1 };
x.P1[1] = new SimpleType { P1 = "cd", P2 = 2 };
x.P2[0] = -1;
x.P2[1] = 3;
TypeWithGetOnlyArrayProperties y = SerializeAndDeserialize<TypeWithGetOnlyArrayProperties>(x,
@"<?xml version=""1.0""?>
<TypeWithGetOnlyArrayProperties xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />");
Assert.NotNull(y);
// XmlSerializer seems not complain about missing public setter of Array property
// However, it does not serialize the property. So for this test case, I'll use it to verify there are no complaints about missing public setter
}
[Fact]
public static void Xml_ListRoot()
{
MyList x = new MyList("a1", "a2");
MyList y = SerializeAndDeserialize<MyList>(x,
@"<?xml version=""1.0""?>
<ArrayOfAnyType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<anyType xsi:type=""xsd:string"">a1</anyType>
<anyType xsi:type=""xsd:string"">a2</anyType>
</ArrayOfAnyType>");
Assert.NotNull(y);
Assert.True(y.Count == 2);
Assert.Equal((string)x[0], (string)y[0]);
Assert.Equal((string)x[1], (string)y[1]);
}
[Fact]
public static void Xml_EnumAsRoot()
{
Assert.StrictEqual(MyEnum.Two, SerializeAndDeserialize<MyEnum>(MyEnum.Two,
@"<?xml version=""1.0""?>
<MyEnum>Two</MyEnum>"));
Assert.StrictEqual(ByteEnum.Option1, SerializeAndDeserialize<ByteEnum>(ByteEnum.Option1,
@"<?xml version=""1.0""?>
<ByteEnum>Option1</ByteEnum>"));
Assert.StrictEqual(SByteEnum.Option1, SerializeAndDeserialize<SByteEnum>(SByteEnum.Option1,
@"<?xml version=""1.0""?>
<SByteEnum>Option1</SByteEnum>"));
Assert.StrictEqual(ShortEnum.Option1, SerializeAndDeserialize<ShortEnum>(ShortEnum.Option1,
@"<?xml version=""1.0""?>
<ShortEnum>Option1</ShortEnum>"));
Assert.StrictEqual(IntEnum.Option1, SerializeAndDeserialize<IntEnum>(IntEnum.Option1,
@"<?xml version=""1.0""?>
<IntEnum>Option1</IntEnum>"));
Assert.StrictEqual(UIntEnum.Option1, SerializeAndDeserialize<UIntEnum>(UIntEnum.Option1,
@"<?xml version=""1.0""?>
<UIntEnum>Option1</UIntEnum>"));
Assert.StrictEqual(LongEnum.Option1, SerializeAndDeserialize<LongEnum>(LongEnum.Option1,
@"<?xml version=""1.0""?>
<LongEnum>Option1</LongEnum>"));
Assert.StrictEqual(ULongEnum.Option1, SerializeAndDeserialize<ULongEnum>(ULongEnum.Option1,
@"<?xml version=""1.0""?>
<ULongEnum>Option1</ULongEnum>"));
}
[Fact]
public static void Xml_EnumAsMember()
{
TypeWithEnumMembers x = new TypeWithEnumMembers { F1 = MyEnum.Three, P1 = MyEnum.Two };
TypeWithEnumMembers y = SerializeAndDeserialize<TypeWithEnumMembers>(x,
@"<?xml version=""1.0""?>
<TypeWithEnumMembers xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<F1>Three</F1>
<P1>Two</P1>
</TypeWithEnumMembers>");
Assert.NotNull(y);
Assert.StrictEqual(x.F1, y.F1);
Assert.StrictEqual(x.P1, y.P1);
}
[Fact]
public static void Xml_DCClassWithEnumAndStruct()
{
DCClassWithEnumAndStruct value = new DCClassWithEnumAndStruct(true);
DCClassWithEnumAndStruct actual = SerializeAndDeserialize<DCClassWithEnumAndStruct>(value,
@"<?xml version=""1.0""?>
<DCClassWithEnumAndStruct xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<MyStruct>
<Data>Data</Data>
</MyStruct>
<MyEnum1>One</MyEnum1>
</DCClassWithEnumAndStruct>");
Assert.StrictEqual(value.MyEnum1, actual.MyEnum1);
Assert.Equal(value.MyStruct.Data, actual.MyStruct.Data);
}
[Fact]
public static void Xml_BuiltInTypes()
{
BuiltInTypes x = new BuiltInTypes
{
ByteArray = new byte[] { 1, 2 }
};
BuiltInTypes y = SerializeAndDeserialize<BuiltInTypes>(x,
@"<?xml version=""1.0""?>
<BuiltInTypes xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ByteArray>AQI=</ByteArray>
</BuiltInTypes>");
Assert.NotNull(y);
Assert.Equal(x.ByteArray, y.ByteArray);
}
[Fact]
public static void Xml_TypesWithArrayOfOtherTypes()
{
SerializeAndDeserialize<TypeHasArrayOfASerializedAsB>(new TypeHasArrayOfASerializedAsB(true),
@"<?xml version=""1.0""?>
<TypeHasArrayOfASerializedAsB xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Items>
<TypeA>
<Name>typeAValue</Name>
</TypeA>
<TypeA>
<Name>typeBValue</Name>
</TypeA>
</Items>
</TypeHasArrayOfASerializedAsB>");
}
[Fact]
public static void Xml_TypeNamesWithSpecialCharacters()
{
SerializeAndDeserialize<__TypeNameWithSpecialCharacters\u6F22\u00F1>(
new __TypeNameWithSpecialCharacters\u6F22\u00F1() { PropertyNameWithSpecialCharacters\u6F22\u00F1 = "Test" },
"<?xml version=\"1.0\"?><__TypeNameWithSpecialCharacters\u6F22\u00F1 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <PropertyNameWithSpecialCharacters\u6F22\u00F1>Test</PropertyNameWithSpecialCharacters\u6F22\u00F1></__TypeNameWithSpecialCharacters\u6F22\u00F1>");
}
[Fact]
public static void Xml_KnownTypesThroughConstructor()
{
KnownTypesThroughConstructor value = new KnownTypesThroughConstructor() { EnumValue = MyEnum.One, SimpleTypeValue = new SimpleKnownTypeValue() { StrProperty = "PropertyValue" } };
KnownTypesThroughConstructor actual = SerializeAndDeserialize<KnownTypesThroughConstructor>(value,
@"<?xml version=""1.0""?>
<KnownTypesThroughConstructor xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<EnumValue xsi:type=""MyEnum"">One</EnumValue>
<SimpleTypeValue xsi:type=""SimpleKnownTypeValue"">
<StrProperty>PropertyValue</StrProperty>
</SimpleTypeValue>
</KnownTypesThroughConstructor>",
() => { return new XmlSerializer(typeof(KnownTypesThroughConstructor), new Type[] { typeof(MyEnum), typeof(SimpleKnownTypeValue) }); });
Assert.StrictEqual((MyEnum)value.EnumValue, (MyEnum)actual.EnumValue);
Assert.Equal(((SimpleKnownTypeValue)value.SimpleTypeValue).StrProperty, ((SimpleKnownTypeValue)actual.SimpleTypeValue).StrProperty);
}
[Fact]
public static void Xml_BaseClassAndDerivedClassWithSameProperty()
{
DerivedClassWithSameProperty value = new DerivedClassWithSameProperty() { DateTimeProperty = new DateTime(100), IntProperty = 5, StringProperty = "TestString", ListProperty = new List<string>() };
value.ListProperty.AddRange(new string[] { "one", "two", "three" });
DerivedClassWithSameProperty actual = SerializeAndDeserialize<DerivedClassWithSameProperty>(value,
@"<?xml version=""1.0""?>
<DerivedClassWithSameProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<StringProperty>TestString</StringProperty>
<IntProperty>5</IntProperty>
<DateTimeProperty>0001-01-01T00:00:00.00001</DateTimeProperty>
<ListProperty>
<string>one</string>
<string>two</string>
<string>three</string>
</ListProperty>
</DerivedClassWithSameProperty>");
Assert.StrictEqual(value.DateTimeProperty, actual.DateTimeProperty);
Assert.StrictEqual(value.IntProperty, actual.IntProperty);
Assert.Equal(value.StringProperty, actual.StringProperty);
Assert.Equal(value.ListProperty.ToArray(), actual.ListProperty.ToArray());
}
[Fact]
public static void Xml_EnumFlags()
{
EnumFlags value1 = EnumFlags.One | EnumFlags.Four;
var value2 = SerializeAndDeserialize<EnumFlags>(value1,
@"<?xml version=""1.0""?>
<EnumFlags>One Four</EnumFlags>");
Assert.StrictEqual(value1, value2);
}
[Fact]
public static void Xml_SerializeClassThatImplementsInteface()
{
ClassImplementsInterface value = new ClassImplementsInterface() { ClassID = "ClassID", DisplayName = "DisplayName", Id = "Id", IsLoaded = true };
ClassImplementsInterface actual = SerializeAndDeserialize<ClassImplementsInterface>(value,
@"<?xml version=""1.0""?>
<ClassImplementsInterface xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ClassID>ClassID</ClassID>
<DisplayName>DisplayName</DisplayName>
<Id>Id</Id>
<IsLoaded>true</IsLoaded>
</ClassImplementsInterface>");
Assert.Equal(value.ClassID, actual.ClassID);
Assert.Equal(value.DisplayName, actual.DisplayName);
Assert.Equal(value.Id, actual.Id);
Assert.StrictEqual(value.IsLoaded, actual.IsLoaded);
}
[Fact]
public static void Xml_XmlAttributesTest()
{
var value = new XmlSerializerAttributes();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<AttributeTesting xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" XmlAttributeName=""2"">
<Word>String choice value</Word>
<XmlIncludeProperty xsi:type=""ItemChoiceType"">DecimalNumber</XmlIncludeProperty>
<XmlEnumProperty>
<ItemChoiceType>DecimalNumber</ItemChoiceType>
<ItemChoiceType>Number</ItemChoiceType>
<ItemChoiceType>Word</ItemChoiceType>
<ItemChoiceType>None</ItemChoiceType>
</XmlEnumProperty><xml>Hello XML</xml><XmlNamespaceDeclarationsProperty>XmlNamespaceDeclarationsPropertyValue</XmlNamespaceDeclarationsProperty><XmlElementPropertyNode xmlns=""http://element"">1</XmlElementPropertyNode><CustomXmlArrayProperty xmlns=""http://mynamespace""><string>one</string><string>two</string><string>three</string></CustomXmlArrayProperty></AttributeTesting>");
Assert.StrictEqual(actual.EnumType, value.EnumType);
Assert.StrictEqual(actual.MyChoice, value.MyChoice);
object[] stringArray = actual.XmlArrayProperty.Where(x => x != null)
.Select(x => x.ToString())
.ToArray();
Assert.Equal(stringArray, value.XmlArrayProperty);
Assert.StrictEqual(actual.XmlAttributeProperty, value.XmlAttributeProperty);
Assert.StrictEqual(actual.XmlElementProperty, value.XmlElementProperty);
Assert.Equal(actual.XmlEnumProperty, value.XmlEnumProperty);
Assert.StrictEqual(actual.XmlIncludeProperty, value.XmlIncludeProperty);
Assert.Equal(actual.XmlNamespaceDeclarationsProperty, value.XmlNamespaceDeclarationsProperty);
Assert.Equal(actual.XmlTextProperty, value.XmlTextProperty);
}
[Fact]
public static void Xml_XmlAnyAttributeTest()
{
var serializer = new XmlSerializer(typeof(TypeWithAnyAttribute));
const string format = @"<?xml version=""1.0"" encoding=""utf-8""?><TypeWithAnyAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" GroupType = '{0}' IntProperty = '{1}' GroupBase = '{2}'><Name>{3}</Name></TypeWithAnyAttribute>";
const int intProperty = 42;
const string attribute1 = "Technical";
const string attribute2 = "Red";
const string name = "MyGroup";
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(format, attribute1, intProperty, attribute2, name);
writer.Flush();
stream.Position = 0;
var obj = (TypeWithAnyAttribute)serializer.Deserialize(stream);
Assert.NotNull(obj);
Assert.StrictEqual(intProperty, obj.IntProperty);
Assert.Equal(name, obj.Name);
Assert.StrictEqual(2, obj.Attributes.Length);
Assert.Equal(attribute1, obj.Attributes[0].Value);
Assert.Equal(attribute2, obj.Attributes[1].Value);
}
}
[Fact]
public static void Xml_Struct()
{
var value = new WithStruct { Some = new SomeStruct { A = 1, B = 2 } };
var result = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<WithStruct xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Some>
<A>1</A>
<B>2</B>
</Some>
</WithStruct>");
// Assert
Assert.StrictEqual(result.Some.A, value.Some.A);
Assert.StrictEqual(result.Some.B, value.Some.B);
}
[Fact]
public static void Xml_Enums()
{
var item = new WithEnums() { Int = IntEnum.Option1, Short = ShortEnum.Option2 };
var actual = SerializeAndDeserialize(item,
@"<?xml version=""1.0""?>
<WithEnums xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Int>Option1</Int>
<Short>Option2</Short>
</WithEnums>");
Assert.StrictEqual(item.Short, actual.Short);
Assert.StrictEqual(item.Int, actual.Int);
}
[Fact]
public static void Xml_Nullables()
{
var item = new WithNullables() { Optional = IntEnum.Option1, OptionalInt = 42, Struct1 = new SomeStruct { A = 1, B = 2 } };
var actual = SerializeAndDeserialize(item,
@"<?xml version=""1.0""?>
<WithNullables xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Optional>Option1</Optional>
<Optionull xsi:nil=""true"" />
<OptionalInt>42</OptionalInt>
<OptionullInt xsi:nil=""true"" />
<Struct1>
<A>1</A>
<B>2</B>
</Struct1>
<Struct2 xsi:nil=""true"" />
</WithNullables>");
Assert.StrictEqual(item.OptionalInt, actual.OptionalInt);
Assert.StrictEqual(item.Optional, actual.Optional);
Assert.StrictEqual(item.Optionull, actual.Optionull);
Assert.StrictEqual(item.OptionullInt, actual.OptionullInt);
Assert.Null(actual.Struct2);
Assert.StrictEqual(item.Struct1.Value.A, actual.Struct1.Value.A);
Assert.StrictEqual(item.Struct1.Value.B, actual.Struct1.Value.B);
}
[Fact]
public static void Xml_ClassImplementingIXmlSerialiable()
{
var value = new ClassImplementingIXmlSerialiable() { StringValue = "Hello world" };
var actual = SerializeAndDeserialize<ClassImplementingIXmlSerialiable>(value,
@"<?xml version=""1.0""?>
<ClassImplementingIXmlSerialiable StringValue=""Hello world"" BoolValue=""True"" />");
Assert.Equal(value.StringValue, actual.StringValue);
Assert.StrictEqual(value.GetPrivateMember(), actual.GetPrivateMember());
Assert.True(ClassImplementingIXmlSerialiable.ReadXmlInvoked);
Assert.True(ClassImplementingIXmlSerialiable.WriteXmlInvoked);
}
[Fact]
public static void Xml_TypeWithFieldNameEndBySpecified()
{
var value = new TypeWithPropertyNameSpecified() { MyField = "MyField", MyFieldIgnored = 99, MyFieldSpecified = true, MyFieldIgnoredSpecified = false };
var actual = SerializeAndDeserialize<TypeWithPropertyNameSpecified>(value,
@"<?xml version=""1.0""?><TypeWithPropertyNameSpecified xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><MyField>MyField</MyField></TypeWithPropertyNameSpecified>");
Assert.Equal(value.MyField, actual.MyField);
Assert.StrictEqual(0, actual.MyFieldIgnored);
}
[Fact]
public static void XML_TypeWithXmlSchemaFormAttribute()
{
var value = new TypeWithXmlSchemaFormAttribute() { NoneSchemaFormListProperty = new List<string> { "abc" }, QualifiedSchemaFormListProperty = new List<bool> { true }, UnqualifiedSchemaFormListProperty = new List<int> { 1 } };
var actual = SerializeAndDeserialize<TypeWithXmlSchemaFormAttribute>(value,
@"<?xml version=""1.0""?><TypeWithXmlSchemaFormAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><UnqualifiedSchemaFormListProperty><int>1</int></UnqualifiedSchemaFormListProperty><NoneSchemaFormListProperty><NoneParameter>abc</NoneParameter></NoneSchemaFormListProperty><QualifiedSchemaFormListProperty><QualifiedParameter>true</QualifiedParameter></QualifiedSchemaFormListProperty></TypeWithXmlSchemaFormAttribute>");
Assert.StrictEqual(value.NoneSchemaFormListProperty.Count, actual.NoneSchemaFormListProperty.Count);
Assert.Equal(value.NoneSchemaFormListProperty[0], actual.NoneSchemaFormListProperty[0]);
Assert.StrictEqual(value.UnqualifiedSchemaFormListProperty.Count, actual.UnqualifiedSchemaFormListProperty.Count);
Assert.StrictEqual(value.UnqualifiedSchemaFormListProperty[0], actual.UnqualifiedSchemaFormListProperty[0]);
Assert.StrictEqual(value.QualifiedSchemaFormListProperty.Count, actual.QualifiedSchemaFormListProperty.Count);
Assert.StrictEqual(value.QualifiedSchemaFormListProperty[0], actual.QualifiedSchemaFormListProperty[0]);
}
[Fact]
public static void XML_TypeWithTypeNameInXmlTypeAttribute()
{
var value = new TypeWithTypeNameInXmlTypeAttribute();
SerializeAndDeserialize<TypeWithTypeNameInXmlTypeAttribute>(value,
@"<?xml version=""1.0""?><MyXmlType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />");
}
[Fact]
public static void XML_TypeWithXmlTextAttributeOnArray()
{
var original = new TypeWithXmlTextAttributeOnArray() { Text = new string[] { "val1", "val2" } };
var actual = SerializeAndDeserialize<TypeWithXmlTextAttributeOnArray>(original,
@"<?xml version=""1.0""?>
<TypeWithXmlTextAttributeOnArray xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.xmlsoap.org/ws/2005/04/discovery"">val1val2</TypeWithXmlTextAttributeOnArray>");
Assert.NotNull(actual.Text);
Assert.StrictEqual(1, actual.Text.Length);
Assert.Equal("val1val2", actual.Text[0]);
}
[Fact]
public static void Xml_TypeWithSchemaFormInXmlAttribute()
{
var value = new TypeWithSchemaFormInXmlAttribute() { TestProperty = "hello" };
var actual = SerializeAndDeserialize<TypeWithSchemaFormInXmlAttribute>(value,
@"<?xml version=""1.0""?><TypeWithSchemaFormInXmlAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" d1p1:TestProperty=""hello"" xmlns:d1p1=""http://test.com"" />");
Assert.Equal(value.TestProperty, actual.TestProperty);
}
[Fact]
public static void Xml_TypeWithXmlElementProperty()
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(@"<html></html>");
XmlElement productElement = xDoc.CreateElement("Product");
productElement.InnerText = "Product innertext";
XmlElement categoryElement = xDoc.CreateElement("Category");
categoryElement.InnerText = "Category innertext";
var expected = new TypeWithXmlElementProperty() { Elements = new[] { productElement, categoryElement } };
var actual = SerializeAndDeserialize(expected,
@"<?xml version=""1.0"" encoding=""utf-8""?><TypeWithXmlElementProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Product>Product innertext</Product><Category>Category innertext</Category></TypeWithXmlElementProperty>");
Assert.StrictEqual(expected.Elements.Length, actual.Elements.Length);
for (int i = 0; i < expected.Elements.Length; ++i)
{
Assert.Equal(expected.Elements[i].InnerText, actual.Elements[i].InnerText);
}
}
[Fact]
public static void Xml_TypeWithXmlDocumentProperty()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<html><head>Head content</head><body><h1>Heading1</h1><div>Text in body</div></body></html>");
var expected = new TypeWithXmlDocumentProperty() { Document = xmlDoc };
var actual = SerializeAndDeserialize(expected,
@"<TypeWithXmlDocumentProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Document><html><head>Head content</head><body><h1>Heading1</h1><div>Text in body</div></body></html></Document></TypeWithXmlDocumentProperty>");
Assert.NotNull(actual);
Assert.NotNull(actual.Document);
Assert.Equal(expected.Document.OuterXml, actual.Document.OuterXml);
}
[Fact]
public static void Xml_TypeWithNonPublicDefaultConstructor()
{
System.Reflection.TypeInfo ti = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(TypeWithNonPublicDefaultConstructor));
TypeWithNonPublicDefaultConstructor value = null;
value = (TypeWithNonPublicDefaultConstructor)FindDefaultConstructor(ti).Invoke(null);
Assert.Equal("Mr. FooName", value.Name);
var actual = SerializeAndDeserialize<TypeWithNonPublicDefaultConstructor>(value,
@"<?xml version=""1.0""?>
<TypeWithNonPublicDefaultConstructor xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Name>Mr. FooName</Name>
</TypeWithNonPublicDefaultConstructor>");
Assert.Equal(value.Name, actual.Name);
}
private static System.Reflection.ConstructorInfo FindDefaultConstructor(System.Reflection.TypeInfo ti)
{
foreach (System.Reflection.ConstructorInfo ci in ti.DeclaredConstructors)
{
if (!ci.IsStatic && ci.GetParameters().Length == 0)
{
return ci;
}
}
return null;
}
[Fact]
public static void Xml_TestIgnoreWhitespaceForDeserialization()
{
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<ServerSettings>
<DS2Root>
<![CDATA[ http://wxdata.weather.com/wxdata/]]>
</DS2Root>
<MetricConfigUrl><![CDATA[ http://s3.amazonaws.com/windows-prod-twc/desktop8/beacons.xml ]]></MetricConfigUrl>
</ServerSettings>";
XmlSerializer serializer = new XmlSerializer(typeof(ServerSettings));
StringReader reader = new StringReader(xml);
var value = (ServerSettings)serializer.Deserialize(reader);
Assert.Equal(@" http://s3.amazonaws.com/windows-prod-twc/desktop8/beacons.xml ", value.MetricConfigUrl);
Assert.Equal(@" http://wxdata.weather.com/wxdata/", value.DS2Root);
}
[Fact]
public static void Xml_TypeWithBinaryProperty()
{
var obj = new TypeWithBinaryProperty();
var str = "The quick brown fox jumps over the lazy dog.";
obj.Base64Content = Encoding.Unicode.GetBytes(str);
obj.BinaryHexContent = Encoding.Unicode.GetBytes(str);
var actual = SerializeAndDeserialize(obj,
@"<?xml version=""1.0"" encoding=""utf-8""?><TypeWithBinaryProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><BinaryHexContent>540068006500200071007500690063006B002000620072006F0077006E00200066006F00780020006A0075006D007000730020006F00760065007200200074006800650020006C0061007A007900200064006F0067002E00</BinaryHexContent><Base64Content>VABoAGUAIABxAHUAaQBjAGsAIABiAHIAbwB3AG4AIABmAG8AeAAgAGoAdQBtAHAAcwAgAG8AdgBlAHIAIAB0AGgAZQAgAGwAYQB6AHkAIABkAG8AZwAuAA==</Base64Content></TypeWithBinaryProperty>");
Assert.True(Enumerable.SequenceEqual(obj.Base64Content, actual.Base64Content));
Assert.True(Enumerable.SequenceEqual(obj.BinaryHexContent, actual.BinaryHexContent));
}
[Fact]
public static void Xml_DifferentSerializeDeserializeOverloads()
{
var expected = new SimpleType() { P1 = "p1 value", P2 = 123 };
var serializer = new XmlSerializer(typeof(SimpleType));
var writerTypes = new Type[] { typeof(TextWriter), typeof(XmlWriter) };
Assert.Throws<InvalidOperationException>(() =>
{
XmlWriter writer = null;
serializer.Serialize(writer, expected);
});
Assert.Throws<InvalidOperationException>(() =>
{
XmlReader reader = null;
serializer.Deserialize(reader);
});
foreach (var writerType in writerTypes)
{
var stream = new MemoryStream();
if (writerType == typeof(TextWriter))
{
var writer = new StreamWriter(stream);
serializer.Serialize(writer, expected);
}
else
{
var writer = XmlWriter.Create(stream);
serializer.Serialize(writer, expected);
}
stream.Position = 0;
var actualOutput = new StreamReader(stream).ReadToEnd();
const string baseline =
@"<?xml version=""1.0"" encoding=""utf-8""?><SimpleType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><P1>p1 value</P1><P2>123</P2></SimpleType>";
var result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}", Environment.NewLine, result.ErrorMessage, expected, baseline, actualOutput));
stream.Position = 0;
// XmlSerializer.CanSerialize(XmlReader)
XmlReader reader = XmlReader.Create(stream);
Assert.True(serializer.CanDeserialize(reader));
// XmlSerializer.Deserialize(XmlReader)
var actual = (SimpleType)serializer.Deserialize(reader);
Assert.Equal(expected.P1, actual.P1);
Assert.StrictEqual(expected.P2, actual.P2);
stream.Dispose();
}
}
[ConditionalFact(nameof(IsTimeSpanSerializationAvailable))]
public static void Xml_TypeWithTimeSpanProperty()
{
var obj = new TypeWithTimeSpanProperty { TimeSpanProperty = TimeSpan.FromMilliseconds(1) };
var deserializedObj = SerializeAndDeserialize(obj,
@"<?xml version=""1.0"" encoding=""utf-16""?>
<TypeWithTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<TimeSpanProperty>PT0.001S</TimeSpanProperty>
</TypeWithTimeSpanProperty>");
Assert.StrictEqual(obj.TimeSpanProperty, deserializedObj.TimeSpanProperty);
}
[ConditionalFact(nameof(IsTimeSpanSerializationAvailable))]
public static void Xml_TypeWithDefaultTimeSpanProperty()
{
var obj = new TypeWithDefaultTimeSpanProperty { TimeSpanProperty2 = new TimeSpan(0, 1, 0) };
var deserializedObj = SerializeAndDeserialize(obj,
@"<?xml version=""1.0""?>
<TypeWithDefaultTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><TimeSpanProperty2>PT1M</TimeSpanProperty2></TypeWithDefaultTimeSpanProperty>");
Assert.NotNull(deserializedObj);
Assert.Equal(obj.TimeSpanProperty, deserializedObj.TimeSpanProperty);
Assert.Equal(obj.TimeSpanProperty2, deserializedObj.TimeSpanProperty2);
}
[Fact]
public static void Xml_DeserializeTypeWithEmptyTimeSpanProperty()
{
string xml =
@"<?xml version=""1.0""?>
<TypeWithTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<TimeSpanProperty />
</TypeWithTimeSpanProperty>";
XmlSerializer serializer = new XmlSerializer(typeof(TypeWithTimeSpanProperty));
using (StringReader reader = new StringReader(xml))
{
TypeWithTimeSpanProperty deserializedObj = (TypeWithTimeSpanProperty)serializer.Deserialize(reader);
Assert.NotNull(deserializedObj);
Assert.Equal(default(TimeSpan), deserializedObj.TimeSpanProperty);
}
}
[Fact]
public static void Xml_DeserializeEmptyTimeSpanType()
{
string xml =
@"<?xml version=""1.0""?>
<TimeSpan />";
XmlSerializer serializer = new XmlSerializer(typeof(TimeSpan));
using (StringReader reader = new StringReader(xml))
{
TimeSpan deserializedObj = (TimeSpan)serializer.Deserialize(reader);
Assert.Equal(default(TimeSpan), deserializedObj);
}
}
[Fact]
public static void Xml_TypeWithByteProperty()
{
var obj = new TypeWithByteProperty() { ByteProperty = 123 };
var deserializedObj = SerializeAndDeserialize(obj,
@"<?xml version=""1.0"" encoding=""utf-8""?>
<TypeWithByteProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ByteProperty>123</ByteProperty>
</TypeWithByteProperty>");
Assert.StrictEqual(obj.ByteProperty, deserializedObj.ByteProperty);
}
[Fact]
public static void Xml_DeserializeOutOfRangeByteProperty()
{
//Deserialize an instance with out-of-range value for the byte property, expecting exception from deserialization process
var serializer = new XmlSerializer(typeof(TypeWithByteProperty));
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<TypeWithByteProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ByteProperty>-1</ByteProperty>
</TypeWithByteProperty>");
writer.Flush();
stream.Position = 0;
Assert.Throws<InvalidOperationException>(() => {
var deserializedObj = (TypeWithByteProperty)serializer.Deserialize(stream);
});
}
}
[Fact]
public static void Xml_XmlAttributes_RemoveXmlElementAttribute()
{
XmlAttributes attrs = new XmlAttributes();
XmlElementAttribute item = new XmlElementAttribute("elem1");
attrs.XmlElements.Add(item);
Assert.True(attrs.XmlElements.Contains(item));
attrs.XmlElements.Remove(item);
Assert.False(attrs.XmlElements.Contains(item));
}
[Fact]
public static void Xml_ArrayOfXmlNodeProperty()
{
var obj = new TypeWithXmlNodeArrayProperty()
{
CDATA = new[] { new XmlDocument().CreateCDataSection("test&test") }
};
var deserializedObj = SerializeAndDeserialize<TypeWithXmlNodeArrayProperty>(obj, @"<TypeWithXmlNodeArrayProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><![CDATA[test&test]]></TypeWithXmlNodeArrayProperty>");
Assert.Equal(obj.CDATA.Length, deserializedObj.CDATA.Length);
Assert.Equal(obj.CDATA[0].InnerText, deserializedObj.CDATA[0].InnerText);
}
[Fact]
public static void Xml_TypeWithTwoDimensionalArrayProperty2()
{
SimpleType[][] simpleType2D = GetObjectwith2DArrayOfSimpleType();
var obj = new TypeWith2DArrayProperty2()
{
TwoDArrayOfSimpleType = simpleType2D
};
string baseline = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>\r\n<TypeWith2DArrayProperty2 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <TwoDArrayOfSimpleType>\r\n <SimpleType>\r\n <SimpleType>\r\n <P1>0 0 value</P1>\r\n <P2>1</P2>\r\n </SimpleType>\r\n <SimpleType>\r\n <P1>0 1 value</P1>\r\n <P2>2</P2>\r\n </SimpleType>\r\n </SimpleType>\r\n <SimpleType>\r\n <SimpleType>\r\n <P1>1 0 value</P1>\r\n <P2>3</P2>\r\n </SimpleType>\r\n <SimpleType>\r\n <P1>1 1 value</P1>\r\n <P2>4</P2>\r\n </SimpleType>\r\n </SimpleType>\r\n </TwoDArrayOfSimpleType>\r\n</TypeWith2DArrayProperty2>";
TypeWith2DArrayProperty2 actual = SerializeAndDeserialize(obj, baseline);
Assert.NotNull(actual);
Assert.True(SimpleType.AreEqual(simpleType2D[0][0], actual.TwoDArrayOfSimpleType[0][0]));
Assert.True(SimpleType.AreEqual(simpleType2D[0][1], actual.TwoDArrayOfSimpleType[0][1]));
Assert.True(SimpleType.AreEqual(simpleType2D[1][0], actual.TwoDArrayOfSimpleType[1][0]));
Assert.True(SimpleType.AreEqual(simpleType2D[1][1], actual.TwoDArrayOfSimpleType[1][1]));
}
private static SimpleType[][] GetObjectwith2DArrayOfSimpleType()
{
SimpleType[][] simpleType2D = new SimpleType[2][];
simpleType2D[0] = new SimpleType[2];
simpleType2D[1] = new SimpleType[2];
simpleType2D[0][0] = new SimpleType() { P1 = "0 0 value", P2 = 1 };
simpleType2D[0][1] = new SimpleType() { P1 = "0 1 value", P2 = 2 };
simpleType2D[1][0] = new SimpleType() { P1 = "1 0 value", P2 = 3 };
simpleType2D[1][1] = new SimpleType() { P1 = "1 1 value", P2 = 4 };
return simpleType2D;
}
[Fact]
public static void Xml_TypeWithByteArrayAsXmlText()
{
var value = new TypeWithByteArrayAsXmlText() { Value = new byte[] { 1, 2, 3 } };
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithByteArrayAsXmlText xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">AQID</TypeWithByteArrayAsXmlText>");
Assert.NotNull(actual);
Assert.NotNull(actual.Value);
Assert.Equal(value.Value.Length, actual.Value.Length);
Assert.True(Enumerable.SequenceEqual(value.Value, actual.Value));
}
[Fact]
public static void Xml_SimpleType()
{
var serializer = new XmlSerializer(typeof(SimpleType));
var obj = new SimpleType { P1 = "foo", P2 = 1 };
var deserializedObj = SerializeAndDeserialize(obj,
@"<?xml version=""1.0"" encoding=""utf-16""?>
<SimpleType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<P1>foo</P1>
<P2>1</P2>
</SimpleType>");
Assert.NotNull(deserializedObj);
Assert.Equal(obj.P1, deserializedObj.P1);
Assert.StrictEqual(obj.P2, deserializedObj.P2);
}
[Fact]
public static void Xml_BaseClassAndDerivedClass2WithSameProperty()
{
var value = new DerivedClassWithSameProperty2() { DateTimeProperty = new DateTime(100, DateTimeKind.Utc), IntProperty = 5, StringProperty = "TestString", ListProperty = new List<string>() };
value.ListProperty.AddRange(new string[] { "one", "two", "three" });
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<DerivedClassWithSameProperty2 xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<StringProperty>TestString</StringProperty>
<IntProperty>5</IntProperty>
<DateTimeProperty>0001-01-01T00:00:00.00001Z</DateTimeProperty>
<ListProperty>
<string>one</string>
<string>two</string>
<string>three</string>
</ListProperty>
</DerivedClassWithSameProperty2>");
Assert.StrictEqual(value.DateTimeProperty, actual.DateTimeProperty);
Assert.StrictEqual(value.IntProperty, actual.IntProperty);
Assert.Equal(value.StringProperty, actual.StringProperty);
Assert.Equal(value.ListProperty.ToArray(), actual.ListProperty.ToArray());
}
[Fact]
public static void Xml_TypeWithPropertiesHavingDefaultValue_DefaultValue()
{
var value = new TypeWithPropertiesHavingDefaultValue()
{
StringProperty = "DefaultString",
EmptyStringProperty = "",
IntProperty = 11,
CharProperty = 'm'
};
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithPropertiesHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <CharProperty>109</CharProperty>\r\n</TypeWithPropertiesHavingDefaultValue>");
Assert.NotNull(actual);
Assert.Equal(value.StringProperty, actual.StringProperty);
Assert.Equal(value.EmptyStringProperty, actual.EmptyStringProperty);
Assert.StrictEqual(value.IntProperty, actual.IntProperty);
Assert.StrictEqual(value.CharProperty, actual.CharProperty);
}
[Fact]
public static void Xml_TypeWithStringPropertyWithDefaultValue_NonDefaultValue()
{
var value = new TypeWithPropertiesHavingDefaultValue()
{
StringProperty = "NonDefaultValue",
EmptyStringProperty = "NonEmpty",
IntProperty = 12,
CharProperty = 'n'
};
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithPropertiesHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <EmptyStringProperty>NonEmpty</EmptyStringProperty>\r\n <StringProperty>NonDefaultValue</StringProperty>\r\n <IntProperty>12</IntProperty>\r\n <CharProperty>110</CharProperty>\r\n</TypeWithPropertiesHavingDefaultValue>");
Assert.NotNull(actual);
Assert.Equal(value.StringProperty, actual.StringProperty);
}
[Fact]
public static void Xml_TypeWithEnumPropertyHavingDefaultValue()
{
var value = new TypeWithEnumPropertyHavingDefaultValue() { EnumProperty = IntEnum.Option0 };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithEnumPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <EnumProperty>Option0</EnumProperty>\r\n</TypeWithEnumPropertyHavingDefaultValue>",
skipStringCompare: false);
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
value = new TypeWithEnumPropertyHavingDefaultValue() { EnumProperty = IntEnum.Option1 };
actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithEnumPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />",
skipStringCompare: false);
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
}
[Fact]
public static void Xml_TypeWithEnumFlagPropertyHavingDefaultValue()
{
var value = new TypeWithEnumFlagPropertyHavingDefaultValue() { EnumProperty = EnumFlags.Two | EnumFlags.Three };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithEnumFlagPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <EnumProperty>Two Three</EnumProperty>\r\n</TypeWithEnumFlagPropertyHavingDefaultValue>");
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
value = new TypeWithEnumFlagPropertyHavingDefaultValue();
actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithEnumFlagPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />");
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
}
[Fact]
public static void Xml_Soap_TypeWithEnumFlagPropertyHavingDefaultValue()
{
var mapping = new SoapReflectionImporter().ImportTypeMapping(typeof(TypeWithEnumFlagPropertyHavingDefaultValue));
var serializer = new XmlSerializer(mapping);
var value = new TypeWithEnumFlagPropertyHavingDefaultValue() { EnumProperty = EnumFlags.Two | EnumFlags.Three };
var actual = SerializeAndDeserialize(
value,
"<?xml version=\"1.0\"?>\r\n<TypeWithEnumFlagPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" id=\"id1\">\r\n <EnumProperty xsi:type=\"EnumFlags\">Two Three</EnumProperty>\r\n</TypeWithEnumFlagPropertyHavingDefaultValue>",
() => serializer);
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
value = new TypeWithEnumFlagPropertyHavingDefaultValue();
actual = SerializeAndDeserialize(
value,
"<?xml version=\"1.0\"?>\r\n<TypeWithEnumFlagPropertyHavingDefaultValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" id=\"id1\">\r\n <EnumProperty xsi:type=\"EnumFlags\">One Four</EnumProperty>\r\n</TypeWithEnumFlagPropertyHavingDefaultValue>",
() => serializer);
Assert.NotNull(actual);
Assert.StrictEqual(value.EnumProperty, actual.EnumProperty);
}
[Fact]
public static void Xml_TypeWithXmlQualifiedName()
{
var value = new TypeWithXmlQualifiedName()
{
Value = new XmlQualifiedName("FooName")
};
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithXmlQualifiedName xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <Value xmlns=\"\">FooName</Value>\r\n</TypeWithXmlQualifiedName>", skipStringCompare: false);
Assert.NotNull(actual);
Assert.StrictEqual(value.Value, actual.Value);
}
[Fact]
public static void Xml_Soap_TypeWithXmlQualifiedName()
{
var mapping = new SoapReflectionImporter().ImportTypeMapping(typeof(TypeWithXmlQualifiedName));
var serializer = new XmlSerializer(mapping);
var value = new TypeWithXmlQualifiedName()
{
Value = new XmlQualifiedName("FooName")
};
var actual = SerializeAndDeserialize(
value,
"<?xml version=\"1.0\"?>\r\n<TypeWithXmlQualifiedName xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" id=\"id1\">\r\n <Value xmlns=\"\" xsi:type=\"xsd:QName\">FooName</Value>\r\n</TypeWithXmlQualifiedName>",
() => serializer);
Assert.NotNull(actual);
Assert.StrictEqual(value.Value, actual.Value);
}
[Fact]
public static void Xml_TypeWithShouldSerializeMethod_WithDefaultValue()
{
var value = new TypeWithShouldSerializeMethod();
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithShouldSerializeMethod xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />");
Assert.NotNull(actual);
Assert.Equal(value.Foo, actual.Foo);
}
[Fact]
public static void Xml_TypeWithShouldSerializeMethod_WithNonDefaultValue()
{
var value = new TypeWithShouldSerializeMethod() { Foo = "SomeValue" };
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithShouldSerializeMethod xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Foo>SomeValue</Foo></TypeWithShouldSerializeMethod>");
Assert.NotNull(actual);
Assert.Equal(value.Foo, actual.Foo);
}
[Fact]
public static void Xml_KnownTypesThroughConstructorWithArrayProperties()
{
int[] intArray = new int[] { 1, 2, 3 };
string[] stringArray = new string[] { "a", "b" };
var value = new KnownTypesThroughConstructorWithArrayProperties() { IntArrayValue = intArray, StringArrayValue = stringArray };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<KnownTypesThroughConstructorWithArrayProperties xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <StringArrayValue xsi:type=\"ArrayOfString\">\r\n <string>a</string>\r\n <string>b</string>\r\n </StringArrayValue>\r\n <IntArrayValue xsi:type=\"ArrayOfInt\">\r\n <int>1</int>\r\n <int>2</int>\r\n <int>3</int>\r\n </IntArrayValue>\r\n</KnownTypesThroughConstructorWithArrayProperties>",
() => { return new XmlSerializer(typeof(KnownTypesThroughConstructorWithArrayProperties), new Type[] { typeof(int[]), typeof(string[]) }); },
skipStringCompare: false);
Assert.NotNull(actual);
var actualIntArray = (int[])actual.IntArrayValue;
Assert.NotNull(actualIntArray);
Assert.Equal(intArray.Length, actualIntArray.Length);
Assert.True(Enumerable.SequenceEqual(intArray, actualIntArray));
var actualStringArray = (string[])actual.StringArrayValue;
Assert.NotNull(actualStringArray);
Assert.True(Enumerable.SequenceEqual(stringArray, actualStringArray));
Assert.Equal(stringArray.Length, actualStringArray.Length);
}
[Fact]
public static void Xml_KnownTypesThroughConstructorWithEnumFlags()
{
var enumFlags = EnumFlags.One | EnumFlags.Four;
var value = new KnownTypesThroughConstructorWithValue() { Value = enumFlags };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<KnownTypesThroughConstructorWithValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <Value xsi:type=\"EnumFlags\">One Four</Value>\r\n</KnownTypesThroughConstructorWithValue>",
() => { return new XmlSerializer(typeof(KnownTypesThroughConstructorWithValue), new Type[] { typeof(EnumFlags) }); },
skipStringCompare: false);
Assert.NotNull(actual);
Assert.Equal((EnumFlags)value.Value, (EnumFlags)actual.Value);
}
[Fact]
public static void Xml_KnownTypesThroughConstructorWithEnumFlagsXmlQualifiedName()
{
var value = new KnownTypesThroughConstructorWithValue() { Value = new XmlQualifiedName("foo") };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<KnownTypesThroughConstructorWithValue xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <Value xsi:type=\"xsd:QName\">foo</Value>\r\n</KnownTypesThroughConstructorWithValue>",
() => { return new XmlSerializer(typeof(KnownTypesThroughConstructorWithValue), new Type[] { typeof(XmlQualifiedName) }); },
skipStringCompare: false);
Assert.NotNull(actual);
Assert.Equal((XmlQualifiedName)value.Value, (XmlQualifiedName)actual.Value);
}
[Fact]
public static void Xml_TypeWithTypesHavingCustomFormatter()
{
var str = "The quick brown fox jumps over the lazy dog.";
var value = new TypeWithTypesHavingCustomFormatter()
{
DateTimeContent = new DateTime(2016, 7, 18, 0, 0, 0, DateTimeKind.Utc),
QNameContent = new XmlQualifiedName("QNameContent"),
DateContent = new DateTime(2016, 7, 18, 0, 0, 0, DateTimeKind.Utc),
NameContent = "NameContent",
NCNameContent = "NCNameContent",
NMTOKENContent = "NMTOKENContent",
NMTOKENSContent = "NMTOKENSContent",
Base64BinaryContent = Encoding.Unicode.GetBytes(str),
HexBinaryContent = Encoding.Unicode.GetBytes(str),
};
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithTypesHavingCustomFormatter xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <DateTimeContent>2016-07-18T00:00:00Z</DateTimeContent>\r\n <QNameContent xmlns=\"\">QNameContent</QNameContent>\r\n <DateContent>2016-07-18</DateContent>\r\n <NameContent>NameContent</NameContent>\r\n <NCNameContent>NCNameContent</NCNameContent>\r\n <NMTOKENContent>NMTOKENContent</NMTOKENContent>\r\n <NMTOKENSContent>NMTOKENSContent</NMTOKENSContent>\r\n <Base64BinaryContent>VABoAGUAIABxAHUAaQBjAGsAIABiAHIAbwB3AG4AIABmAG8AeAAgAGoAdQBtAHAAcwAgAG8AdgBlAHIAIAB0AGgAZQAgAGwAYQB6AHkAIABkAG8AZwAuAA==</Base64BinaryContent>\r\n <HexBinaryContent>540068006500200071007500690063006B002000620072006F0077006E00200066006F00780020006A0075006D007000730020006F00760065007200200074006800650020006C0061007A007900200064006F0067002E00</HexBinaryContent>\r\n</TypeWithTypesHavingCustomFormatter>");
Assert.NotNull(actual);
Assert.True(value.DateTimeContent == actual.DateTimeContent, $"Actual DateTimeContent was not as expected. \r\n Expected: {value.DateTimeContent} \r\n Actual: {actual.DateTimeContent}");
Assert.True(value.QNameContent == actual.QNameContent, $"Actual QNameContent was not as expected. \r\n Expected: {value.QNameContent} \r\n Actual: {actual.QNameContent}");
Assert.True(value.DateContent == actual.DateContent, $"Actual DateContent was not as expected. \r\n Expected: {value.DateContent} \r\n Actual: {actual.DateContent}");
Assert.True(value.NameContent == actual.NameContent, $"Actual NameContent was not as expected. \r\n Expected: {value.NameContent} \r\n Actual: {actual.NameContent}");
Assert.True(value.NCNameContent == actual.NCNameContent, $"Actual NCNameContent was not as expected. \r\n Expected: {value.NCNameContent} \r\n Actual: {actual.NCNameContent}");
Assert.True(value.NMTOKENContent == actual.NMTOKENContent, $"Actual NMTOKENContent was not as expected. \r\n Expected: {value.NMTOKENContent} \r\n Actual: {actual.NMTOKENContent}");
Assert.True(value.NMTOKENSContent == actual.NMTOKENSContent, $"Actual NMTOKENSContent was not as expected. \r\n Expected: {value.NMTOKENSContent} \r\n Actual: {actual.NMTOKENSContent}");
Assert.NotNull(actual.Base64BinaryContent);
Assert.True(Enumerable.SequenceEqual(value.Base64BinaryContent, actual.Base64BinaryContent), "Actual Base64BinaryContent was not as expected.");
Assert.NotNull(actual.HexBinaryContent);
Assert.True(Enumerable.SequenceEqual(value.HexBinaryContent, actual.HexBinaryContent), "Actual HexBinaryContent was not as expected.");
}
[Fact]
public static void Xml_TypeWithArrayPropertyHavingChoice()
{
object[] choices = new object[] { "Food", 5 };
// For each item in the choices array, add an
// enumeration value.
MoreChoices[] itemChoices = new MoreChoices[] { MoreChoices.Item, MoreChoices.Amount };
var value = new TypeWithArrayPropertyHavingChoice() { ManyChoices = choices, ChoiceArray = itemChoices };
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithArrayPropertyHavingChoice xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <Item>Food</Item>\r\n <Amount>5</Amount>\r\n</TypeWithArrayPropertyHavingChoice>");
Assert.NotNull(actual);
Assert.NotNull(actual.ManyChoices);
Assert.Equal(value.ManyChoices.Length, actual.ManyChoices.Length);
Assert.True(Enumerable.SequenceEqual(value.ManyChoices, actual.ManyChoices));
}
[Fact]
public static void XML_TypeWithTypeNameInXmlTypeAttribute_WithValue()
{
var value = new TypeWithTypeNameInXmlTypeAttribute() { XmlAttributeForm = "SomeValue" };
var actual = SerializeAndDeserialize(value,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<MyXmlType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" XmlAttributeForm=\"SomeValue\" />",
skipStringCompare: false);
Assert.NotNull(actual);
Assert.Equal(value.XmlAttributeForm, actual.XmlAttributeForm);
}
[Fact]
public static void XML_TypeWithFieldsOrdered()
{
var value = new TypeWithFieldsOrdered()
{
IntField1 = 1,
IntField2 = 2,
StringField1 = "foo1",
StringField2 = "foo2"
};
var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TypeWithFieldsOrdered xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <IntField1>1</IntField1>\r\n <IntField2>2</IntField2>\r\n <StringField2>foo2</StringField2>\r\n <StringField1>foo1</StringField1>\r\n</TypeWithFieldsOrdered>");
Assert.NotNull(actual);
Assert.Equal(value.IntField1, actual.IntField1);
Assert.Equal(value.IntField2, actual.IntField2);
Assert.Equal(value.StringField1, actual.StringField1);
Assert.Equal(value.StringField2, actual.StringField2);
}
[Fact]
public static void XmlSerializerFactoryTest()
{
string baseline = "<?xml version=\"1.0\"?>\r\n<Dog xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <Age>5</Age>\r\n <Name>Bear</Name>\r\n <Breed>GermanShepherd</Breed>\r\n</Dog>";
var xsf = new XmlSerializerFactory();
Func<XmlSerializer> serializerfunc = () => xsf.CreateSerializer(typeof(Dog));
var dog1 = new Dog() { Name = "Bear", Age = 5, Breed = DogBreed.GermanShepherd };
var dog2 = SerializeAndDeserialize(dog1, baseline, serializerfunc);
Assert.Equal(dog1.Name, dog2.Name);
Assert.Equal(dog1.Age, dog2.Age);
Assert.Equal(dog1.Breed, dog2.Breed);
}
[Fact]
public static void XmlUnknownElementAndEventHandlerTest()
{
List<string> grouplists = new List<string>();
int count = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Group));
serializer.UnknownElement += new XmlElementEventHandler((o, args) =>
{
Group myGroup = (Group)args.ObjectBeingDeserialized;
Assert.NotNull(myGroup);
grouplists.Add(args.Element.Name);
++count;
});
string xmlFileContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Group xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema"">
<GroupName>MyGroup</GroupName>
<GroupSize>Large</GroupSize>
<GroupNumber>444</GroupNumber>
<GroupBase>West</GroupBase>
</Group >";
Group group = (Group)serializer.Deserialize(GetStreamFromString(xmlFileContent));
Assert.NotNull(group);
Assert.NotNull(group.GroupName);
Assert.Null(group.GroupVehicle);
Assert.Equal(3, count);
Assert.Equal(3, grouplists.Count());
bool b = grouplists.Contains("GroupSize") && grouplists.Contains("GroupNumber") && grouplists.Contains("GroupBase");
Assert.True(b);
}
[Fact]
public static void XmlUnknownNodeAndEventHandlerTest()
{
List<string> grouplists = new List<string>();
int count = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Group));
serializer.UnknownNode += new XmlNodeEventHandler((o, args) =>
{
Group myGroup = (Group)args.ObjectBeingDeserialized;
Assert.NotNull(myGroup);
grouplists.Add(args.LocalName);
++count;
});
string xmlFileContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Group xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:coho=""http://www.cohowinery.com"" xmlns:cp=""http://www.cpandl.com"">
<coho:GroupName>MyGroup</coho:GroupName>
<cp:GroupSize>Large</cp:GroupSize>
<cp:GroupNumber>444</cp:GroupNumber>
<coho:GroupBase>West</coho:GroupBase>
<coho:ThingInfo>
<Number>1</Number>
<Name>Thing1</Name>
<Elmo>
<Glue>element</Glue>
</Elmo>
</coho:ThingInfo>
</Group>";
Group group = (Group)serializer.Deserialize(GetStreamFromString(xmlFileContent));
Assert.NotNull(group);
Assert.Null(group.GroupName);
Assert.Equal(5, count);
Assert.Equal(5, grouplists.Count());
bool b = grouplists.Contains("GroupName") && grouplists.Contains("GroupSize") && grouplists.Contains("GroupNumber") && grouplists.Contains("GroupBase") && grouplists.Contains("ThingInfo");
Assert.True(b);
}
[Fact]
public static void XmlUnknownAttributeAndEventHandlerTest()
{
List<string> grouplists = new List<string>();
int count = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Group));
serializer.UnknownAttribute += new XmlAttributeEventHandler((o, args) =>
{
Group myGroup = (Group)args.ObjectBeingDeserialized;
Assert.NotNull(myGroup);
grouplists.Add(args.Attr.LocalName);
++count;
});
string xmlFileContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Group xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" GroupType='Technical' GroupNumber='42' GroupBase='Red'>
<GroupName>MyGroup</GroupName>
</Group>";
Group group = (Group)serializer.Deserialize(GetStreamFromString(xmlFileContent));
Assert.NotNull(group);
Assert.NotNull(group.GroupName);
Assert.Null(group.GroupVehicle);
Assert.Equal(3, count);
Assert.Equal(3, grouplists.Count());
bool b = grouplists.Contains("GroupType") && grouplists.Contains("GroupNumber") && grouplists.Contains("GroupBase");
Assert.True(b);
}
[Fact]
public static void XmlDeserializationEventsTest()
{
List<string> grouplists = new List<string>();
int count = 0;
// Create an instance of the XmlSerializer class.
XmlSerializer serializer = new XmlSerializer(typeof(Group));
XmlDeserializationEvents events = new XmlDeserializationEvents();
events.OnUnknownAttribute += new XmlAttributeEventHandler((o, args) =>
{
Group myGroup = (Group)args.ObjectBeingDeserialized;
Assert.NotNull(myGroup);
grouplists.Add(args.Attr.LocalName);
++count;
});
string xmlFileContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Group xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" GroupType='Technical' GroupNumber='42' GroupBase='Red'>
<GroupName>MyGroup</GroupName>
</Group>";
Group group = (Group)serializer.Deserialize(XmlReader.Create(GetStreamFromString(xmlFileContent)), events);
Assert.NotNull(group);
Assert.NotNull(group.GroupName);
Assert.Null(group.GroupVehicle);
Assert.Equal(3, count);
Assert.Equal(3, grouplists.Count());
bool b = grouplists.Contains("GroupType") && grouplists.Contains("GroupNumber") && grouplists.Contains("GroupBase");
Assert.True(b);
}
private static Stream GetStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
[Fact]
public static void XmlSerializerImplementationTest()
{
Employee emp = new Employee() { EmployeeName = "Allice" };
SerializeIm sm = new SerializeIm();
Func<XmlSerializer> serializerfunc = () => sm.GetSerializer(typeof(Employee));
string expected = "<?xml version=\"1.0\"?>\r\n<Employee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <EmployeeName>Allice</EmployeeName>\r\n</Employee>";
SerializeAndDeserialize(emp, expected, serializerfunc);
}
[Fact]
public static void Xml_HiddenDerivedFieldTest()
{
var value = new DerivedClass { value = "on derived" };
var actual = SerializeAndDeserialize<BaseClass>(value,
@"<?xml version=""1.0""?>
<BaseClass xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:type=""DerivedClass"">
<value>on derived</value>
</BaseClass>");
Assert.NotNull(actual);
Assert.Null(actual.Value);
Assert.Null(actual.value);
Assert.Null(((DerivedClass)actual).Value);
Assert.Equal(value.value, ((DerivedClass)actual).value);
}
[Fact]
public static void Xml_NullRefInXmlSerializerCtorTest()
{
string defaultNamespace = "http://www.contoso.com";
var value = PurchaseOrder.CreateInstance();
string baseline =
@"<?xml version=""1.0""?>
<PurchaseOrder xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://www.contoso1.com"">
<ShipTo Name=""John Doe"">
<Line1>1 Main St.</Line1>
<City>AnyTown</City>
<State>WA</State>
<Zip>00000</Zip>
</ShipTo>
<OrderDate>Monday, 10 April 2017</OrderDate>
<Items>
<OrderedItem>
<ItemName>Widget S</ItemName>
<Description>Small widget</Description>
<UnitPrice>5.23</UnitPrice>
<Quantity>3</Quantity>
<LineTotal>15.69</LineTotal>
</OrderedItem>
</Items>
<SubTotal>15.69</SubTotal>
<ShipCost>12.51</ShipCost>
<TotalCost>28.20</TotalCost>
</PurchaseOrder>";
var actual = SerializeAndDeserialize(value,
baseline,
() => new XmlSerializer(value.GetType(), null, null, null, defaultNamespace)
);
Assert.NotNull(actual);
Assert.Equal(value.OrderDate, actual.OrderDate);
Assert.Equal(value.ShipCost, actual.ShipCost);
Assert.Equal(value.SubTotal, actual.SubTotal);
Assert.Equal(value.TotalCost, actual.TotalCost);
Assert.Equal(value.ShipTo.City, actual.ShipTo.City);
Assert.Equal(value.ShipTo.Line1, actual.ShipTo.Line1);
Assert.Equal(value.ShipTo.Name, actual.ShipTo.Name);
Assert.Equal(value.ShipTo.State, actual.ShipTo.State);
Assert.Equal(value.ShipTo.Zip, actual.ShipTo.Zip);
Assert.Equal(value.OrderedItems.Length, actual.OrderedItems.Length);
for (int i = 0; i < value.OrderedItems.Length; i++)
{
Assert.Equal(value.OrderedItems.ElementAt(i).Description, actual.OrderedItems.ElementAt(i).Description);
Assert.Equal(value.OrderedItems.ElementAt(i).ItemName, actual.OrderedItems.ElementAt(i).ItemName);
Assert.Equal(value.OrderedItems.ElementAt(i).LineTotal, actual.OrderedItems.ElementAt(i).LineTotal);
Assert.Equal(value.OrderedItems.ElementAt(i).Quantity, actual.OrderedItems.ElementAt(i).Quantity);
Assert.Equal(value.OrderedItems.ElementAt(i).UnitPrice, actual.OrderedItems.ElementAt(i).UnitPrice);
}
actual = SerializeAndDeserialize(value,
baseline,
() => new XmlSerializer(value.GetType(), null, null, null, defaultNamespace, null)
);
Assert.NotNull(actual);
Assert.Equal(value.OrderDate, actual.OrderDate);
Assert.Equal(value.ShipCost, actual.ShipCost);
Assert.Equal(value.SubTotal, actual.SubTotal);
Assert.Equal(value.TotalCost, actual.TotalCost);
Assert.Equal(value.ShipTo.City, actual.ShipTo.City);
Assert.Equal(value.ShipTo.Line1, actual.ShipTo.Line1);
Assert.Equal(value.ShipTo.Name, actual.ShipTo.Name);
Assert.Equal(value.ShipTo.State, actual.ShipTo.State);
Assert.Equal(value.ShipTo.Zip, actual.ShipTo.Zip);
Assert.Equal(value.OrderedItems.Length, actual.OrderedItems.Length);
for (int i = 0; i < value.OrderedItems.Length; i++)
{
Assert.Equal(value.OrderedItems.ElementAt(i).Description, actual.OrderedItems.ElementAt(i).Description);
Assert.Equal(value.OrderedItems.ElementAt(i).ItemName, actual.OrderedItems.ElementAt(i).ItemName);
Assert.Equal(value.OrderedItems.ElementAt(i).LineTotal, actual.OrderedItems.ElementAt(i).LineTotal);
Assert.Equal(value.OrderedItems.ElementAt(i).Quantity, actual.OrderedItems.ElementAt(i).Quantity);
Assert.Equal(value.OrderedItems.ElementAt(i).UnitPrice, actual.OrderedItems.ElementAt(i).UnitPrice);
}
}
[Fact]
public static void Xml_AliasedPropertyTest()
{
var inputList = new List<string> { "item0", "item1", "item2", "item3", "item4" };
var value = new AliasedTestType { Aliased = inputList };
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<AliasedTestType xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<Y>
<string>item0</string>
<string>item1</string>
<string>item2</string>
<string>item3</string>
<string>item4</string>
</Y>
</AliasedTestType>");
Assert.NotNull(actual);
Assert.NotNull(actual.Aliased);
Assert.Equal(inputList.GetType(), actual.Aliased.GetType());
Assert.Equal(inputList.Count, ((List<string>)actual.Aliased).Count);
for (int i = 0; i < inputList.Count; i++)
{
Assert.Equal(inputList[i], ((List<string>)actual.Aliased).ElementAt(i));
}
}
[Fact]
public static void Xml_DeserializeHiddenMembersTest()
{
var xmlSerializer = new XmlSerializer(typeof(DerivedClass1));
string inputXml = "<DerivedClass1><Prop>2012-07-07T00:18:29.7538612Z</Prop></DerivedClass1>";
var dateTime = new DateTime(634772171097538612);
using (var reader = new StringReader(inputXml))
{
var derivedClassInstance = (DerivedClass1)xmlSerializer.Deserialize(reader);
Assert.NotNull(derivedClassInstance.Prop);
Assert.Equal(1, derivedClassInstance.Prop.Count<DateTime>());
Assert.Equal(dateTime, derivedClassInstance.Prop.ElementAt(0));
}
}
[Fact]
public static void Xml_SerializeClassNestedInStaticClassTest()
{
var value = new Outer.Person()
{
FirstName = "Harry",
MiddleName = "James",
LastName = "Potter"
};
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<Person xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<FirstName>Harry</FirstName>
<MiddleName>James</MiddleName>
<LastName>Potter</LastName>
</Person>");
Assert.NotNull(actual);
Assert.Equal(value.FirstName, actual.FirstName);
Assert.Equal(value.MiddleName, actual.MiddleName);
Assert.Equal(value.LastName, actual.LastName);
}
[Fact]
public static void Xml_XSCoverTest()
{
var band = new Orchestra();
var brass = new Brass()
{
Name = "Trumpet",
IsValved = true
};
Instrument[] myInstruments = { brass };
band.Instruments = myInstruments;
var attrs = new XmlAttributes();
var attr = new XmlElementAttribute()
{
ElementName = "Brass",
Type = typeof(Brass)
};
attrs.XmlElements.Add(attr);
var attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
var actual = SerializeAndDeserialize(band,
@"<Orchestra xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Brass>
<Name>Trumpet</Name>
<IsValved>true</IsValved>
</Brass>
</Orchestra>", () => { return new XmlSerializer(typeof(Orchestra), attrOverrides); });
Assert.Equal(band.Instruments.Length, actual.Instruments.Length);
for (int i = 0; i < band.Instruments.Length; i++)
{
Assert.Equal(((Brass)band.Instruments.ElementAt(i)).Name, ((Brass)actual.Instruments[i]).Name);
Assert.Equal(((Brass)band.Instruments.ElementAt(i)).IsValved, ((Brass)actual.Instruments[i]).IsValved);
}
band = new Orchestra();
band.Instruments = new Instrument[1] { new Instrument { Name = "Instrument1" } };
attrs = new XmlAttributes();
var xArray = new XmlArrayAttribute("CommonInstruments");
xArray.Namespace = "http://www.contoso.com";
attrs.XmlArray = xArray;
attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
actual = SerializeAndDeserialize(band,
@"<?xml version=""1.0""?>
<Orchestra xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<CommonInstruments xmlns=""http://www.contoso.com"">
<Instrument>
<Name>Instrument1</Name>
</Instrument>
</CommonInstruments>
</Orchestra>", () => { return new XmlSerializer(typeof(Orchestra), attrOverrides); });
Assert.Equal(band.Instruments.Length, actual.Instruments.Length);
for (int i = 0; i < band.Instruments.Length; i++)
{
Assert.Equal((band.Instruments.ElementAt(i)).Name, (actual.Instruments[i]).Name);
}
band = new Orchestra();
var trumpet = new Trumpet() { Name = "TrumpetKeyC", IsValved = false, Modulation = 'C' };
band.Instruments = new Instrument[2] { brass, trumpet };
attrs = new XmlAttributes();
var xArrayItem = new XmlArrayItemAttribute(typeof(Brass));
xArrayItem.Namespace = "http://www.contoso.com";
attrs.XmlArrayItems.Add(xArrayItem);
var xArrayItem2 = new XmlArrayItemAttribute(typeof(Trumpet));
xArrayItem2.Namespace = "http://www.contoso.com";
attrs.XmlArrayItems.Add(xArrayItem2);
attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
actual = SerializeAndDeserialize(band,
@"<?xml version=""1.0""?>
<Orchestra xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Instruments>
<Brass xmlns=""http://www.contoso.com"">
<Name>Trumpet</Name>
<IsValved>true</IsValved>
</Brass>
<Trumpet xmlns=""http://www.contoso.com"">
<Name>TrumpetKeyC</Name>
<IsValved>false</IsValved>
<Modulation>67</Modulation>
</Trumpet>
</Instruments>
</Orchestra>", () => { return new XmlSerializer(typeof(Orchestra), attrOverrides); });
Assert.Equal(band.Instruments.Length, actual.Instruments.Length);
for (int i = 0; i < band.Instruments.Length; i++)
{
Assert.Equal((band.Instruments.ElementAt(i)).Name, (actual.Instruments[i]).Name);
}
attrOverrides = new XmlAttributeOverrides();
attrs = new XmlAttributes();
object defaultAnimal = "Cat";
attrs.XmlDefaultValue = defaultAnimal;
attrOverrides.Add(typeof(Pet), "Animal", attrs);
attrs = new XmlAttributes();
attrs.XmlIgnore = false;
attrOverrides.Add(typeof(Pet), "Comment", attrs);
attrs = new XmlAttributes();
var xType = new XmlTypeAttribute();
xType.TypeName = "CuteFishes";
xType.IncludeInSchema = true;
attrs.XmlType = xType;
attrOverrides.Add(typeof(Pet), attrs);
var myPet = new Pet();
myPet.Animal = "fish";
myPet.Comment = "What a cute fish!";
myPet.Comment2 = "I think it is cool!";
var actual2 = SerializeAndDeserialize(myPet,
@"<?xml version=""1.0""?>
<CuteFishes xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Animal>fish</Animal>
<Comment>What a cute fish!</Comment>
<Comment2>I think it is cool!</Comment2>
</CuteFishes>
", () => { return new XmlSerializer(typeof(Pet), attrOverrides); });
Assert.Equal(myPet.Animal, actual2.Animal);
Assert.Equal(myPet.Comment, actual2.Comment);
Assert.Equal(myPet.Comment2, actual2.Comment2);
}
[Fact]
public static void Xml_TypeWithMyCollectionField()
{
var value = new TypeWithMyCollectionField();
value.Collection = new MyCollection<string>() { "s1", "s2" };
var actual = SerializeAndDeserializeWithWrapper(value, new XmlSerializer(typeof(TypeWithMyCollectionField)), "<root><TypeWithMyCollectionField xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Collection><string>s1</string><string>s2</string></Collection></TypeWithMyCollectionField></root>");
Assert.NotNull(actual);
Assert.NotNull(actual.Collection);
Assert.True(value.Collection.SequenceEqual(actual.Collection));
}
[Fact]
public static void Xml_Soap_TypeWithMyCollectionField()
{
XmlTypeMapping myTypeMapping = new SoapReflectionImporter().ImportTypeMapping(typeof(TypeWithMyCollectionField));
var serializer = new XmlSerializer(myTypeMapping);
var value = new TypeWithMyCollectionField();
value.Collection = new MyCollection<string>() { "s1", "s2" };
var actual = SerializeAndDeserializeWithWrapper(value, serializer, "<root><TypeWithMyCollectionField xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" id=\"id1\"><Collection href=\"#id2\" /></TypeWithMyCollectionField><q1:Array id=\"id2\" xmlns:q2=\"http://www.w3.org/2001/XMLSchema\" q1:arrayType=\"q2:string[]\" xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\"><Item>s1</Item><Item>s2</Item></q1:Array></root>");
Assert.NotNull(actual);
Assert.NotNull(actual.Collection);
Assert.True(value.Collection.SequenceEqual(actual.Collection));
}
[Fact]
public static void Xml_DefaultValueAttributeSetToNaNTest()
{
var value = new DefaultValuesSetToNaN();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<DefaultValuesSetToNaN xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<DoubleField>0</DoubleField>
<SingleField>0</SingleField>
<DoubleProp>0</DoubleProp>
<FloatProp>0</FloatProp>
</DefaultValuesSetToNaN>");
Assert.NotNull(actual);
Assert.Equal(value, actual);
}
[Fact]
public static void Xml_DefaultValueAttributeSetToPositiveInfinityTest()
{
var value = new DefaultValuesSetToPositiveInfinity();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<DefaultValuesSetToPositiveInfinity xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<DoubleField>0</DoubleField>
<SingleField>0</SingleField>
<DoubleProp>0</DoubleProp>
<FloatProp>0</FloatProp>
</DefaultValuesSetToPositiveInfinity>");
Assert.NotNull(actual);
Assert.Equal(value, actual);
}
[Fact]
public static void Xml_DefaultValueAttributeSetToNegativeInfinityTest()
{
var value = new DefaultValuesSetToNegativeInfinity();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<DefaultValuesSetToNegativeInfinity xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<DoubleField>0</DoubleField>
<SingleField>0</SingleField>
<DoubleProp>0</DoubleProp>
<FloatProp>0</FloatProp>
</DefaultValuesSetToNegativeInfinity>");
Assert.NotNull(actual);
Assert.Equal(value, actual);
}
[Fact]
public static void SerializeWithDefaultValueSetToPositiveInfinityTest()
{
var value = new DefaultValuesSetToPositiveInfinity();
value.DoubleField = double.PositiveInfinity;
value.SingleField = float.PositiveInfinity;
value.FloatProp = float.PositiveInfinity;
value.DoubleProp = double.PositiveInfinity;
bool result = SerializeWithDefaultValue(value,
@"<?xml version=""1.0""?>
<DefaultValuesSetToPositiveInfinity xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />");
Assert.True(result);
}
[Fact]
public static void SerializeWithDefaultValueSetToNegativeInfinityTest()
{
var value = new DefaultValuesSetToNegativeInfinity();
value.DoubleField = double.NegativeInfinity;
value.SingleField = float.NegativeInfinity;
value.FloatProp = float.NegativeInfinity;
value.DoubleProp = double.NegativeInfinity;
bool result = SerializeWithDefaultValue(value,
@"<?xml version=""1.0""?>
<DefaultValuesSetToNegativeInfinity xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />");
Assert.True(result);
}
[Fact]
public static void DeserializeIDREFSIntoStringTest()
{
string xmlstring = @"<?xml version = ""1.0"" encoding = ""utf-8"" ?><Document xmlns = ""http://example.com"" id = ""ID1"" refs=""ID1 ID2 ID3"" ></Document>";
Stream ms = GenerateStreamFromString(xmlstring);
XmlSerializer ser = new XmlSerializer(typeof(MsgDocumentType));
var value = (MsgDocumentType)ser.Deserialize(ms);
Assert.NotNull(value);
Assert.Equal("ID1", value.Id);
Assert.NotNull(value.Refs);
Assert.Equal(3, value.Refs.Count());
Assert.Equal("ID1", value.Refs[0]);
Assert.Equal("ID2", value.Refs[1]);
Assert.Equal("ID3", value.Refs[2]);
}
private static bool SerializeWithDefaultValue<T>(T value, string baseline)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
serializer.Serialize(ms, value);
ms.Position = 0;
string output = new StreamReader(ms).ReadToEnd();
Utils.CompareResult result = Utils.Compare(baseline, output);
return result.Equal;
}
}
[Fact]
public static void Xml_TypeWithMismatchBetweenAttributeAndPropertyType()
{
var value = new TypeWithMismatchBetweenAttributeAndPropertyType();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?><RootElement xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" IntValue=""120"" />");
Assert.StrictEqual(value.IntValue, actual.IntValue);
}
[Fact]
public static void Xml_XsdValidationAndDeserialization()
{
var xsdstring = @"<?xml version='1.0' encoding='utf-8'?>
<xs:schema attributeFormDefault='unqualified' elementFormDefault='unqualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='RootClass'>
<xs:complexType>
<xs:sequence>
<xs:element name='Parameters' type='parameters' minOccurs='1' maxOccurs='unbounded' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name='parameters'>
<xs:sequence>
<xs:element name='Parameter' type='parameter' minOccurs='1' maxOccurs='unbounded' />
</xs:sequence>
</xs:complexType>
<xs:complexType name='parameter'>
<xs:attribute type='xs:string' name='Name' use='required' />
</xs:complexType>
<xs:complexType name='stringParameter' >
<xs:complexContent>
<xs:extension base='parameter'>
<xs:sequence>
<xs:element name='Value' minOccurs='0' maxOccurs='1'/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
";
var param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<RootClass xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<Parameters>" +
"<Parameter xsi:type=\"stringParameter\" Name=\"SomeName\">" +
"<Value />" +
"</Parameter>" +
"</Parameters>" +
"</RootClass>";
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
writer.Write(param);
writer.Flush();
stream.Position = 0;
var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.ValidationEventHandler += (sender, args) =>
{
throw new XmlSchemaValidationException(args.Message);
};
xmlReaderSettings.Schemas.Add(null, XmlReader.Create(new StringReader(xsdstring)));
var xmlReader = XmlReader.Create(stream, xmlReaderSettings);
var overrides = new XmlAttributeOverrides();
var parametersXmlAttribute = new XmlAttributes { XmlType = new XmlTypeAttribute("stringParameter") };
overrides.Add(typeof(Parameter<string>), parametersXmlAttribute);
var serializer = new XmlSerializer(typeof(RootClass), overrides);
var result=(RootClass)serializer.Deserialize(xmlReader);
Assert.Equal("SomeName", result.Parameters[0].Name);
Assert.Equal(string.Empty, ((Parameter<string>)result.Parameters[0]).Value);
}
}
}
[Fact]
public static void Xml_TypeWithSpecialCharacterInStringMember()
{
TypeA x = new TypeA() { Name = "Lily&Lucy" };
TypeA y = SerializeAndDeserialize<TypeA>(x,
@"<?xml version=""1.0""?>
<TypeA xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Name>Lily&Lucy</Name>
</TypeA>");
Assert.NotNull(y);
Assert.Equal(x.Name, y.Name);
}
private static readonly string s_defaultNs = "http://tempuri.org/";
private static T RoundTripWithXmlMembersMapping<T>(object requestBodyValue, string memberName, string baseline, bool skipStringCompare = false, string wrapperName = null)
{
string ns = s_defaultNs;
object[] value = new object[] { requestBodyValue };
XmlReflectionMember member = GetReflectionMember<T>(memberName, ns);
var members = new XmlReflectionMember[] { member };
object[] actual = RoundTripWithXmlMembersMapping(value, baseline, skipStringCompare, members: members, wrapperName: wrapperName);
Assert.Equal(value.Length, actual.Length);
return (T)actual[0];
}
private static object[] RoundTripWithXmlMembersMapping(object[] value, string baseline, bool skipStringCompare, XmlReflectionMember[] members, string ns = null, string wrapperName = null, bool rpc = false)
{
ns = ns ?? s_defaultNs;
var importer = new XmlReflectionImporter(null, ns);
var membersMapping = importer.ImportMembersMapping(wrapperName, ns, members, wrapperName != null, rpc: rpc);
var serializer = XmlSerializer.FromMappings(new XmlMapping[] { membersMapping })[0];
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, value);
ms.Flush();
ms.Position = 0;
string actualOutput = new StreamReader(ms).ReadToEnd();
if (!skipStringCompare)
{
Utils.CompareResult result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}",
Environment.NewLine, result.ErrorMessage, value, baseline, actualOutput));
}
ms.Position = 0;
var actual = serializer.Deserialize(ms) as object[];
Assert.NotNull(actual);
return actual;
}
}
private static T RoundTripWithXmlMembersMappingSoap<T>(object item, string memberName, string baseline, bool skipStringCompare = false, string wrapperName = null, bool validate = false)
{
string ns = s_defaultNs;
object[] value = new object[] { item };
XmlReflectionMember member = GetReflectionMember<T>(memberName, ns);
var members = new XmlReflectionMember[] { member };
object[] actual = RoundTripWithXmlMembersMappingSoap(value, baseline, skipStringCompare, members: members, wrapperName: wrapperName, validate: validate);
Assert.Equal(value.Length, actual.Length);
return (T)actual[0];
}
private static object[] RoundTripWithXmlMembersMappingSoap(object[] value, string baseline, bool skipStringCompare, XmlReflectionMember[] members, string ns = null, string wrapperName = null, bool writeAccessors = false, bool validate = false)
{
ns = ns ?? s_defaultNs;
var importer = new SoapReflectionImporter(null, ns);
var membersMapping = importer.ImportMembersMapping(wrapperName, ns, members, hasWrapperElement: wrapperName != null, writeAccessors: writeAccessors, validate: validate);
var serializer = XmlSerializer.FromMappings(new XmlMapping[] { membersMapping })[0];
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, value);
ms.Flush();
ms.Position = 0;
string actualOutput = new StreamReader(ms).ReadToEnd();
if (!skipStringCompare)
{
Utils.CompareResult result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}",
Environment.NewLine, result.ErrorMessage, value, baseline, actualOutput));
}
ms.Position = 0;
var actual = serializer.Deserialize(ms) as object[];
Assert.NotNull(actual);
return actual;
}
}
private static XmlReflectionMember GetReflectionMember<T>(string memberName)
{
return GetReflectionMember<T>(memberName, s_defaultNs);
}
private static XmlReflectionMember GetReflectionMember<T>(string memberName, string ns)
{
var member = new XmlReflectionMember();
member.MemberName = memberName;
member.MemberType = typeof(T);
member.XmlAttributes = new XmlAttributes();
var elementAttribute = new XmlElementAttribute();
elementAttribute.ElementName = memberName;
elementAttribute.Namespace = ns;
member.XmlAttributes.XmlElements.Add(elementAttribute);
return member;
}
private static XmlReflectionMember GetReflectionMemberNoXmlElement<T>(string memberName, string ns = null)
{
ns = ns ?? s_defaultNs;
var member = new XmlReflectionMember();
member.MemberName = memberName;
member.MemberType = typeof(T);
member.XmlAttributes = new XmlAttributes();
return member;
}
private static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
private static T SerializeAndDeserialize<T>(T value, string baseline, Func<XmlSerializer> serializerFactory = null,
bool skipStringCompare = false, XmlSerializerNamespaces xns = null)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
if (serializerFactory != null)
{
serializer = serializerFactory();
}
using (MemoryStream ms = new MemoryStream())
{
if (xns == null)
{
serializer.Serialize(ms, value);
}
else
{
serializer.Serialize(ms, value, xns);
}
ms.Position = 0;
string actualOutput = new StreamReader(ms).ReadToEnd();
if (!skipStringCompare)
{
Utils.CompareResult result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}",
Environment.NewLine, result.ErrorMessage, value, baseline, actualOutput));
}
ms.Position = 0;
T deserialized = (T)serializer.Deserialize(ms);
return deserialized;
}
}
private static T SerializeAndDeserializeWithWrapper<T>(T value, XmlSerializer serializer, string baseline)
{
T actual;
using (var ms = new MemoryStream())
{
var writer = new XmlTextWriter(ms, Encoding.UTF8);
writer.WriteStartElement("root");
serializer.Serialize(writer, value);
writer.WriteEndElement();
writer.Flush();
ms.Position = 0;
string actualOutput = new StreamReader(ms).ReadToEnd();
Utils.CompareResult result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}",
Environment.NewLine, result.ErrorMessage, value, baseline, actualOutput));
ms.Position = 0;
using (var reader = new XmlTextReader(ms))
{
reader.ReadStartElement("root");
actual = (T)serializer.Deserialize(reader);
}
}
return actual;
}
private static void AssertSerializationFailure<T, ExceptionType>() where T : new() where ExceptionType : Exception
{
try
{
SerializeAndDeserialize(new T(), string.Empty, skipStringCompare: true);
Assert.True(false, $"Assert.True failed for {typeof(T)}. The above operation should have thrown, but it didn't.");
}
catch (Exception e)
{
Assert.True(e is ExceptionType, $"Assert.True failed for {typeof(T)}. Expected: {typeof(ExceptionType)}; Actual: {e.GetType()}");
}
}
}
| 46.844137 | 995 | 0.668107 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs | 94,672 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Cosmos;
using TaylorHutchison.EffortApp.Models;
namespace TaylorHutchison.EffortApp.Functions
{
public static class RoomFunctions
{
private static CosmosClient GetCosmosClient()
{
var connectionString = Environment.GetEnvironmentVariable("CosmosDBConnectionString");
var options = new CosmosClientOptions()
{
SerializerOptions = new CosmosSerializationOptions()
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
}
};
return new CosmosClient(connectionString, options);
}
private static Container GetRoomContainer(CosmosClient client)
{
var databaseId = Environment.GetEnvironmentVariable("DatabaseId");
var containerId = Environment.GetEnvironmentVariable("ContainerId");
return client.GetContainer(databaseId, containerId);
}
[FunctionName("createroom")]
public static async Task<IActionResult> CreateRoom(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var room = JsonConvert.DeserializeObject<Room>(requestBody);
if (!string.IsNullOrEmpty(room.Id))
{
using var client = GetCosmosClient();
var container = GetRoomContainer(client);
await container.CreateItemAsync<Room>(room, new PartitionKey(room.Id));
return new OkResult();
}
return new BadRequestObjectResult("Room ID was not provided while trying to create a room");
}
}
}
| 36.689655 | 104 | 0.657425 | [
"Unlicense"
] | taylorhutchison/effortapp | api/RoomFn.cs | 2,128 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System.Net;
using EnsureThat;
using Newtonsoft.Json;
namespace Microsoft.Health.Fhir.Core.Features.Operations.Export.Models
{
public class ExportJobFailureDetails
{
public ExportJobFailureDetails(string failureReason, HttpStatusCode statusCode)
{
EnsureArg.IsNotNullOrWhiteSpace(failureReason, nameof(failureReason));
FailureReason = failureReason;
FailureStatusCode = statusCode;
}
[JsonConstructor]
private ExportJobFailureDetails()
{
}
[JsonProperty(JobRecordProperties.FailureReason)]
public string FailureReason { get; private set; }
[JsonProperty(JobRecordProperties.FailureStatusCode)]
public HttpStatusCode FailureStatusCode { get; private set; }
}
}
| 34.294118 | 101 | 0.57976 | [
"MIT"
] | AKQHealthService/fhir-server | src/Microsoft.Health.Fhir.Core/Features/Operations/Export/Models/ExportJobFailureDetails.cs | 1,168 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Avro.Specific;
namespace YCherkes.SchemaRegistry.Serdes.Avro.Helpers
{
internal static class ReflectionHelper
{
internal static IEnumerable<Type> GetSpecificTypes(IEnumerable<Assembly> assemblies)
{
return assemblies
.SelectMany(a => a.GetTypes())
.Where(IsSpecificType);
}
internal static bool IsSpecificType(Type type)
{
return type.IsClass &&
!type.IsAbstract &&
typeof(ISpecificRecord).IsAssignableFrom(type) &&
GetSchema(type) != null;
}
internal static global::Avro.Schema GetSchema(IReflect type)
{
return (global::Avro.Schema)type.GetField("_SCHEMA", BindingFlags.Public | BindingFlags.Static)?.GetValue(null);
}
}
}
| 29.1875 | 124 | 0.614561 | [
"MIT"
] | ycherkes/multi-schema-avro-desrializer | src/YCherkes.SchemaRegistry.Serdes.Avro/Helpers/ReflectionHelper.cs | 936 | 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 monitoring-2010-08-01.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.CloudWatch.Model
{
/// <summary>
/// Container for the parameters to the DescribeAnomalyDetectors operation.
/// Lists the anomaly detection models that you have created in your account. For single
/// metric anomaly detectors, you can list all of the models in your account or filter
/// the results to only the models that are related to a certain namespace, metric name,
/// or metric dimension. For metric math anomaly detectors, you can list them by adding
/// <code>METRIC_MATH</code> to the <code>AnomalyDetectorTypes</code> array. This will
/// return all metric math anomaly detectors in your account.
/// </summary>
public partial class DescribeAnomalyDetectorsRequest : AmazonCloudWatchRequest
{
private List<string> _anomalyDetectorTypes = new List<string>();
private List<Dimension> _dimensions = new List<Dimension>();
private int? _maxResults;
private string _metricName;
private string _awsNamespace;
private string _nextToken;
/// <summary>
/// Gets and sets the property AnomalyDetectorTypes.
/// <para>
/// The anomaly detector types to request when using <code>DescribeAnomalyDetectorsInput</code>.
/// If empty, defaults to <code>SINGLE_METRIC</code>.
/// </para>
/// </summary>
[AWSProperty(Max=2)]
public List<string> AnomalyDetectorTypes
{
get { return this._anomalyDetectorTypes; }
set { this._anomalyDetectorTypes = value; }
}
// Check to see if AnomalyDetectorTypes property is set
internal bool IsSetAnomalyDetectorTypes()
{
return this._anomalyDetectorTypes != null && this._anomalyDetectorTypes.Count > 0;
}
/// <summary>
/// Gets and sets the property Dimensions.
/// <para>
/// Limits the results to only the anomaly detection models that are associated with the
/// specified metric dimensions. If there are multiple metrics that have these dimensions
/// and have anomaly detection models associated, they're all returned.
/// </para>
/// </summary>
[AWSProperty(Max=10)]
public List<Dimension> Dimensions
{
get { return this._dimensions; }
set { this._dimensions = value; }
}
// Check to see if Dimensions property is set
internal bool IsSetDimensions()
{
return this._dimensions != null && this._dimensions.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to return in one operation. The maximum value that you
/// can specify is 100.
/// </para>
///
/// <para>
/// To retrieve the remaining results, make another call with the returned <code>NextToken</code>
/// value.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property MetricName.
/// <para>
/// Limits the results to only the anomaly detection models that are associated with the
/// specified metric name. If there are multiple metrics with this name in different namespaces
/// that have anomaly detection models, they're all returned.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string MetricName
{
get { return this._metricName; }
set { this._metricName = value; }
}
// Check to see if MetricName property is set
internal bool IsSetMetricName()
{
return this._metricName != null;
}
/// <summary>
/// Gets and sets the property Namespace.
/// <para>
/// Limits the results to only the anomaly detection models that are associated with the
/// specified namespace.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string Namespace
{
get { return this._awsNamespace; }
set { this._awsNamespace = value; }
}
// Check to see if Namespace property is set
internal bool IsSetNamespace()
{
return this._awsNamespace != null;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// Use the token returned by the previous operation to request the next page of results.
/// </para>
/// </summary>
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.285714 | 108 | 0.607773 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/CloudWatch/Generated/Model/DescribeAnomalyDetectorsRequest.cs | 6,175 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using HandyControl.Data;
namespace HandyControl.Controls
{
public class CirclePanel : Panel
{
public static readonly DependencyProperty DiameterProperty = DependencyProperty.Register(
"Diameter", typeof(double), typeof(CirclePanel), new FrameworkPropertyMetadata(170.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
public double Diameter
{
get => (double) GetValue(DiameterProperty);
set => SetValue(DiameterProperty, value);
}
public static readonly DependencyProperty KeepVerticalProperty = DependencyProperty.Register(
"KeepVertical", typeof(bool), typeof(CirclePanel), new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsMeasure));
public bool KeepVertical
{
get => (bool) GetValue(KeepVerticalProperty);
set => SetValue(KeepVerticalProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty OffsetAngleProperty = DependencyProperty.Register(
"OffsetAngle", typeof(double), typeof(CirclePanel), new FrameworkPropertyMetadata(ValueBoxes.Double0Box, FrameworkPropertyMetadataOptions.AffectsMeasure));
public double OffsetAngle
{
get => (double) GetValue(OffsetAngleProperty);
set => SetValue(OffsetAngleProperty, value);
}
protected override Size MeasureOverride(Size availableSize)
{
var diameter = Diameter;
if (Children.Count == 0) return new Size(diameter, diameter);
var newSize = new Size(diameter, diameter);
foreach (UIElement element in Children)
{
element.Measure(newSize);
}
return newSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
var keepVertical = KeepVertical;
var offsetAngle = OffsetAngle;
var i = 0;
var perDeg = 360.0 / Children.Count;
var radius = Diameter / 2;
foreach (UIElement element in Children)
{
var centerX = element.DesiredSize.Width / 2.0;
var centerY = element.DesiredSize.Height / 2.0;
var angle = perDeg * i++ + offsetAngle;
var transform = new RotateTransform
{
CenterX = centerX,
CenterY = centerY,
Angle = keepVertical ? 0 : angle
};
element.RenderTransform = transform;
var r = Math.PI * angle / 180.0;
var x = radius * Math.Cos(r);
var y = radius * Math.Sin(r);
var rectX = x + finalSize.Width / 2 - centerX;
var rectY = y + finalSize.Height / 2 - centerY;
element.Arrange(new Rect(rectX, rectY, element.DesiredSize.Width, element.DesiredSize.Height));
}
return finalSize;
}
}
}
| 34.78022 | 167 | 0.59842 | [
"MIT"
] | 5653325/HandyControl | src/Shared/HandyControl_Shared/Controls/Panel/CirclePanel.cs | 3,167 | C# |
namespace StringInAnotherApperancesService.Client
{
using System;
class ClientUI
{
static void Main()
{
string decorationLine = new string('-', Console.WindowWidth);
Console.Write(decorationLine);
Console.WriteLine("***Consuming the service for getting the appearances count of a");
Console.WriteLine("string in another string***");
Console.Write(decorationLine);
StringInAnotherApperancesServiceClient client = new StringInAnotherApperancesServiceClient();
string originString = "aaa";
string testString = "a";
int appearancesCount = client.GetStringAppearancesInAnotherString(originString, testString);
Console.WriteLine("The appearances of '{0}' in '{1}' are: {2}", testString, originString, appearancesCount);
originString = "Pesho pesha hodi";
testString = "gosho";
appearancesCount = client.GetStringAppearancesInAnotherString(originString, testString);
Console.WriteLine("The appearances of '{0}' in '{1}' are: {2}", testString, originString, appearancesCount);
}
}
}
| 40.965517 | 120 | 0.647306 | [
"MIT"
] | vladislav-karamfilov/TelerikAcademy | Web Services Projects/Homework-WindowsCommunicationFoundation/StringInAnotherApperancesService.Client/ClientUI.cs | 1,190 | C# |
using UnityEngine;
using System.Collections;
using System;
public class FireController : MonoBehaviour {
public AI.FSM.StateMachine<FireController> fsm;
public float senseTimer = 0.01f;
public FireWeapon weapon;
public bool PointClick = false;
public Transform target=null;
public float rotationToTarget=180f;
public bool LoS=false;
public void UpdateRotationToTarget()
{
if (target)
{
Vector3 dirV = target.position - transform.position;
Quaternion toRotation = Quaternion.LookRotation(dirV);
rotationToTarget = Quaternion.Angle(transform.rotation,toRotation
);
}
}
public bool RotatedToTarget()
{
if (!target)
return false;
return Mathf.Abs(rotationToTarget) < 15;
}
public void UpdateLoSToTarget()
{
if (target)
{
Ray rayBlast = new Ray(transform.position + new Vector3(0, 1f, 0),
(target.position - transform.position));
RaycastHit hit;
if (Physics.Raycast(rayBlast, out hit, 100))
{
LoS = hit.collider.gameObject.CompareTag("Player");
}
}
else
{
LoS = false;
}
}
public bool IsLoS()
{
return LoS;
}
private void Sense()
{
UpdateLoSToTarget();
UpdateRotationToTarget();
}
public void SetTarget(Transform tgt)
{
target = tgt;
fsm.Start();
}
internal void RotateToTarget()
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.position),0.2f);
}
void Start()
{
fsm = new AI.FSM.StateMachine<FireController>(this, new AI.FSM.Targeting.ReadyState());
}
// Update is called once per frame
void Update()
{
if (PointClick)
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
if (hit.collider.gameObject.CompareTag("Player"))
{
SetTarget( hit.collider.gameObject.transform);
}
}
}
Sense();
fsm.NextAction();
}
}
| 22.910714 | 134 | 0.521824 | [
"CC0-1.0"
] | luispenya/UnityCourseSamples | DungeonMaze/Assets/AI/FireController.cs | 2,568 | 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("07.Sort3Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07.Sort3Numbers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("45865ae8-ad70-401c-9f76-7159e74ab690")]
// 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.918919 | 84 | 0.744833 | [
"MIT"
] | PAFICH/cSHARP | 05.Conditional-Statements/07.Sort3Numbers/Properties/AssemblyInfo.cs | 1,406 | C# |
using Newtonsoft.Json;
using System.Configuration;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ReCaptcha.Library
{
public class ReCaptchaValidator : BaseValidator
{
protected override bool ControlPropertiesValid()
{
var reCaptcha = FindControl(ControlToValidate) as Challenge;
return (reCaptcha != null);
}
protected override bool EvaluateIsValid()
{
var reCaptchaFormValue = Page.Request.Form["g-Recaptcha-Response"];
if (string.IsNullOrEmpty(reCaptchaFormValue))
{
return false;
}
var secret = ConfigurationManager.AppSettings["ReCaptchaLib.SecretKey"];
var client = new WebClient();
var reCaptchaVerificationUrl = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={reCaptchaFormValue}");
ReCaptchaResponse reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(reCaptchaVerificationUrl);
return reCaptchaResponse.IsHuman;
}
}
} | 34.606061 | 163 | 0.664623 | [
"Unlicense"
] | Swimburger/Webforms-ReCaptcha | ReCaptcha.Library/ReCaptchaValidator.cs | 1,144 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Dashboard.Data
{
public interface IFunctionIndexVersionManager
{
void UpdateOrCreateIfLatest(DateTimeOffset version);
}
}
| 27.153846 | 111 | 0.753541 | [
"Apache-2.0"
] | alpaix/azure-jobs | src/Dashboard/Data/IFunctionIndexVersionManager.cs | 355 | C# |
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Toolkit.Graphics
{
public class VertexBufferBindingCollection : List<VertexBufferBinding>
{
public VertexBufferBindingCollection()
{
}
public VertexBufferBindingCollection(int capacity)
: base(capacity)
{
}
public VertexBufferBindingCollection(IEnumerable<VertexBufferBinding> collection)
: base(collection)
{
}
}
} | 39.292683 | 89 | 0.726257 | [
"MIT"
] | shoelzer/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/VertexBufferBindingCollection.cs | 1,613 | C# |
namespace StockInventoryManagement.forms
{
partial class frmStock
{
/// <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.lvStock = new BrightIdeasSoftware.ObjectListView();
this.olvColumnRef = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumnWoodType = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn3 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
((System.ComponentModel.ISupportInitialize)(this.lvStock)).BeginInit();
this.SuspendLayout();
//
// lvStock
//
this.lvStock.AllColumns.Add(this.olvColumnRef);
this.lvStock.AllColumns.Add(this.olvColumnWoodType);
this.lvStock.AllColumns.Add(this.olvColumn3);
this.lvStock.AllowColumnReorder = true;
this.lvStock.AlternateRowBackColor = System.Drawing.Color.Gainsboro;
this.lvStock.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lvStock.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.DoubleClick;
this.lvStock.CellEditTabChangesRows = true;
this.lvStock.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvColumnRef,
this.olvColumnWoodType,
this.olvColumn3});
this.lvStock.Cursor = System.Windows.Forms.Cursors.Default;
this.lvStock.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvStock.EmptyListMsg = "Stock Empty";
this.lvStock.EmptyListMsgFont = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lvStock.FullRowSelect = true;
this.lvStock.GridLines = true;
this.lvStock.HeaderWordWrap = true;
this.lvStock.HighlightBackgroundColor = System.Drawing.SystemColors.Highlight;
this.lvStock.HighlightForegroundColor = System.Drawing.Color.White;
this.lvStock.Location = new System.Drawing.Point(12, 12);
this.lvStock.Margin = new System.Windows.Forms.Padding(4);
this.lvStock.Name = "lvStock";
this.lvStock.OverlayText.Text = "";
this.lvStock.RenderNonEditableCheckboxesAsDisabled = true;
this.lvStock.SelectedColumnTint = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(0)))));
this.lvStock.ShowCommandMenuOnRightClick = true;
this.lvStock.ShowGroups = false;
this.lvStock.ShowItemToolTips = true;
this.lvStock.Size = new System.Drawing.Size(1236, 886);
this.lvStock.TabIndex = 4;
this.lvStock.TintSortColumn = true;
this.lvStock.UnfocusedHighlightBackgroundColor = System.Drawing.Color.SteelBlue;
this.lvStock.UnfocusedHighlightForegroundColor = System.Drawing.Color.White;
this.lvStock.UseCompatibleStateImageBehavior = false;
this.lvStock.UseCustomSelectionColors = true;
this.lvStock.UseExplorerTheme = true;
this.lvStock.UseFilterIndicator = true;
this.lvStock.UseFiltering = true;
this.lvStock.UseHotItem = true;
this.lvStock.UseHyperlinks = true;
this.lvStock.View = System.Windows.Forms.View.Details;
this.lvStock.CellClick += new System.EventHandler<BrightIdeasSoftware.CellClickEventArgs>(this.lvStock_CellClick);
this.lvStock.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.lvStock_MouseDoubleClick);
//
// olvColumnRef
//
this.olvColumnRef.AspectName = "itemCode";
this.olvColumnRef.IsEditable = false;
this.olvColumnRef.Text = "Reference";
this.olvColumnRef.Width = 104;
//
// olvColumnWoodType
//
this.olvColumnWoodType.AspectName = "itemName";
this.olvColumnWoodType.IsEditable = false;
this.olvColumnWoodType.Text = "Item";
this.olvColumnWoodType.Width = 184;
//
// olvColumn3
//
this.olvColumn3.AspectName = "qty";
this.olvColumn3.IsEditable = false;
this.olvColumn3.Text = "Available";
this.olvColumn3.Width = 142;
//
// frmStock
//
this.AutoScaleDimensions = new System.Drawing.SizeF(120F, 120F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(1260, 910);
this.Controls.Add(this.lvStock);
this.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(5);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmStock";
this.Padding = new System.Windows.Forms.Padding(12);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Sales";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.frmSale_Load);
((System.ComponentModel.ISupportInitialize)(this.lvStock)).EndInit();
this.ResumeLayout(false);
}
#endregion
public BrightIdeasSoftware.ObjectListView lvStock;
private BrightIdeasSoftware.OLVColumn olvColumnRef;
private BrightIdeasSoftware.OLVColumn olvColumnWoodType;
private BrightIdeasSoftware.OLVColumn olvColumn3;
}
} | 49.453237 | 169 | 0.625546 | [
"MIT"
] | SrinivasanMuthukannu/InvGen | StockInventoryManagement/StockInventoryManagement/forms/frmStock.Designer.cs | 6,876 | 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 rds-2014-10-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.RDS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.RDS.Model.Internal.MarshallTransformations
{
/// <summary>
/// CopyDBClusterSnapshot Request Marshaller
/// </summary>
public class CopyDBClusterSnapshotRequestMarshaller : IMarshaller<IRequest, CopyDBClusterSnapshotRequest> , 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((CopyDBClusterSnapshotRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CopyDBClusterSnapshotRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS");
request.Parameters.Add("Action", "CopyDBClusterSnapshot");
request.Parameters.Add("Version", "2014-10-31");
if(publicRequest != null)
{
if(publicRequest.IsSetCopyTags())
{
request.Parameters.Add("CopyTags", StringUtils.FromBool(publicRequest.CopyTags));
}
if(publicRequest.IsSetKmsKeyId())
{
request.Parameters.Add("KmsKeyId", StringUtils.FromString(publicRequest.KmsKeyId));
}
if(publicRequest.IsSetPreSignedUrl())
{
request.Parameters.Add("PreSignedUrl", StringUtils.FromString(publicRequest.PreSignedUrl));
}
if(publicRequest.IsSetSourceDBClusterSnapshotIdentifier())
{
request.Parameters.Add("SourceDBClusterSnapshotIdentifier", StringUtils.FromString(publicRequest.SourceDBClusterSnapshotIdentifier));
}
if(publicRequest.IsSetTags())
{
int publicRequestlistValueIndex = 1;
foreach(var publicRequestlistValue in publicRequest.Tags)
{
if(publicRequestlistValue.IsSetKey())
{
request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValue.Key));
}
if(publicRequestlistValue.IsSetValue())
{
request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValue.Value));
}
publicRequestlistValueIndex++;
}
}
if(publicRequest.IsSetTargetDBClusterSnapshotIdentifier())
{
request.Parameters.Add("TargetDBClusterSnapshotIdentifier", StringUtils.FromString(publicRequest.TargetDBClusterSnapshotIdentifier));
}
}
return request;
}
private static CopyDBClusterSnapshotRequestMarshaller _instance = new CopyDBClusterSnapshotRequestMarshaller();
internal static CopyDBClusterSnapshotRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CopyDBClusterSnapshotRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.210084 | 183 | 0.58279 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/CopyDBClusterSnapshotRequestMarshaller.cs | 4,904 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports
{
[ExportLanguageService(typeof(IRemoveUnnecessaryImportsService), LanguageNames.CSharp), Shared]
internal partial class CSharpRemoveUnnecessaryImportsService :
AbstractRemoveUnnecessaryImportsService<UsingDirectiveSyntax>, IRemoveUnnecessaryImportsService
{
public static IEnumerable<SyntaxNode> GetUnnecessaryImports(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken)
{
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
if (!diagnostics.Any())
{
return null;
}
var unnecessaryImports = new HashSet<UsingDirectiveSyntax>();
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Id == "CS8019")
{
var node = root.FindNode(diagnostic.Location.SourceSpan) as UsingDirectiveSyntax;
if (node != null)
{
unnecessaryImports.Add(node);
}
}
}
if (cancellationToken.IsCancellationRequested || !unnecessaryImports.Any())
{
return null;
}
return unnecessaryImports;
}
public async Task<Document> RemoveUnnecessaryImportsAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_CSharp, cancellationToken))
{
var unnecessaryImports = await GetCommonUnnecessaryImportsOfAllContextAsync(document, cancellationToken).ConfigureAwait(false);
if (unnecessaryImports == null || unnecessaryImports.Any(import => import.OverlapsHiddenPosition(cancellationToken)))
{
return document;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var oldRoot = (CompilationUnitSyntax)root;
var newRoot = (CompilationUnitSyntax)new Rewriter(unnecessaryImports, cancellationToken).Visit(oldRoot);
if (cancellationToken.IsCancellationRequested)
{
return null;
}
return document.WithSyntaxRoot(await FormatResultAsync(document, newRoot, cancellationToken).ConfigureAwait(false));
}
}
protected override IEnumerable<UsingDirectiveSyntax> GetUnusedUsings(SemanticModel model, SyntaxNode root, CancellationToken cancellationToken)
{
return GetUnnecessaryImports(model, root, cancellationToken) as IEnumerable<UsingDirectiveSyntax>;
}
private Task<SyntaxNode> FormatResultAsync(Document document, CompilationUnitSyntax newRoot, CancellationToken cancellationToken)
{
var spans = new List<TextSpan>();
AddFormattingSpans(newRoot, spans, cancellationToken);
return Formatter.FormatAsync(newRoot, spans, document.Project.Solution.Workspace, document.Options, cancellationToken: cancellationToken);
}
private void AddFormattingSpans(
CompilationUnitSyntax compilationUnit,
List<TextSpan> spans,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
spans.Add(TextSpan.FromBounds(0, GetEndPosition(compilationUnit, compilationUnit.Members)));
foreach (var @namespace in compilationUnit.Members.OfType<NamespaceDeclarationSyntax>())
{
AddFormattingSpans(@namespace, spans, cancellationToken);
}
}
private void AddFormattingSpans(
NamespaceDeclarationSyntax namespaceMember,
List<TextSpan> spans,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
spans.Add(TextSpan.FromBounds(namespaceMember.SpanStart, GetEndPosition(namespaceMember, namespaceMember.Members)));
foreach (var @namespace in namespaceMember.Members.OfType<NamespaceDeclarationSyntax>())
{
AddFormattingSpans(@namespace, spans, cancellationToken);
}
}
private int GetEndPosition(SyntaxNode container, SyntaxList<MemberDeclarationSyntax> list)
{
return list.Count > 0 ? list[0].SpanStart : container.Span.End;
}
}
}
| 42.290323 | 160 | 0.668192 | [
"Apache-2.0"
] | OceanYan/roslyn | src/Features/CSharp/Portable/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.cs | 5,244 | C# |
using System;
namespace B2C.WebApi
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 18.1875 | 69 | 0.597938 | [
"MIT"
] | manoj-choudhari-git/MSAL-3.0-Samples | B2C.WebApi/WeatherForecast.cs | 291 | 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("09.FrequentNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("09.FrequentNumber")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("886bdc8f-509c-4010-b9a0-a3bcb1c3557d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.745558 | [
"MIT"
] | Vladeff/TelerikAcademy | C#2 Homework/Arrays/09.FrequentNumber/Properties/AssemblyInfo.cs | 1,410 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Recognizers.Text.Choice;
using Microsoft.Recognizers.Text.DateTime;
using Microsoft.Recognizers.Text.DateTime.Dutch;
using Microsoft.Recognizers.Text.DateTime.English;
using Microsoft.Recognizers.Text.DateTime.French;
using Microsoft.Recognizers.Text.DateTime.German;
using Microsoft.Recognizers.Text.DateTime.Italian;
using Microsoft.Recognizers.Text.DateTime.Portuguese;
using Microsoft.Recognizers.Text.DateTime.Spanish;
using Microsoft.Recognizers.Text.DateTime.Turkish;
using Microsoft.Recognizers.Text.Number;
using Microsoft.Recognizers.Text.NumberWithUnit;
using Microsoft.Recognizers.Text.Sequence;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DateObject = System.DateTime;
namespace Microsoft.Recognizers.Text.DataDrivenTests
{
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1602: CSharp.Naming : Enumeration items should be documented", Justification = "TODO")]
public enum Models
{
Number,
NumberPercentMode,
NumberExperimentalMode,
Ordinal,
OrdinalSuppressExtendedTypes,
Percent,
PercentPercentMode,
NumberRange,
NumberRangeExperimentalMode,
CustomNumber,
Age,
Currency,
Dimension,
Temperature,
DateTime,
DateTimeSplitDateAndTime,
DateTimeCalendarMode,
DateTimeExtendedTypes,
DateTimeComplexCalendar,
DateTimeExperimentalMode,
PhoneNumber,
IpAddress,
Mention,
Hashtag,
Email,
URL,
GUID,
Boolean,
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1602: CSharp.Naming : Enumeration items should be documented", Justification = "TODO")]
public enum DateTimeExtractors
{
Date,
Time,
DatePeriod,
TimePeriod,
DateTime,
DateTimePeriod,
Duration,
Holiday,
TimeZone,
Set,
Merged,
MergedSkipFromTo,
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1602: CSharp.Naming : Enumeration items should be documented", Justification = "TODO")]
public enum DateTimeParsers
{
Date,
Time,
DatePeriod,
TimePeriod,
DateTime,
DateTimePeriod,
Duration,
Holiday,
TimeZone,
Set,
Merged,
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1649: CSharp.Naming", Justification = "TODO")]
public static class TestContextExtensions
{
private static IDictionary<Models, Func<TestModel, string, IList<ModelResult>>> modelFunctions = new Dictionary<Models, Func<TestModel, string, IList<ModelResult>>>()
{
{ Models.Number, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.NumberPercentMode, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, NumberOptions.PercentageMode, fallbackToDefaultCulture: false) },
{ Models.NumberExperimentalMode, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, NumberOptions.ExperimentalMode, fallbackToDefaultCulture: false) },
{ Models.Ordinal, (test, culture) => NumberRecognizer.RecognizeOrdinal(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.OrdinalSuppressExtendedTypes, (test, culture) => NumberRecognizer.RecognizeOrdinal(test.Input, culture, NumberOptions.SuppressExtendedTypes, fallbackToDefaultCulture: false) },
{ Models.Percent, (test, culture) => NumberRecognizer.RecognizePercentage(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.PercentPercentMode, (test, culture) => NumberRecognizer.RecognizePercentage(test.Input, culture, NumberOptions.PercentageMode, fallbackToDefaultCulture: false) },
{ Models.NumberRange, (test, culture) => NumberRecognizer.RecognizeNumberRange(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.NumberRangeExperimentalMode, (test, culture) => NumberRecognizer.RecognizeNumberRange(test.Input, culture, NumberOptions.ExperimentalMode, fallbackToDefaultCulture: false) },
{ Models.Age, (test, culture) => NumberWithUnitRecognizer.RecognizeAge(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Currency, (test, culture) => NumberWithUnitRecognizer.RecognizeCurrency(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Dimension, (test, culture) => NumberWithUnitRecognizer.RecognizeDimension(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Temperature, (test, culture) => NumberWithUnitRecognizer.RecognizeTemperature(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.DateTime, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.DateTimeSplitDateAndTime, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.SplitDateAndTime, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.DateTimeCalendarMode, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.CalendarMode, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.DateTimeExtendedTypes, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExtendedTypes, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.DateTimeComplexCalendar, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExtendedTypes | DateTimeOptions.CalendarMode | DateTimeOptions.EnablePreview, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.DateTimeExperimentalMode, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExperimentalMode, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) },
{ Models.PhoneNumber, (test, culture) => SequenceRecognizer.RecognizePhoneNumber(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.IpAddress, (test, culture) => SequenceRecognizer.RecognizeIpAddress(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Mention, (test, culture) => SequenceRecognizer.RecognizeMention(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Hashtag, (test, culture) => SequenceRecognizer.RecognizeHashtag(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Email, (test, culture) => SequenceRecognizer.RecognizeEmail(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.URL, (test, culture) => SequenceRecognizer.RecognizeURL(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.GUID, (test, culture) => SequenceRecognizer.RecognizeGUID(test.Input, culture, fallbackToDefaultCulture: false) },
{ Models.Boolean, (test, culture) => ChoiceRecognizer.RecognizeBoolean(test.Input, culture, fallbackToDefaultCulture: false) },
};
public static IList<ModelResult> GetModelParseResults(this TestContext context, TestModel test)
{
var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName);
var modelName = TestUtils.GetModel(context.TestName);
var modelFunction = modelFunctions[modelName];
return modelFunction(test, culture);
}
public static IDateTimeExtractor GetExtractor(this TestContext context)
{
var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName);
var extractorName = TestUtils.GetExtractor(context.TestName);
switch (culture)
{
case Culture.English:
return GetEnglishExtractor(extractorName);
case Culture.EnglishOthers:
return GetEnglishOthersExtractor(extractorName);
case Culture.Spanish:
return GetSpanishExtractor(extractorName);
case Culture.Portuguese:
return GetPortugueseExtractor(extractorName);
case Culture.Chinese:
return GetChineseExtractor(extractorName);
case Culture.French:
return GetFrenchExtractor(extractorName);
case Culture.German:
return GetGermanExtractor(extractorName);
case Culture.Italian:
return GetItalianExtractor(extractorName);
case Culture.Dutch:
return GetDutchExtractor(extractorName);
case Culture.Japanese:
return GetJapaneseExtractor(extractorName);
case Culture.Turkish:
return GetTurkishExtractor(extractorName);
}
throw new Exception($"Extractor '{extractorName}' for '{culture}' not supported");
}
public static IDateTimeParser GetDateTimeParser(this TestContext context)
{
var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName);
var parserName = TestUtils.GetParser(context.TestName);
switch (culture)
{
case Culture.English:
return GetEnglishParser(parserName);
case Culture.EnglishOthers:
return GetEnglishOthersParser(parserName);
case Culture.Spanish:
return GetSpanishParser(parserName);
case Culture.Portuguese:
return GetPortugueseParser(parserName);
case Culture.Chinese:
return GetChineseParser(parserName);
case Culture.French:
return GetFrenchParser(parserName);
case Culture.German:
return GetGermanParser(parserName);
case Culture.Italian:
return GetItalianParser(parserName);
case Culture.Japanese:
return GetJapaneseParser(parserName);
case Culture.Dutch:
return GetDutchParser(parserName);
case Culture.Turkish:
return GetTurkishParser(parserName);
}
throw new Exception($"Parser '{parserName}' for '{culture}' not supported");
}
public static IDateTimeExtractor GetDutchExtractor(DateTimeExtractors extractorName)
{
var enableDmyConfig = new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true);
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new DutchDateExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new DutchTimeExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new DutchDatePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new DutchTimePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new DutchDateTimeExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new DutchDateTimePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new DutchDurationExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new DutchHolidayExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.TimeZone:
return new BaseTimeZoneExtractor(new DutchTimeZoneExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new DutchSetExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new DutchMergedExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new DutchMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge)));
}
throw new Exception($"Extractor '{extractorName}' for Dutch not supported");
}
public static IDateTimeParser GetDutchParser(DateTimeParsers parserName)
{
var commonConfiguration = new DutchCommonDateTimeParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true));
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new DutchDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.Dutch.TimeParser(new DutchTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new DutchDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new DutchTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new DutchDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new DutchDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new DutchDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new DutchHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.TimeZone:
return new BaseTimeZoneParser();
case DateTimeParsers.Set:
return new BaseSetParser(new DutchSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new DutchMergedParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true)));
}
throw new Exception($"Parser '{parserName}' for Dutch not supported");
}
public static IDateTimeExtractor GetEnglishExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
var previewConfig = new BaseOptionsConfiguration(DateTimeOptions.EnablePreview);
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new EnglishDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new EnglishTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new EnglishDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new EnglishTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new EnglishDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new EnglishDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new EnglishDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new EnglishHolidayExtractorConfiguration(config));
case DateTimeExtractors.TimeZone:
return new BaseTimeZoneExtractor(new EnglishTimeZoneExtractorConfiguration(previewConfig));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new EnglishSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(config));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge)));
}
throw new Exception($"Extractor '{extractorName}' for English not supported");
}
public static IDateTimeParser GetEnglishParser(DateTimeParsers parserName)
{
var commonConfiguration = new EnglishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new EnglishDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.English.TimeParser(new EnglishTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new EnglishDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new EnglishTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new EnglishDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new EnglishDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new EnglishDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new EnglishHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.TimeZone:
return new BaseTimeZoneParser();
case DateTimeParsers.Set:
return new BaseSetParser(new EnglishSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new EnglishMergedParserConfiguration(new BaseOptionsConfiguration()));
}
throw new Exception($"Parser '{parserName}' for English not supported");
}
public static IDateTimeExtractor GetEnglishOthersExtractor(DateTimeExtractors extractorName)
{
var enableDmyConfig = new BaseOptionsConfiguration(DateTimeOptions.None, true);
var enableDmyPreviewConfig = new BaseOptionsConfiguration(DateTimeOptions.EnablePreview, true);
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new EnglishDateExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new EnglishTimeExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new EnglishDatePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new EnglishTimePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new EnglishDateTimeExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new EnglishDateTimePeriodExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new EnglishDurationExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new EnglishHolidayExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.TimeZone:
return new BaseTimeZoneExtractor(new EnglishTimeZoneExtractorConfiguration(enableDmyPreviewConfig));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new EnglishSetExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(enableDmyConfig));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge, true)));
}
throw new Exception($"Extractor '{extractorName}' for English-Others not supported");
}
public static IDateTimeParser GetEnglishOthersParser(DateTimeParsers parserName)
{
var commonConfiguration = new EnglishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, true));
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new EnglishDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.English.TimeParser(new EnglishTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new EnglishDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new EnglishTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new EnglishDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new EnglishDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new EnglishDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new EnglishHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.TimeZone:
return new BaseTimeZoneParser();
case DateTimeParsers.Set:
return new BaseSetParser(new EnglishSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new EnglishMergedParserConfiguration(new BaseOptionsConfiguration()));
}
throw new Exception($"Parser '{parserName}' for English-Others not supported");
}
public static IDateTimeExtractor GetChineseExtractor(DateTimeExtractors extractorName)
{
switch (extractorName)
{
case DateTimeExtractors.Date:
return new DateTime.Chinese.ChineseDateExtractorConfiguration();
case DateTimeExtractors.Time:
return new DateTime.Chinese.ChineseTimeExtractorConfiguration();
case DateTimeExtractors.DatePeriod:
return new DateTime.Chinese.ChineseDatePeriodExtractorConfiguration();
case DateTimeExtractors.TimePeriod:
return new DateTime.Chinese.ChineseTimePeriodExtractorChsConfiguration();
case DateTimeExtractors.DateTime:
return new DateTime.Chinese.ChineseDateTimeExtractorConfiguration();
case DateTimeExtractors.DateTimePeriod:
return new DateTime.Chinese.ChineseDateTimePeriodExtractorConfiguration();
case DateTimeExtractors.Duration:
return new DateTime.Chinese.ChineseDurationExtractorConfiguration();
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new DateTime.Chinese.ChineseHolidayExtractorConfiguration());
case DateTimeExtractors.Set:
return new DateTime.Chinese.ChineseSetExtractorConfiguration();
case DateTimeExtractors.Merged:
return new DateTime.Chinese.ChineseMergedExtractorConfiguration(DateTimeOptions.None);
case DateTimeExtractors.MergedSkipFromTo:
return new DateTime.Chinese.ChineseMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge);
}
throw new Exception($"Extractor '{extractorName}' for Chinese not supported");
}
public static IDateTimeParser GetChineseParser(DateTimeParsers parserName)
{
// var commonConfiguration = new EnglishCommonDateTimeParserConfiguration();
switch (parserName)
{
case DateTimeParsers.Date:
return new DateTime.Chinese.ChineseDateParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.Time:
return new DateTime.Chinese.ChineseTimeParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.DatePeriod:
return new DateTime.Chinese.ChineseDatePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.TimePeriod:
return new DateTime.Chinese.ChineseTimePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.DateTime:
return new DateTime.Chinese.ChineseDateTimeParser(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.DateTimePeriod:
return new DateTime.Chinese.ChineseDateTimePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.Duration:
return new DateTime.Chinese.ChineseDurationParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.Holiday:
return new DateTime.Chinese.ChineseHolidayParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.Set:
return new DateTime.Chinese.ChineseSetParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
case DateTimeParsers.Merged:
return new FullDateTimeParser(new DateTime.Chinese.ChineseDateTimeParserConfiguration());
}
throw new Exception($"Parser '{parserName}' for Chinese not supported");
}
public static IDateTimeExtractor GetJapaneseExtractor(DateTimeExtractors extractorName)
{
switch (extractorName)
{
case DateTimeExtractors.Date:
return new DateTime.Japanese.JapaneseDateExtractorConfiguration();
case DateTimeExtractors.Time:
return new DateTime.Japanese.JapaneseTimeExtractorConfiguration();
case DateTimeExtractors.DatePeriod:
return new DateTime.Japanese.JapaneseDatePeriodExtractorConfiguration();
case DateTimeExtractors.TimePeriod:
return new DateTime.Japanese.JapaneseTimePeriodExtractorConfiguration();
case DateTimeExtractors.DateTime:
return new DateTime.Japanese.JapaneseDateTimeExtractorConfiguration();
case DateTimeExtractors.DateTimePeriod:
return new DateTime.Japanese.JapaneseDateTimePeriodExtractorConfiguration();
case DateTimeExtractors.Duration:
return new DateTime.Japanese.JapaneseDurationExtractorConfiguration();
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new DateTime.Japanese.JapaneseHolidayExtractorConfiguration());
case DateTimeExtractors.Set:
return new DateTime.Japanese.JapaneseSetExtractorConfiguration();
case DateTimeExtractors.Merged:
return new DateTime.Japanese.JapaneseMergedExtractorConfiguration(DateTimeOptions.None);
case DateTimeExtractors.MergedSkipFromTo:
return new DateTime.Japanese.JapaneseMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge);
}
throw new Exception($"Extractor '{extractorName}' for Japanese not supported");
}
public static IDateTimeParser GetJapaneseParser(DateTimeParsers parserName)
{
switch (parserName)
{
case DateTimeParsers.Date:
return new DateTime.Japanese.JapaneseDateParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.Time:
return new DateTime.Japanese.JapaneseTimeParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.DatePeriod:
return new DateTime.Japanese.JapaneseDatePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.TimePeriod:
return new DateTime.Japanese.JapaneseTimePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.DateTime:
return new DateTime.Japanese.JapaneseDateTimeParser(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.DateTimePeriod:
return new DateTime.Japanese.JapaneseDateTimePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.Duration:
return new DateTime.Japanese.JapaneseDurationParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.Holiday:
return new DateTime.Japanese.JapaneseHolidayParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.Set:
return new DateTime.Japanese.JapaneseSetParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
case DateTimeParsers.Merged:
return new FullDateTimeParser(new DateTime.Japanese.JapaneseDateTimeParserConfiguration());
}
throw new Exception($"Parser '{parserName}' for Japanese not supported");
}
public static IDateTimeExtractor GetSpanishExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration(DateTimeOptions.None);
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new SpanishDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new SpanishTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new SpanishDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new SpanishTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new SpanishDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new SpanishDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new SpanishDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new SpanishHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new SpanishSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new SpanishMergedExtractorConfiguration(DateTimeOptions.None));
}
throw new Exception($"Extractor '{extractorName}' for Spanish not supported");
}
public static IDateTimeParser GetSpanishParser(DateTimeParsers parserName)
{
var commonConfiguration = new SpanishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new SpanishDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new BaseTimeParser(new SpanishTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new SpanishDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new SpanishTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new SpanishDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new DateTime.Spanish.DateTimePeriodParser(new SpanishDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new SpanishDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new SpanishHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new SpanishSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new SpanishMergedParserConfiguration(commonConfiguration));
}
throw new Exception($"Parser '{parserName}' for Spanish not supported");
}
public static IDateTimeExtractor GetPortugueseExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new PortugueseDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new PortugueseTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new PortugueseDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new PortugueseTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new PortugueseDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new PortugueseDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new PortugueseDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new PortugueseHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new PortugueseSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new PortugueseMergedExtractorConfiguration(DateTimeOptions.None));
}
throw new Exception($"Extractor '{extractorName}' for Portuguese not supported");
}
public static IDateTimeParser GetPortugueseParser(DateTimeParsers parserName)
{
var commonConfiguration = new PortugueseCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new PortugueseDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new BaseTimeParser(new PortugueseTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new PortugueseDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new PortugueseTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new PortugueseDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new DateTime.Portuguese.DateTimePeriodParser(new PortugueseDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new PortugueseDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new PortugueseHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new PortugueseSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new PortugueseMergedParserConfiguration(commonConfiguration));
}
throw new Exception($"Parser '{parserName}' for Portuguese not supported");
}
public static IDateTimeExtractor GetFrenchExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new FrenchDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new FrenchTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new FrenchDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new FrenchTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new FrenchDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new FrenchDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new FrenchDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new FrenchHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new FrenchSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new FrenchMergedExtractorConfiguration(DateTimeOptions.None));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new FrenchMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge));
}
throw new Exception($"Extractor '{extractorName}' for French not supported");
}
public static IDateTimeParser GetFrenchParser(DateTimeParsers parserName)
{
var commonConfiguration = new FrenchCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new FrenchDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.French.TimeParser(new FrenchTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new FrenchDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new FrenchTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new FrenchDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new FrenchDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new FrenchDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new FrenchHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new FrenchSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new FrenchMergedParserConfiguration(commonConfiguration));
}
throw new Exception($"Parser '{parserName}' for French not supported");
}
public static IDateTimeExtractor GetGermanExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new GermanDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new GermanTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new GermanDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new GermanTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new GermanDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new GermanDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new GermanDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new GermanHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new GermanSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new GermanMergedExtractorConfiguration(DateTimeOptions.None));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new GermanMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge));
}
throw new Exception($"Extractor '{extractorName}' for German not supported");
}
public static IDateTimeParser GetGermanParser(DateTimeParsers parserName)
{
var commonConfiguration = new GermanCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new GermanDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.German.TimeParser(new GermanTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new GermanDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new GermanTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new GermanDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new GermanDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new GermanDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new HolidayParserGer(new GermanHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new GermanSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new GermanMergedParserConfiguration(commonConfiguration));
}
throw new Exception($"Parser '{parserName}' for German not supported");
}
public static IDateTimeExtractor GetItalianExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new ItalianDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new ItalianTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new ItalianDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new ItalianTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new ItalianDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new ItalianDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new ItalianDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new ItalianHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new ItalianSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new ItalianMergedExtractorConfiguration(config));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new ItalianMergedExtractorConfiguration(config));
case DateTimeExtractors.TimeZone:
return new BaseTimeZoneExtractor(new ItalianTimeZoneExtractorConfiguration(config));
}
throw new Exception($"Extractor '{extractorName}' for Italian not supported");
}
public static IDateTimeParser GetItalianParser(DateTimeParsers parserName)
{
var commonConfiguration = new ItalianCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new ItalianDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.Italian.TimeParser(new ItalianTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new ItalianDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new ItalianTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new ItalianDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new ItalianDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new ItalianDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new ItalianHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new ItalianSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new ItalianMergedParserConfiguration(commonConfiguration));
}
throw new Exception($"Parser '{parserName}' for Italian not supported");
}
public static IDateTimeExtractor GetTurkishExtractor(DateTimeExtractors extractorName)
{
var config = new BaseOptionsConfiguration();
var previewConfig = new BaseOptionsConfiguration(DateTimeOptions.EnablePreview);
switch (extractorName)
{
case DateTimeExtractors.Date:
return new BaseDateExtractor(new TurkishDateExtractorConfiguration(config));
case DateTimeExtractors.Time:
return new BaseTimeExtractor(new TurkishTimeExtractorConfiguration(config));
case DateTimeExtractors.DatePeriod:
return new BaseDatePeriodExtractor(new TurkishDatePeriodExtractorConfiguration(config));
case DateTimeExtractors.TimePeriod:
return new BaseTimePeriodExtractor(new TurkishTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.DateTime:
return new BaseDateTimeExtractor(new TurkishDateTimeExtractorConfiguration(config));
case DateTimeExtractors.DateTimePeriod:
return new BaseDateTimePeriodExtractor(new TurkishDateTimePeriodExtractorConfiguration(config));
case DateTimeExtractors.Duration:
return new BaseDurationExtractor(new TurkishDurationExtractorConfiguration(config));
case DateTimeExtractors.Holiday:
return new BaseHolidayExtractor(new TurkishHolidayExtractorConfiguration(config));
case DateTimeExtractors.Set:
return new BaseSetExtractor(new TurkishSetExtractorConfiguration(config));
case DateTimeExtractors.Merged:
return new BaseMergedDateTimeExtractor(new TurkishMergedExtractorConfiguration(config));
case DateTimeExtractors.MergedSkipFromTo:
return new BaseMergedDateTimeExtractor(new TurkishMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge)));
}
throw new Exception($"Extractor '{extractorName}' for Turkish not supported");
}
public static IDateTimeParser GetTurkishParser(DateTimeParsers parserName)
{
var commonConfiguration = new TurkishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration());
switch (parserName)
{
case DateTimeParsers.Date:
return new BaseDateParser(new TurkishDateParserConfiguration(commonConfiguration));
case DateTimeParsers.Time:
return new DateTime.Turkish.TimeParser(new TurkishTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DatePeriod:
return new BaseDatePeriodParser(new TurkishDatePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.TimePeriod:
return new BaseTimePeriodParser(new TurkishTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTime:
return new BaseDateTimeParser(new TurkishDateTimeParserConfiguration(commonConfiguration));
case DateTimeParsers.DateTimePeriod:
return new BaseDateTimePeriodParser(new TurkishDateTimePeriodParserConfiguration(commonConfiguration));
case DateTimeParsers.Duration:
return new BaseDurationParser(new TurkishDurationParserConfiguration(commonConfiguration));
case DateTimeParsers.Holiday:
return new BaseHolidayParser(new TurkishHolidayParserConfiguration(commonConfiguration));
case DateTimeParsers.Set:
return new BaseSetParser(new TurkishSetParserConfiguration(commonConfiguration));
case DateTimeParsers.Merged:
return new BaseMergedDateTimeParser(new TurkishMergedParserConfiguration(new BaseOptionsConfiguration()));
}
throw new Exception($"Parser '{parserName}' for Turkish not supported");
}
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1402: CSharp.Naming : File may only contain a single type", Justification = "TODO")]
public static class TestModelExtensions
{
public static bool IsNotSupported(this TestModel testSpec)
{
return testSpec.NotSupported.HasFlag(Platform.DotNet);
}
public static bool IsNotSupportedByDesign(this TestModel testSpec)
{
return testSpec.NotSupportedByDesign.HasFlag(Platform.DotNet);
}
public static DateObject GetReferenceDateTime(this TestModel testSpec)
{
if (testSpec.Context.TryGetValue("ReferenceDateTime", out object dateTimeObject))
{
return (DateObject)dateTimeObject;
}
return DateObject.Now;
}
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1402: CSharp.Naming : File may only contain a single type", Justification = "TODO")]
public static class TestUtils
{
public static string GetCulture(string source)
{
var langStr = source.Substring(source.LastIndexOf('_') + 1);
return Culture.SupportedCultures.First(c => c.CultureName == langStr).CultureCode;
}
public static bool EvaluateSpec(TestModel spec, out string message)
{
if (string.IsNullOrEmpty(spec.Input))
{
message = $"spec not found";
return true;
}
if (spec.IsNotSupported())
{
message = $"input '{spec.Input}' not supported";
return true;
}
if (spec.IsNotSupportedByDesign())
{
message = $"input '{spec.Input}' not supported by design";
return true;
}
message = string.Empty;
return false;
}
public static string SanitizeSourceName(string source)
{
return source.Replace("Model", string.Empty).Replace("Extractor", string.Empty).Replace("Parser", string.Empty);
}
public static Models GetModel(string source)
{
var model = SanitizeSourceName(source);
Models modelEnum = Models.Number;
if (Enum.TryParse(model, out modelEnum))
{
return modelEnum;
}
throw new Exception($"Model '{model}' not supported");
}
public static DateTimeParsers GetParser(string source)
{
var parser = SanitizeSourceName(source);
DateTimeParsers parserEnum = DateTimeParsers.Date;
if (Enum.TryParse(parser, out parserEnum))
{
return parserEnum;
}
throw new Exception($"Parser '{parser}' not supported");
}
public static DateTimeExtractors GetExtractor(string source)
{
var extractor = SanitizeSourceName(source);
DateTimeExtractors extractorEnum = DateTimeExtractors.Date;
if (Enum.TryParse(extractor, out extractorEnum))
{
return extractorEnum;
}
throw new Exception($"Extractor '{extractor}' not supported");
}
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1402: CSharp.Naming : File may only contain a single type", Justification = "TODO")]
public static class RecognizerExtensions
{
public static ConcurrentDictionary<(string culture, Type modelType, string modelOptions), IModel> GetInternalCache<TRecognizerOptions>(this Recognizer<TRecognizerOptions> source)
where TRecognizerOptions : struct
{
var modelFactoryProp = typeof(Recognizer<TRecognizerOptions>).GetField("factory", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var modelFactory = modelFactoryProp.GetValue(source);
var cacheProp = modelFactory.GetType().GetField("cache", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
return cacheProp.GetValue(modelFactory) as ConcurrentDictionary<(string culture, Type modelType, string modelOptions), IModel>;
}
}
} | 61.208704 | 291 | 0.663844 | [
"MIT"
] | LionbridgeCSII/Recognizers-Text | .NET/Microsoft.Recognizers.Text.DataDrivenTests/TestHelpers.cs | 61,884 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NetCoreKit.Infrastructure.EfCore.Extensions;
using NetCoreKit.Infrastructure.EfCore.Repository;
namespace VND.CoolStore.Services.Cart.v1.Extensions
{
public static class CartRepositoryExtensions
{
public static async Task<Domain.Cart> GetFullCartAsync(
this IEfQueryRepository<Domain.Cart> cartRepo,
Guid cartId,
bool tracking = true)
{
var cart = await cartRepo.GetByIdAsync(
cartId,
cartQueryable => cartQueryable
.Include(x => x.CartItems)
.ThenInclude(cartItem => cartItem.Product),
!tracking);
if (cart == null) throw new Exception($"Could not find the cart[{cartId}]");
return cart;
}
}
}
| 30.37931 | 88 | 0.61748 | [
"MIT"
] | Anberm/coolstore-microservices | src/services/cart/v1/Extensions/CartRepositoryExtensions.cs | 881 | C# |
namespace Models.Responses
{
public class CustomerCreatedModel
{
public int Id { get; set; }
public string InfoMessage { get; set; }
}
}
| 18.444444 | 47 | 0.608434 | [
"MIT"
] | ST4NSB/checkout-api | Models/Responses/CustomerCreatedModel.cs | 168 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 07.12.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Int16.SET001.STD.Equals.Complete.Double{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Int16;
using T_DATA2 =System.Double;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=3;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !((vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Int16.SET001.STD.Equals.Complete.Double
| 23.524249 | 125 | 0.526016 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/Int16/SET001/STD/Equals/Complete/Double/TestSet_504__param__01__VV.cs | 10,188 | C# |
using System;
using Xunit;
using Util;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace WordLadder
{
public class Solution
{
public int LadderLength(string beginWord, string endWord, IList<string> wordList)
{
// give up.
// copy from: https://cloud.tencent.com/developer/article/1407026
var wordSet = new HashSet<string>(wordList);
var cur_level = new List<string> { beginWord };
var next_level = new List<string>();
var depth = 1;
var n = beginWord.Length;
while (cur_level.Count > 0)
{
foreach (var item in cur_level)
{
if (item == endWord)
return depth;
for (var i = 0; i < n; i++)
{
foreach (var c in "abcdefghijklmnopqrstuvwxyz")
{
var word = item.Substring(0, i) + c + item.Substring(i + 1);
if (wordSet.Contains(word))
{
wordSet.Remove(word);
next_level.Add(word);
}
}
}
}
depth += 1;
cur_level.Clear();
foreach (var i in next_level)
{
cur_level.Add(i);
}
next_level.Clear();
// cur_level = next_level;
// next_level = new List<string>();
}
return 0;
}
}
// public class Solution1
// {
// int minLen;
// int wordListCount;
// // Dictionary<(string, int), int> cache = new Dictionary<(string, int), int>();
// Dictionary<string, int> cache = new Dictionary<string, int>();
// public int LadderLength(string beginWord, string endWord, IList<string> wordList)
// {
// if (beginWord == endWord)
// return 2;
// if (!wordList.Contains(endWord)) return 0;
// minLen = wordList.Count;
// wordListCount = wordList.Count;
// var x = CachedMyLadderLength(beginWord, endWord, wordList);
// return x;
// }
// int CachedMyLadderLength(string beginWord, string endWord, IList<string> wordList)
// {
// var k = $"{beginWord}|{wordList.Count}";
// // var k = (beginWord, wordList.Count);
// // var k = string.Join('|', wordList);
// if (!cache.ContainsKey(k))
// {
// var len = wordListCount - wordList.Count + 1;
// if (len >= minLen)
// {
// // Console.WriteLine($"{len}>{minLen}");
// cache[k] = 0;
// return 0;
// }
// cache[k] = MyLadderLength(beginWord, endWord, wordList);
// if (cache[k] > 0)
// {
// len = wordListCount - wordList.Count + 1;
// len += cache[k];
// if (len < minLen)
// minLen = len;
// }
// }
// return cache[k];
// }
// int MyLadderLength(string beginWord, string endWord, IList<string> wordList)
// {
// int Diff(string w1, string w2)
// {
// var d = 0;
// for (var i = 0; i < w1.Length; i++)
// {
// if (w1[i] != w2[i]) d++;
// }
// return d;
// }
// var positive = new List<int>();
// foreach (var w in wordList)
// // for (var i = 0; i < wordList.Count; i++)
// {
// // var w = wordList[i];
// // if (w == "-") continue;
// var diff = Diff(beginWord, w);
// if (diff == 1)
// {
// if (w == endWord) return 2;
// var wordList2 = wordList.Where(i => i != w).ToList();
// var x = CachedMyLadderLength(w, endWord, wordList2);
// // var x = CachedMyLadderLength(w, endWord, wordList);
// if (x > 0) positive.Add(x);
// }
// }
// if (positive.Count == 0) return 0;
// return 1 + positive.Min();
// }
// }
public class Test
{
static public void Run()
{
var input = @"
#start line, to avoid removed by CleanInput
";
var lines = input.CleanInput();
lines = "0127-data.txt".InputFromFile();
Verify.Method(new Solution(), lines);
}
}
} | 35.177305 | 93 | 0.409879 | [
"MIT"
] | beingj/LeetCode | 0127-WordLadder.cs | 4,960 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orleans
{
internal static class SetExtensions
{
/// <summary>
/// Shortcut to create HashSet from IEnumerable that supports type inference
/// (which the standard constructor does not)
/// </summary>
/// <typeparam name="TK"></typeparam>
/// <typeparam name="TV"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static HashSet<T> ToSet<T>(this IEnumerable<T> values)
{
if (values == null)
return null;
return new HashSet<T>(values);
}
public static bool ListEquals<T>(this IList<T> a, IList<T> b)
{
if (a.Count != b.Count)
return false;
return new HashSet<T>(a).SetEquals(new HashSet<T>(b));
}
public static bool IEnumerableEquals<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return new HashSet<T>(a).SetEquals(new HashSet<T>(b));
}
public static bool IsSupersetOf<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return new HashSet<T>(a).IsSupersetOf(new HashSet<T>(b));
}
/// <summary>
/// Synchronize contents of two dictionaries with mutable values
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="a">Dictionary</param>
/// <param name="b">Dictionary</param>
/// <param name="copy">Return a copy of a value</param>
/// <param name="sync">Synchronize two mutable values</param>
private static void Synchronize<TKey, TValue>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue> b, Func<TValue, TValue> copy, Action<TValue, TValue> sync)
{
var akeys = a.Keys.ToSet();
var bkeys = b.Keys.ToSet();
var aonly = akeys.Except(bkeys).ToSet();
var bonly = bkeys.Except(akeys).ToSet();
var both = akeys.Intersect(bkeys).ToSet();
foreach (var ak in aonly)
{
b.Add(ak, copy(a[ak]));
}
foreach (var bk in bonly)
{
a.Add(bk, copy(b[bk]));
}
foreach (var k in both)
{
sync(a[k], b[k]);
}
}
/// <summary>
/// Synchronize contents of two dictionaries with immutable values
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="a">Dictionary</param>
/// <param name="b">Dictionary</param>
/// <param name="sync">Synchronize two values, return synced value</param>
private static void Synchronize<TKey, TValue>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue> b, Func<TValue, TValue, TValue> sync)
{
var akeys = a.Keys.ToSet();
var bkeys = b.Keys.ToSet();
var aonly = akeys.Except(bkeys).ToSet();
var bonly = bkeys.Except(akeys).ToSet();
var both = akeys.Intersect(bkeys).ToSet();
foreach (var ak in aonly)
{
b.Add(ak, a[ak]);
}
foreach (var bk in bonly)
{
a.Add(bk, b[bk]);
}
foreach (var k in both)
{
var s = sync(a[k], b[k]);
a[k] = s;
b[k] = s;
}
}
/// <summary>
/// Synchronize contents of two nested dictionaries with mutable values
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TKey2">Nested key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="a">Dictionary</param>
/// <param name="b">Dictionary</param>
/// <param name="copy">Return a copy of a value</param>
/// <param name="sync">Synchronize two mutable values</param>
private static void Synchronize2<TKey, TKey2, TValue>(this Dictionary<TKey, Dictionary<TKey2, TValue>> a, Dictionary<TKey, Dictionary<TKey2, TValue>> b, Func<TValue, TValue> copy, Action<TValue, TValue> sync)
{
a.Synchronize(b, d => d.Copy(copy), (d1, d2) => d1.Synchronize(d2, copy, sync));
}
/// <summary>
/// Synchronize contents of two nested dictionaries with immutable values
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TKey2">Nested key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="a">Dictionary</param>
/// <param name="b">Dictionary</param>
/// <param name="copy">Return a copy of a value</param>
/// <param name="sync">Synchronize two immutable values</param>
private static void Synchronize2<TKey, TKey2, TValue>(this Dictionary<TKey, Dictionary<TKey2, TValue>> a, Dictionary<TKey, Dictionary<TKey2, TValue>> b, Func<TValue, TValue, TValue> sync)
{
a.Synchronize(b, d => new Dictionary<TKey2, TValue>(d), (d1, d2) => d1.Synchronize(d2, sync));
}
public static Dictionary<TKey, TValue> Copy<TKey, TValue>(this Dictionary<TKey, TValue> original)
{
return new Dictionary<TKey, TValue>(original);
}
/// <summary>
/// Copy a dictionary with mutable values
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="original"></param>
/// <param name="copy"></param>
/// <returns></returns>
private static Dictionary<TKey, TValue> Copy<TKey, TValue>(this Dictionary<TKey, TValue> original, Func<TValue, TValue> copy)
{
return original.ToDictionary(pair => pair.Key, pair => copy(pair.Value));
}
/// <summary>
/// ToString every element of an enumeration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="toString">Can supply null to use Object.ToString()</param>
/// <param name="before">Before each element, or space if unspecified</param>
/// <returns></returns>
public static string ToStrings<T>(this IEnumerable<T> list, Func<T, object> toString = null, string separator = " ")
{
if (list == null) return "";
toString = toString ?? (x => x);
//Func<T, string> toStringPrinter = (x =>
// {
// object obj = toString(x);
// if(obj != null)
// return obj.ToString();
// else
// return "null";
// });
//return Utils.IEnumerableToString(list, toStringPrinter, separator);
//Do NOT use Aggregate for string concatenation. It is very inefficient, will reallocate and copy lots of intermediate strings.
//toString = toString ?? (x => x);
return list.Aggregate("", (s, x) => s + separator + toString(x));
}
public static List<T> Union<T>(List<T> list1, List<T> list2)
{
if (list1 == null && list2 == null)
return null;
if (list1 == null)
return list2;
if (list2 == null)
return list1;
list1.AddRange(list2);
return list1;
}
}
}
| 40.863158 | 216 | 0.535677 | [
"MIT"
] | Drawaes/orleans | src/Orleans/Utils/SetExtensions.cs | 7,764 | C# |
using System;
#if NET472
using Microsoft.IO;
using Microsoft.IO.Enumeration;
#else
using System.IO;
using System.IO.Enumeration;
#endif
namespace Meziantou.Framework.Globbing
{
public abstract class GlobCollectionFileSystemEnumerator<T> : FileSystemEnumerator<T>
{
private readonly GlobCollection _globs;
protected GlobCollectionFileSystemEnumerator(GlobCollection globs, string directory, EnumerationOptions? options = null)
: base(directory, options)
{
_globs = globs;
}
protected override bool ShouldRecurseIntoEntry(ref FileSystemEntry entry)
{
return base.ShouldRecurseIntoEntry(ref entry) && _globs.IsPartialMatch(ref entry);
}
protected override bool ShouldIncludeEntry(ref FileSystemEntry entry)
{
return base.ShouldIncludeEntry(ref entry) && !entry.IsDirectory && _globs.IsMatch(ref entry);
}
private static ReadOnlySpan<char> GetRelativeDirectory(ref FileSystemEntry entry)
{
if (entry.Directory.Length == entry.RootDirectory.Length)
return ReadOnlySpan<char>.Empty;
return entry.Directory[(entry.RootDirectory.Length + 1)..];
}
}
public sealed class GlobCollectionFileSystemEnumerator : GlobCollectionFileSystemEnumerator<string>
{
public GlobCollectionFileSystemEnumerator(GlobCollection globs, string directory, EnumerationOptions? options = null)
: base(globs, directory, options)
{
}
protected override string TransformEntry(ref FileSystemEntry entry)
{
return entry.ToFullPath();
}
}
}
| 30.909091 | 128 | 0.675882 | [
"MIT"
] | DomLatr/Meziantou.Framework | src/Meziantou.Framework.Globbing/GlobCollectionFileSystemEnumerator.cs | 1,702 | C# |
using System.Diagnostics;
using Volte.Commands;
using Volte.Commands.Results;
namespace Volte.Core.Models.EventArgs
{
public sealed class CommandBadRequestEventArgs : CommandEventArgs
{
public BadRequestResult Result { get; }
public ResultCompletionData ResultCompletionData { get; }
public override VolteContext Context { get; }
public string Arguments { get; }
public Stopwatch Stopwatch { get; }
public CommandBadRequestEventArgs(BadRequestResult res, ResultCompletionData data, VolteContext ctx, string args, Stopwatch sw)
{
Result = res;
ResultCompletionData = data;
Context = ctx;
Arguments = args;
Stopwatch = sw;
}
}
}
| 30.64 | 135 | 0.655352 | [
"MIT"
] | Perksey/Volte | src/Core/Models/EventArgs/Commands/CommandBadRequestEventArgs.cs | 768 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Copyright (c) Denis Kuzmin <x-3F@outlook.com> github/3F
// Copyright (c) IeXod contributors https://github.com/3F/IeXod/graphs/contributors
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
namespace net.r_eg.IeXod.Framework
{
/// <summary>
/// Arguments for telemetry events.
/// </summary>
[Serializable]
public sealed class TelemetryEventArgs : BuildEventArgs
{
/// <summary>
/// Gets or sets the name of the event.
/// </summary>
public string EventName { get; set; }
/// <summary>
/// Gets or sets a list of properties associated with the event.
/// </summary>
public IDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
}
}
| 32.642857 | 103 | 0.654267 | [
"MIT"
] | 3F/IeXod | src/Framework/TelemetryEventArgs.cs | 916 | C# |
using System;
using RunescapeNavigator.Core.Enums;
using RunescapeNavigator.Data;
namespace RunescapeNavigator.ConsoleTester
{
class Program
{
static void Main(string[] args)
{
var client = new RS3RestClient();
var p2 = client.GetRegularPlayer("Dreamhack");
Console.WriteLine(p2.GetSkill(Skill.Ranged).Experience);
}
}
} | 24.625 | 68 | 0.64467 | [
"MIT"
] | RunescapeNavigator/RunescapeNavigator | RunescapeNavigator.ConsoleTester/Program.cs | 396 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Toolkit.Uwp.UI.Lottie.WinCompData;
namespace Microsoft.Toolkit.Uwp.UI.Lottie.LottieToWinComp
{
/// <summary>
/// The result of translating a Lottie animation into an equivalent WinCompData form.
/// </summary>
#if PUBLIC
public
#endif
sealed class TranslationResult
{
internal TranslationResult(
Visual? rootVisual,
IEnumerable<TranslationIssue> translationIssues,
uint minimumRequiredUapVersion,
IReadOnlyDictionary<Guid, object> sourceMetadata)
{
RootVisual = rootVisual;
TranslationIssues = translationIssues.ToArray();
MinimumRequiredUapVersion = minimumRequiredUapVersion;
SourceMetadata = sourceMetadata;
}
/// <summary>
/// The <see cref="Visual"/> at the root of the translation, or null if the translation failed.
/// </summary>
public Visual? RootVisual { get; }
/// <summary>
/// Metadata from the source.
/// </summary>
public IReadOnlyDictionary<Guid, object> SourceMetadata { get; }
/// <summary>
/// The list of issues discovered during translation.
/// </summary>
public IReadOnlyList<TranslationIssue> TranslationIssues { get; }
/// <summary>
/// The minimum version of UAP required to instantiate the result of the translation.
/// </summary>
public uint MinimumRequiredUapVersion { get; }
// Returns a TranslationResult with the same contents as this but a different root visual.
internal TranslationResult WithDifferentRoot(Visual rootVisual)
=> new TranslationResult(rootVisual, TranslationIssues, MinimumRequiredUapVersion, SourceMetadata);
}
}
| 35.305085 | 111 | 0.666347 | [
"MIT"
] | CommunityToolkit/Lottie-Windows | source/LottieToWinComp/TranslationResult.cs | 2,085 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.