content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (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.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using NuGet.Common; using NuGet.Services.Metadata.Catalog.Persistence; namespace NuGet.Services.Metadata.Catalog.Icons { public class IconProcessor : IIconProcessor { private const string DefaultCacheControl = "max-age=120"; private const int MaxExternalIconSize = 1024 * 1024; // 1 MB private readonly ITelemetryService _telemetryService; private readonly ILogger<IconProcessor> _logger; public IconProcessor( ITelemetryService telemetryService, ILogger<IconProcessor> logger) { _telemetryService = telemetryService ?? throw new ArgumentNullException(nameof(telemetryService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<Uri> CopyIconFromExternalSourceAsync( Stream iconDataStream, IStorage destinationStorage, string destinationStoragePath, CancellationToken cancellationToken, string packageId, string normalizedPackageVersion) { var destinationUri = destinationStorage.ResolveUri(destinationStoragePath); var iconData = await GetStreamBytesAsync(iconDataStream, MaxExternalIconSize, cancellationToken); if (iconData == null) { return null; } var contentType = DetermineContentType(iconData, onlyGallerySupported: false); if (string.IsNullOrWhiteSpace(contentType)) { _logger.LogInformation("Failed to determine image type."); return null; } _logger.LogInformation("Content type for {PackageId} {PackageVersion} {ContentType}", packageId, normalizedPackageVersion, contentType); var content = new ByteArrayStorageContent(iconData, contentType, DefaultCacheControl); await destinationStorage.SaveAsync(destinationUri, content, cancellationToken); _telemetryService.TrackExternalIconIngestionSuccess(packageId, normalizedPackageVersion); return destinationUri; } public async Task DeleteIconAsync( IStorage destinationStorage, string destinationStoragePath, CancellationToken cancellationToken, string packageId, string normalizedPackageVersion) { _logger.LogInformation("Deleting icon blob {IconPath}", destinationStoragePath); var iconUri = new Uri(destinationStorage.BaseAddress, destinationStoragePath); try { await destinationStorage.DeleteAsync(iconUri, cancellationToken, new DeleteRequestOptionsWithAccessCondition(AccessCondition.GenerateIfExistsCondition())); } catch { _telemetryService.TrackIconDeletionFailure(packageId, normalizedPackageVersion); throw; } _telemetryService.TrackIconDeletionSuccess(packageId, normalizedPackageVersion); } public async Task<Uri> CopyEmbeddedIconFromPackageAsync( Stream packageStream, string iconFilename, IStorage destinationStorage, string destinationStoragePath, CancellationToken cancellationToken, string packageId, string normalizedPackageVersion) { var iconPath = PathUtility.StripLeadingDirectorySeparators(iconFilename); var destinationUri = destinationStorage.ResolveUri(destinationStoragePath); await ExtractAndStoreIconAsync(packageStream, iconPath, destinationStorage, destinationUri, cancellationToken, packageId, normalizedPackageVersion); return destinationUri; } private async Task ExtractAndStoreIconAsync( Stream packageStream, string iconPath, IStorage destinationStorage, Uri destinationUri, CancellationToken cancellationToken, string packageId, string normalizedPackageVersion) { using (var zipArchive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true)) { var iconEntry = zipArchive.Entries.FirstOrDefault(e => e.FullName.Equals(iconPath, StringComparison.InvariantCultureIgnoreCase)); if (iconEntry != null) { using (var iconStream = iconEntry.Open()) { _logger.LogInformation("Extracting icon to the destination storage {DestinationUri}", destinationUri); var iconData = await GetStreamBytesAsync(iconStream, cancellationToken); // files with embedded icons are expected to only contain image types Gallery allows in // (jpeg and png). Others are still going to be saved for correctness sake, but we won't // try to determine their type (they shouldn't have made this far anyway). var contentType = DetermineContentType(iconData, onlyGallerySupported: true); _logger.LogInformation("Content type for {PackageId} {PackageVersion} {ContentType}", packageId, normalizedPackageVersion, contentType); var iconContent = new ByteArrayStorageContent(iconData, contentType, DefaultCacheControl); await destinationStorage.SaveAsync(destinationUri, iconContent, cancellationToken); _telemetryService.TrackIconExtractionSuccess(packageId, normalizedPackageVersion); _logger.LogInformation("Done"); } } else { _telemetryService.TrackIconExtractionFailure(packageId, normalizedPackageVersion); _logger.LogWarning("Zip archive entry {IconPath} does not exist", iconPath); } } } private static async Task<byte[]> GetStreamBytesAsync(Stream sourceStream, CancellationToken cancellationToken) { using (var ms = new MemoryStream()) { await sourceStream.CopyToAsync(ms, 8192, cancellationToken); return ms.ToArray(); } } private async Task<byte[]> GetStreamBytesAsync(Stream sourceStream, int maxBytes, CancellationToken cancellationToken) { using (var ms = new MemoryStream()) { var buffer = new byte[8192]; var totalBytesRead = 0; var bytesRead = 0; do { bytesRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); totalBytesRead += bytesRead; await ms.WriteAsync(buffer, 0, bytesRead, cancellationToken); } while (bytesRead > 0 && totalBytesRead < maxBytes + 1); if (totalBytesRead > maxBytes) { _logger.LogInformation("Source data too long, discarding."); return null; } return ms.ToArray(); } } /// <summary> /// The PNG file header bytes. All PNG files are expected to have those at the beginning of the file. /// </summary> /// <remarks> /// https://www.w3.org/TR/PNG/#5PNG-file-signature /// </remarks> private static readonly byte[] PngHeader = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; /// <summary> /// The JPG file header bytes. /// </summary> /// <remarks> /// Technically, JPEG start with two byte SOI (start of image) segment: FFD8, followed by several other segments or fill bytes. /// All of the segments start with FF, and fill bytes are FF, so we check the first 3 bytes instead of the first two. /// https://www.w3.org/Graphics/JPEG/itu-t81.pdf "B.1.1.2 Markers" /// </remarks> private static readonly byte[] JpegHeader = new byte[] { 0xFF, 0xD8, 0xFF }; /// <summary> /// The GIF87a file header. /// </summary> /// <remarks> /// https://www.w3.org/Graphics/GIF/spec-gif87.txt /// </remarks> private static readonly byte[] Gif87aHeader = new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }; /// <summary> /// The GIF89a file header. /// </summary> /// <remarks> /// https://www.w3.org/Graphics/GIF/spec-gif89a.txt /// </remarks> private static readonly byte[] Gif89aHeader = new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }; /// <summary> /// The .ico file "header". /// </summary> /// <remarks> /// This is the first 4 bytes of the ICONDIR structure expected for .ico files /// https://docs.microsoft.com/en-us/previous-versions/ms997538(v=msdn.10) /// </remarks> private static readonly byte[] IcoHeader = new byte[] { 0x00, 0x00, 0x01, 0x00 }; private static string DetermineContentType(byte[] imageData, bool onlyGallerySupported) { // checks are ordered by format popularity among external icons for existing packages if (ArrayStartsWith(imageData, PngHeader)) { return "image/png"; } if (ArrayStartsWith(imageData, JpegHeader)) { return "image/jpeg"; } if (onlyGallerySupported) { return ""; } if (ArrayStartsWith(imageData, IcoHeader)) { return "image/x-icon"; } if (ArrayStartsWith(imageData, Gif89aHeader) || ArrayStartsWith(imageData, Gif87aHeader)) { return "image/gif"; } if (IsSvgData(imageData)) { return "image/svg+xml"; } return ""; } private static bool IsSvgData(byte[] imageData) { bool isTextFile = imageData.All(b => b >= 32 || b == '\n' || b == '\f' || b == '\r' || b == '\t'); if (!isTextFile) { return false; } var stringContent = Encoding.UTF8.GetString(imageData); return !stringContent.Contains("<html") && stringContent.Contains("<svg"); } private static bool ArrayStartsWith(byte[] array, byte[] expectedBytes) { if (array.Length < expectedBytes.Length) { return false; } for (int index = 0; index < expectedBytes.Length; ++index) { if (array[index] != expectedBytes[index]) { return false; } } return true; } } }
40.712766
171
0.588363
[ "Apache-2.0" ]
CyberAndrii/NuGet.Jobs
src/Catalog/Icons/IconProcessor.cs
11,483
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; using Pulumi.Utilities; namespace Pulumi.Azure.NotificationHub { public static class GetHub { /// <summary> /// Use this data source to access information about an existing Notification Hub within a Notification Hub Namespace. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = Output.Create(Azure.NotificationHub.GetHub.InvokeAsync(new Azure.NotificationHub.GetHubArgs /// { /// Name = "notification-hub", /// NamespaceName = "namespace-name", /// ResourceGroupName = "resource-group-name", /// })); /// this.Id = example.Apply(example =&gt; example.Id); /// } /// /// [Output("id")] /// public Output&lt;string&gt; Id { get; set; } /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Task<GetHubResult> InvokeAsync(GetHubArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetHubResult>("azure:notificationhub/getHub:getHub", args ?? new GetHubArgs(), options.WithVersion()); /// <summary> /// Use this data source to access information about an existing Notification Hub within a Notification Hub Namespace. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = Output.Create(Azure.NotificationHub.GetHub.InvokeAsync(new Azure.NotificationHub.GetHubArgs /// { /// Name = "notification-hub", /// NamespaceName = "namespace-name", /// ResourceGroupName = "resource-group-name", /// })); /// this.Id = example.Apply(example =&gt; example.Id); /// } /// /// [Output("id")] /// public Output&lt;string&gt; Id { get; set; } /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Output<GetHubResult> Invoke(GetHubInvokeArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.Invoke<GetHubResult>("azure:notificationhub/getHub:getHub", args ?? new GetHubInvokeArgs(), options.WithVersion()); } public sealed class GetHubArgs : Pulumi.InvokeArgs { /// <summary> /// Specifies the Name of the Notification Hub. /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; /// <summary> /// Specifies the Name of the Notification Hub Namespace which contains the Notification Hub. /// </summary> [Input("namespaceName", required: true)] public string NamespaceName { get; set; } = null!; /// <summary> /// Specifies the Name of the Resource Group within which the Notification Hub exists. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetHubArgs() { } } public sealed class GetHubInvokeArgs : Pulumi.InvokeArgs { /// <summary> /// Specifies the Name of the Notification Hub. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Specifies the Name of the Notification Hub Namespace which contains the Notification Hub. /// </summary> [Input("namespaceName", required: true)] public Input<string> NamespaceName { get; set; } = null!; /// <summary> /// Specifies the Name of the Resource Group within which the Notification Hub exists. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public GetHubInvokeArgs() { } } [OutputType] public sealed class GetHubResult { /// <summary> /// A `apns_credential` block as defined below. /// </summary> public readonly ImmutableArray<Outputs.GetHubApnsCredentialResult> ApnsCredentials; /// <summary> /// A `gcm_credential` block as defined below. /// </summary> public readonly ImmutableArray<Outputs.GetHubGcmCredentialResult> GcmCredentials; /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; /// <summary> /// The Azure Region in which this Notification Hub exists. /// </summary> public readonly string Location; public readonly string Name; public readonly string NamespaceName; public readonly string ResourceGroupName; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public readonly ImmutableDictionary<string, string> Tags; [OutputConstructor] private GetHubResult( ImmutableArray<Outputs.GetHubApnsCredentialResult> apnsCredentials, ImmutableArray<Outputs.GetHubGcmCredentialResult> gcmCredentials, string id, string location, string name, string namespaceName, string resourceGroupName, ImmutableDictionary<string, string> tags) { ApnsCredentials = apnsCredentials; GcmCredentials = gcmCredentials; Id = id; Location = location; Name = name; NamespaceName = namespaceName; ResourceGroupName = resourceGroupName; Tags = tags; } } }
34.625
157
0.551444
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/NotificationHub/GetHub.cs
6,648
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("CodeAndMagic")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CodeAndMagic")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("e2b62de6-2339-4f3a-a0f9-fa312b193bc6")] // 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.756757
84
0.745168
[ "MIT" ]
YLiohenki/CodeAndMagic
CodeAndMagic/Properties/AssemblyInfo.cs
1,400
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using DynamicReconfigure; using Messages.dynamic_reconfigure; namespace DynamicReconfigureSharp { [DataContract] public class EnumDescription { public string enum_description; public EnumValue[] Enum; } [DataContract] public class EnumValue { public int srcline; public string description; public string srcfile; public string cconsttype; public string value; public string ctype; public string type; public string name; } public static class EnumParser { public static Dictionary<string, string> Parse(string s) { Dictionary<string, string> fields = new Dictionary<string, string>(); Stack<char> stack = new Stack<char>(); string currentname = ""; string currentvalue = null; bool insidearray = false; int index = 0; for(int i=0;i<s.Length;i++) { char c = s[i]; if (insidearray) { if (c == ':') continue; if (c == ']') { stack.Pop(); insidearray = false; fields[currentname.Trim()] = currentvalue.Trim(); currentname = ""; currentvalue = null; continue; } currentvalue += c; continue; } if (c == '[') { stack.Push(c); insidearray = true; continue; } if (c == ':') continue; if ((c == "'"[0] || c == '"' || c == '}') && stack.Count > 0 && stack.Peek() == c) { //close stack.Pop(); if (currentvalue != null) { fields[currentname.Trim()] = currentvalue.Trim(); currentname = ""; currentvalue = null; } else { currentvalue = ""; } continue; } else if (c == "'"[0] || c == '"' || c == '{') { //open stack.Push(c); continue; } if (c == ',') continue; if (currentvalue == null) { currentname = currentname + c; } else { currentvalue = currentvalue + c; } } return fields; } public static Dictionary<string, string> SubParse(string s) { Dictionary<string, string> fields = new Dictionary<string, string>(); string[] namevalue = s.Trim("'"[0], '"', '{', '}').Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < namevalue.Length; i++) { string[] spaced = namevalue[i].Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries); string[] pair = new string[2]; pair[1] = ""; pair[0] = spaced[0].Trim("'"[0], '{'); for (int j = 1; j < spaced.Length; j++) pair[1] += " " + spaced[j].Trim("'"[0], '{'); pair[1] = pair[1].Trim(); fields.Add(pair[0], pair[1]); } return fields; } } internal enum DROPDOWN_TYPE { STR, INT } /// <summary> /// Interaction logic for DynamicReconfigureStringDropdown.xaml /// </summary> public partial class DynamicReconfigureStringDropdown : UserControl, IDynamicReconfigureLayout { private static readonly Dictionary<string, DROPDOWN_TYPE> types = new Dictionary<string, DROPDOWN_TYPE>() { { "str", DROPDOWN_TYPE.STR }, { "int", DROPDOWN_TYPE.INT } }; private DynamicReconfigureInterface dynamic; private string name; private object def, max, min; private string edit_method; private bool ignore = true; private EnumDescription enumdescription; public DynamicReconfigureStringDropdown(DynamicReconfigureInterface dynamic, ParamDescription pd, object def, object max, object min, string edit_method) { this.def = def; this.max = max; this.min = min; this.edit_method = edit_method.Replace("'enum'","'Enum'"); Dictionary<string, string> parsed = EnumParser.Parse(this.edit_method); string[] vals = parsed["Enum"].Split(new []{'}'}, StringSplitOptions.RemoveEmptyEntries); List<Dictionary<string, string>> descs = vals.Select(s => EnumParser.SubParse(s+"}")).ToList(); descs = descs.Except(descs.Where((d) => d.Count == 0)).ToList(); enumdescription = new EnumDescription(); enumdescription.Enum = new EnumValue[descs.Count]; enumdescription.enum_description = parsed["enum_description"]; Type tdesc = typeof (EnumValue); for (int i = 0; i < descs.Count; i++) { Dictionary<string, string> desc = descs[i]; EnumValue newval = new EnumValue(); foreach (string s in desc.Keys) { FieldInfo fi = tdesc.GetField(s); if (fi.FieldType == typeof (int)) fi.SetValue(newval, int.Parse(desc[s])); else fi.SetValue(newval, desc[s]); } enumdescription.Enum[i] = newval; } name = pd.name.data; this.dynamic = dynamic; InitializeComponent(); for (int i = 0; i < enumdescription.Enum.Length; i++) { if (!types.ContainsKey(enumdescription.Enum[i].type)) { throw new Exception("HANDLE " + enumdescription.Enum[i].type); } switch (types[enumdescription.Enum[i].type]) { case DROPDOWN_TYPE.INT: { ComboBoxItem cbi = new ComboBoxItem() {Tag = int.Parse(enumdescription.Enum[i].value), Content = enumdescription.Enum[i].name, ToolTip = new ToolTip() {Content = enumdescription.Enum[i].description+" ("+enumdescription.Enum[i].value+")"}}; @enum.Items.Add(cbi); if (i == 0) { @enum.SelectedValue = this.def; dynamic.Subscribe(name, (Action<int>) changed); } else if (enumdescription.Enum[i].type != enumdescription.Enum[i - 1].type) throw new Exception("NO CHANGSIES MINDSIES"); } break; case DROPDOWN_TYPE.STR: { ComboBoxItem cbi = new ComboBoxItem() {Tag = enumdescription.Enum[i].value, Content = enumdescription.Enum[i].name, ToolTip = new ToolTip() {Content = enumdescription.Enum[i].description}}; @enum.Items.Add(cbi); if (i == 0) { @enum.SelectedValue = this.def; dynamic.Subscribe(name, (Action<string>) changed); } else if (enumdescription.Enum[i].type != enumdescription.Enum[i - 1].type) throw new Exception("NO CHANGSIES MINDSIES"); } break; } } description.Content = name + ":"; JustTheTip.Content = pd.description.data; ignore = false; } private void changed(string newstate) { ignore = true; Dispatcher.BeginInvoke(new Action(() => { @enum.SelectedValue = newstate; if (stringchanged != null) stringchanged(newstate); ignore = false; })); } private void changed(int newstate) { ignore = true; Dispatcher.BeginInvoke(new Action(() => { @enum.SelectedValue = newstate; if (intchanged != null) intchanged(newstate); ignore = false; })); } private void Enum_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (ignore) return; switch (types[enumdescription.Enum[0].type]) { case DROPDOWN_TYPE.INT: dynamic.Set(name, (int)(@enum.Items[@enum.SelectedIndex] as ComboBoxItem).Tag); break; case DROPDOWN_TYPE.STR: dynamic.Set(name, (string)(@enum.Items[@enum.SelectedIndex] as ComboBoxItem).Tag); break; } } private event Action<int> intchanged; private event Action<string> stringchanged; internal Action<int> Instrument(Action<int> cb) { intchanged += cb; return (d) => { foreach (ComboBoxItem i in @enum.Items) { if ((int)i.Tag == d) { ignore = false; i.IsSelected = true; break; } } }; } internal Action<string> Instrument(Action<string> cb) { stringchanged += cb; return (d) => { foreach (ComboBoxItem i in @enum.Items) { if ((string)i.Tag == d) { ignore = false; i.IsSelected = true; break; } } }; } #region IDynamicReconfigureLayout Members public double getDescriptionWidth() { return (Content as Grid).ColumnDefinitions[0].ActualWidth; } public void setDescriptionWidth(double w) { (Content as Grid).ColumnDefinitions[0].Width = new GridLength(w); } #endregion } }
35.302181
263
0.464613
[ "BSD-2-Clause" ]
mikefoxnobel/ROS.NET
DynamicReconfigureSharp/DynamicReconfigureStringDropdown.xaml.cs
11,334
C#
using DSharpPlus.EventArgs; using Scruffy.Data.Entity; using Scruffy.Data.Entity.Repositories.Guild; using Scruffy.Services.Core.Discord; using Scruffy.Services.Core.Localization; namespace Scruffy.Services.Guild.DialogElements; /// <summary> /// Deletion of a guild special rank /// </summary> public class GuildRankDeletionDialogElement : DialogReactionElementBase<bool> { #region Fields /// <summary> /// Reactions /// </summary> private List<ReactionData<bool>> _reactions; #endregion // Fields #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="localizationService">Localization service</param> public GuildRankDeletionDialogElement(LocalizationService localizationService) : base(localizationService) { } #endregion // Constructor #region DialogReactionElementBase<bool> /// <summary> /// Editing the embedded message /// </summary> /// <returns>Message</returns> public override string GetMessage() => LocalizationGroup.GetText("DeletePrompt", "Are you sure you want to delete the rank?"); /// <summary> /// Returns the reactions which should be added to the message /// </summary> /// <returns>Reactions</returns> public override IReadOnlyList<ReactionData<bool>> GetReactions() { return _reactions ??= new List<ReactionData<bool>> { new () { Emoji = DiscordEmojiService.GetCheckEmoji(CommandContext.Client), Func = () => { using (var dbFactory = RepositoryFactory.CreateInstance()) { var rankId = DialogContext.GetValue<int>("RankId"); if (dbFactory.GetRepository<GuildRankRepository>() .Remove(obj => obj.Id == rankId)) { var order = 0; foreach (var currentRankId in dbFactory.GetRepository<GuildRankRepository>() .GetQuery() .OrderBy(obj => obj.Order) .Select(obj => obj.Id)) { dbFactory.GetRepository<GuildRankRepository>() .Refresh(obj => obj.Id == currentRankId, obj => obj.Order = order); order++; } } } return Task.FromResult(true); } }, new () { Emoji = DiscordEmojiService.GetCrossEmoji(CommandContext.Client), Func = () => Task.FromResult(true) } }; } /// <summary> /// Default case if none of the given reactions is used /// </summary> /// <param name="reaction">Reaction</param> /// <returns>Result</returns> protected override bool DefaultFunc(MessageReactionAddEventArgs reaction) => false; #endregion // DialogReactionElementBase<bool> }
42.535354
133
0.407979
[ "MIT" ]
thoenissen/Scruffy
Scruffy.Services/Guild/DialogElements/GuildRankDeletionDialogElement.cs
4,213
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/IPExport.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='IP_ADAPTER_ORDER_MAP.xml' path='doc/member[@name="IP_ADAPTER_ORDER_MAP"]/*' /> public unsafe partial struct IP_ADAPTER_ORDER_MAP { /// <include file='IP_ADAPTER_ORDER_MAP.xml' path='doc/member[@name="IP_ADAPTER_ORDER_MAP.NumAdapters"]/*' /> [NativeTypeName("ULONG")] public uint NumAdapters; /// <include file='IP_ADAPTER_ORDER_MAP.xml' path='doc/member[@name="IP_ADAPTER_ORDER_MAP.AdapterOrder"]/*' /> [NativeTypeName("ULONG [1]")] public fixed uint AdapterOrder[1]; }
44.052632
145
0.740741
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/IPExport/IP_ADAPTER_ORDER_MAP.cs
839
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.CompilerServices; using Microsoft.EntityFrameworkCore; using guid = System.UInt64; namespace Botwinder.entities { [Table("server_stats")] public class ServerStats { [Key] [Required] [Column("serverid")] [DatabaseGenerated(DatabaseGeneratedOption.None)] public guid ServerId{ get; set; } = 0; [Column("name", TypeName = "varchar(255)")] public string ServerName{ get; set; } = ""; [Column("shardid")] public Int64 ShardId{ get; set; } = 0; [Column("ownerid")] public guid OwnerId{ get; set; } = 0; [Column("owner_name", TypeName = "varchar(255)")] public string OwnerName{ get; set; } = ""; [Column("joined_count")] public Int64 JoinedCount{ get; set; } = 0; [Column("joined_first")] public DateTime JoinedTimeFirst{ get; set; } = DateTime.MaxValue; [Column("joined_last")] public DateTime JoinedTime{ get; set; } = DateTime.MaxValue; [Column("user_count")] public Int64 UserCount{ get; set; } = 0; [Column("vip")] public bool IsDiscordPartner{ get; set; } = false; [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() { return $"**Server ID: `{this.ServerId}`**\n" + $"Server Name: `{this.ServerName}`\n" + $"Owner: <@{this.OwnerId}>\n" + $"Owner ID: `{this.OwnerId}`\n" + $"Owner name: `{this.OwnerName}`\n" + $"Discord Partner: `{this.IsDiscordPartner}`\n" + $"Members count: `{this.UserCount}`\n" + $"Shard ID: `{this.ShardId}`\n" + $"First Joined at: `{Utils.GetTimestamp(this.JoinedTimeFirst)}`\n" + $"Last Joined at: `{Utils.GetTimestamp(this.JoinedTime)}`\n" + $"Joined count: `{this.JoinedCount}`\n"; } } }
28.953125
78
0.641662
[ "MIT" ]
Linfur/Botwinder.core
Entities/ServerStats.cs
1,855
C#
using Aiursoft.Developer.Data; using Aiursoft.Pylon; using Aiursoft.Pylon.Models.Developer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Aiursoft.Developer { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DeveloperDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection"))); services.AddIdentity<DeveloperUser, IdentityRole>() .AddEntityFrameworkStores<DeveloperDbContext>() .AddDefaultTokenProviders(); services.AddAiurMvc(); services.AddAiurDependencies<DeveloperUser>("Developer"); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseAiurUserHandler(env.IsDevelopment()); app.UseAiursoftDefault(); } } }
30.953488
95
0.695718
[ "MIT" ]
zhanghaiboshiwo/Nexus
Developer/Startup.cs
1,333
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace CastIron.Sql.Mapping.Compilers { /// <summary> /// Maps to any dictionary type which inherits string-keyed IDictionary /// </summary> public class ConcreteDictionaryCompiler : ICompiler { private readonly ICompiler _valueCompiler; public ConcreteDictionaryCompiler(ICompiler valueCompiler) { _valueCompiler = valueCompiler; } public ConstructedValueExpression Compile(MapTypeContext context) { if (!IsSupportedType(context.TargetType)) return ConstructedValueExpression.Nothing; var idictType = GetIDictionaryType(context); var elementType = idictType.GetGenericArguments()[1]; var constructor = GetDictionaryConstructor(context.TargetType); var addMethod = GetIDictionaryAddMethod(context.TargetType, idictType); var dictVar = DictionaryExpressionFactory.GetMaybeInstantiateDictionaryExpression(context, constructor); var addStmts = DictionaryExpressionFactory.AddDictionaryPopulateStatements(_valueCompiler, context, elementType, dictVar.FinalValue, addMethod); return new ConstructedValueExpression( dictVar.Expressions.Concat(addStmts.Expressions), Expression.Convert(dictVar.FinalValue, context.TargetType), dictVar.Variables.Concat(addStmts.Variables)); } // It is Dictionary<string,X> or is concrete and inherits from IDictionary<string,X> private static bool IsSupportedType(Type t) { if (t.IsInterface || t.IsAbstract) return false; if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>) && t.GenericTypeArguments[0] == typeof(string)) return true; var dictType = t.GetInterfaces() .Where(i => i.IsGenericType) .FirstOrDefault(i => i.GetGenericTypeDefinition() == typeof(IDictionary<,>) && i.GenericTypeArguments[0] == typeof(string)); return dictType != null; } private static MethodInfo GetIDictionaryAddMethod(Type targetType, Type idictType) { return idictType.GetMethod(nameof(IDictionary<string, object>.Add)) ?? throw MapCompilerException.InvalidDictionaryTargetType(targetType); } private static ConstructorInfo GetDictionaryConstructor(Type targetType) { return targetType.GetConstructor(Type.EmptyTypes) ?? throw MapCompilerException.InvalidDictionaryTargetType(targetType); } private static Type GetIDictionaryType(MapTypeContext context) { return context.TargetType.GetInterfaces() .Where(i => i.IsGenericType) .FirstOrDefault(i => i.GetGenericTypeDefinition() == typeof(IDictionary<,>) && i.GenericTypeArguments[0] == typeof(string)) ?? throw MapCompilerException.InvalidDictionaryTargetType(context.TargetType); } } }
43.287671
156
0.671519
[ "Apache-2.0" ]
Whiteknight/CastIron
Src/CastIron.Sql/Mapping/Compilers/ConcreteDictionaryCompiler.cs
3,162
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime: 4.0.30319.42000 // // Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si // el código se vuelve a generar. // </auto-generated> //------------------------------------------------------------------------------ namespace TypeToChat.Properties { /// <summary> /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [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> /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TypeToChat.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.361111
176
0.616311
[ "MIT" ]
Mirkobien/TypeToChat
TypeToChat/Properties/Resources.Designer.cs
2,919
C#
using System.Web.Mvc; namespace Ext.Net.MVC.Examples.Areas.Form_Groups { public class Form_GroupsAreaRegistration : AreaRegistration { public override string AreaName { get { return "Form_Groups"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Form_Groups_default", "Form_Groups/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
24.08
74
0.531561
[ "Apache-2.0" ]
yataya1987/EXT.Net-Theme-Hard-Coded
src/Areas/Form_Groups/Form_GroupsAreaRegistration.cs
604
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("Romontinka.Server.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Romontinka.Server.Core")] [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("a32885cb-0e1d-4032-8fca-13f46f6aba4c")] // 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.297297
84
0.745942
[ "MIT" ]
alexs0ff/remboard
Server/Romontinka.Server.Core/Properties/AssemblyInfo.cs
1,420
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 codebuild-2016-10-06.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.CodeBuild.Model { /// <summary> /// Information about an environment variable for a build project or a build. /// </summary> public partial class EnvironmentVariable { private string _name; private EnvironmentVariableType _type; private string _value; /// <summary> /// Gets and sets the property Name. /// <para> /// The name or key of the environment variable. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of environment variable. Valid values include: /// </para> /// <ul> <li> /// <para> /// <code>PARAMETER_STORE</code>: An environment variable stored in Amazon EC2 Systems /// Manager Parameter Store. To learn how to specify a parameter store environment variable, /// see <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#parameter-store-build-spec"> /// parameter store reference-key in the buildspec file</a>. /// </para> /// </li> <li> /// <para> /// <code>PLAINTEXT</code>: An environment variable in plain text format. This is the /// default value. /// </para> /// </li> <li> /// <para> /// <code>SECRETS_MANAGER</code>: An environment variable stored in AWS Secrets Manager. /// To learn how to specify a secrets manager environment variable, see <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#secrets-manager-build-spec"> /// secrets manager reference-key in the buildspec file</a>. /// </para> /// </li> </ul> /// </summary> public EnvironmentVariableType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// The value of the environment variable. /// </para> /// <important> /// <para> /// We strongly discourage the use of <code>PLAINTEXT</code> environment variables to /// store sensitive values, especially AWS secret key IDs and secret access keys. <code>PLAINTEXT</code> /// environment variables can be displayed in plain text using the AWS CodeBuild console /// and the AWS Command Line Interface (AWS CLI). For sensitive values, we recommend you /// use an environment variable of type <code>PARAMETER_STORE</code> or <code>SECRETS_MANAGER</code>. /// /// </para> /// </important> /// </summary> [AWSProperty(Required=true)] public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
34.920635
192
0.594545
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/EnvironmentVariable.cs
4,400
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.CloudFormation.Model { /// <summary> /// <para>Contains detailed information about the specified stack resource.</para> /// </summary> public class StackResourceDetail { private string stackName; private string stackId; private string logicalResourceId; private string physicalResourceId; private string resourceType; private DateTime? lastUpdatedTimestamp; private ResourceStatus resourceStatus; private string resourceStatusReason; private string description; private string metadata; /// <summary> /// The name associated with the stack. /// /// </summary> public string StackName { get { return this.stackName; } set { this.stackName = value; } } // Check to see if StackName property is set internal bool IsSetStackName() { return this.stackName != null; } /// <summary> /// Unique identifier of the stack. /// /// </summary> public string StackId { get { return this.stackId; } set { this.stackId = value; } } // Check to see if StackId property is set internal bool IsSetStackId() { return this.stackId != null; } /// <summary> /// The logical name of the resource specified in the template. /// /// </summary> public string LogicalResourceId { get { return this.logicalResourceId; } set { this.logicalResourceId = value; } } // Check to see if LogicalResourceId property is set internal bool IsSetLogicalResourceId() { return this.logicalResourceId != null; } /// <summary> /// The name or unique identifier that corresponds to a physical instance ID of a resource supported by AWS CloudFormation. /// /// </summary> public string PhysicalResourceId { get { return this.physicalResourceId; } set { this.physicalResourceId = value; } } // Check to see if PhysicalResourceId property is set internal bool IsSetPhysicalResourceId() { return this.physicalResourceId != null; } /// <summary> /// Type of the resource. (For more information, go to the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide">AWS /// CloudFormation User Guide</a>.) /// /// </summary> public string ResourceType { get { return this.resourceType; } set { this.resourceType = value; } } // Check to see if ResourceType property is set internal bool IsSetResourceType() { return this.resourceType != null; } /// <summary> /// Time the status was updated. /// /// </summary> public DateTime LastUpdatedTimestamp { get { return this.lastUpdatedTimestamp ?? default(DateTime); } set { this.lastUpdatedTimestamp = value; } } // Check to see if LastUpdatedTimestamp property is set internal bool IsSetLastUpdatedTimestamp() { return this.lastUpdatedTimestamp.HasValue; } /// <summary> /// Current status of the resource. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>CREATE_IN_PROGRESS, CREATE_FAILED, CREATE_COMPLETE, DELETE_IN_PROGRESS, DELETE_FAILED, DELETE_COMPLETE, UPDATE_IN_PROGRESS, UPDATE_FAILED, UPDATE_COMPLETE</description> /// </item> /// </list> /// </para> /// </summary> public ResourceStatus ResourceStatus { get { return this.resourceStatus; } set { this.resourceStatus = value; } } // Check to see if ResourceStatus property is set internal bool IsSetResourceStatus() { return this.resourceStatus != null; } /// <summary> /// Success/failure message associated with the resource. /// /// </summary> public string ResourceStatusReason { get { return this.resourceStatusReason; } set { this.resourceStatusReason = value; } } // Check to see if ResourceStatusReason property is set internal bool IsSetResourceStatusReason() { return this.resourceStatusReason != null; } /// <summary> /// User defined description associated with the resource. /// /// </summary> public string Description { get { return this.description; } set { this.description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// The JSON format content of the <c>Metadata</c> attribute declared for the resource. For more information, see <a /// href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html">Metadata Attribute</a> in the AWS /// CloudFormation User Guide. /// /// </summary> public string Metadata { get { return this.metadata; } set { this.metadata = value; } } // Check to see if Metadata property is set internal bool IsSetMetadata() { return this.metadata != null; } } }
30.925234
201
0.571018
[ "Apache-2.0" ]
zz0733/aws-sdk-net
AWSSDK_DotNet35/Amazon.CloudFormation/Model/StackResourceDetail.cs
6,618
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if SQLSERVER namespace System.Data.Entity.SqlServer.Utilities #elif EF_FUNCTIONALS namespace System.Data.Entity.Functionals.Utilities #else namespace System.Data.Entity.Utilities #endif { using System.Collections.Generic; using System.Data.Entity.Core; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects.DataClasses; using System.Data.Entity.Resources; using System.Data.Entity.Spatial; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; internal static class TypeExtensions { private static readonly Dictionary<Type, PrimitiveType> _primitiveTypesMap = new Dictionary<Type, PrimitiveType>(); [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static TypeExtensions() { foreach (var primitiveType in PrimitiveType.GetEdmPrimitiveTypes()) { if (!_primitiveTypesMap.ContainsKey(primitiveType.ClrEquivalentType)) { _primitiveTypesMap.Add(primitiveType.ClrEquivalentType, primitiveType); } } } public static bool IsCollection(this Type type) { DebugCheck.NotNull(type); return type.IsCollection(out type); } public static bool IsCollection(this Type type, out Type elementType) { DebugCheck.NotNull(type); Debug.Assert(!type.IsGenericTypeDefinition()); elementType = TryGetElementType(type, typeof(ICollection<>)); if (elementType == null || type.IsArray) { elementType = type; return false; } return true; } public static IEnumerable<PropertyInfo> GetNonIndexerProperties(this Type type) { DebugCheck.NotNull(type); return type.GetRuntimeProperties().Where( p => p.IsPublic() && !p.GetIndexParameters().Any()); } // <summary> // Determine if the given type type implements the given generic interface or derives from the given generic type, // and if so return the element type of the collection. If the type implements the generic interface several times // <c>null</c> will be returned. // </summary> // <param name="type"> The type to examine. </param> // <param name="interfaceOrBaseType"> The generic type to be queried for. </param> // <returns> // <c>null</c> if <paramref name="interfaceOrBaseType"/> isn't implemented or implemented multiple times, // otherwise the generic argument. // </returns> public static Type TryGetElementType(this Type type, Type interfaceOrBaseType) { DebugCheck.NotNull(type); DebugCheck.NotNull(interfaceOrBaseType); Debug.Assert(interfaceOrBaseType.GetGenericArguments().Count() == 1); if (!type.IsGenericTypeDefinition()) { var types = GetGenericTypeImplementations(type, interfaceOrBaseType).ToList(); return types.Count == 1 ? types[0].GetGenericArguments().FirstOrDefault() : null; } return null; } // <summary> // Determine if the given type type implements the given generic interface or derives from the given generic type, // and if so return the concrete types implemented. // </summary> // <param name="type"> The type to examine. </param> // <param name="interfaceOrBaseType"> The generic type to be queried for. </param> // <returns> // The generic types constructed from <paramref name="interfaceOrBaseType"/> and implemented by <paramref name="type"/>. // </returns> public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType) { DebugCheck.NotNull(type); DebugCheck.NotNull(interfaceOrBaseType); if (!type.IsGenericTypeDefinition()) { return (interfaceOrBaseType.IsInterface() ? type.GetInterfaces() : type.GetBaseTypes()) .Union(new[] { type }) .Where( t => t.IsGenericType() && t.GetGenericTypeDefinition() == interfaceOrBaseType); } return Enumerable.Empty<Type>(); } public static IEnumerable<Type> GetBaseTypes(this Type type) { DebugCheck.NotNull(type); type = type.BaseType(); while (type != null) { yield return type; type = type.BaseType(); } } public static Type GetTargetType(this Type type) { DebugCheck.NotNull(type); Type elementType; if (!type.IsCollection(out elementType)) { elementType = type; } return elementType; } public static bool TryUnwrapNullableType(this Type type, out Type underlyingType) { DebugCheck.NotNull(type); Debug.Assert(!type.IsGenericTypeDefinition()); underlyingType = Nullable.GetUnderlyingType(type) ?? type; return underlyingType != type; } // <summary> // Returns true if a variable of this type can be assigned a null value // </summary> // <returns> True if a reference type or a nullable value type, false otherwise </returns> public static bool IsNullable(this Type type) { DebugCheck.NotNull(type); return !type.IsValueType() || Nullable.GetUnderlyingType(type) != null; } public static bool IsValidStructuralType(this Type type) { DebugCheck.NotNull(type); return !(type.IsGenericType() || type.IsValueType() || type.IsPrimitive() || type.IsInterface() || type.IsArray || type == typeof(string) || type == typeof(DbGeography) || type == typeof(DbGeometry)) && type.IsValidStructuralPropertyType(); } public static bool IsValidStructuralPropertyType(this Type type) { DebugCheck.NotNull(type); return !(type.IsGenericTypeDefinition() || type.IsPointer || type == typeof(object) || typeof(ComplexObject).IsAssignableFrom(type) || typeof(EntityObject).IsAssignableFrom(type) || typeof(StructuralObject).IsAssignableFrom(type) || typeof(EntityKey).IsAssignableFrom(type) || typeof(EntityReference).IsAssignableFrom(type)); } public static bool IsPrimitiveType(this Type type, out PrimitiveType primitiveType) { return _primitiveTypesMap.TryGetValue(type, out primitiveType); } #if !SQLSERVER && !EF_FUNCTIONALS public static T CreateInstance<T>( this Type type, Func<string, string, string> typeMessageFactory, Func<string, Exception> exceptionFactory = null) { DebugCheck.NotNull(type); DebugCheck.NotNull(typeMessageFactory); exceptionFactory = exceptionFactory ?? (s => new InvalidOperationException(s)); if (!typeof(T).IsAssignableFrom(type)) { throw exceptionFactory(typeMessageFactory(type.ToString(), typeof(T).ToString())); } return CreateInstance<T>(type, exceptionFactory); } public static T CreateInstance<T>(this Type type, Func<string, Exception> exceptionFactory = null) { DebugCheck.NotNull(type); Debug.Assert(typeof(T).IsAssignableFrom(type)); exceptionFactory = exceptionFactory ?? (s => new InvalidOperationException(s)); if (type.GetDeclaredConstructor() == null) { throw exceptionFactory(Strings.CreateInstance_NoParameterlessConstructor(type)); } if (type.IsAbstract()) { throw exceptionFactory(Strings.CreateInstance_AbstractType(type)); } if (type.IsGenericType()) { throw exceptionFactory(Strings.CreateInstance_GenericType(type)); } return (T)Activator.CreateInstance(type, nonPublic: true); } #endif public static bool IsValidEdmScalarType(this Type type) { DebugCheck.NotNull(type); type.TryUnwrapNullableType(out type); PrimitiveType _; return type.IsPrimitiveType(out _) || type.IsEnum(); } public static string NestingNamespace(this Type type) { DebugCheck.NotNull(type); if (!type.IsNested) { return type.Namespace; } var fullName = type.FullName; return fullName.Substring(0, fullName.Length - type.Name.Length - 1).Replace('+', '.'); } public static string FullNameWithNesting(this Type type) { DebugCheck.NotNull(type); if (!type.IsNested) { return type.FullName; } return type.FullName.Replace('+', '.'); } public static bool OverridesEqualsOrGetHashCode(this Type type) { DebugCheck.NotNull(type); while (type != typeof(object)) { if (type.GetDeclaredMethods() .Any( m => (m.Name == "Equals" || m.Name == "GetHashCode") && m.DeclaringType != typeof(object) && m.GetBaseDefinition().DeclaringType == typeof(object))) { return true; } type = type.BaseType(); } return false; } public static bool IsPublic(this Type type) { #if NET40 return type.IsPublic || (type.IsNestedPublic && type.DeclaringType.IsPublic()); #else var typeInfo = type.GetTypeInfo(); return typeInfo.IsPublic || (typeInfo.IsNestedPublic && type.DeclaringType.IsPublic()); #endif } public static bool IsNotPublic(this Type type) { return !type.IsPublic(); } public static MethodInfo GetOnlyDeclaredMethod(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); return type.GetDeclaredMethods(name).SingleOrDefault(); } public static MethodInfo GetDeclaredMethod(this Type type, string name, params Type[] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); DebugCheck.NotNull(parameterTypes); return type.GetDeclaredMethods(name) .SingleOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static MethodInfo GetPublicInstanceMethod(this Type type, string name, params Type[] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); DebugCheck.NotNull(parameterTypes); return type.GetRuntimeMethod(name, m => m.IsPublic && !m.IsStatic, parameterTypes); } public static MethodInfo GetRuntimeMethod( this Type type, string name, Func<MethodInfo, bool> predicate, params Type[][] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); DebugCheck.NotNull(predicate); DebugCheck.NotNull(parameterTypes); return parameterTypes .Select(t => type.GetRuntimeMethod(name, predicate, t)) .FirstOrDefault(m => m != null); } private static MethodInfo GetRuntimeMethod( this Type type, string name, Func<MethodInfo, bool> predicate, Type[] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); DebugCheck.NotNull(predicate); DebugCheck.NotNull(parameterTypes); var methods = type.GetRuntimeMethods().Where( m => name == m.Name && predicate(m) && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)).ToArray(); if (methods.Length == 1) { return methods[0]; } return methods.SingleOrDefault( m => !methods.Any(m2 => m2.DeclaringType.IsSubclassOf(m.DeclaringType))); } #if NET40 public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetMethods(bindingFlags); } #endif public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type) { DebugCheck.NotNull(type); #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetMethods(bindingFlags); #else return type.GetTypeInfo().DeclaredMethods; #endif } public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetMember(name, MemberTypes.Method, bindingFlags).OfType<MethodInfo>(); #else return type.GetTypeInfo().GetDeclaredMethods(name); #endif } public static PropertyInfo GetDeclaredProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetProperty(name, bindingFlags); #else return type.GetTypeInfo().GetDeclaredProperty(name); #endif } public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) { DebugCheck.NotNull(type); #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetProperties(bindingFlags); #else return type.GetTypeInfo().DeclaredProperties; #endif } public static IEnumerable<PropertyInfo> GetInstanceProperties(this Type type) { DebugCheck.NotNull(type); return type.GetRuntimeProperties().Where(p => !p.IsStatic()); } public static IEnumerable<PropertyInfo> GetNonHiddenProperties(this Type type) { DebugCheck.NotNull(type); return from property in type.GetRuntimeProperties() group property by property.Name into propertyGroup select MostDerived(propertyGroup); } private static PropertyInfo MostDerived(IEnumerable<PropertyInfo> properties) { PropertyInfo mostDerivedProperty = null; foreach (var property in properties) { if (mostDerivedProperty == null || (mostDerivedProperty.DeclaringType != null && mostDerivedProperty.DeclaringType.IsAssignableFrom(property.DeclaringType))) { mostDerivedProperty = property; } } return mostDerivedProperty; } #if NET40 public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetProperties(bindingFlags); } #endif #if NET40 public static PropertyInfo GetRuntimeProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); return type.GetProperty(name); } #endif public static PropertyInfo GetAnyProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList(); if (props.Count() > 1) { throw new AmbiguousMatchException(); } return props.SingleOrDefault(); } public static PropertyInfo GetInstanceProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); var props = type.GetRuntimeProperties().Where(p => p.Name == name && !p.IsStatic()).ToList(); if (props.Count() > 1) { throw new AmbiguousMatchException(); } return props.SingleOrDefault(); } public static PropertyInfo GetStaticProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); var properties = type.GetRuntimeProperties().Where(p => p.Name == name && p.IsStatic()).ToList(); if (properties.Count() > 1) { throw new AmbiguousMatchException(); } return properties.SingleOrDefault(); } public static PropertyInfo GetTopProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); do { #if NET40 const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var propertyInfo = type.GetProperty(name, bindingFlags); if (propertyInfo != null) { return propertyInfo; } type = type.BaseType; #else var typeInfo = type.GetTypeInfo(); var propertyInfo = typeInfo.GetDeclaredProperty(name); if (propertyInfo != null && !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic) { return propertyInfo; } type = typeInfo.BaseType; #endif } while (type != null); return null; } public static Assembly Assembly(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.Assembly; #else return type.GetTypeInfo().Assembly; #endif } public static Type BaseType(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.BaseType; #else return type.GetTypeInfo().BaseType; #endif } #if NET40 public static IEnumerable<FieldInfo> GetRuntimeFields(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetFields(bindingFlags); } #endif public static bool IsGenericType(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsGenericType; #else return type.GetTypeInfo().IsGenericType; #endif } public static bool IsGenericTypeDefinition(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsGenericTypeDefinition; #else return type.GetTypeInfo().IsGenericTypeDefinition; #endif } public static TypeAttributes Attributes(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.Attributes; #else return type.GetTypeInfo().Attributes; #endif } public static bool IsClass(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsClass; #else return type.GetTypeInfo().IsClass; #endif } public static bool IsInterface(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsInterface; #else return type.GetTypeInfo().IsInterface; #endif } public static bool IsValueType(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsValueType; #else return type.GetTypeInfo().IsValueType; #endif } public static bool IsAbstract(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsAbstract; #else return type.GetTypeInfo().IsAbstract; #endif } public static bool IsSealed(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsSealed; #else return type.GetTypeInfo().IsSealed; #endif } public static bool IsEnum(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsEnum; #else return type.GetTypeInfo().IsEnum; #endif } public static bool IsSerializable(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsSerializable; #else return type.GetTypeInfo().IsSerializable; #endif } public static bool IsGenericParameter(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsGenericParameter; #else return type.GetTypeInfo().IsGenericParameter; #endif } public static bool ContainsGenericParameters(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.ContainsGenericParameters; #else return type.GetTypeInfo().ContainsGenericParameters; #endif } public static bool IsPrimitive(this Type type) { DebugCheck.NotNull(type); #if NET40 return type.IsPrimitive; #else return type.GetTypeInfo().IsPrimitive; #endif } public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) { DebugCheck.NotNull(type); #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetConstructors(bindingFlags); #else return type.GetTypeInfo().DeclaredConstructors; #endif } public static ConstructorInfo GetDeclaredConstructor(this Type type, params Type[] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotNull(parameterTypes); return type.GetDeclaredConstructors().SingleOrDefault( c => !c.IsStatic && c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static ConstructorInfo GetPublicConstructor(this Type type, params Type[] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotNull(parameterTypes); var constructor = type.GetDeclaredConstructor(parameterTypes); return constructor != null && constructor.IsPublic ? constructor : null; } public static ConstructorInfo GetDeclaredConstructor( this Type type, Func<ConstructorInfo, bool> predicate, params Type[][] parameterTypes) { DebugCheck.NotNull(type); DebugCheck.NotNull(parameterTypes); return parameterTypes .Select(p => type.GetDeclaredConstructor(p)) .FirstOrDefault(c => c != null && predicate(c)); } #if !NET40 // This extension method will only be used when compiling for a platform on which Type // does not expose this method directly. public static bool IsSubclassOf(this Type type, Type otherType) { DebugCheck.NotNull(type); DebugCheck.NotNull(otherType); return type.GetTypeInfo().IsSubclassOf(otherType); } #endif } }
32.537975
137
0.584439
[ "Apache-2.0" ]
Cireson/EntityFramework6
src/Common/TypeExtensions.cs
25,705
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using AutoMapper; using Castle.MicroKernel.Registration; namespace Web.Infrastructure.Injection.Installers { public class MappersInstaller : IWindsorInstaller { public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store) { container.Register(Component.For<IMappingEngine>().UsingFactoryMethod(() => Mapper.Engine)); } } }
31.235294
142
0.753296
[ "MIT" ]
williamverdolini/FastCatalog
Catalog/Web/Infrastructure/Injection/Installers/MappersInstaller.cs
533
C#
using System.Windows.Forms; using System.Diagnostics; using System; using System.Runtime.InteropServices; namespace VAN_Demo { public partial class MyMessageBox : Form { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); /// <summary> /// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter. /// </summary> [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); const UInt32 WM_CLOSE = 0x0010; static MyMessageBox newMessageBox; public MyMessageBox() { InitializeComponent(); } public static void ShowBox(string txtMessage) { string[] msg = txtMessage.Split(';'); newMessageBox = new MyMessageBox(); newMessageBox.TopMost = true; try { newMessageBox.label1.Text = msg[0]; newMessageBox.label2.Text = msg[1]; newMessageBox.label3.Text = msg[2]; } catch { } newMessageBox.ShowDialog(); } public static void close() { IntPtr windowPtr = FindWindowByCaption(IntPtr.Zero, "Warning"); SendMessage(windowPtr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } }
32.745098
96
0.592216
[ "Apache-2.0" ]
ADVANTECH-Corp/node-red-contrib-virtual-app-node
Apps SDK/Source/C#/VAN Demo/VAN Demo/MyMessageBox.cs
1,672
C#
using UnityEngine; using System.Collections; public class ComponentsList : MonoBehaviour { public Inventory inventory; public BodyController bodyController; public NetworkPawn networkPawn; }
21.777778
45
0.826531
[ "MIT" ]
GenaSG/UnityUnetMovement
Scripts/ComponentsList.cs
198
C#
// Copyright (c) 2012-2017 fo-dicom contributors. // Licensed under the Microsoft Public License (MS-PL). using System; using System.IO; using Dicom; using Dicom.Imaging; using Dicom.Log; using UIKit; namespace SimpleViewer.iOS { public partial class ViewController : UIViewController { private readonly string[] _fileNames = { "Assets/CT-MONO2-8-abdo", "Assets/jpeg-baseline.dcm", "Assets/US1_J2KI" }; private int _counter = 0; public ViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); Display(_fileNames[_counter]); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } partial void NextImageButtonTouchUpInside(UIButton sender) { ++_counter; if (_counter >= _fileNames.Length) _counter = 0; Display(_fileNames[_counter]); } private void Display(string fileName) { try { // Read and render DICOM image UIImage image; string dump; using (var stream = File.OpenRead(fileName)) { var dicomFile = DicomFile.Open(stream); var dicomImage = new DicomImage(dicomFile.Dataset); image = dicomImage.RenderImage().AsUIImage(); dump = dicomFile.WriteToString(); } // Draw rendered image in image view _imageView.Image = image; // Display dump _textView.Text = dump; } catch (Exception e) { var alert = new UIAlertView() { Title = "DICOM display failed", Message = e.Message }; alert.AddButton("OK"); alert.Show(); } } } }
21.441558
117
0.63719
[ "BSD-3-Clause" ]
007souvikdas/fo-dicom-samples
iOS/SimpleViewer.iOS/ViewController.cs
1,653
C#
/* Program Architecture & Framework: @HoLLy-HaCKeR Archive Format and Engine Reversing: @HoLLy-HaCKeR */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Text.RegularExpressions; using ArchiveUnpacker.Core; using ArchiveUnpacker.Core.Exceptions; using ArchiveUnpacker.Core.ExtractableFileTypes; using ArchiveUnpacker.Unpackers.Utils.Pickle; namespace ArchiveUnpacker.Unpackers.Unpackers { /// <summary> /// Unpacks files from VNs created using the Ren'Py engine. /// /// Tested on renpy v6.17.3, v6.99.3, v6.99.12, v6.99.13, v6.99.14.3, v7.2.0. /// </summary> internal class RenPyUnpacker : IUnpacker { private const string MagicRegex = @"^RPA-3\.0 [a-f\d]{16} [a-f\d]{8}\nMade with Ren'Py.$"; private const int MagicLength = 51; public IEnumerable<IExtractableFile> LoadFiles(string gameDirectory) => GetArchivesFromGameFolder(gameDirectory).SelectMany(LoadFilesFromArchive); public IEnumerable<IExtractableFile> LoadFilesFromArchive(string inputArchive) { using (var fs = File.OpenRead(inputArchive)) using (var br = new BinaryReader(fs)) { var readMagic = Encoding.ASCII.GetString(br.ReadBytes(MagicLength)); if (!Regex.IsMatch(readMagic, MagicRegex)) throw new InvalidMagicException(); long indexOff = Convert.ToInt64(readMagic.Substring(8, 16), 16); uint key = Convert.ToUInt32(readMagic.Substring(25, 8), 16); // seek to index offset and read it fs.Seek(indexOff + 2, SeekOrigin.Begin); // TODO: skipping zlib header here using (var decStream = new DeflateStream(fs, CompressionMode.Decompress, true)) { var indexObject = PickleReader.ReadFromStream(decStream); if (!(indexObject is Dictionary<object, object> dic)) throw new Exception("File index was not a dictionary."); foreach (var o in dic) { var val = (object[])((List<object>)o.Value)[0]; long v1 = Convert.ToInt64(val[0]) ^ key; uint v2 = (uint)(Convert.ToInt64(val[1]) ^ key); var v3 = (string)val[2]; if (!string.IsNullOrEmpty(v3)) Debugger.Break(); yield return new FileSlice((string)o.Key, v1, v2, inputArchive); } } } } private IEnumerable<string> GetArchivesFromGameFolder(string gameDirectory) => Directory.GetFiles(gameDirectory, "*.rpa", SearchOption.AllDirectories); public static bool IsGameFolder(string folder) => File.Exists(Path.Combine(folder, "renpy", "main.py")) || File.Exists(Path.Combine(folder, "renpy", "main.pyo")); } }
43.492754
170
0.616128
[ "MIT" ]
Azukee/Macaron
ArchiveUnpacker.Unpackers/Unpackers/RenPyUnpacker.cs
3,001
C#
namespace NBitcoin.Tests { public class alert_tests { public alert_tests() { // These flags may get set due to static network initializers // which include the initializers for Stratis. Transaction.TimeStamp = false; Block.BlockSignature = false; } /* * TODO: Consider importing to FN. [Fact] [Trait("UnitTest", "UnitTest")] public void CanParseAlertAndChangeUpdatePayloadAndSignature() { var alertStr = "73010000003766404f00000000b305434f00000000f2030000f1030000001027000048ee00000064000000004653656520626974636f696e2e6f72672f666562323020696620796f7520686176652074726f75626c6520636f6e6e656374696e67206166746572203230204665627275617279004730450221008389df45f0703f39ec8c1cc42c13810ffcae14995bb648340219e353b63b53eb022009ec65e1c1aaeec1fd334c6b684bde2b3f573060d5b70c3a46723326e4e8a4f1"; AlertPayload alert = new AlertPayload(); alert.FromBytes(TestUtils.ParseHex(alertStr)); Assert.True(alert.CheckSignature(Network.Main)); Assert.Equal("See bitcoin.org/feb20 if you have trouble connecting after 20 February", alert.StatusBar); alert.StatusBar = "Changing..."; Assert.True(alert.CheckSignature(Network.Main)); alert.UpdatePayload(); Assert.False(alert.CheckSignature(Network.Main)); Key key = new Key(); alert.UpdateSignature(key); Assert.True(alert.CheckSignature(key.PubKey)); } [Fact] [Trait("Core", "Core")] public void AlertApplies() { var alerts = ReadAlerts(); foreach(var alert in alerts) { Assert.True(alert.CheckSignature(Network.Main)); Assert.True(!alert.CheckSignature(Network.TestNet)); alert.Now = Utils.UnixTimeToDateTime(11); } Assert.True(alerts.Length >= 3); // Matches: Assert.True(alerts[0].AppliesTo(1, "")); Assert.True(alerts[0].AppliesTo(999001, "")); Assert.True(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/")); Assert.True(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/")); Assert.True(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/")); Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/")); Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/")); // Don't match: Assert.True(!alerts[0].AppliesTo(-1, "")); Assert.True(!alerts[0].AppliesTo(999002, "")); Assert.True(!alerts[1].AppliesTo(1, "")); Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0")); Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0")); Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/")); Assert.True(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/")); Assert.True(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/")); Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/")); Assert.True(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/")); } private AlertPayload[] ReadAlerts() { List<AlertPayload> alerts = new List<AlertPayload>(); using(var fs = File.OpenRead("data/alertTests.raw")) { BitcoinStream stream = new BitcoinStream(fs, false); while(stream.Inner.Position != stream.Inner.Length) { AlertPayload payload = null; stream.ReadWrite(ref payload); alerts.Add(payload); } } return alerts.ToArray(); } */ } }
39.778947
406
0.580048
[ "MIT" ]
MIPPL/StratisBitcoinFullNode
src/NBitcoin.Tests/alert_tests.cs
3,781
C#
//-------------------------------------------------------------- // Vehicle Physics Pro: advanced vehicle physics kit // Copyright © 2011-2019 Angel Garcia "Edy" // http://vehiclephysics.com | @VehiclePhysics //-------------------------------------------------------------- // GenericMenu: a toggle-based menu using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using System; namespace VehiclePhysics.UI { public class GenericMenu : MonoBehaviour { [Serializable] public class MenuItem { public Toggle toggle; public GameObject gameObject; } public MenuItem[] items = new MenuItem[0]; // Optional: a dropdown that triggers the change. public Dropdown dropdown; void OnEnable () { foreach (MenuItem item in items) AddListener(item.toggle, OnValueChanged); if (dropdown != null) dropdown.onValueChanged.AddListener(OnValueChanged); // Re-enabling the object leaves scroll rects when they where. UpdateMenuItems(false); } void OnDisable () { foreach (MenuItem item in items) RemoveListener(item.toggle, OnValueChanged); if (dropdown != null) dropdown.onValueChanged.RemoveListener(OnValueChanged); } void OnValueChanged (bool value) { // Note: the Toggle that was changed may be read here: // EventSystem.current.currentSelectedGameObject UpdateMenuItems(true); } void OnValueChanged (int value) { UpdateMenuItems(true); } void UpdateMenuItems (bool updateScroll) { for (int i = 0; i < items.Length; i++) { MenuItem item = items[i]; if (item.gameObject != null) { bool visible = item.toggle != null && item.toggle.isOn || dropdown != null && dropdown.value == i; if (visible && updateScroll) { ScrollRect[] scrollRects = GetComponentsInChildren<ScrollRect>(); foreach (ScrollRect sr in scrollRects) { // Horizontal position is slightly moved to prevent element cropping. // Don't reset it here. // sr.horizontalNormalizedPosition = 0.0f; sr.verticalNormalizedPosition = 1.0f; } } item.gameObject.SetActive(visible); } } } void AddListener (Toggle toggle, UnityAction<bool> call) { if (toggle != null) toggle.onValueChanged.AddListener(call); } void RemoveListener (Toggle toggle, UnityAction<bool> call) { if (toggle != null) toggle.onValueChanged.RemoveListener(call); } } }
20.697479
75
0.648802
[ "MIT" ]
LakshyaNandwana/car-racing-game-unity
Assets/Vehicle Physics Pro/Scenes/UI/Scripts/GenericMenu.cs
2,466
C#
namespace KifuwarabeUec11Gui.InputScript { /// <summary> /// `JSON {ここにJSON}` みたいなコマンド☆(^~^) /// </summary> public class JsonInstructionArgument { /// <summary> /// 前後の空白はトリムするぜ☆(^~^) /// </summary> public string Json { get; private set; } public JsonInstructionArgument(string text) { this.Json = text; } /// <summary> /// デバッグ表示用☆(^~^) /// </summary> /// <returns></returns> public string ToDisplay() { return $"{this.Json}"; } } }
21.321429
51
0.470687
[ "MIT" ]
muzudho/rensyu
visual-studio/kifuwarabe-uec11-gui/Model/Input/Script/Instruction/JsonInstructionArgument.cs
695
C#
using System; using System.Text.Json; using System.Text.Json.Serialization; namespace ReunionGet.Aria2Rpc.Json.Converters { internal class Base64MemoryConverter : JsonConverter<ReadOnlyMemory<byte>> { public override ReadOnlyMemory<byte> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.GetBytesFromBase64(); public override void Write(Utf8JsonWriter writer, ReadOnlyMemory<byte> value, JsonSerializerOptions options) => writer.WriteBase64StringValue(value.Span); } }
35.4375
127
0.753086
[ "MIT" ]
huoyaoyuan/ReunionGet
Source/Portable/ReunionGet.Aria2Rpc/Json/Converters/Base64MemoryConverter.cs
569
C#
// ********************************************************************* // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License // ********************************************************************* using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; namespace Microsoft.StreamProcessing { internal partial class ClipJoinTemplate { private static int ClipSequenceNumber = 0; private Type keyType; private Type leftType; private Type rightType; private string TKey; private string TLeft; private string TRight; private string className; private string genericParameters = string.Empty; private string BatchGeneratedFrom_TKey_TLeft; private string TKeyTLeftGenericParameters; private string BatchGeneratedFrom_TKey_TRight; private string TKeyTRightGenericParameters; private IEnumerable<MyFieldInfo> leftFields; private Func<string, string, string> keyComparer; private Func<string, string, string> leftComparer; private string staticCtor; private string ActiveEventType; private bool noFields; private ClipJoinTemplate() { } /// <summary> /// Generate a batch class definition to be used as a Clip pipe. /// Compile the definition, dynamically load the assembly containing it, and return the Type representing the /// aggregate class. /// </summary> /// <typeparam name="TKey">The key type for both sides.</typeparam> /// <typeparam name="TLeft">The payload type for the left side.</typeparam> /// <typeparam name="TRight">The payload type for the right side.</typeparam> /// <returns> /// A type that is defined to be a subtype of BinaryPipe&lt;<typeparamref name="TKey"/>,<typeparamref name="TLeft"/>, <typeparamref name="TKey"/>, <typeparamref name="TRight"/>&gt;. /// </returns> internal static Tuple<Type, string> Generate<TKey, TLeft, TRight>(ClipJoinStreamable<TKey, TLeft, TRight> stream) { Contract.Requires(stream != null); Contract.Ensures(Contract.Result<Tuple<Type, string>>() == null || typeof(BinaryPipe<TKey, TLeft, TRight, TLeft>).GetTypeInfo().IsAssignableFrom(Contract.Result<Tuple<Type, string>>().Item1)); string errorMessages = null; try { var template = new ClipJoinTemplate(); var keyType = template.keyType = typeof(TKey); var leftType = template.leftType = typeof(TLeft); var rightType = template.rightType = typeof(TRight); var tm = new TypeMapper(keyType, leftType, rightType); template.TKey = tm.CSharpNameFor(keyType); template.TLeft = tm.CSharpNameFor(leftType); template.TRight = tm.CSharpNameFor(rightType); var gps = tm.GenericTypeVariables(keyType, leftType, rightType); template.genericParameters = gps.BracketedCommaSeparatedString(); template.className = string.Format("GeneratedClip_{0}", ClipSequenceNumber++); var leftMessageRepresentation = new ColumnarRepresentation(leftType); var resultRepresentation = new ColumnarRepresentation(leftType); template.ActiveEventType = leftType.GetTypeInfo().IsValueType ? template.TLeft : "Active_Event"; #region Key Comparer var keyComparer = stream.Properties.KeyEqualityComparer.GetEqualsExpr(); template.keyComparer = (left, right) => keyComparer.Inline(left, right); #endregion #region Left Comparer var leftComparer = stream.LeftComparer.GetEqualsExpr(); var newLambda = Extensions.TransformFunction<TKey, TLeft>(leftComparer, "index_ProcessLeftEvent", 0); template.leftComparer = (left, right) => newLambda.Inline(left, right); #endregion template.BatchGeneratedFrom_TKey_TLeft = Transformer.GetBatchClassName(keyType, leftType); template.TKeyTLeftGenericParameters = tm.GenericTypeVariables(keyType, leftType).BracketedCommaSeparatedString(); template.BatchGeneratedFrom_TKey_TRight = Transformer.GetBatchClassName(keyType, rightType); template.TKeyTRightGenericParameters = tm.GenericTypeVariables(keyType, rightType).BracketedCommaSeparatedString(); template.leftFields = resultRepresentation.AllFields; template.noFields = resultRepresentation.noFields; template.staticCtor = Transformer.StaticCtor(template.className); var expandedCode = template.TransformText(); var assemblyReferences = Transformer.AssemblyReferencesNeededFor(typeof(TKey), typeof(TLeft), typeof(TRight)); assemblyReferences.Add(typeof(IStreamable<,>).GetTypeInfo().Assembly); assemblyReferences.Add(Transformer.GeneratedStreamMessageAssembly<TKey, TLeft>()); assemblyReferences.Add(Transformer.GeneratedStreamMessageAssembly<TKey, TRight>()); assemblyReferences.AddRange(Transformer.AssemblyReferencesNeededFor(leftComparer)); var a = Transformer.CompileSourceCode(expandedCode, assemblyReferences, out errorMessages); var realClassName = template.className.AddNumberOfNecessaryGenericArguments(keyType, leftType, rightType); var t = a.GetType(realClassName); if (t.GetTypeInfo().IsGenericType) { var list = keyType.GetAnonymousTypes(); list.AddRange(leftType.GetAnonymousTypes()); list.AddRange(rightType.GetAnonymousTypes()); return Tuple.Create(t.MakeGenericType(list.ToArray()), errorMessages); } else { return Tuple.Create(t, errorMessages); } } catch { if (Config.CodegenOptions.DontFallBackToRowBasedExecution) { throw new InvalidOperationException("Code Generation failed when it wasn't supposed to!"); } return Tuple.Create((Type)null, errorMessages); } } } }
49.526316
204
0.621527
[ "MIT" ]
domoritz/Trill
Sources/Core/Microsoft.StreamProcessing/Operators/Clip/ClipJoinTransformer.cs
6,589
C#
namespace ACT.SpecialSpellTimer { using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Advanced_Combat_Tracker; public static partial class FF14PluginHelper { private static object lockObject = new object(); private static object plugin; private static object pluginMemory; private static dynamic pluginConfig; private static dynamic pluginScancombat; public static void Initialize() { lock (lockObject) { if (!ActGlobals.oFormActMain.Visible) { return; } if (plugin == null) { foreach (var item in ActGlobals.oFormActMain.ActPlugins) { if (item.pluginFile.Name.ToUpper() == "FFXIV_ACT_Plugin.dll".ToUpper() && item.lblPluginStatus.Text.ToUpper() == "FFXIV Plugin Started.".ToUpper()) { plugin = item.pluginObj; break; } } } if (plugin != null) { FieldInfo fi; if (pluginMemory == null) { fi = plugin.GetType().GetField("_Memory", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); pluginMemory = fi.GetValue(plugin); } if (pluginMemory == null) { return; } if (pluginConfig == null) { fi = pluginMemory.GetType().GetField("_config", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); pluginConfig = fi.GetValue(pluginMemory); } if (pluginConfig == null) { return; } if (pluginScancombat == null) { fi = pluginConfig.GetType().GetField("ScanCombatants", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); pluginScancombat = fi.GetValue(pluginConfig); } } } } public static Process GetFFXIVProcess { get { try { Initialize(); if (pluginConfig == null) { return null; } var process = pluginConfig.Process; return (Process)process; } catch { return null; } } } public static List<Combatant> GetCombatantList() { Initialize(); var result = new List<Combatant>(); if (plugin == null) { return result; } if (GetFFXIVProcess == null) { return result; } if (pluginScancombat == null) { return result; } dynamic list = pluginScancombat.GetCombatantList(); foreach (dynamic item in list.ToArray()) { if (item == null) { continue; } var combatant = new Combatant(); combatant.ID = (uint)item.ID; combatant.OwnerID = (uint)item.OwnerID; combatant.Job = (int)item.Job; combatant.Name = (string)item.Name; combatant.type = (byte)item.type; combatant.Level = (int)item.Level; combatant.CurrentHP = (int)item.CurrentHP; combatant.MaxHP = (int)item.MaxHP; combatant.CurrentMP = (int)item.CurrentMP; combatant.MaxMP = (int)item.MaxMP; combatant.CurrentTP = (int)item.CurrentTP; result.Add(combatant); } return result; } public static List<uint> GetCurrentPartyList( out int partyCount) { Initialize(); var partyList = new List<uint>(); partyCount = 0; if (plugin == null) { return partyList; } if (GetFFXIVProcess == null) { return partyList; } if (pluginScancombat == null) { return partyList; } partyList = pluginScancombat.GetCurrentPartyList( out partyCount) as List<uint>; return partyList; } } public class Combatant { public uint ID; public uint OwnerID; public int Order; public byte type; public int Job; public int Level; public string Name; public int CurrentHP; public int MaxHP; public int CurrentMP; public int MaxMP; public int CurrentTP; } }
28.150259
151
0.435119
[ "BSD-3-Clause" ]
danakj/ACT.SpecialSpellTimer
ACT.SpecialSpellTimer/FF14PluginHelper.cs
5,435
C#
// Decompiled with JetBrains decompiler // Type: Diga.WebView2.Interop.ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler // Assembly: WebView2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: B5F140DB-135D-4E8A-B1A2-1275CE2FD56A // Assembly location: O:\webview2\webview2packages\V9488\WebView2.dll using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Diga.WebView2.Interop { [Guid("8B4F98CE-DB0D-4E71-85FD-C4C4EF1F2630")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Invoke([MarshalAs(UnmanagedType.Error)] int result, [MarshalAs(UnmanagedType.Interface)] ICoreWebView2Environment created_environment); } }
41.857143
144
0.82025
[ "MIT" ]
ITAgnesmeyer/Diga.WebView2
Archive/V9488/Diga.WebView2.Interop.V9488/ICoreWebView2CreateCoreWebView2EnvironmentComplete.cs
881
C#
namespace ClassLib037 { public class Class045 { public static string Property => "ClassLib037"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib037/Class045.cs
120
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Collections; namespace DevinDow.VisionBoard { public class VisionBoard { // Public Static Fields public static VisionBoard Current; // Public Fields public string Filename; public int NextIndex = 1; public bool IsDirty = false; public ArrayList Items = new ArrayList(); public bool Reordering = false; public int OrderIndex; public int ReorderCurrentIndex; // Private Fields // Steps in ScreenSaver private int itemIndex; private int Step; private const int MaxStep = 100; // total number of ticks per picture private const int PauseSteps = 20; // ticks to pause private const int HalfwayStep = MaxStep / 2 - PauseSteps / 2; // Public Properties public Box Bounds { get { Box bounds = new Box(); foreach (ImageItem item in Items) bounds.Include(item.Bounds); return bounds; } } // Private Fields private Bitmap bitmapOfStaticItems; private ImageItem currentActiveItem; // Public Methods public Bitmap GetBitmap(int width, int height) { Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(Brushes.Black, 0, 0, width, height); g.TranslateTransform(width / 2, height / 2); Draw(g); g.Dispose(); return bitmap; } public void Draw(Graphics g, object itemToSkip = null) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; for (int i = Items.Count - 1; i >= 0; i--) // Draw in Reverse Order so First ends up on top { ImageItem item = (ImageItem)Items[i]; if (item != itemToSkip) item.Draw(g); } } public void InitPlaying() { VisionBoard.Current.itemIndex = 0; VisionBoard.Current.Step = 0; // clear previous bitmapOfStaticItems to generate a new one if (bitmapOfStaticItems != null) { bitmapOfStaticItems.Dispose(); bitmapOfStaticItems = null; } } public void PlayAStep(Graphics g, int width, int height) { if (itemIndex >= Items.Count || itemIndex < 0) return; ImageItem activeItem = (ImageItem)Items[itemIndex]; // bitmap to draw to and its bitmapG Graphics object Bitmap bitmap = new Bitmap(width, height); Graphics bitmapG = Graphics.FromImage(bitmap); //bitmapG.SetClip(new Rectangle(0, 0, width, height)); // draw bitmapOfStaticItems of all items except activeItem to bitmapG getBitmapOfStaticItems(width, height, activeItem); bitmapG.DrawImage(bitmapOfStaticItems, 0, 0); bitmapG.TranslateTransform(width / 2, height / 2); // center (0,0) bitmapG.ScaleTransform(ScreensaverForm.ScaleFactor, ScreensaverForm.ScaleFactor); // Scale down to fit // actualStep between original position & zoomed-in position int actualStep; if (Step < MaxStep / 2 - PauseSteps / 2) // zooming in actualStep = Step; else if (Step > MaxStep / 2 + PauseSteps / 2) // zooming out actualStep = MaxStep - Step; else // pausing actualStep = MaxStep / 2 - PauseSteps / 2; // draw activeItem at its current zoom step to bitmapG // offset to accelerate //int offset = (int)Math.Round(Math.Sqrt(Math.Pow(HalfMaxStep / 2, 2) - Math.Pow(actualStep - HalfMaxStep / 2, 2))); // offset is in the range of [0..HalfMaxStep], slow moving on the ends and fast moving in the middle int x = /*-activeItem.X * offset / HalfMaxStep; //*/(int)Math.Round(Math.Pow((Math.Pow(Math.Abs(activeItem.X), 0.666) / HalfwayStep * actualStep), 1.5)); if (activeItem.X > 0) x = -x; int y = /*-activeItem.Y * offset / HalfMaxStep; //*/(int)Math.Round(Math.Pow((Math.Pow(Math.Abs(activeItem.Y), 0.33) / HalfwayStep * actualStep), 3)); //-activeItem.Y * actualStep / HalfMaxStep; if (activeItem.Y > 0) y = -y; float rot = -activeItem.RotationDegrees / HalfwayStep * actualStep; float maxScale = Math.Min(width * 0.95f / ScreensaverForm.ScaleFactor / activeItem.Size.Width, height * 0.95f / ScreensaverForm.ScaleFactor / activeItem.Size.Height); float scale = 1 + (maxScale - 1) * actualStep / HalfwayStep; if (scale == 0) scale = 1; activeItem.Draw(bitmapG, x, y, rot, scale); // draw the bitmap to the screen g.DrawImage(bitmap, 0, 0); bitmapG.Dispose(); } public void NextStep() { if (Step < VisionBoard.MaxStep) Step++; else { NextItem(); Reset(); } } public void NextItem() { itemIndex++; if (itemIndex >= Items.Count) itemIndex = 0; } public void PrevItem() { itemIndex--; if (itemIndex < 0) itemIndex = Items.Count-1; } public void Reset() { Step = 0; } public void Maximize() { Step = MaxStep / 2; } // Private Methods private void getBitmapOfStaticItems(int width, int height, ImageItem activeItem) { // Only generate bitmapOfStaticItems once for all placements of activeItem if (bitmapOfStaticItems != null && activeItem == currentActiveItem) return; if (bitmapOfStaticItems != null) bitmapOfStaticItems.Dispose(); // Only Dispose() when generating next bitmapOfStaticItems bitmapOfStaticItems = new Bitmap(width, height); currentActiveItem = activeItem; Graphics bitmapG = Graphics.FromImage(bitmapOfStaticItems); bitmapG.SetClip(new Rectangle(0, 0, width, height)); bitmapG.TranslateTransform(width / 2, height / 2); // center (0,0) bitmapG.ScaleTransform(ScreensaverForm.ScaleFactor, ScreensaverForm.ScaleFactor); // Scale down to fit Draw(bitmapG, activeItem); bitmapG.Dispose(); } } }
33.980198
229
0.555507
[ "MIT" ]
DevinDow/VisionBoard
VisionBoard.cs
6,866
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using MyRESTServer.Models; namespace MyRESTServer.Controllers { public class BooksController : ApiController { private BooksModel db = new BooksModel(); // GET: api/Books public IQueryable<Book> GetBooks() { return db.Books; } // GET: api/Books/5 [ResponseType(typeof(Book))] public IHttpActionResult GetBook(int id) { Book book = db.Books.Find(id); if (book == null) { return NotFound(); } return Ok(book); } // PUT: api/Books/5 [ResponseType(typeof(void))] public IHttpActionResult PutBook(int id, Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != book.Id) { return BadRequest(); } db.Entry(book).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!BookExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Books [ResponseType(typeof(Book))] public IHttpActionResult PostBook(Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Books.Add(book); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = book.Id }, book); } //// DELETE: api/Books/5 //[ResponseType(typeof(Book))] //public IHttpActionResult DeleteBook(int id) //{ // Book book = db.Books.Find(id); // if (book == null) // { // return NotFound(); // } // db.Books.Remove(book); // db.SaveChanges(); // return Ok(book); //} protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool BookExists(int id) { return db.Books.Count(e => e.Id == id) > 0; } } }
23.550847
76
0.468154
[ "MIT" ]
CNinnovation/HTMLOct2017
MyRESTServer/MyRESTServer/Controllers/BooksController.cs
2,781
C#
/* * Copyright © 2019 Federation of State Medical Boards * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the “Software”), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Fsmb.Apis.Fcvs.Clients { [Description("Name of a person")] public class Name { [Required(AllowEmptyStrings = false)] [Description("First name")] public string FirstName { get; set; } [Description("Middle name")] public string MiddleName { get; set; } [Required(AllowEmptyStrings = false)] [Description("Last name")] public string LastName { get; set; } [Description("Suffix")] public string Suffix { get; set; } } }
43.642857
130
0.708129
[ "MIT" ]
fsmb/fcvs-api
samples/csharp/Fsmb.Apis.Fcvs.Clients/Models/Name.cs
1,844
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Player.cs" company="SyndicatedLife"> // Copyright© 2007 - 2021 Ryan Wilson &amp;lt;syndicated.life@gmail.com&amp;gt; (https://syndicated.life/) // Licensed under the MIT license. See LICENSE.md in the solution root for full license information. // </copyright> // <summary> // Player.cs Implementation // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace FFXIVAPP.Plugin.Parse.Models.StatGroups { using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Timers; using FFXIVAPP.Common.Models; using FFXIVAPP.Common.Utilities; using FFXIVAPP.Plugin.Parse.Models.LinkedStats; using FFXIVAPP.Plugin.Parse.Models.Stats; using FFXIVAPP.Plugin.Parse.ViewModels; using NLog; using Sharlayan.Core; public partial class Player : StatGroup { private static readonly IList<string> LD = new[] { "Counter", "Block", "Parry", "Resist", "Evade", }; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public readonly Timer IsActiveTimer = new Timer(1000); public readonly Timer StatusUpdateTimer = new Timer(1000); public List<StatusItem> StatusEntriesMonsters = new List<StatusItem>(); public List<StatusItem> StatusEntriesPlayers = new List<StatusItem>(); public List<StatusItem> StatusEntriesSelf = new List<StatusItem>(); private ActorItem _npcEntry; public Player(string name, ParseControl parseControl) : base(name) { Controller = parseControl; this.ID = 0; this.LineHistory = new List<LineHistory>(); this.Last20DamageActions = new List<LineHistory>(); this.Last20DamageTakenActions = new List<LineHistory>(); this.Last20HealingActions = new List<LineHistory>(); this.Last20Items = new List<LineHistory>(); this.LastActionTime = DateTime.Now; this.InitStats(); this.StatusUpdateTimer.Elapsed += this.StatusUpdateTimerOnElapsed; this.IsActiveTimer.Elapsed += this.IsActiveTimerOnElapsed; this.StatusUpdateTimer.Start(); this.IsActiveTimer.Start(); } public uint ID { get; set; } public List<LineHistory> Last20DamageActions { get; set; } public List<LineHistory> Last20DamageTakenActions { get; set; } public List<LineHistory> Last20HealingActions { get; set; } public List<LineHistory> Last20Items { get; set; } public DateTime LastActionTime { get; set; } public List<LineHistory> LineHistory { get; set; } public ActorItem NPCEntry { get { return this._npcEntry; } set { if (this._npcEntry != value) { this._npcEntry = value; this.RaisePropertyChanged(); } } } public bool StatusUpdateTimerProcessing { get; set; } public double TotalInActiveTime { get; set; } private static ParseControl Controller { get; set; } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> BuffStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.BuffStats(); // setup per damage taken "percent of" stats switch (useSub) { case true: break; case false: break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"> </param> /// <param name="useSub"></param> /// <returns> </returns> private IEnumerable<Stat<double>> DamageOverTimeStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.DamageOverTimeStats(); // setup per ability "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallDamageOverTime", new PercentStat("PercentOfTotalOverallDamageOverTime", stats["TotalOverallDamageOverTime"], sub.Stats.GetStat("TotalOverallDamageOverTime"))); stats.Add("PercentOfRegularDamageOverTime", new PercentStat("PercentOfRegularDamageOverTime", stats["RegularDamageOverTime"], sub.Stats.GetStat("RegularDamageOverTime"))); stats.Add("PercentOfCriticalDamageOverTime", new PercentStat("PercentOfCriticalDamageOverTime", stats["CriticalDamageOverTime"], sub.Stats.GetStat("CriticalDamageOverTime"))); break; case false: stats.Add("PercentOfTotalOverallDamageOverTime", new PercentStat("PercentOfTotalOverallDamageOverTime", stats["TotalOverallDamageOverTime"], this.Stats.GetStat("TotalOverallDamageOverTime"))); stats.Add("PercentOfRegularDamageOverTime", new PercentStat("PercentOfRegularDamageOverTime", stats["RegularDamageOverTime"], this.Stats.GetStat("RegularDamageOverTime"))); stats.Add("PercentOfCriticalDamageOverTime", new PercentStat("PercentOfCriticalDamageOverTime", stats["CriticalDamageOverTime"], this.Stats.GetStat("CriticalDamageOverTime"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"> </param> /// <param name="useSub"></param> /// <returns> </returns> private IEnumerable<Stat<double>> DamageStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.DamageStats(); // setup per ability "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallDamage", new PercentStat("PercentOfTotalOverallDamage", stats["TotalOverallDamage"], sub.Stats.GetStat("TotalOverallDamage"))); stats.Add("PercentOfRegularDamage", new PercentStat("PercentOfRegularDamage", stats["RegularDamage"], sub.Stats.GetStat("RegularDamage"))); stats.Add("PercentOfCriticalDamage", new PercentStat("PercentOfCriticalDamage", stats["CriticalDamage"], sub.Stats.GetStat("CriticalDamage"))); break; case false: stats.Add("PercentOfTotalOverallDamage", new PercentStat("PercentOfTotalOverallDamage", stats["TotalOverallDamage"], this.Stats.GetStat("TotalOverallDamage"))); stats.Add("PercentOfRegularDamage", new PercentStat("PercentOfRegularDamage", stats["RegularDamage"], this.Stats.GetStat("RegularDamage"))); stats.Add("PercentOfCriticalDamage", new PercentStat("PercentOfCriticalDamage", stats["CriticalDamage"], this.Stats.GetStat("CriticalDamage"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> DamageTakenOverTimeStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.DamageTakenOverTimeStats(); // setup per damage taken "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallDamageTakenOverTime", new PercentStat("PercentOfTotalOverallDamageTakenOverTime", stats["TotalOverallDamageTakenOverTime"], sub.Stats.GetStat("TotalOverallDamageTakenOverTime"))); stats.Add("PercentOfRegularDamageTakenOverTime", new PercentStat("PercentOfRegularDamageTakenOverTime", stats["RegularDamageTakenOverTime"], sub.Stats.GetStat("RegularDamageTakenOverTime"))); stats.Add("PercentOfCriticalDamageTakenOverTime", new PercentStat("PercentOfCriticalDamageTakenOverTime", stats["CriticalDamageTakenOverTime"], sub.Stats.GetStat("CriticalDamageTakenOverTime"))); break; case false: stats.Add("PercentOfTotalOverallDamageTakenOverTime", new PercentStat("PercentOfTotalOverallDamageTakenOverTime", stats["TotalOverallDamageTakenOverTime"], this.Stats.GetStat("TotalOverallDamageTakenOverTime"))); stats.Add("PercentOfRegularDamageTakenOverTime", new PercentStat("PercentOfRegularDamageTakenOverTime", stats["RegularDamageTakenOverTime"], this.Stats.GetStat("RegularDamageTakenOverTime"))); stats.Add("PercentOfCriticalDamageTakenOverTime", new PercentStat("PercentOfCriticalDamageTakenOverTime", stats["CriticalDamageTakenOverTime"], this.Stats.GetStat("CriticalDamageTakenOverTime"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> DamageTakenStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.DamageTakenStats(); // setup per damage taken "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallDamageTaken", new PercentStat("PercentOfTotalOverallDamageTaken", stats["TotalOverallDamageTaken"], sub.Stats.GetStat("TotalOverallDamageTaken"))); stats.Add("PercentOfRegularDamageTaken", new PercentStat("PercentOfRegularDamageTaken", stats["RegularDamageTaken"], sub.Stats.GetStat("RegularDamageTaken"))); stats.Add("PercentOfCriticalDamageTaken", new PercentStat("PercentOfCriticalDamageTaken", stats["CriticalDamageTaken"], sub.Stats.GetStat("CriticalDamageTaken"))); break; case false: stats.Add("PercentOfTotalOverallDamageTaken", new PercentStat("PercentOfTotalOverallDamageTaken", stats["TotalOverallDamageTaken"], this.Stats.GetStat("TotalOverallDamageTaken"))); stats.Add("PercentOfRegularDamageTaken", new PercentStat("PercentOfRegularDamageTaken", stats["RegularDamageTaken"], this.Stats.GetStat("RegularDamageTaken"))); stats.Add("PercentOfCriticalDamageTaken", new PercentStat("PercentOfCriticalDamageTaken", stats["CriticalDamageTaken"], this.Stats.GetStat("CriticalDamageTaken"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> HealingMitigatedStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.HealingMitigatedStats(); // setup per HealingMitigated "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallHealingMitigated", new PercentStat("PercentOfTotalOverallHealingMitigated", stats["TotalOverallHealingMitigated"], sub.Stats.GetStat("TotalOverallHealingMitigated"))); stats.Add("PercentOfRegularHealingMitigated", new PercentStat("PercentOfRegularHealingMitigated", stats["RegularHealingMitigated"], sub.Stats.GetStat("RegularHealingMitigated"))); stats.Add("PercentOfCriticalHealingMitigated", new PercentStat("PercentOfCriticalHealingMitigated", stats["CriticalHealingMitigated"], sub.Stats.GetStat("CriticalHealingMitigated"))); break; case false: stats.Add("PercentOfTotalOverallHealingMitigated", new PercentStat("PercentOfTotalOverallHealingMitigated", stats["TotalOverallHealingMitigated"], this.Stats.GetStat("TotalOverallHealingMitigated"))); stats.Add("PercentOfRegularHealingMitigated", new PercentStat("PercentOfRegularHealingMitigated", stats["RegularHealingMitigated"], this.Stats.GetStat("RegularHealingMitigated"))); stats.Add("PercentOfCriticalHealingMitigated", new PercentStat("PercentOfCriticalHealingMitigated", stats["CriticalHealingMitigated"], this.Stats.GetStat("CriticalHealingMitigated"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> HealingOverHealingStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.HealingOverHealingStats(); // setup per HealingOverHealing "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallHealingOverHealing", new PercentStat("PercentOfTotalOverallHealingOverHealing", stats["TotalOverallHealingOverHealing"], sub.Stats.GetStat("TotalOverallHealingOverHealing"))); stats.Add("PercentOfRegularHealingOverHealing", new PercentStat("PercentOfRegularHealingOverHealing", stats["RegularHealingOverHealing"], sub.Stats.GetStat("RegularHealingOverHealing"))); stats.Add("PercentOfCriticalHealingOverHealing", new PercentStat("PercentOfCriticalHealingOverHealing", stats["CriticalHealingOverHealing"], sub.Stats.GetStat("CriticalHealingOverHealing"))); break; case false: stats.Add("PercentOfTotalOverallHealingOverHealing", new PercentStat("PercentOfTotalOverallHealingOverHealing", stats["TotalOverallHealingOverHealing"], this.Stats.GetStat("TotalOverallHealingOverHealing"))); stats.Add("PercentOfRegularHealingOverHealing", new PercentStat("PercentOfRegularHealingOverHealing", stats["RegularHealingOverHealing"], this.Stats.GetStat("RegularHealingOverHealing"))); stats.Add("PercentOfCriticalHealingOverHealing", new PercentStat("PercentOfCriticalHealingOverHealing", stats["CriticalHealingOverHealing"], this.Stats.GetStat("CriticalHealingOverHealing"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> HealingOverTimeStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.HealingOverTimeStats(); // setup per HealingOverTime "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallHealingOverTime", new PercentStat("PercentOfTotalOverallHealingOverTime", stats["TotalOverallHealingOverTime"], sub.Stats.GetStat("TotalOverallHealingOverTime"))); stats.Add("PercentOfRegularHealingOverTime", new PercentStat("PercentOfRegularHealingOverTime", stats["RegularHealingOverTime"], sub.Stats.GetStat("RegularHealingOverTime"))); stats.Add("PercentOfCriticalHealingOverTime", new PercentStat("PercentOfCriticalHealingOverTime", stats["CriticalHealingOverTime"], sub.Stats.GetStat("CriticalHealingOverTime"))); break; case false: stats.Add("PercentOfTotalOverallHealingOverTime", new PercentStat("PercentOfTotalOverallHealingOverTime", stats["TotalOverallHealingOverTime"], this.Stats.GetStat("TotalOverallHealingOverTime"))); stats.Add("PercentOfRegularHealingOverTime", new PercentStat("PercentOfRegularHealingOverTime", stats["RegularHealingOverTime"], this.Stats.GetStat("RegularHealingOverTime"))); stats.Add("PercentOfCriticalHealingOverTime", new PercentStat("PercentOfCriticalHealingOverTime", stats["CriticalHealingOverTime"], this.Stats.GetStat("CriticalHealingOverTime"))); break; } return stats.Select(s => s.Value).ToList(); } /// <summary> /// </summary> /// <param name="sub"></param> /// <param name="useSub"></param> /// <returns></returns> private IEnumerable<Stat<double>> HealingStatList(StatGroup sub, bool useSub = false) { Dictionary<string, Stat<double>> stats = StatGeneration.HealingStats(); // setup per healing "percent of" stats switch (useSub) { case true: stats.Add("PercentOfTotalOverallHealing", new PercentStat("PercentOfTotalOverallHealing", stats["TotalOverallHealing"], sub.Stats.GetStat("TotalOverallHealing"))); stats.Add("PercentOfRegularHealing", new PercentStat("PercentOfRegularHealing", stats["RegularHealing"], sub.Stats.GetStat("RegularHealing"))); stats.Add("PercentOfCriticalHealing", new PercentStat("PercentOfCriticalHealing", stats["CriticalHealing"], sub.Stats.GetStat("CriticalHealing"))); break; case false: stats.Add("PercentOfTotalOverallHealing", new PercentStat("PercentOfTotalOverallHealing", stats["TotalOverallHealing"], this.Stats.GetStat("TotalOverallHealing"))); stats.Add("PercentOfRegularHealing", new PercentStat("PercentOfRegularHealing", stats["RegularHealing"], this.Stats.GetStat("RegularHealing"))); stats.Add("PercentOfCriticalHealing", new PercentStat("PercentOfCriticalHealing", stats["CriticalHealing"], this.Stats.GetStat("CriticalHealing"))); break; } return stats.Select(s => s.Value).ToList(); } private void InitStats() { this.Stats.AddStats(this.TotalStatList()); } private void IsActiveTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { try { if (!Controller.Timeline.FightingRightNow) { return; } this.Stats.GetStat("TotalParserTime").Value = Controller.EndTime.Subtract(Controller.StartTime).TotalSeconds; Stat<double> parserTime = this.Stats.GetStat("TotalParserTime"); Stat<double> activeTime = this.Stats.GetStat("TotalActiveTime"); var inactiveTime = DateTime.Now.Subtract(this.LastActionTime).TotalSeconds; if (inactiveTime > 5) { this.TotalInActiveTime++; } this.TotalInActiveTime = this.TotalInActiveTime > parserTime.Value ? parserTime.Value : this.TotalInActiveTime; activeTime.Value = parserTime.Value - this.TotalInActiveTime; } catch (Exception ex) { Logging.Log(Logger, new LogItem(ex, true)); } } private void StatusUpdateTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { if (this.StatusUpdateTimerProcessing) { return; } this.StatusUpdateTimerProcessing = true; List<ActorItem> monsterEntries = XIVInfoViewModel.Instance.CurrentMonsters.Select(entity => entity.Value).ToList(); List<ActorItem> pcEntries = XIVInfoViewModel.Instance.CurrentPCs.Select(entity => entity.Value).ToList(); this.StatusEntriesSelf.Clear(); this.StatusEntriesPlayers.Clear(); this.StatusEntriesMonsters.Clear(); if (pcEntries.Any()) { try { var cleanedName = Regex.Replace(this.Name, @"\[[\w]+\]", string.Empty).Trim(); var isYou = Regex.IsMatch(cleanedName, @"^(([Dd](ich|ie|u))|You|Vous)$") || string.Equals(cleanedName, Constants.CharacterName, Constants.InvariantComparer); var isPet = false; try { this.NPCEntry = isYou ? XIVInfoViewModel.Instance.CurrentUser : null; if (!isYou) { try { this.NPCEntry = pcEntries.First(p => string.Equals(p.Name, cleanedName, Constants.InvariantComparer)); } catch (Exception) { isPet = true; } } } catch (Exception) { } if (this.NPCEntry != null) { this.ID = this.NPCEntry.ID; if (this.ID > 0) { this.StatusEntriesSelf = this.NPCEntry.StatusItems; try { foreach (StatusItem statusEntry in monsterEntries.ToList().Where(p => p.HPCurrent > 0).SelectMany(monster => monster.StatusItems).Where(statusEntry => statusEntry.CasterID == this.ID)) { this.StatusEntriesMonsters.Add(statusEntry); } } catch (Exception ex) { Logging.Log(Logger, new LogItem(ex, true)); } try { foreach (StatusItem statusEntry in pcEntries.ToList().Where(p => p.HPCurrent > 0).SelectMany(pc => pc.StatusItems).Where(statusEntry => statusEntry.CasterID == this.ID)) { this.StatusEntriesPlayers.Add(statusEntry); } } catch (Exception ex) { Logging.Log(Logger, new LogItem(ex, true)); } } } } catch (Exception ex) { Logging.Log(Logger, new LogItem(ex, true)); } } if (!this.StatusEntriesMonsters.Any() && !this.StatusEntriesPlayers.Any()) { this.StatusUpdateTimerProcessing = false; return; } if (this.StatusEntriesMonsters.Any()) { this.ProcessDamageOverTime(this.StatusEntriesMonsters); } if (this.StatusEntriesPlayers.Any()) { this.ProcessHealingOverTime(this.StatusEntriesPlayers); this.ProcessBuffs(this.StatusEntriesPlayers); } this.StatusUpdateTimerProcessing = false; } /// <summary> /// </summary> /// <returns> </returns> private IEnumerable<Stat<double>> TotalStatList() { Dictionary<string, Stat<double>> stats = new Dictionary<string, Stat<double>>(); stats.Add("TotalActiveTime", new TotalStat("TotalActiveTime")); stats.Add("TotalParserTime", new TotalStat("TotalParserTime")); // setup player ability stats foreach (KeyValuePair<string, Stat<double>> damageStat in StatGeneration.DamageStats()) { stats.Add(damageStat.Key, damageStat.Value); } foreach (KeyValuePair<string, Stat<double>> damageStat in StatGeneration.DamageOverTimeStats()) { stats.Add(damageStat.Key, damageStat.Value); } // setup player healing stats foreach (KeyValuePair<string, Stat<double>> healingStat in StatGeneration.HealingStats()) { stats.Add(healingStat.Key, healingStat.Value); } foreach (KeyValuePair<string, Stat<double>> healingStat in StatGeneration.HealingOverHealingStats()) { stats.Add(healingStat.Key, healingStat.Value); } foreach (KeyValuePair<string, Stat<double>> healingStat in StatGeneration.HealingOverTimeStats()) { stats.Add(healingStat.Key, healingStat.Value); } foreach (KeyValuePair<string, Stat<double>> healingStat in StatGeneration.HealingMitigatedStats()) { stats.Add(healingStat.Key, healingStat.Value); } // setup player damage taken stats foreach (KeyValuePair<string, Stat<double>> damageTakenStat in StatGeneration.DamageTakenStats()) { stats.Add(damageTakenStat.Key, damageTakenStat.Value); } foreach (KeyValuePair<string, Stat<double>> damageTakenStat in StatGeneration.DamageTakenOverTimeStats()) { stats.Add(damageTakenStat.Key, damageTakenStat.Value); } // setup player buff stats foreach (KeyValuePair<string, Stat<double>> buffStat in StatGeneration.BuffStats()) { stats.Add(buffStat.Key, buffStat.Value); } // setup combined stats foreach (KeyValuePair<string, Stat<double>> combinedStat in StatGeneration.CombinedStats()) { stats.Add(combinedStat.Key, combinedStat.Value); } // link to main party stats Dictionary<string, Stat<double>> oStats = Controller.Timeline.Overall.Stats.ToDictionary(o => o.Name); ((TotalStat) oStats["TotalOverallDamage"]).AddDependency(stats["TotalOverallDamage"]); ((TotalStat) oStats["RegularDamage"]).AddDependency(stats["RegularDamage"]); ((TotalStat) oStats["CriticalDamage"]).AddDependency(stats["CriticalDamage"]); ((TotalStat) oStats["TotalOverallDamageOverTime"]).AddDependency(stats["TotalOverallDamageOverTime"]); ((TotalStat) oStats["RegularDamageOverTime"]).AddDependency(stats["RegularDamageOverTime"]); ((TotalStat) oStats["CriticalDamageOverTime"]).AddDependency(stats["CriticalDamageOverTime"]); #region Healing ((TotalStat) oStats["TotalOverallHealing"]).AddDependency(stats["TotalOverallHealing"]); ((TotalStat) oStats["RegularHealing"]).AddDependency(stats["RegularHealing"]); ((TotalStat) oStats["CriticalHealing"]).AddDependency(stats["CriticalHealing"]); ((TotalStat) oStats["TotalOverallHealingOverHealing"]).AddDependency(stats["TotalOverallHealingOverHealing"]); ((TotalStat) oStats["RegularHealingOverHealing"]).AddDependency(stats["RegularHealingOverHealing"]); ((TotalStat) oStats["CriticalHealingOverHealing"]).AddDependency(stats["CriticalHealingOverHealing"]); ((TotalStat) oStats["TotalOverallHealingOverTime"]).AddDependency(stats["TotalOverallHealingOverTime"]); ((TotalStat) oStats["RegularHealingOverTime"]).AddDependency(stats["RegularHealingOverTime"]); ((TotalStat) oStats["CriticalHealingOverTime"]).AddDependency(stats["CriticalHealingOverTime"]); ((TotalStat) oStats["TotalOverallHealingMitigated"]).AddDependency(stats["TotalOverallHealingMitigated"]); ((TotalStat) oStats["RegularHealingMitigated"]).AddDependency(stats["RegularHealingMitigated"]); ((TotalStat) oStats["CriticalHealingMitigated"]).AddDependency(stats["CriticalHealingMitigated"]); #endregion Healing #region Damage Taken ((TotalStat) oStats["TotalOverallDamageTaken"]).AddDependency(stats["TotalOverallDamageTaken"]); ((TotalStat) oStats["RegularDamageTaken"]).AddDependency(stats["RegularDamageTaken"]); ((TotalStat) oStats["CriticalDamageTaken"]).AddDependency(stats["CriticalDamageTaken"]); ((TotalStat) oStats["TotalOverallDamageTakenOverTime"]).AddDependency(stats["TotalOverallDamageTakenOverTime"]); ((TotalStat) oStats["RegularDamageTakenOverTime"]).AddDependency(stats["RegularDamageTakenOverTime"]); ((TotalStat) oStats["CriticalDamageTakenOverTime"]).AddDependency(stats["CriticalDamageTakenOverTime"]); #endregion Damage Taken #region Global Percent Of Total Stats // damage stats.Add("PercentOfTotalOverallDamage", new PercentStat("PercentOfTotalOverallDamage", stats["TotalOverallDamage"], (TotalStat) oStats["TotalOverallDamage"])); stats.Add("PercentOfRegularDamage", new PercentStat("PercentOfRegularDamage", stats["RegularDamage"], (TotalStat) oStats["RegularDamage"])); stats.Add("PercentOfCriticalDamage", new PercentStat("PercentOfCriticalDamage", stats["CriticalDamage"], (TotalStat) oStats["CriticalDamage"])); stats.Add("PercentOfTotalOverallDamageOverTime", new PercentStat("PercentOfTotalOverallDamageOverTime", stats["TotalOverallDamageOverTime"], (TotalStat) oStats["TotalOverallDamageOverTime"])); stats.Add("PercentOfRegularDamageOverTime", new PercentStat("PercentOfRegularDamageOverTime", stats["RegularDamageOverTime"], (TotalStat) oStats["RegularDamageOverTime"])); stats.Add("PercentOfCriticalDamageOverTime", new PercentStat("PercentOfCriticalDamageOverTime", stats["CriticalDamageOverTime"], (TotalStat) oStats["CriticalDamageOverTime"])); // healing stats.Add("PercentOfTotalOverallHealing", new PercentStat("PercentOfTotalOverallHealing", stats["TotalOverallHealing"], (TotalStat) oStats["TotalOverallHealing"])); stats.Add("PercentOfRegularHealing", new PercentStat("PercentOfRegularHealing", stats["RegularHealing"], (TotalStat) oStats["RegularHealing"])); stats.Add("PercentOfCriticalHealing", new PercentStat("PercentOfCriticalHealing", stats["CriticalHealing"], (TotalStat) oStats["CriticalHealing"])); stats.Add("PercentOfTotalOverallHealingOverHealing", new PercentStat("PercentOfTotalOverallHealingOverHealing", stats["TotalOverallHealingOverHealing"], (TotalStat) oStats["TotalOverallHealingOverHealing"])); stats.Add("PercentOfRegularHealingOverHealing", new PercentStat("PercentOfRegularHealingOverHealing", stats["RegularHealingOverHealing"], (TotalStat) oStats["RegularHealingOverHealing"])); stats.Add("PercentOfCriticalHealingOverHealing", new PercentStat("PercentOfCriticalHealingOverHealing", stats["CriticalHealingOverHealing"], (TotalStat) oStats["CriticalHealingOverHealing"])); stats.Add("PercentOfTotalOverallHealingOverTime", new PercentStat("PercentOfTotalOverallHealingOverTime", stats["TotalOverallHealingOverTime"], (TotalStat) oStats["TotalOverallHealingOverTime"])); stats.Add("PercentOfRegularHealingOverTime", new PercentStat("PercentOfRegularHealingOverTime", stats["RegularHealingOverTime"], (TotalStat) oStats["RegularHealingOverTime"])); stats.Add("PercentOfCriticalHealingOverTime", new PercentStat("PercentOfCriticalHealingOverTime", stats["CriticalHealingOverTime"], (TotalStat) oStats["CriticalHealingOverTime"])); stats.Add("PercentOfTotalOverallHealingMitigated", new PercentStat("PercentOfTotalOverallHealingMitigated", stats["TotalOverallHealingMitigated"], (TotalStat) oStats["TotalOverallHealingMitigated"])); stats.Add("PercentOfRegularHealingMitigated", new PercentStat("PercentOfRegularHealingMitigated", stats["RegularHealingMitigated"], (TotalStat) oStats["RegularHealingMitigated"])); stats.Add("PercentOfCriticalHealingMitigated", new PercentStat("PercentOfCriticalHealingMitigated", stats["CriticalHealingMitigated"], (TotalStat) oStats["CriticalHealingMitigated"])); // damage taken stats.Add("PercentOfTotalOverallDamageTaken", new PercentStat("PercentOfTotalOverallDamageTaken", stats["TotalOverallDamageTaken"], (TotalStat) oStats["TotalOverallDamageTaken"])); stats.Add("PercentOfRegularDamageTaken", new PercentStat("PercentOfRegularDamageTaken", stats["RegularDamageTaken"], (TotalStat) oStats["RegularDamageTaken"])); stats.Add("PercentOfCriticalDamageTaken", new PercentStat("PercentOfCriticalDamageTaken", stats["CriticalDamageTaken"], (TotalStat) oStats["CriticalDamageTaken"])); stats.Add("PercentOfTotalOverallDamageTakenOverTime", new PercentStat("PercentOfTotalOverallDamageTakenOverTime", stats["TotalOverallDamageTakenOverTime"], (TotalStat) oStats["TotalOverallDamageTakenOverTime"])); stats.Add("PercentOfRegularDamageTakenOverTime", new PercentStat("PercentOfRegularDamageTakenOverTime", stats["RegularDamageTakenOverTime"], (TotalStat) oStats["RegularDamageTakenOverTime"])); stats.Add("PercentOfCriticalDamageTakenOverTime", new PercentStat("PercentOfCriticalDamageTakenOverTime", stats["CriticalDamageTakenOverTime"], (TotalStat) oStats["CriticalDamageTakenOverTime"])); #endregion Global Percent Of Total Stats #region Player Combined // ((TotalStat) stats["CombinedTotalOverallDamage"]).AddDependency(stats["TotalOverallDamage"]); // ((TotalStat) stats["CombinedTotalOverallDamage"]).AddDependency(stats["TotalOverallDamageOverTime"]); // ((TotalStat) stats["CombinedCriticalDamage"]).AddDependency(stats["CriticalDamage"]); // ((TotalStat) stats["CombinedRegularDamage"]).AddDependency(stats["RegularDamage"]); // ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealing"]); // ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealingOverTime"]); // ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealingMitigated"]); // ((TotalStat) stats["CombinedCriticalHealing"]).AddDependency(stats["CriticalHealing"]); // ((TotalStat) stats["CombinedRegularHealing"]).AddDependency(stats["RegularHealing"]); // ((TotalStat) stats["CombinedTotalOverallDamageTaken"]).AddDependency(stats["TotalOverallDamageTaken"]); // ((TotalStat) stats["CombinedTotalOverallDamageTaken"]).AddDependency(stats["TotalOverallDamageTakenOverTime"]); // ((TotalStat) stats["CombinedCriticalDamageTaken"]).AddDependency(stats["CriticalDamageTaken"]); // ((TotalStat) stats["CombinedRegularDamageTaken"]).AddDependency(stats["RegularDamageTaken"]); ((TotalStat) stats["CombinedTotalOverallDamage"]).AddDependency(stats["TotalOverallDamage"]); ((TotalStat) stats["CombinedRegularDamage"]).AddDependency(stats["RegularDamage"]); ((TotalStat) stats["CombinedCriticalDamage"]).AddDependency(stats["CriticalDamage"]); ((MinStat) stats["CombinedDamageRegLow"]).AddDependency(stats["DamageRegLow"]); ((MaxStat) stats["CombinedDamageRegHigh"]).AddDependency(stats["DamageRegHigh"]); ((AverageStat) stats["CombinedDamageRegAverage"]).AddDependency(stats["DamageRegAverage"]); ((TotalStat) stats["CombinedDamageRegMod"]).AddDependency(stats["DamageRegMod"]); ((AverageStat) stats["CombinedDamageRegModAverage"]).AddDependency(stats["DamageRegModAverage"]); ((MinStat) stats["CombinedDamageCritLow"]).AddDependency(stats["DamageCritLow"]); ((MaxStat) stats["CombinedDamageCritHigh"]).AddDependency(stats["DamageCritHigh"]); ((AverageStat) stats["CombinedDamageCritAverage"]).AddDependency(stats["DamageCritAverage"]); ((TotalStat) stats["CombinedDamageCritMod"]).AddDependency(stats["DamageCritMod"]); ((AverageStat) stats["CombinedDamageCritModAverage"]).AddDependency(stats["DamageCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallDamage"]).AddDependency(stats["TotalOverallDamageOverTime"]); ((TotalStat) stats["CombinedRegularDamage"]).AddDependency(stats["RegularDamageOverTime"]); ((TotalStat) stats["CombinedCriticalDamage"]).AddDependency(stats["CriticalDamageOverTime"]); ((MinStat) stats["CombinedDamageRegLow"]).AddDependency(stats["DamageOverTimeRegLow"]); ((MaxStat) stats["CombinedDamageRegHigh"]).AddDependency(stats["DamageOverTimeRegHigh"]); ((AverageStat) stats["CombinedDamageRegAverage"]).AddDependency(stats["DamageOverTimeRegAverage"]); ((TotalStat) stats["CombinedDamageRegMod"]).AddDependency(stats["DamageOverTimeRegMod"]); ((AverageStat) stats["CombinedDamageRegModAverage"]).AddDependency(stats["DamageOverTimeRegModAverage"]); ((MinStat) stats["CombinedDamageCritLow"]).AddDependency(stats["DamageOverTimeCritLow"]); ((MaxStat) stats["CombinedDamageCritHigh"]).AddDependency(stats["DamageOverTimeCritHigh"]); ((AverageStat) stats["CombinedDamageCritAverage"]).AddDependency(stats["DamageOverTimeCritAverage"]); ((TotalStat) stats["CombinedDamageCritMod"]).AddDependency(stats["DamageOverTimeCritMod"]); ((AverageStat) stats["CombinedDamageCritModAverage"]).AddDependency(stats["DamageOverTimeCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealing"]); ((TotalStat) stats["CombinedRegularHealing"]).AddDependency(stats["RegularHealing"]); ((TotalStat) stats["CombinedCriticalHealing"]).AddDependency(stats["CriticalHealing"]); ((MinStat) stats["CombinedHealingRegLow"]).AddDependency(stats["HealingRegLow"]); ((MaxStat) stats["CombinedHealingRegHigh"]).AddDependency(stats["HealingRegHigh"]); ((AverageStat) stats["CombinedHealingRegAverage"]).AddDependency(stats["HealingRegAverage"]); ((TotalStat) stats["CombinedHealingRegMod"]).AddDependency(stats["HealingRegMod"]); ((AverageStat) stats["CombinedHealingRegModAverage"]).AddDependency(stats["HealingRegModAverage"]); ((MinStat) stats["CombinedHealingCritLow"]).AddDependency(stats["HealingCritLow"]); ((MaxStat) stats["CombinedHealingCritHigh"]).AddDependency(stats["HealingCritHigh"]); ((AverageStat) stats["CombinedHealingCritAverage"]).AddDependency(stats["HealingCritAverage"]); ((TotalStat) stats["CombinedHealingCritMod"]).AddDependency(stats["HealingCritMod"]); ((AverageStat) stats["CombinedHealingCritModAverage"]).AddDependency(stats["HealingCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealingOverTime"]); ((TotalStat) stats["CombinedRegularHealing"]).AddDependency(stats["RegularHealingOverTime"]); ((TotalStat) stats["CombinedCriticalHealing"]).AddDependency(stats["CriticalHealingOverTime"]); ((MinStat) stats["CombinedHealingRegLow"]).AddDependency(stats["HealingOverTimeRegLow"]); ((MaxStat) stats["CombinedHealingRegHigh"]).AddDependency(stats["HealingOverTimeRegHigh"]); ((AverageStat) stats["CombinedHealingRegAverage"]).AddDependency(stats["HealingOverTimeRegAverage"]); ((TotalStat) stats["CombinedHealingRegMod"]).AddDependency(stats["HealingOverTimeRegMod"]); ((AverageStat) stats["CombinedHealingRegModAverage"]).AddDependency(stats["HealingOverTimeRegModAverage"]); ((MinStat) stats["CombinedHealingCritLow"]).AddDependency(stats["HealingOverTimeCritLow"]); ((MaxStat) stats["CombinedHealingCritHigh"]).AddDependency(stats["HealingOverTimeCritHigh"]); ((AverageStat) stats["CombinedHealingCritAverage"]).AddDependency(stats["HealingOverTimeCritAverage"]); ((TotalStat) stats["CombinedHealingCritMod"]).AddDependency(stats["HealingOverTimeCritMod"]); ((AverageStat) stats["CombinedHealingCritModAverage"]).AddDependency(stats["HealingOverTimeCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallHealing"]).AddDependency(stats["TotalOverallHealingMitigated"]); ((TotalStat) stats["CombinedRegularHealing"]).AddDependency(stats["RegularHealingMitigated"]); ((TotalStat) stats["CombinedCriticalHealing"]).AddDependency(stats["CriticalHealingMitigated"]); ((MinStat) stats["CombinedHealingRegLow"]).AddDependency(stats["HealingMitigatedRegLow"]); ((MaxStat) stats["CombinedHealingRegHigh"]).AddDependency(stats["HealingMitigatedRegHigh"]); ((AverageStat) stats["CombinedHealingRegAverage"]).AddDependency(stats["HealingMitigatedRegAverage"]); ((TotalStat) stats["CombinedHealingRegMod"]).AddDependency(stats["HealingMitigatedRegMod"]); ((AverageStat) stats["CombinedHealingRegModAverage"]).AddDependency(stats["HealingMitigatedRegModAverage"]); ((MinStat) stats["CombinedHealingCritLow"]).AddDependency(stats["HealingMitigatedCritLow"]); ((MaxStat) stats["CombinedHealingCritHigh"]).AddDependency(stats["HealingMitigatedCritHigh"]); ((AverageStat) stats["CombinedHealingCritAverage"]).AddDependency(stats["HealingMitigatedCritAverage"]); ((TotalStat) stats["CombinedHealingCritMod"]).AddDependency(stats["HealingMitigatedCritMod"]); ((AverageStat) stats["CombinedHealingCritModAverage"]).AddDependency(stats["HealingMitigatedCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallDamageTaken"]).AddDependency(stats["TotalOverallDamageTaken"]); ((TotalStat) stats["CombinedRegularDamageTaken"]).AddDependency(stats["RegularDamageTaken"]); ((TotalStat) stats["CombinedCriticalDamageTaken"]).AddDependency(stats["CriticalDamageTaken"]); ((MinStat) stats["CombinedDamageTakenRegLow"]).AddDependency(stats["DamageTakenRegLow"]); ((MaxStat) stats["CombinedDamageTakenRegHigh"]).AddDependency(stats["DamageTakenRegHigh"]); ((AverageStat) stats["CombinedDamageTakenRegAverage"]).AddDependency(stats["DamageTakenRegAverage"]); ((TotalStat) stats["CombinedDamageTakenRegMod"]).AddDependency(stats["DamageTakenRegMod"]); ((AverageStat) stats["CombinedDamageTakenRegModAverage"]).AddDependency(stats["DamageTakenRegModAverage"]); ((MinStat) stats["CombinedDamageTakenCritLow"]).AddDependency(stats["DamageTakenCritLow"]); ((MaxStat) stats["CombinedDamageTakenCritHigh"]).AddDependency(stats["DamageTakenCritHigh"]); ((AverageStat) stats["CombinedDamageTakenCritAverage"]).AddDependency(stats["DamageTakenCritAverage"]); ((TotalStat) stats["CombinedDamageTakenCritMod"]).AddDependency(stats["DamageTakenCritMod"]); ((AverageStat) stats["CombinedDamageTakenCritModAverage"]).AddDependency(stats["DamageTakenCritModAverage"]); ((TotalStat) stats["CombinedTotalOverallDamageTaken"]).AddDependency(stats["TotalOverallDamageTakenOverTime"]); ((TotalStat) stats["CombinedRegularDamageTaken"]).AddDependency(stats["RegularDamageTakenOverTime"]); ((TotalStat) stats["CombinedCriticalDamageTaken"]).AddDependency(stats["CriticalDamageTakenOverTime"]); ((MinStat) stats["CombinedDamageTakenRegLow"]).AddDependency(stats["DamageTakenOverTimeRegLow"]); ((MaxStat) stats["CombinedDamageTakenRegHigh"]).AddDependency(stats["DamageTakenOverTimeRegHigh"]); ((AverageStat) stats["CombinedDamageTakenRegAverage"]).AddDependency(stats["DamageTakenOverTimeRegAverage"]); ((TotalStat) stats["CombinedDamageTakenRegMod"]).AddDependency(stats["DamageTakenOverTimeRegMod"]); ((AverageStat) stats["CombinedDamageTakenRegModAverage"]).AddDependency(stats["DamageTakenOverTimeRegModAverage"]); ((MinStat) stats["CombinedDamageTakenCritLow"]).AddDependency(stats["DamageTakenOverTimeCritLow"]); ((MaxStat) stats["CombinedDamageTakenCritHigh"]).AddDependency(stats["DamageTakenOverTimeCritHigh"]); ((AverageStat) stats["CombinedDamageTakenCritAverage"]).AddDependency(stats["DamageTakenOverTimeCritAverage"]); ((TotalStat) stats["CombinedDamageTakenCritMod"]).AddDependency(stats["DamageTakenOverTimeCritMod"]); ((AverageStat) stats["CombinedDamageTakenCritModAverage"]).AddDependency(stats["DamageTakenOverTimeCritModAverage"]); ((PerSecondAverageStat) stats["CombinedDPS"]).AddDependency(stats["CombinedTotalOverallDamage"]); ((PerSecondAverageStat) stats["CombinedHPS"]).AddDependency(stats["CombinedTotalOverallHealing"]); ((PerSecondAverageStat) stats["CombinedDTPS"]).AddDependency(stats["CombinedTotalOverallDamageTaken"]); #endregion Player Combined #region Global Combined ((TotalStat) oStats["CombinedTotalOverallDamage"]).AddDependency(stats["CombinedTotalOverallDamage"]); ((TotalStat) oStats["CombinedRegularDamage"]).AddDependency(stats["CombinedRegularDamage"]); ((TotalStat) oStats["CombinedCriticalDamage"]).AddDependency(stats["CombinedCriticalDamage"]); ((TotalStat) oStats["CombinedTotalOverallHealing"]).AddDependency(stats["CombinedTotalOverallHealing"]); ((TotalStat) oStats["CombinedRegularHealing"]).AddDependency(stats["CombinedRegularHealing"]); ((TotalStat) oStats["CombinedCriticalHealing"]).AddDependency(stats["CombinedCriticalHealing"]); ((TotalStat) oStats["CombinedTotalOverallDamageTaken"]).AddDependency(stats["CombinedTotalOverallDamageTaken"]); ((TotalStat) oStats["CombinedRegularDamageTaken"]).AddDependency(stats["CombinedRegularDamageTaken"]); ((TotalStat) oStats["CombinedCriticalDamageTaken"]).AddDependency(stats["CombinedCriticalDamageTaken"]); #endregion Global Combined stats.Add("ActivePercent", new PercentStat("ActivePercent", stats["TotalActiveTime"], stats["TotalParserTime"])); return stats.Select(s => s.Value).ToList(); } } }
65.690577
232
0.660879
[ "MIT" ]
FFXIVAPP/ffxivapp-plugin-parse
FFXIVAPP.Plugin.Parse/Models/StatGroups/Player.cs
46,709
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Domainvalue { public interface MucosalAbsorptionRoute : Code { } }
37.892857
83
0.713478
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Domainvalue/MucosalAbsorptionRoute.cs
1,061
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Reflection; using NLog.Internal; /// <summary> /// Default implementation of <see cref="IPropertyTypeConverter"/> /// </summary> internal class PropertyTypeConverter : IPropertyTypeConverter { /// <summary> /// Singleton instance of the serializer. /// </summary> public static PropertyTypeConverter Instance { get; } = new PropertyTypeConverter(); private static Dictionary<Type, Func<string, string, IFormatProvider, object>> StringConverterLookup => _stringConverters ?? (_stringConverters = BuildStringConverterLookup()); private static Dictionary<Type, Func<string, string, IFormatProvider, object>> _stringConverters; private static Dictionary<Type, Func<string, string, IFormatProvider, object>> BuildStringConverterLookup() { return new Dictionary<Type, Func<string, string, IFormatProvider, object>>() { { typeof(System.Text.Encoding), (stringvalue, format, formatProvider) => ConvertToEncoding(stringvalue) }, { typeof(System.Globalization.CultureInfo), (stringvalue, format, formatProvider) => new System.Globalization.CultureInfo(stringvalue) }, { typeof(Type), (stringvalue, format, formatProvider) => Type.GetType(stringvalue, true) }, { typeof(NLog.Targets.LineEndingMode), (stringvalue, format, formatProvider) => NLog.Targets.LineEndingMode.FromString(stringvalue) }, { typeof(LogLevel), (stringvalue, format, formatProvider) => LogLevel.FromString(stringvalue) }, { typeof(Uri), (stringvalue, format, formatProvider) => new Uri(stringvalue) }, { typeof(DateTime), (stringvalue, format, formatProvider) => ConvertToDateTime(format, formatProvider, stringvalue) }, { typeof(DateTimeOffset), (stringvalue, format, formatProvider) => ConvertToDateTimeOffset(format, formatProvider, stringvalue) }, { typeof(TimeSpan), (stringvalue, format, formatProvider) => ConvertToTimeSpan(format, formatProvider, stringvalue) }, { typeof(Guid), (stringvalue, format, formatProvider) => ConvertGuid(format, stringvalue) }, }; } internal static bool IsComplexType(Type type) { return !type.IsValueType() && !typeof(IConvertible).IsAssignableFrom(type) && !StringConverterLookup.ContainsKey(type) && type.GetFirstCustomAttribute<System.ComponentModel.TypeConverterAttribute>() is null; } /// <inheritdoc/> public object Convert(object propertyValue, Type propertyType, string format, IFormatProvider formatProvider) { if (propertyValue is null || propertyType is null || propertyType == typeof(object)) { return propertyValue; // No type conversion required } var propertyValueType = propertyValue.GetType(); if (propertyType.Equals(propertyValueType)) { return propertyValue; // Same type } var nullableType = Nullable.GetUnderlyingType(propertyType); if (nullableType != null) { if (nullableType.Equals(propertyValueType)) { return propertyValue; // Same type } if (propertyValue is string propertyString && StringHelpers.IsNullOrWhiteSpace(propertyString)) { return null; } propertyType = nullableType; } return ChangeObjectType(propertyValue, propertyType, format, formatProvider); } private static bool TryConvertFromString(string propertyString, Type propertyType, string format, IFormatProvider formatProvider, out object propertyValue) { propertyValue = propertyString = propertyString.Trim(); if (StringConverterLookup.TryGetValue(propertyType, out var converter)) { propertyValue = converter.Invoke(propertyString, format, formatProvider); return true; } if (propertyType.IsEnum() && NLog.Common.ConversionHelpers.TryParseEnum(propertyString, propertyType, out var enumValue)) { propertyValue = enumValue; return true; } if (!typeof(IConvertible).IsAssignableFrom(propertyType) && PropertyHelper.TryTypeConverterConversion(propertyType, propertyString, out var convertedValue)) { propertyValue = convertedValue; return true; } return false; } private static object ChangeObjectType(object propertyValue, Type propertyType, string format, IFormatProvider formatProvider) { if (propertyValue is string propertyString && TryConvertFromString(propertyString, propertyType, format, formatProvider, out propertyValue)) { return propertyValue; } if (propertyValue is IConvertible convertibleValue) { var typeCode = convertibleValue.GetTypeCode(); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (typeCode == TypeCode.DBNull) return convertibleValue; #endif if (typeCode == TypeCode.Empty) return null; } else { var logConverter = System.ComponentModel.TypeDescriptor.GetConverter(propertyValue.GetType()); if (logConverter != null && logConverter.CanConvertTo(propertyType)) { return logConverter.ConvertTo(propertyValue, propertyType); } } if (!string.IsNullOrEmpty(format) && propertyValue is IFormattable formattableValue) { propertyValue = formattableValue.ToString(format, formatProvider); } return System.Convert.ChangeType(propertyValue, propertyType, formatProvider); } private static object ConvertGuid(string format, string propertyString) { #if !NET35 return string.IsNullOrEmpty(format) ? Guid.Parse(propertyString) : Guid.ParseExact(propertyString, format); #else return new Guid(propertyString); #endif } private static object ConvertToEncoding(string stringValue) { stringValue = stringValue.Trim(); if (string.Equals(stringValue, nameof(System.Text.Encoding.UTF8), StringComparison.OrdinalIgnoreCase)) stringValue = System.Text.Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8) return System.Text.Encoding.GetEncoding(stringValue); } private static object ConvertToTimeSpan(string format, IFormatProvider formatProvider, string propertyString) { #if !NET35 if (!string.IsNullOrEmpty(format)) return TimeSpan.ParseExact(propertyString, format, formatProvider); return TimeSpan.Parse(propertyString, formatProvider); #else return TimeSpan.Parse(propertyString); #endif } private static object ConvertToDateTimeOffset(string format, IFormatProvider formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) return DateTimeOffset.ParseExact(propertyString, format, formatProvider); return DateTimeOffset.Parse(propertyString, formatProvider); } private static object ConvertToDateTime(string format, IFormatProvider formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) return DateTime.ParseExact(propertyString, format, formatProvider); return DateTime.Parse(propertyString, formatProvider); } } }
46.109005
219
0.654332
[ "BSD-3-Clause" ]
304NotModified/NLog
src/NLog/Config/PropertyTypeConverter.cs
9,729
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace computegen { class JavascriptClient : ComputeClient { protected override string Prefix { get { return @"var RhinoCompute = { version: '" + Version + @"', url: 'https://compute.rhino3d.com/', authToken: null, apiKey: null, getAuthToken: function (useLocalStorage=true) { let auth = null if (useLocalStorage) auth = localStorage['compute_auth'] if (auth == null) { auth = window.prompt('Rhino Accounts auth token\nVisit https://www.rhino3d.com/compute/login') if (auth != null && auth.length>20) { auth = 'Bearer ' + auth localStorage.setItem('compute_auth', auth) } } return auth }, computeFetch: function(endpoint, arglist, returnJson=true) { let request = { 'method':'POST', 'body': JSON.stringify(arglist), 'headers': {'User-Agent': `compute.rhino3d.js/${RhinoCompute.version}`} } if (RhinoCompute.authToken) { request.headers['Authorization'] = RhinoCompute.authToken } if (RhinoCompute.apiKey) { request.headers['RhinoComputeKey'] = RhinoCompute.apiKey } let p = fetch(RhinoCompute.url+endpoint, request) if (returnJson) return p.then(r=>r.json()) return p }, Grasshopper: { DataTree: class { constructor (name) { this.data = { 'ParamName': name, 'InnerTree': {} } } /** * Append a path to this tree * @param path (arr): a list of integers defining a path * @param items (arr): list of data to add to the tree */ append (path, items) { let key = path.join(';') let innerTreeData = [] items.forEach(item => { innerTreeData.push({ 'data': item }) }) this.data.InnerTree[key] = innerTreeData } }, /** * Evaluate a grasshopper definition * @param definition (str|bytearray) contents of .gh/.ghx file or * url pointing to a grasshopper definition file * @param trees (arr) list of DataTree instances * @param returnJson (bool) if true, return a Promise with json data * otherwise a Promise with Response data */ evaluateDefinition : function (definition, trees, returnJson=true) { let args = { 'algo': null, 'pointer': null, 'values': null } if (definition.constructor === Uint8Array) { args['algo'] = base64ByteArray(definition) } else { if (definition.startsWith('http')) { args['pointer'] = definition } else { args['algo'] = btoa(definition) } } let values = [] trees.forEach(tree => { values.push(tree.data) }) args['values'] = values return RhinoCompute.computeFetch('grasshopper', args, returnJson) } }, zipArgs: function(multiple, ...args) { if (!multiple) return args if (args.length==1) return args[0].map(function(_,i) { return [args[0][i]] }) if (args.length==2) return args[0].map(function(_,i) { return [args[0][i],args[1][i]] }) if (args.length==3) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i]] } ) if (args.length==4) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i],args[3][i]] } ) if (args.length==5) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i],args[3][i],args[4][i]] } ) if (args.length==6) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i],args[3][i],args[4][i],args[5][i]] } ) if (args.length==7) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i],args[3][i],args[4][i],args[5][i],args[6][i]] } ) return args[0].map(function(_,i) { return [args[0][i],args[1][i],args[2][i],args[3][i],args[4][i],args[5][i],args[6][i],args[7][i]] } ) }, "; } } protected override string Suffix { get { return @" Python: { pythonEvaluate : function(script, input, output){ let inputEncoded = rhino3dm.ArchivableDictionary.encodeDict(input) let url = 'rhino/python/evaluate' let args = [script, JSON.stringify(inputEncoded), output] let result = RhinoCompute.computeFetch(url, args) let objects = rhino3dm.ArchivableDictionary.decodeDict(JSON.parse(result)) return objects } } } // https://gist.github.com/jonleighton/958841 /* MIT LICENSE Copyright 2011 Jon Leighton 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. */ function base64ByteArray(bytes) { var base64 = '' var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' // var bytes = new Uint8Array(arrayBuffer) // strip bom if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) bytes = bytes.slice(3) var byteLength = bytes.byteLength var byteRemainder = byteLength % 3 var mainLength = byteLength - byteRemainder var a, b, c, d var chunk // Main loop deals with bytes in chunks of 3 for (var i = 0; i < mainLength; i = i + 3) { // Combine the three bytes into a single integer chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2] // Use bitmasks to extract 6-bit segments from the triplet a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18 b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12 c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6 d = chunk & 63 // 63 = 2^6 - 1 // Convert the raw binary segments to the appropriate ASCII encoding base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d] } // Deal with the remaining bytes and padding if (byteRemainder == 1) { chunk = bytes[mainLength] a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2 // Set the 4 least significant bits to zero b = (chunk & 3) << 4 // 3 = 2^2 - 1 base64 += encodings[a] + encodings[b] + '==' } else if (byteRemainder == 2) { chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1] a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10 b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4 // Set the 2 least significant bits to zero c = (chunk & 15) << 2 // 15 = 2^4 - 1 base64 += encodings[a] + encodings[b] + encodings[c] + '=' } return base64 } // NODE.JS // check if we're running in a browser or in node.js let _is_node = typeof exports === 'object' && typeof module === 'object' // polyfills if (_is_node && typeof require === 'function') { if (typeof fetch !== 'function') fetch = require('node-fetch') } // export RhinoCompute object if (_is_node) module.exports = RhinoCompute "; } } public static string GetMethodName(MethodDeclarationSyntax method, ClassBuilder c) { return CamelCase(PythonClient.GetMethodName(method, c)); } protected override int TabSize => 2; protected override string ToComputeClient(ClassBuilder cb) { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine($"{T1}{cb.ClassName} : {{"); int iMethod = 0; foreach (var (method, comment) in cb.Methods) { string methodName = GetMethodName(method, cb); if (string.IsNullOrWhiteSpace(methodName)) continue; sb.Append($"{T2}{methodName} : function("); List<string> parameters = new List<string>(); for (int i = 0; i < method.ParameterList.Parameters.Count; i++) { bool isOutParamter = false; foreach (var modifier in method.ParameterList.Parameters[i].Modifiers) { if (modifier.Text == "out") { isOutParamter = true; } } if(!isOutParamter) parameters.Add(method.ParameterList.Parameters[i].Identifier.ToString()); } if (!method.IsStatic()) { string paramName = cb.ClassName.ToLower(); // make sure this paramName is not already in the parameter list for(int i=0; i<parameters.Count; i++) { if( paramName.Equals(parameters[i],StringComparison.OrdinalIgnoreCase) ) { paramName = "_" + paramName; break; } } parameters.Insert(0, paramName); } for (int i = 0; i < parameters.Count; i++) { sb.Append(parameters[i]); if (i < (parameters.Count - 1)) sb.Append(", "); } sb.AppendLine(", multiple=false) {"); sb.AppendLine($"{T3}let url='{cb.EndPoint(method)}'"); sb.AppendLine($"{T3}if(multiple) url = url + '?multiple=true'"); sb.Append($"{T3}let args = RhinoCompute.zipArgs(multiple, "); for (int i = 0; i < parameters.Count; i++) { sb.Append(parameters[i]); if (i < (parameters.Count - 1)) sb.Append(", "); } sb.AppendLine(")"); string endpoint = method.Identifier.ToString(); sb.AppendLine($"{T3}let promise = RhinoCompute.computeFetch(url, args)"); sb.AppendLine($"{T3}return promise"); sb.AppendLine($"{T2}}},"); iMethod++; if (iMethod < cb.Methods.Count) sb.AppendLine(); } sb.AppendLine($"{T1}}},"); return sb.ToString(); } } }
35.043478
462
0.552995
[ "MIT" ]
DanielAbalde/compute.rhino3d
tools/computegen/JavascriptClient.cs
11,286
C#
// ***************************************************************************** // // © Component Factory Pty Ltd 2012 - 2019. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; namespace ContextualTabs { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
31.4
81
0.537155
[ "BSD-3-Clause" ]
anuprakash/Krypton-NET-5.472
Source/Krypton Ribbon Examples/Contextual Tabs/Program.cs
945
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codebuild-2016-10-06.normal.json service model. */ using Amazon.Runtime; namespace Amazon.CodeBuild.Model { /// <summary> /// Paginator for the ListReportGroups operation ///</summary> public interface IListReportGroupsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListReportGroupsResponse> Responses { get; } /// <summary> /// Enumerable containing all of the ReportGroups /// </summary> IPaginatedEnumerable<string> ReportGroups { get; } } } #endif
33
108
0.668939
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/_bcl45+netstandard/IListReportGroupsPaginator.cs
1,320
C#
using System; using Foundation; using ObjCRuntime; namespace FieldEnumTests { [Native] enum FooNIntEnum : long { Zero, One, Two } [Native] enum FooNUIntEnum : ulong { Zero, One, Two } enum FooSmartEnum { [Field ("ZeroSmartField", "__Internal")] Zero, [Field ("OneSmartField", "__Internal")] One, [Field ("TwoSmartField", "__Internal")] Two } enum FooIntEnum { Zero, One, Two } [BaseType (typeof (NSObject))] interface MyFooClass { [Field ("UIntField", "__Internal")] uint UIntField { get; set; } [Field ("ULongField", "__Internal")] ulong ULongField { get; set; } [Field ("LongField", "__Internal")] long LongField { get; set; } [Field ("NUIntField", "__Internal")] nuint NUIntField { get; set; } [Field ("NIntField", "__Internal")] nint NIntField { get; set; } [Field ("NIntField", "__Internal")] FooNIntEnum FooNIntField { get; set; } [Field ("NUIntField", "__Internal")] FooNUIntEnum FooNUIntField { get; set; } [Field ("FooSmartField", "__Internal")] FooSmartEnum FooSmartField { get; set; } [Field ("FooIntEnumField", "__Internal")] FooIntEnum FooIntEnumField { get; set; } } }
17.818182
43
0.64881
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
tests/generator/fieldenumtests.cs
1,176
C#
using System; namespace OpenRiaServices.Server { /// <summary> /// Attribute applied to a <see cref="DomainService"/> method to indicate that it is an update method. /// </summary> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class UpdateAttribute : Attribute { } }
27.866667
106
0.681818
[ "Apache-2.0" ]
Daniel-Svensson/OpenRiaServices
src/OpenRiaServices.Server/Framework/Data/UpdateAttribute.cs
420
C#
// Compiler options: -langversion:future using System; static class C { public static int Test (this int a, int b = 5, string s = "") { return a * 3 + b; } static T Foo<T> (T t, int a) { return t; } static void Lambda (Func<int, int> a) { a (6); } public static int Main () { if (2.Test () != 11) return 1; if (1.Test (b : 2) != 5) return 2; if (Foo ("n", a : 4) != "n") return 3; if (Foo (t : "x", a : 4) != "x") return 4; Lambda (a : (a) => 1); // Hoisted variable int var = 8; Lambda (a : (a) => var); Console.WriteLine ("ok"); return 0; } }
13.521739
62
0.495177
[ "Apache-2.0" ]
Sectoid/debian-mono
mcs/tests/gtest-named-01.cs
622
C#
namespace _02.Students_by_First_and_Last_Name { using System; using System.Collections.Generic; using System.Linq; public static class StudentNames { public static void Main() { var input = Console.ReadLine(); var result = new List<string>(); while (input != "END") { var tokens = input.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries).ToArray(); var first = tokens[0].ToLower()[0]; var second = tokens[1].ToLower()[0]; if (first.CompareTo(second) < 0) { result.Add(input); } input = Console.ReadLine(); } foreach (var res in result) { Console.WriteLine(res); } } } }
26.454545
103
0.474227
[ "MIT" ]
maio246/C-Advanced
Linq/02. Students by First and Last Name/StudentNames.cs
875
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Linq; using System.Threading.Tasks; namespace XLParser.Tests { [TestClass] // Visual Studio standard data sources where tried for this class, but it was found to be very slow public class DatasetTests { public TestContext TestContext { get; set; } private const int MaxParseErrors = 10; [TestMethod] [TestCategory("Slow")] public void EnronFormulasParseTest() { ParseCsvDataSet("data/enron/formulas.txt", "data/enron/knownfails.txt"); } [TestMethod] [TestCategory("Slow")] public void EusesFormulasParseTest() { ParseCsvDataSet("data/euses/formulas.txt", "data/euses/knownfails.txt"); } [TestMethod] public void ParseTestFormulasStructuredReferences() { ParseCsvDataSet("data/testformulas/structured_references.txt"); } [TestMethod] public void ParseTestFormulasUserContributed() { ParseCsvDataSet("data/testformulas/user_contributed.txt"); } private void ParseCsvDataSet(string filename, string knownFailsFile = null) { ISet<string> knownfails = new HashSet<string>(ReadFormulaCsv(knownFailsFile)); var parseErrors = 0; var lockObj = new object(); Parallel.ForEach(ReadFormulaCsv(filename), (formula, control, lineNumber) => { if (parseErrors > MaxParseErrors) { control.Stop(); return; } try { ParserTests.Test(formula); } catch (ArgumentException) { if (!knownfails.Contains(formula)) { lock (lockObj) { #if !_NETCORE_ TestContext.WriteLine($"Failed parsing line {lineNumber} <<{formula}>>"); #endif parseErrors++; } } } }); if (parseErrors > 0) { Assert.Fail("Parse Errors on file " + filename); } } private static IEnumerable<string> ReadFormulaCsv(string f) { return f == null ? new string[0] : File.ReadLines(f).Where(line => !string.IsNullOrWhiteSpace(line)).Select(UnQuote); } private static string UnQuote(string line) { return line.Length > 0 && line[0] == '"' ? line.Substring(1, line.Length - 2).Replace("\"\"", "\"") : line; } } }
31.387097
130
0.511134
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
androdev4u/XLParser
src/XLParser.Tests/DatasetTests.cs
2,829
C#
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using Microsoft.Extensions.Logging; namespace Silverback.Diagnostics { /// <summary> /// Used to perform logging in Silverback. /// </summary> public interface ISilverbackLogger { /// <summary> /// Gets the underlying <see cref="ILogger" />. /// </summary> ILogger InnerLogger { get; } /// <summary> /// Checks if the given <see cref="LogEvent" /> is enabled according to its default or overridden /// <see cref="LogLevel" />. /// </summary> /// <param name="logEvent"> /// The <see cref="LogEvent" /> to be checked. /// </param> /// <returns> /// <c>true</c> if enabled. /// </returns> bool IsEnabled(LogEvent logEvent); } }
29.354839
109
0.550549
[ "MIT" ]
BEagle1984/silverback
src/Silverback.Core/Diagnostics/ISilverbackLogger.cs
912
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using HPSocketCS; namespace HPSocketCS { /// <summary> /// 通信组件服务状态,用程序可以通过通信组件的 GetState() 方法获取组件当前服务状态 /// </summary> public enum ServiceState { Starting = 0, // 正在启动 Started = 1, // 已经启动 Stoping = 2, // 正在停止 Stoped = 3, // 已经启动 } /// <summary> /// Socket 操作类型,应用程序的 OnErrror() 事件中通过该参数标识是哪种操作导致的错误 /// </summary> public enum SocketOperation { Unknown = 0, // Unknown Acccept = 1, // Acccept Connnect = 2, // Connnect Send = 3, // Send Receive = 4, // Receive }; /// <summary> /// 事件通知处理结果,事件通知的返回值,不同的返回值会影响通信组件的后续行为 /// </summary> public enum HandleResult { Ok = 0, // 成功 Ignore = 1, // 忽略 Error = 2, // 错误 }; /// <summary> /// 名称:操作结果代码 /// 描述:组件 Start() / Stop() 方法执行失败时,可通过 GetLastError() 获取错误代码 /// </summary> public enum SocketError { Ok = 0, // 成功 IllegalState = 1, // 当前状态不允许操作 InvalidParam = 2, // 非法参数 SocketCreate = 3, // 创建 SOCKET 失败 SocketBind = 4, // 绑定 SOCKET 失败 SocketPrepare = 5, // 设置 SOCKET 失败 SocketListen = 6, // 监听 SOCKET 失败 CPCreate = 7, // 创建完成端口失败 WorkerThreadCreate = 8, // 创建工作线程失败 DetectThreadCreate = 9, // 创建监测线程失败 SocketAttachToCP = 10, // 绑定完成端口失败 ConnectServer = 11, // 连接服务器失败 Network = 12, // 网络错误 DataProc = 13, // 数据处理错误 DataSend = 14, // 数据发送失败 }; /// <summary> /// 数据抓取结果,数据抓取操作的返回值 /// </summary> public enum FetchResult { Ok = 0, // 成功 LengthTooLong = 1, // 抓取长度过大 DataNotFound = 2, // 找不到 ConnID 对应的数据 }; /// <summary> /// 发送策略 /// </summary> public enum SendPolicy { Pack = 0, // 打包模式(默认) Safe = 1, // 安全模式 Direct = 2, // 直接模式 }; /// <summary> /// 接收策略 /// </summary> public enum RecvPolicy { Serial = 0, // 串行模式(默认) Parallel = 1, // 并行模式 }; /****************************************************/ /************** sockaddr结构体,udp服务器时OnAccept最后个参数可转化 **************/ [StructLayout(LayoutKind.Sequential)] public struct in_addr { public ulong S_addr; } //[StructLayout(LayoutKind.Sequential)] //public struct in_addr //{ // public byte s_b1, s_b2, s_b3, s_b4; //} [StructLayout(LayoutKind.Sequential)] public struct sockaddr_in { public short sin_family; public ushort sin_port; public in_addr sin_addr; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] sLibNamesin_zero; } /****************************************************/ [StructLayout(LayoutKind.Sequential)] public struct WSABUF { public int Length; public IntPtr Buffer; } } namespace HPSocketCS.SDK { /// <summary> /// Unicode版本 /// </summary> public class HPSocketSdk { /// <summary> /// HPSocket的文件路径 /// </summary> //#if DEBUG // private const string SOCKET_DLL_PATH = "HPSocket4C_UD.dll"; //#else private const string SOCKET_DLL_PATH = "HPSocket4C_U.dll"; //#endif /*****************************************************************************************************/ /******************************************** 公共类、接口 ********************************************/ /*****************************************************************************************************/ /****************************************************/ /************** HPSocket4C.dll 回调函数 **************/ /* Agent & Server & Clent */ public delegate HandleResult OnSend(IntPtr dwConnId, IntPtr pData, int iLength); public delegate HandleResult OnReceive(IntPtr dwConnId, IntPtr pData, int iLength); public delegate HandleResult OnPullReceive(IntPtr dwConnId, int iLength); public delegate HandleResult OnClose(IntPtr dwConnId); public delegate HandleResult OnError(IntPtr dwConnId, SocketOperation enOperation, int iErrorCode); /* Agent & Server */ public delegate HandleResult OnShutdown(); /* Agent & Client */ public delegate HandleResult OnPrepareConnect(IntPtr dwConnId /* IntPtr pClient */, uint socket); public delegate HandleResult OnConnect(IntPtr dwConnId /* IntPtr pClient */); /* Server */ public delegate HandleResult OnPrepareListen(IntPtr soListen); public delegate HandleResult OnAccept(IntPtr dwConnId, IntPtr pClient); /****************************************************/ /************** HPSocket4C.dll 导出函数 **************/ /// <summary> /// 创建 TcpServer 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpServer(IntPtr pListener); /// <summary> /// 创建 TcpClient 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpClient(IntPtr pListener); /// <summary> /// 创建 TcpAgent 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpAgent(IntPtr pListener); /// <summary> /// 创建 TcpPullServer 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullServer(IntPtr pListener); /// <summary> /// 创建 TcpPullClient 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullClient(IntPtr pListener); /// <summary> /// 创建 TcpPullAgent 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullAgent(IntPtr pListener); /// <summary> /// 创建 UdpServer 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_UdpServer(IntPtr pListener); /// <summary> /// 创建 UdpClient 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_UdpClient(IntPtr pListener); /// <summary> /// 销毁 TcpServer 对象 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpServer(IntPtr pServer); /// <summary> /// 销毁 TcpClient 对象 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpClient(IntPtr pClient); /// <summary> /// 销毁 TcpAgent 对象 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpAgent(IntPtr pAgent); /// <summary> /// 销毁 TcpPullServer 对象 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullServer(IntPtr pServer); /// <summary> /// 销毁 TcpPullClient 对象 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullClient(IntPtr pClient); /// <summary> /// 销毁 TcpPullAgent 对象 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullAgent(IntPtr pAgent); /// <summary> /// 销毁 UdpServer 对象 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_UdpServer(IntPtr pServer); /// <summary> /// 销毁 UdpClient 对象 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_UdpClient(IntPtr pClient); /// <summary> /// 创建 TcpServerListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpServerListener(); /// <summary> /// 创建 TcpClientListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpClientListener(); /// <summary> /// 创建 TcpAgentListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpAgentListener(); /// <summary> /// 创建 TcpPullServerListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullServerListener(); /// <summary> /// 创建 TcpPullClientListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullClientListener(); /// <summary> /// 创建 TcpPullAgentListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_TcpPullAgentListener(); /// <summary> /// 创建 UdpServerListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_UdpServerListener(); /// <summary> /// 创建 UdpClientListener 对象 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr Create_HP_UdpClientListener(); /// <summary> /// 销毁 TcpServerListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpServerListener(IntPtr pListener); /// <summary> /// 销毁 TcpClientListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpClientListener(IntPtr pListener); /// <summary> /// 销毁 TcpAgentListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpAgentListener(IntPtr pListener); /// <summary> /// 销毁 TcpPullServerListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullServerListener(IntPtr pListener); /// <summary> /// 销毁 TcpPullClientListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullClientListener(IntPtr pListener); /// <summary> /// 销毁 TcpPullAgentListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_TcpPullAgentListener(IntPtr pListener); /// <summary> /// 销毁 UdpServerListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_UdpServerListener(IntPtr pListener); /// <summary> /// 销毁 UdpClientListener 对象 /// </summary> /// <param name="pListener"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern void Destroy_HP_UdpClientListener(IntPtr pListener); /**********************************************************************************/ /***************************** Server 回调函数设置方法 *****************************/ [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnPrepareListen(IntPtr pListener, OnPrepareListen fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnAccept(IntPtr pListener, OnAccept fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnSend(IntPtr pListener, OnSend fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnReceive(IntPtr pListener, OnReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnPullReceive(IntPtr pListener, OnPullReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnClose(IntPtr pListener, OnClose fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnError(IntPtr pListener, OnError fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Server_OnShutdown(IntPtr pListener, OnShutdown fn); /**********************************************************************************/ /***************************** Client 回调函数设置方法 *****************************/ [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnPrepareConnect(IntPtr pListener, OnPrepareConnect fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnConnect(IntPtr pListener, OnConnect fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnSend(IntPtr pListener, OnSend fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnReceive(IntPtr pListener, OnReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnPullReceive(IntPtr pListener, OnPullReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnClose(IntPtr pListener, OnClose fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Client_OnError(IntPtr pListener, OnError fn); /**********************************************************************************/ /****************************** Agent 回调函数设置方法 *****************************/ [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnPrepareConnect(IntPtr pListener, OnPrepareConnect fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnConnect(IntPtr pListener, OnConnect fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnSend(IntPtr pListener, OnSend fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnReceive(IntPtr pListener, OnReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnPullReceive(IntPtr pListener, OnPullReceive fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnClose(IntPtr pListener, OnClose fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnError(IntPtr pListener, OnError fn); [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Set_FN_Agent_OnShutdown(IntPtr pListener, OnShutdown fn); /**************************************************************************/ /***************************** Server 操作方法 *****************************/ /// <summary> /// 名称:启动通信组件 /// 描述:启动服务端通信组件,启动完成后可开始接收客户端连接并收发数据 /// </summary> /// <param name="pServer"></param> /// <param name="pszBindAddress">监听地址</param> /// <param name="usPort">监听端口</param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode)] public static extern bool HP_Server_Start(IntPtr pServer, String pszBindAddress, ushort usPort); /// <summary> /// 关闭服务端通信组件,关闭完成后断开所有客户端连接并释放所有资源 /// </summary> /// <param name="pServer"></param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_Stop(IntPtr pServer); /// <summary> /// 用户通过该方法向指定客户端发送数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">发送数据长度</param> /// <param name="iLength">发送数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Ansi, SetLastError = true)] public static extern bool HP_Server_Send(IntPtr pServer, IntPtr dwConnId, byte[] pBuffer, int iLength); /// <summary> /// 用户通过该方法向指定客户端发送数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">发送数据长度</param> /// <param name="iLength">发送数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Server_Send(IntPtr pServer, IntPtr dwConnId, IntPtr pBuffer, int iLength); /// <summary> /// 用户通过该方法向指定客户端发送数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Ansi, SetLastError = true)] public static extern bool HP_Server_SendPart(IntPtr pServer, IntPtr dwConnId, byte[] pBuffer, int iLength, int iOffset); /// <summary> /// 用户通过该方法向指定客户端发送数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Server_SendPart(IntPtr pServer, IntPtr dwConnId, IntPtr pBuffer, int iLength, int iOffset); /// <summary> /// 发送多组数据 /// 向指定连接发送多组数据 /// TCP - 顺序发送所有数据包 /// UDP - 把所有数据包组合成一个数据包发送(数据包的总长度不能大于设置的 UDP 包最大长度) /// </summary> /// <param name="pServer"></param> /// <param name="dwConnID">连接 ID</param> /// <param name="pBuffers">发送缓冲区数组</param> /// <param name="iCount">发送缓冲区数目</param> /// <returns>TRUE.成功,FALSE.失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Server_SendPackets(IntPtr pServer, IntPtr dwConnID, WSABUF[] pBuffers, int iCount); /// <summary> /// 断开与某个客户端的连接 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="bForce">是否强制断开连接</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_Disconnect(IntPtr pServer, IntPtr dwConnId, bool bForce); /// <summary> /// 断开超过指定时长的连接 /// </summary> /// <param name="pServer"></param> /// <param name="dwPeriod">时长(毫秒)</param> /// <param name="bForce">是否强制断开连接</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_DisconnectLongConnections(IntPtr pServer, uint dwPeriod, bool bForce); /******************************************************************************/ /***************************** Server 属性访问方法 *****************************/ /// <summary> /// 设置数据发送策略 /// </summary> /// <param name="pServer"></param> /// <param name="enSendPolicy"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetSendPolicy(IntPtr pServer, SendPolicy enSendPolicy); /// <summary> /// 获取数据发送策略 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern SendPolicy HP_Server_GetSendPolicy(IntPtr pServer); /// <summary> /// 设置数据接受策略 /// </summary> /// <param name="pServer"></param> /// <param name="enSendPolicy"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetRecvPolicy(IntPtr pServer, RecvPolicy enSendPolicy); /// <summary> /// 获取数据接收策略 /// </summary> [DllImport(SOCKET_DLL_PATH)] public static extern RecvPolicy HP_Server_GetRecvPolicy(IntPtr pServer); /// <summary> /// 设置连接的附加数据 /// 是否为连接绑定附加数据或者绑定什么样的数据,均由应用程序只身决定 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pExtra"></param> /// <returns>若返回 false 失败则为(无效的连接 ID)</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_SetConnectionExtra(IntPtr pServer, IntPtr dwConnId, IntPtr pExtra); /// <summary> /// 获取连接的附加数据 /// 是否为连接绑定附加数据或者绑定什么样的数据,均由应用程序只身决定 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pExtra">数据指针</param> /// <returns>若返回 false 失败则为(无效的连接 ID)</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetConnectionExtra(IntPtr pServer, IntPtr dwConnId, ref IntPtr pExtra); /// <summary> /// 检查通信组件是否已启动 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_HasStarted(IntPtr pServer); /// <summary> /// 查看通信组件当前状态 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern ServiceState HP_Server_GetState(IntPtr pServer); /// <summary> /// 获取最近一次失败操作的错误代码 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern SocketError HP_Server_GetLastError(IntPtr pServer); /// <summary> /// 获取最近一次失败操作的错误描述 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_Server_GetLastErrorDesc(IntPtr pServer); /// <summary> /// 获取连接中未发出数据的长度 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId"></param> /// <param name="piPending"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetPendingDataLength(IntPtr pServer, IntPtr dwConnId, ref int piPending); /// <summary> /// 获取客户端连接数 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetConnectionCount(IntPtr pServer); /// <summary> /// 获取所有连接的 CONNID /// </summary> /// <param name="pServer"></param> /// <param name="pIDs"></param> /// <param name="pdwCount"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetAllConnectionIDs(IntPtr pServer, IntPtr[] pIDs, ref uint pdwCount); /// <summary> /// 获取某个客户端连接时长(毫秒) /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId"></param> /// <param name="pdwPeriod"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetConnectPeriod(IntPtr pServer, IntPtr dwConnId, ref uint pdwPeriod); /// <summary> /// 获取监听 Socket 的地址信息 /// </summary> /// <param name="pServer"></param> /// <param name="lpszAddress"></param> /// <param name="piAddressLen"></param> /// <param name="pusPort"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetListenAddress(IntPtr pServer, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszAddress, ref int piAddressLen, ref ushort pusPort); /// <summary> /// 获取某个客户端连接的地址信息 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId"></param> /// <param name="lpszAddress"></param> /// <param name="piAddressLen">传入传出值,大小最好在222.222.222.222的长度以上</param> /// <param name="pusPort"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Server_GetRemoteAddress(IntPtr pServer, IntPtr dwConnId, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszAddress, ref int piAddressLen, ref ushort pusPort); /// <summary> /// 设置 Socket 缓存对象锁定时间(毫秒,在锁定期间该 Socket 缓存对象不能被获取使用) /// </summary> /// <param name="pServer"></param> /// <param name="dwFreeSocketObjLockTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetFreeSocketObjLockTime(IntPtr pServer, uint dwFreeSocketObjLockTime); /// <summary> /// 设置 Socket 缓存池大小(通常设置为平均并发连接数量的 1/3 - 1/2) /// </summary> /// <param name="pServer"></param> /// <param name="dwFreeSocketObjPool"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetFreeSocketObjPool(IntPtr pServer, uint dwFreeSocketObjPool); /// <summary> /// 设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍) /// </summary> /// <param name="pServer"></param> /// <param name="dwFreeBufferObjPool"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetFreeBufferObjPool(IntPtr pServer, uint dwFreeBufferObjPool); /// <summary> /// 设置 Socket 缓存池回收阀值(通常设置为 Socket 缓存池大小的 3 倍) /// </summary> /// <param name="pServer"></param> /// <param name="dwFreeSocketObjHold"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetFreeSocketObjHold(IntPtr pServer, uint dwFreeSocketObjHold); /// <summary> /// 设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍) /// </summary> /// <param name="pServer"></param> /// <param name="dwFreeBufferObjHold"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetFreeBufferObjHold(IntPtr pServer, uint dwFreeBufferObjHold); /// <summary> /// 设置工作线程数量(通常设置为 2 * CPU + 2) /// </summary> /// <param name="pServer"></param> /// <param name="dwWorkerThreadCount"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetWorkerThreadCount(IntPtr pServer, uint dwWorkerThreadCount); /// <summary> /// 设置关闭服务前等待连接关闭的最长时限(毫秒,0 则不等待) /// </summary> /// <param name="pServer"></param> /// <param name="dwMaxShutdownWaitTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Server_SetMaxShutdownWaitTime(IntPtr pServer, uint dwMaxShutdownWaitTime); /// <summary> /// 获取 Socket 缓存对象锁定时间 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetFreeSocketObjLockTime(IntPtr pServer); /// <summary> /// 获取 Socket 缓存池大小 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetFreeSocketObjPool(IntPtr pServer); /// <summary> /// 获取内存块缓存池大小 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetFreeBufferObjPool(IntPtr pServer); /// <summary> /// 获取 Socket 缓存池回收阀值 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetFreeSocketObjHold(IntPtr pServer); /// <summary> /// 获取内存块缓存池回收阀值 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetFreeBufferObjHold(IntPtr pServer); /// <summary> /// 获取工作线程数量 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetWorkerThreadCount(IntPtr pServer); /// <summary> /// 获取关闭服务前等待连接关闭的最长时限 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Server_GetMaxShutdownWaitTime(IntPtr pServer); /**********************************************************************************/ /***************************** TCP Server 操作方法 *****************************/ /// <summary> /// 名称:发送小文件 /// 描述:向指定连接发送 4096 KB 以下的小文件 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnID">连接 ID</param> /// <param name="lpszFileName">文件路径</param> /// <param name="pHead">头部附加数据</param> /// <param name="pTail">尾部附加数据</param> /// <returns>TRUE.成功 FALSE -- 失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool HP_TcpServer_SendSmallFile(IntPtr pServer, IntPtr dwConnID, string lpszFileName, ref WSABUF pHead, ref WSABUF pTail); /**********************************************************************************/ /***************************** TCP Server 属性访问方法 *****************************/ /// <summary> /// 设置 Accept 预投递数量(根据负载调整设置,Accept 预投递数量越大则支持的并发连接请求越多) /// </summary> /// <param name="pServer"></param> /// <param name="dwAcceptSocketCount"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpServer_SetAcceptSocketCount(IntPtr pServer, uint dwAcceptSocketCount); /// <summary> /// 设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为 1024 的倍数) /// </summary> /// <param name="pServer"></param> /// <param name="dwSocketBufferSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpServer_SetSocketBufferSize(IntPtr pServer, uint dwSocketBufferSize); /// <summary> /// 设置监听 Socket 的等候队列大小(根据并发连接数量调整设置) /// </summary> /// <param name="pServer"></param> /// <param name="dwSocketListenQueue"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpServer_SetSocketListenQueue(IntPtr pServer, uint dwSocketListenQueue); /// <summary> /// 设置心跳包间隔(毫秒,0 则不发送心跳包) /// </summary> /// <param name="pServer"></param> /// <param name="dwKeepAliveTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpServer_SetKeepAliveTime(IntPtr pServer, uint dwKeepAliveTime); /// <summary> /// 设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线) /// </summary> /// <param name="pServer"></param> /// <param name="dwKeepAliveInterval"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpServer_SetKeepAliveInterval(IntPtr pServer, uint dwKeepAliveInterval); /// <summary> /// 获取 Accept 预投递数量 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpServer_GetAcceptSocketCount(IntPtr pServer); /// <summary> /// 获取通信数据缓冲区大小 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpServer_GetSocketBufferSize(IntPtr pServer); /// <summary> /// 获取监听 Socket 的等候队列大小 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpServer_GetSocketListenQueue(IntPtr pServer); /// <summary> /// 获取心跳检查次数 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpServer_GetKeepAliveTime(IntPtr pServer); /// <summary> /// 获取心跳检查间隔 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpServer_GetKeepAliveInterval(IntPtr pServer); /**********************************************************************************/ /***************************** UDP Server 属性访问方法 *****************************/ /// <summary> /// 设置数据报文最大长度(建议在局域网环境下不超过 1472 字节,在广域网环境下不超过 548 字节) /// </summary> /// <param name="pServer"></param> /// <param name="dwMaxDatagramSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpServer_SetMaxDatagramSize(IntPtr pServer, uint dwMaxDatagramSize); /// <summary> /// 获取数据报文最大长度 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpServer_GetMaxDatagramSize(IntPtr pServer); /// <summary> /// 设置 Receive 预投递数量(根据负载调整设置,Receive 预投递数量越大则丢包概率越小) /// </summary> /// <param name="pServer"></param> /// <param name="dwPostReceiveCount"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpServer_SetPostReceiveCount(IntPtr pServer, uint dwPostReceiveCount); /// <summary> /// 获取 Receive 预投递数量 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpServer_GetPostReceiveCount(IntPtr pServer); /// <summary> /// 设置监测包尝试次数(0 则不发送监测跳包,如果超过最大尝试次数则认为已断线) /// </summary> /// <param name="pServer"></param> /// <param name="dwMaxDatagramSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpServer_SetDetectAttempts(IntPtr pServer, uint dwMaxDatagramSize); /// <summary> /// 设置监测包发送间隔(秒,0 不发送监测包) /// </summary> /// <param name="pServer"></param> /// <param name="dwMaxDatagramSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpServer_SetDetectInterval(IntPtr pServer, uint dwMaxDatagramSize); /// <summary> /// 获取心跳检查次数 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpServer_GetDetectAttempts(IntPtr pServer); /// <summary> /// 获取心跳检查间隔 /// </summary> /// <param name="pServer"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpServer_GetDetectInterval(IntPtr pServer); /******************************************************************************/ /***************************** Client 组件操作方法 *****************************/ /// <summary> /// 启动客户端通信组件并连接服务端,启动完成后可开始收发数据 /// </summary> /// <param name="pClient"></param> /// <param name="pszRemoteAddress">服务端地址</param> /// <param name="usPort">服务端端口</param> /// <param name="bAsyncConnect">是否采用异步 Connnect</param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode)] public static extern bool HP_Client_Start(IntPtr pClient, string pszRemoteAddress, ushort usPort, bool bAsyncConnect); /// <summary> /// 关闭客户端通信组件,关闭完成后断开与服务端的连接并释放所有资源 /// </summary> /// <param name="pClient"></param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Client_Stop(IntPtr pClient); /// <summary> /// 用户通过该方法向服务端发送数据 /// </summary> /// <param name="pClient"></param> /// <param name="dwConnId">连接 ID(保留参数,目前该参数并未使用)</param> /// <param name="pBuffer">发送数据缓冲区</param> /// <param name="iLength">发送数据长度</param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Ansi, SetLastError = true)] public static extern bool HP_Client_Send(IntPtr pClient, byte[] pBuffer, int iLength); /// <summary> /// 用户通过该方法向服务端发送数据 /// </summary> /// <param name="pClient"></param> /// <param name="dwConnId">连接 ID(保留参数,目前该参数并未使用)</param> /// <param name="pBuffer">发送数据缓冲区</param> /// <param name="iLength">发送数据长度</param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Client_Send(IntPtr pClient, IntPtr pBuffer, int iLength); /// <summary> /// 用户通过该方法向服务端发送数据 /// </summary> /// <param name="pClient"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Ansi, SetLastError = true)] public static extern bool HP_Client_SendPart(IntPtr pClient, byte[] pBuffer, int iLength, int iOffset); /// <summary> /// 用户通过该方法向服务端发送数据 /// </summary> /// <param name="pClient"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Client_SendPart(IntPtr pClient, IntPtr pBuffer, int iLength, int iOffset); /// <summary> /// 发送多组数据 /// 向服务端发送多组数据 /// TCP - 顺序发送所有数据包 /// UDP - 把所有数据包组合成一个数据包发送(数据包的总长度不能大于设置的 UDP 包最大长度) /// </summary> /// <param name="pClient"></param> /// <param name="pBuffers">发送缓冲区数组</param> /// <param name="iCount">发送缓冲区数目</param> /// <returns>TRUE.成功,FALSE.失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Client_SendPackets(IntPtr pClient, WSABUF[] pBuffers, int iCount); /******************************************************************************/ /***************************** Client 属性访问方法 *****************************/ /// <summary> /// 设置连接的附加数据 /// </summary> /// <param name="pClient"></param> /// <param name="pExtra"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Client_SetExtra(IntPtr pClient, IntPtr pExtra); /// <summary> /// 获取连接的附加数据 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_Client_GetExtra(IntPtr pClient); /// <summary> /// 检查通信组件是否已启动 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Client_HasStarted(IntPtr pClient); /// <summary> /// 查看通信组件当前状态 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern ServiceState HP_Client_GetState(IntPtr pClient); /// <summary> /// 获取最近一次失败操作的错误代码 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern SocketError HP_Client_GetLastError(IntPtr pClient); /// <summary> /// 获取最近一次失败操作的错误描述 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_Client_GetLastErrorDesc(IntPtr pClient); /// <summary> /// 获取该组件对象的连接 ID /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_Client_GetConnectionID(IntPtr pClient); /// <summary> /// 获取 Client Socket 的地址信息 /// </summary> /// <param name="pClient"></param> /// <param name="lpszAddress"></param> /// <param name="piAddressLen"></param> /// <param name="pusPort"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Client_GetLocalAddress(IntPtr pClient, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszAddress, ref int piAddressLen, ref ushort pusPort); /// <summary> /// 获取连接中未发出数据的长度 /// </summary> /// <param name="pClient"></param> /// <param name="piPending"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Client_GetPendingDataLength(IntPtr pClient, ref int piPending); /// <summary> /// 设置内存块缓存池大小(通常设置为 -> PUSH 模型:5 - 10;PULL 模型:10 - 20 ) /// </summary> /// <param name="pClient"></param> /// <param name="dwFreeBufferPoolSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Client_SetFreeBufferPoolSize(IntPtr pClient, uint dwFreeBufferPoolSize); /// <summary> /// 设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍) /// </summary> /// <param name="pClient"></param> /// <param name="dwFreeBufferPoolHold"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Client_SetFreeBufferPoolHold(IntPtr pClient, uint dwFreeBufferPoolHold); /// <summary> /// 获取内存块缓存池大小 /// </summary> /// <param name="pClient"></param> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Client_GetFreeBufferPoolSize(IntPtr pClient); /// <summary> /// 获取内存块缓存池回收阀值 /// </summary> /// <param name="pClient"></param> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Client_GetFreeBufferPoolHold(IntPtr pClient); /**********************************************************************************/ /***************************** TCP Client 操作方法 *****************************/ /// <summary> /// 名称:发送小文件 /// 描述:向指定连接发送 4096 KB 以下的小文件 /// </summary> /// <param name="pServer"></param> /// <param name="lpszFileName">文件路径</param> /// <param name="pHead">头部附加数据</param> /// <param name="pTail">尾部附加数据</param> /// <returns>TRUE.成功 FALSE -- 失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool HP_TcpClient_SendSmallFile(IntPtr pClient, string lpszFileName, ref WSABUF pHead, ref WSABUF pTail); /**********************************************************************************/ /***************************** TCP Client 属性访问方法 *****************************/ /// <summary> /// 设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为:(N * 1024) - sizeof(TBufferObj)) /// </summary> /// <param name="pClient"></param> /// <param name="dwSocketBufferSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpClient_SetSocketBufferSize(IntPtr pClient, uint dwSocketBufferSize); /// <summary> /// 设置心跳包间隔(毫秒,0 则不发送心跳包) /// </summary> /// <param name="pClient"></param> /// <param name="dwKeepAliveTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpClient_SetKeepAliveTime(IntPtr pClient, uint dwKeepAliveTime); /// <summary> /// 设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线) /// </summary> /// <param name="pClient"></param> /// <param name="dwKeepAliveInterval"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpClient_SetKeepAliveInterval(IntPtr pClient, uint dwKeepAliveInterval); /// <summary> /// 获取通信数据缓冲区大小 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpClient_GetSocketBufferSize(IntPtr pClient); /// <summary> /// 获取心跳检查次数 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpClient_GetKeepAliveTime(IntPtr pClient); /// <summary> /// 获取心跳检查间隔 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpClient_GetKeepAliveInterval(IntPtr pClient); /**********************************************************************************/ /***************************** UDP Client 属性访问方法 *****************************/ /// <summary> /// 设置数据报文最大长度(建议在局域网环境下不超过 1472 字节,在广域网环境下不超过 548 字节) /// </summary> /// <param name="pClient"></param> /// <param name="dwMaxDatagramSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpClient_SetMaxDatagramSize(IntPtr pClient, uint dwMaxDatagramSize); /// <summary> /// 获取数据报文最大长度 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpClient_GetMaxDatagramSize(IntPtr pClient); /// <summary> /// 设置监测包尝试次数(0 则不发送监测跳包,如果超过最大尝试次数则认为已断线 /// </summary> /// <param name="pClient"></param> /// <param name="dwDetectAttempts"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpClient_SetDetectAttempts(IntPtr pClient, uint dwDetectAttempts); /// <summary> /// 设置监测包发送间隔(秒,0 不发送监测包) /// </summary> /// <param name="pClient"></param> /// <param name="dwDetectInterval"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_UdpClient_SetDetectInterval(IntPtr pClient, uint dwDetectInterval); /// <summary> /// 获取心跳检查次数 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpClient_GetDetectAttempts(IntPtr pClient); /// <summary> /// 获取心跳检查间隔 /// </summary> /// <param name="pClient"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_UdpClient_GetDetectInterval(IntPtr pClient); /**************************************************************************/ /***************************** Agent 操作方法 *****************************/ /// <summary> /// 启动通信组件 /// 启动通信代理组件,启动完成后可开始连接远程服务器 /// </summary> /// <param name="pAgent"></param> /// <param name="pszBindAddress">监听地址</param> /// <param name="bAsyncConnect">是否采用异步 Connect</param> /// <returns>失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode)] public static extern bool HP_Agent_Start(IntPtr pAgent, String pszBindAddress, bool bAsyncConnect); /// <summary> /// 关闭通信组件 /// 关闭通信组件,关闭完成后断开所有连接并释放所有资源 /// </summary> /// <param name="pAgent"></param> /// <returns>-- 失败,可通过 GetLastError() 获取错误代码</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_Stop(IntPtr pAgent); /// <summary> /// 连接服务器 /// 连接服务器,连接成功后 IAgentListener 会接收到 OnConnect() 事件 /// </summary> /// <param name="pAgent"></param> /// <param name="pszBindAddress">服务端地址</param> /// <param name="usPort">服务端端口</param> /// <param name="pdwConnID">传出连接 ID</param> /// <returns>失败,可通过 SYS_GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool HP_Agent_Connect(IntPtr pAgent, String pszBindAddress, ushort usPort, ref IntPtr pdwConnID); /// <summary> /// 发送数据 /// 用户通过该方法向指定连接发送数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">发送数据缓冲区</param> /// <param name="iLength">发送数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Ansi, SetLastError = true)] public static extern bool HP_Agent_Send(IntPtr pAgent, IntPtr dwConnId, byte[] pBuffer, int iLength); /// <summary> /// 发送数据 /// 用户通过该方法向指定连接发送数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">发送数据缓冲区</param> /// <param name="iLength">发送数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Agent_Send(IntPtr pAgent, IntPtr dwConnId, IntPtr pBuffer, int iLength); /// <summary> /// 发送数据 /// 用户通过该方法向指定连接发送数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Agent_SendPart(IntPtr pAgent, IntPtr dwConnId, byte[] pBuffer, int iLength, int iOffset); /// <summary> /// 发送数据 /// 用户通过该方法向指定连接发送数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="pBuffer"></param> /// <param name="iLength"></param> /// <param name="iOffset">针对pBuffer的偏移</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Agent_SendPart(IntPtr pAgent, IntPtr dwConnId, IntPtr pBuffer, int iLength, int iOffset); /// <summary> /// 发送多组数据 /// 向指定连接发送多组数据 /// TCP - 顺序发送所有数据包 /// UDP - 把所有数据包组合成一个数据包发送(数据包的总长度不能大于设置的 UDP 包最大长度) /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnID">连接 ID</param> /// <param name="pBuffers">发送缓冲区数组</param> /// <param name="iCount">发送缓冲区数目</param> /// <returns>TRUE.成功,FALSE .失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern bool HP_Agent_SendPackets(IntPtr pAgent, IntPtr dwConnID, WSABUF[] pBuffers, int iCount); /// <summary> /// 断开某个连接 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="bForce">是否强制断开连接</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_Disconnect(IntPtr pAgent, IntPtr dwConnId, bool bForce); /// <summary> /// 断开超过指定时长的连接 /// </summary> /// <param name="pAgent"></param> /// <param name="dwPeriod">时长(毫秒)</param> /// <param name="bForce">是否强制断开连接</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_DisconnectLongConnections(IntPtr pAgent, uint dwPeriod, bool bForce); /******************************************************************************/ /***************************** Agent 操作方法 *****************************/ /// <summary> /// 名称:发送小文件 /// 描述:向指定连接发送 4096 KB 以下的小文件 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnID">连接 ID</param> /// <param name="lpszFileName">文件路径</param> /// <param name="pHead">头部附加数据</param> /// <param name="pTail">尾部附加数据</param> /// <returns>TRUE.成功 FALSE -- 失败,可通过 Windows API 函数 ::GetLastError() 获取 Windows 错误代码</returns> [DllImport(SOCKET_DLL_PATH, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool HP_TcpAgent_SendSmallFile(IntPtr pAgent, IntPtr dwConnID, string lpszFileName, ref WSABUF pHead, ref WSABUF pTail); /******************************************************************************/ /***************************** Agent 属性访问方法 *****************************/ /// <summary> /// 设置数据发送策略 /// </summary> /// <param name="pAgent"></param> /// <param name="enSendPolicy"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetSendPolicy(IntPtr pAgent, SendPolicy enSendPolicy); /// <summary> /// 获取数据发送策略 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern SendPolicy HP_Agent_GetSendPolicy(IntPtr pAgent); /// <summary> /// 获取数据接收策略 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern RecvPolicy HP_Agent_GetRecvPolicy(IntPtr pAgent); /// <summary> /// 设置数据接收策略 /// </summary> /// <param name="pAgent"></param> /// <param name="enRecvPolicy"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetRecvPolicy(IntPtr pAgent, RecvPolicy enRecvPolicy); /// <summary> /// 设置连接的附加数据 /// 是否为连接绑定附加数据或者绑定什么样的数据,均由应用程序只身决定 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pExtra">数据</param> /// <returns>FALSE -- 失败(无效的连接 ID)</returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_SetConnectionExtra(IntPtr pAgent, IntPtr dwConnId, IntPtr pExtra); /// <summary> /// 获取连接的附加数据 /// 是否为连接绑定附加数据或者绑定什么样的数据,均由应用程序只身决定 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="pExtra"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetConnectionExtra(IntPtr pAgent, IntPtr dwConnId, ref IntPtr pExtra); /// <summary> /// 检查通信组件是否已启动 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_HasStarted(IntPtr pAgent); /// <summary> /// 查看通信组件当前状态 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern ServiceState HP_Agent_GetState(IntPtr pAgent); /// <summary> /// 获取连接数 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetConnectionCount(IntPtr pAgent); /// <summary> /// 获取所有连接的 CONNID /// </summary> /// <param name="pServer"></param> /// <param name="pIDs"></param> /// <param name="pdwCount"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetAllConnectionIDs(IntPtr pAgent, IntPtr[] pIDs, ref uint pdwCount); /// <summary> /// 获取某个连接时长(毫秒) /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="pdwPeriod"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetConnectPeriod(IntPtr pAgent, IntPtr dwConnId, ref uint pdwPeriod); /// <summary> /// 获取监听 Socket 的地址信息 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="lpszAddress"></param> /// <param name="piAddressLen"></param> /// <param name="pusPort"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetLocalAddress(IntPtr pAgent, IntPtr dwConnId, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszAddress, ref int piAddressLen, ref ushort pusPort); /// <summary> /// 获取某个连接的地址信息 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="lpszAddress"></param> /// <param name="piAddressLen"></param> /// <param name="pusPort"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetRemoteAddress(IntPtr pAgent, IntPtr dwConnId, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszAddress, ref int piAddressLen, ref ushort pusPort); /// <summary> /// 获取最近一次失败操作的错误代码 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern SocketError HP_Agent_GetLastError(IntPtr pAgent); /// <summary> /// 获取最近一次失败操作的错误描述 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_Agent_GetLastErrorDesc(IntPtr pAgent); /// <summary> /// 获取连接中未发出数据的长度 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId"></param> /// <param name="piPending"></param> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_Agent_GetPendingDataLength(IntPtr pAgent, IntPtr dwConnId, ref int piPending); /// <summary> /// 设置 Socket 缓存对象锁定时间(毫秒,在锁定期间该 Socket 缓存对象不能被获取使用) /// </summary> /// <param name="pAgent"></param> /// <param name="dwFreeSocketObjLockTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetFreeSocketObjLockTime(IntPtr pAgent, uint dwFreeSocketObjLockTime); /// <summary> /// 设置 Socket 缓存池大小(通常设置为平均并发连接数量的 1/3 - 1/2) /// </summary> /// <param name="pAgent"></param> /// <param name="dwFreeSocketObjPool"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetFreeSocketObjPool(IntPtr pAgent, uint dwFreeSocketObjPool); /// <summary> /// 设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍) /// </summary> /// <param name="pAgent"></param> /// <param name="dwFreeBufferObjPool"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetFreeBufferObjPool(IntPtr pAgent, uint dwFreeBufferObjPool); /// <summary> /// 设置 Socket 缓存池回收阀值(通常设置为 Socket 缓存池大小的 3 倍) /// </summary> /// <param name="pAgent"></param> /// <param name="dwFreeSocketObjHold"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetFreeSocketObjHold(IntPtr pAgent, uint dwFreeSocketObjHold); /// <summary> /// 设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍) /// </summary> /// <param name="pAgent"></param> /// <param name="dwFreeBufferObjHold"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetFreeBufferObjHold(IntPtr pAgent, uint dwFreeBufferObjHold); /// <summary> /// 设置工作线程数量(通常设置为 2 * CPU + 2) /// </summary> /// <param name="pAgent"></param> /// <param name="dwWorkerThreadCount"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetWorkerThreadCount(IntPtr pAgent, uint dwWorkerThreadCount); /// <summary> /// 设置关闭组件前等待连接关闭的最长时限(毫秒,0 则不等待) /// </summary> /// <param name="pAgent"></param> /// <param name="dwMaxShutdownWaitTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_Agent_SetMaxShutdownWaitTime(IntPtr pAgent, uint dwMaxShutdownWaitTime); /// <summary> /// 获取 Socket 缓存对象锁定时间 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetFreeSocketObjLockTime(IntPtr pAgent); /// <summary> /// 获取 Socket 缓存池大小 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetFreeSocketObjPool(IntPtr pAgent); /// <summary> /// 获取内存块缓存池大小 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetFreeBufferObjPool(IntPtr pAgent); /// <summary> /// 获取 Socket 缓存池回收阀值 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetFreeSocketObjHold(IntPtr pAgent); /// <summary> /// 获取内存块缓存池回收阀值 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetFreeBufferObjHold(IntPtr pAgent); /// <summary> /// 获取工作线程数量 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetWorkerThreadCount(IntPtr pAgent); /// <summary> /// 获取关闭组件前等待连接关闭的最长时限 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_Agent_GetMaxShutdownWaitTime(IntPtr pAgent); /**********************************************************************************/ /***************************** TCP Agent 属性访问方法 *****************************/ /// <summary> /// 置是否启用地址重用机制(默认:不启用) /// </summary> /// <param name="pAgent"></param> /// <param name="bReuseAddress"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpAgent_SetReuseAddress(IntPtr pAgent, bool bReuseAddress); /// <summary> /// 检测是否启用地址重用机制 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern bool HP_TcpAgent_IsReuseAddress(IntPtr pAgent); /// <summary> /// 设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为 1024 的倍数) /// </summary> /// <param name="pAgent"></param> /// <param name="dwSocketBufferSize"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpAgent_SetSocketBufferSize(IntPtr pAgent, uint dwSocketBufferSize); /// <summary> /// 设置心跳包间隔(毫秒,0 则不发送心跳包) /// </summary> /// <param name="pAgent"></param> /// <param name="dwKeepAliveTime"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpAgent_SetKeepAliveTime(IntPtr pAgent, uint dwKeepAliveTime); /// <summary> /// 设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线) /// </summary> /// <param name="pAgent"></param> /// <param name="dwKeepAliveInterval"></param> [DllImport(SOCKET_DLL_PATH)] public static extern void HP_TcpAgent_SetKeepAliveInterval(IntPtr pAgent, uint dwKeepAliveInterval); /// <summary> /// 获取通信数据缓冲区大小 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpAgent_GetSocketBufferSize(IntPtr pAgent); /// <summary> /// 获取心跳检查次数 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpAgent_GetKeepAliveTime(IntPtr pAgent); /// <summary> /// 获取心跳检查间隔 /// </summary> /// <param name="pAgent"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern uint HP_TcpAgent_GetKeepAliveInterval(IntPtr pAgent); /***************************************************************************************/ /***************************** TCP Pull Server 组件操作方法 *****************************/ /// <summary> /// 抓取数据 /// 用户通过该方法从 Socket 组件中抓取数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">数据抓取缓冲区</param> /// <param name="iLength">抓取数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullServer_Fetch(IntPtr pServer, IntPtr dwConnId, IntPtr pBuffer, int iLength); /// <summary> /// 窥探数据(不会移除缓冲区数据) /// 描述:用户通过该方法从 Socket 组件中窥探数据 /// </summary> /// <param name="pServer"></param> /// <param name="dwConnID">连接 ID</param> /// <param name="pBuffer">窥探缓冲区</param> /// <param name="iLength">窥探数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullServer_Peek(IntPtr pServer, IntPtr dwConnID, IntPtr pBuffer, int iLength); /***************************************************************************************/ /***************************** TCP Pull Server 属性访问方法 *****************************/ /***************************************************************************************/ /***************************** TCP Pull Client 组件操作方法 *****************************/ /// <summary> /// 抓取数据 /// 用户通过该方法从 Socket 组件中抓取数据 /// </summary> /// <param name="pClient"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">数据抓取缓冲区</param> /// <param name="iLength">抓取数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullClient_Fetch(IntPtr pClient, IntPtr pBuffer, int iLength); /// <summary> /// 名称:窥探数据(不会移除缓冲区数据) /// 描述:用户通过该方法从 Socket 组件中窥探数据 /// </summary> /// <param name="pClient"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">数据抓取缓冲区</param> /// <param name="iLength">抓取数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullClient_Peek(IntPtr pClient, IntPtr pBuffer, int iLength); /***************************************************************************************/ /***************************** TCP Pull Client 属性访问方法 *****************************/ /***************************************************************************************/ /***************************** TCP Pull Agent 组件操作方法 *****************************/ /// <summary> /// 抓取数据 /// 用户通过该方法从 Socket 组件中抓取数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">数据抓取缓冲区</param> /// <param name="iLength">抓取数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullAgent_Fetch(IntPtr pAgent, IntPtr dwConnId, IntPtr pBuffer, int iLength); /// <summary> /// 名称:窥探数据(不会移除缓冲区数据) /// 描述:用户通过该方法从 Socket 组件中窥探数据 /// </summary> /// <param name="pAgent"></param> /// <param name="dwConnId">连接 ID</param> /// <param name="pBuffer">数据抓取缓冲区</param> /// <param name="iLength">抓取数据长度</param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern FetchResult HP_TcpPullAgent_Peek(IntPtr pAgent, IntPtr dwConnId, IntPtr pBuffer, int iLength); /***************************************************************************************/ /***************************** TCP Pull Agent 属性访问方法 *****************************/ /***************************************************************************************/ /*************************************** 其它方法 ***************************************/ /// <summary> /// 获取错误描述文本 /// </summary> /// <param name="enCode"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH)] public static extern IntPtr HP_GetSocketErrorDesc(SocketError enCode); /// <summary> /// 调用系统的 ::GetLastError() 方法获取系统错误代码 /// </summary> /// <returns></returns> public static int SYS_GetLastError() { return Marshal.GetLastWin32Error(); } /// <summary> /// 调用系统的 ::WSAGetLastError() 方法获取通信错误代码 /// </summary> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern int SYS_WSAGetLastError(); /// <summary> /// 调用系统的 setsockopt() /// </summary> /// <param name="sock"></param> /// <param name="level"></param> /// <param name="name"></param> /// <param name="val"></param> /// <param name="len"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern int SYS_SetSocketOption(IntPtr sock, int level, int name, IntPtr val, int len); /// <summary> /// 调用系统的 getsockopt() /// </summary> /// <param name="sock"></param> /// <param name="level"></param> /// <param name="name"></param> /// <param name="val"></param> /// <param name="len"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern int SYS_GetSocketOption(IntPtr sock, int level, int name, IntPtr val, ref int len); /// <summary> /// 调用系统的 ioctlsocket() /// </summary> /// <param name="sock"></param> /// <param name="cmd"></param> /// <param name="arg"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern int SYS_IoctlSocket(IntPtr sock, long cmd, IntPtr arg); /// <summary> /// 调用系统的 ::WSAIoctl() /// </summary> /// <param name="sock"></param> /// <param name="dwIoControlCode"></param> /// <param name="lpvInBuffer"></param> /// <param name="cbInBuffer"></param> /// <param name="lpvOutBuffer"></param> /// <param name="cbOutBuffer"></param> /// <param name="lpcbBytesReturned"></param> /// <returns></returns> [DllImport(SOCKET_DLL_PATH, SetLastError = true)] public static extern int SYS_WSAIoctl(IntPtr sock, uint dwIoControlCode, IntPtr lpvInBuffer, uint cbInBuffer, IntPtr lpvOutBuffer, uint cbOutBuffer, uint lpcbBytesReturned); } }
38.571283
197
0.553938
[ "Apache-2.0" ]
teaccc/HP-Socket
HP-Socket/Demo/Other Languages Demos/C#/HPSocket4CS/HPSocketCS/Sdk.cs
84,064
C#
using System; using Newtonsoft.Json; namespace VkNet.Model { /// <summary> /// Authorization error. /// </summary> [Serializable] public class VkAuthError { /// <summary> /// Error. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error type. /// </summary> [JsonProperty("error_type")] public string ErrorType { get; set; } /// <summary> /// Error description. /// </summary> [JsonProperty("error_description")] public string ErrorDescription { get; set; } /// <summary> /// Captcha id. /// </summary> [JsonProperty("captcha_sid")] public ulong? CaptchaSid { get; set; } /// <summary> /// Captcha image Uri. /// </summary> [JsonProperty("captcha_img")] public Uri CaptchaImg { get; set; } } }
18.97619
46
0.613551
[ "MIT" ]
DeNcHiK3713/vk
VkNet/Model/VkAuthError.cs
797
C#
using System; using System.Numerics; using System.Threading.Tasks; using NeoModules.JsonRpc.Client; using NeoModules.RPC.Infrastructure; using NeoModules.RPC.Services.Nep5; namespace NeoModules.RPC.Services { public class NeoNep5Service : RpcClientWrapper { public NeoNep5Service(IClient client) : base(client) { if (client == null) throw new ArgumentNullException(nameof(client)); GetTokenBalance = new TokenBalanceOf(client); GetTokenDecimals = new TokenDecimals(client); GetTokenName = new TokenName(client); GetTokenTotalSupply = new TokenTotalSupply(client); GetTokenSymbol = new TokenSymbol(client); } private TokenBalanceOf GetTokenBalance { get; } private TokenDecimals GetTokenDecimals { get; } private TokenName GetTokenName { get; } private TokenTotalSupply GetTokenTotalSupply { get; } private TokenSymbol GetTokenSymbol { get; } public async Task<string> GetName(string tokenScriptHash, bool humanReadable = false) { var result = await GetTokenName.SendRequestAsync(tokenScriptHash); if (result.State == "FAULT, BREAK") throw new RpcResponseException(new RpcError(0, "RPC state response: FAULT, BREAK ")); var resultString = result.Stack[0].Value.ToString(); if (!humanReadable) return resultString; return resultString.HexToString(); } public async Task<string> GetSymbol(string tokenScriptHash, bool humanReadable = false) { var result = await GetTokenSymbol.SendRequestAsync(tokenScriptHash); if (result.State == "FAULT, BREAK") throw new RpcResponseException(new RpcError(0, "RPC state response: FAULT, BREAK ")); var resultString = result.Stack[0].Value.ToString(); if (!humanReadable) return resultString; return resultString.HexToString(); } public async Task<decimal> GetTotalSupply(string tokenScriptHash, int decimals = 8) { var result = await GetTokenTotalSupply.SendRequestAsync(tokenScriptHash); if (result.State == "FAULT, BREAK") throw new RpcResponseException(new RpcError(0, "RPC state response: FAULT, BREAK ")); var totalSupplyBigInteger = new BigInteger(result.Stack[0].Value.ToString().HexStringToBytes()); if (decimals.Equals(0)) return (decimal) totalSupplyBigInteger; var totalSupply = Nep5Helper.CalculateDecimalFromBigInteger(totalSupplyBigInteger, decimals); return totalSupply; } public async Task<int> GetDecimals(string tokenScriptHash) { var result = await GetTokenDecimals.SendRequestAsync(tokenScriptHash); if (result.State == "FAULT, BREAK") throw new RpcResponseException(new RpcError(0, "RPC state response: FAULT, BREAK ")); return int.Parse(result.Stack[0].Value.ToString()); } public async Task<decimal> GetBalance(string tokenScriptHash, string addressScriptHash, int decimals = 0) { var result = await GetTokenBalance.SendRequestAsync(addressScriptHash, tokenScriptHash); if (result.State == "FAULT, BREAK") throw new RpcResponseException(new RpcError(0, "RPC state response: FAULT, BREAK ")); var balanceBigInteger = new BigInteger(result.Stack[0].Value.ToString().HexStringToBytes()); if (decimals.Equals(0)) return (decimal) balanceBigInteger; var balance = Nep5Helper.CalculateDecimalFromBigInteger(balanceBigInteger, decimals); return balance; } } }
40.255319
113
0.655391
[ "MIT" ]
CityOfZion/Neo-RPC-SharpClient
src/NeoModules.RPC/Services/NeoNep5Service.cs
3,784
C#
using System; using System.Data; using System.Collections.Generic; using System.Text; using Platinium.Entidade; using Pro.Utils; using Pro.Dal; using Plutonium.Entidade; namespace Platinium.Entidade { [ClassAttribute(Schema = "platinium", Table = "TB_UNIDADE_GESTORA_ORDENADOR_UNGO")] public class UnidadeGestoraOrdenador { #region Variáveis e Propriedades private Dao oDao; private int iID = 0; private int? iIdUnidadeGestora; private UnidadeGestora oUnidadeGestora; private int? iIdOrdenador; private Pessoal oOrdenador; private DateTime? dDataCriado; private DateTime? dDataDesativado; private DateTime? dDataInicio; private DateTime? dDataFim; private bool bAtivo; [PropertyAttribute(Field = "ID_ORDENADOR_DESPESA", AllowNull = false, PropertyType = PropertyCategories.PrimaryKey, Variable = "iID")] public int ID { get { return iID; } } [PropertyAttribute(Field = "FK_UNIDADE_GESTORA", AllowNull = false, Description = "Unidade Gestora", PropertyType = PropertyCategories.ForeignKey, Variable = "iIdUnidadeGestora")] public UnidadeGestora UnidadeGestora { get { if (oUnidadeGestora == null && iIdUnidadeGestora != null) oUnidadeGestora = new UnidadeGestora((int)iIdUnidadeGestora, oDao); return oUnidadeGestora; } set { oUnidadeGestora = value; iIdUnidadeGestora = oUnidadeGestora.ID; } } [PropertyAttribute(Field = "FK_ORDENADOR", AllowNull = false, Description = "Ordenador", PropertyType = PropertyCategories.ForeignKey, Variable = "iIdOrdenador")] public Pessoal Ordenador { get { if (oOrdenador == null && iIdOrdenador != null) oOrdenador = new Pessoal((int)iIdOrdenador, oDao); return oOrdenador; } set { oOrdenador = value; iIdOrdenador = oOrdenador.ID; } } [PropertyAttribute(Field = "DAT_INICIO", Description = "Início da Gestão", AllowNull = false, PropertyType = PropertyCategories.Field)] public DateTime? DataInicio { get { return dDataInicio; } set { dDataInicio = value; } } [PropertyAttribute(Field = "DAT_FIM", Description = "Data Final", AllowNull = true, PropertyType = PropertyCategories.Field)] public DateTime? DataFim { get { return dDataFim; } set { dDataFim = value; } } [PropertyAttribute(Field = "DAT_CRIADO", Description = "Data de criação", AllowNull = false, PropertyType = PropertyCategories.Field)] public DateTime? DataCriado { get { return dDataCriado; } set { dDataCriado = value; } } [PropertyAttribute(Field = "DAT_DESATIVADO", Description = "Data de desativação", AllowNull = true, PropertyType = PropertyCategories.Field)] public DateTime? DataDesativado { get { return dDataDesativado; } set { dDataDesativado = value; } } [PropertyAttribute(Field = "FLG_ATIVO", AllowNull = false, PropertyType = PropertyCategories.Field, DataType = DataTypes.Char, Size = 1)] public bool Ativo { get { return bAtivo; } set { bAtivo = value; } } #endregion #region Construtores public UnidadeGestoraOrdenador() { } public UnidadeGestoraOrdenador(Dao dao) { oDao = dao; } public UnidadeGestoraOrdenador(int id, Dao dao) { List<Parameter> parametro = new List<Parameter>(); parametro.Add(new Parameter("ID", id, ParameterTypes.Filter)); oDao = dao; oDao.Load(this, parametro); } #endregion #region Métodos public CrudActionTypes Salvar() { ManipularDatas(); Validar(); if (iID == 0) return oDao.Insert(this); else return oDao.Update(this); } private void ManipularDatas() { if (iID == 0) this.DataCriado = DateTime.Now; this.DataDesativado = null; if (!this.Ativo) this.DataDesativado = DateTime.Now; } public CrudActionTypes Excluir() { try { return oDao.Delete(this); } catch { throw new ViolacaoRegraException("Registro não pode ser excluido !"); } } private void Validar() { CampoNuloOuInvalidoException ex = new CampoNuloOuInvalidoException(); ex.Mensagens = Pro.Utils.ClassFunctions.ValidateRules(this); if (ex.Mensagens.Count > 0) throw ex; } #endregion } }
29.735632
187
0.562814
[ "MIT" ]
CesarRabelo/eGovernos.Corporativo
src/Entidade/Dominio/UnidadeGestoraOrdenador.cs
5,183
C#
using PcapDotNet.Core; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SharpVelodyne { public class ProgressReportEventArgs { public double Precentage { get; private set; } public long ReadBytes { get; private set; } public DateTime CurrentDataTime { get; private set; } public ProgressReportEventArgs(double precentage, long readBytes, DateTime currentDataTime) { this.Precentage = precentage; this.ReadBytes = readBytes; this.CurrentDataTime = currentDataTime; } } public class VelodyneConverter { public delegate void ProgressReportEventHandler(object sender, ProgressReportEventArgs args); public event ProgressReportEventHandler ProgressReport; public static int NMEA_LENGTH { get; private set; } protected virtual void OnReportProgress(ProgressReportEventArgs e) { ProgressReport?.Invoke(this, e); } public String PcapFile { get; private set; } private VelodyneConverter() { } public static VelodyneConverter Create(String pcapFile) { VelodyneConverter converter = new VelodyneConverter(); converter.PcapFile = pcapFile; return converter; } public static String GetDefaultIndexFile(String pcapFile) { String baseFileName = (new FileInfo(pcapFile)).Directory.FullName + "\\" + Path.GetFileNameWithoutExtension(pcapFile); return baseFileName + ".idx"; } public String GetDefaultIndexFile() { return GetDefaultIndexFile(PcapFile); } public static String GetDefaultPointFile(String pcapFile) { String baseFileName = (new FileInfo(pcapFile)).Directory.FullName + "\\" + Path.GetFileNameWithoutExtension(pcapFile); return baseFileName + ".bin"; } public String GetDefaultPointFile() { return GetDefaultPointFile(PcapFile); } public void Convert(CancellationToken cancellationToken = default(CancellationToken)) { FileInfo fi = new FileInfo(PcapFile); long fileSize = fi.Length; BinaryWriter idxWriter = new BinaryWriter(File.Open(GetDefaultIndexFile(PcapFile), FileMode.Create)); OfflinePacketDevice selectedDevice = new OfflinePacketDevice(PcapFile); PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout using (BinaryWriter pointWriter = new BinaryWriter(File.Open(GetDefaultPointFile(PcapFile), FileMode.Create))) { Packet packet; bool isEof = false; VelodyneNmeaPacket lastNmea = null; long sumBytes = 0; long indexId = 0; while (!isEof) { if (cancellationToken.IsCancellationRequested) { idxWriter.Close(); cancellationToken.ThrowIfCancellationRequested(); } PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Timeout: case PacketCommunicatorReceiveResult.Ok: sumBytes += packet.Length; if (packet.Length == 554) { lastNmea = PacketInterpreter.ReadRecordNMEA(packet.Buffer); indexId++; } else { pointWriter.Write(packet.Timestamp.Ticks); pointWriter.Write(packet.Buffer); if (lastNmea != null) { int l = packet.Length - 6; // this is the end of the pack! double internal_time = BitConverter.ToUInt32(new byte[] { packet[l], packet[l + 1], packet[l + 2], packet[l + 3] }, 0) / 1000000.00; DateTime utcPacketTimestamp = packet.Timestamp.ToUniversalTime(); DateTime time = (new DateTime(utcPacketTimestamp.Year, utcPacketTimestamp.Month, utcPacketTimestamp.Day, utcPacketTimestamp.Hour, 0, 0)).AddSeconds(internal_time); idxWriter.Write(time.Ticks); idxWriter.Write(packet.Timestamp.Ticks); idxWriter.Write(pointWriter.BaseStream.Position); byte[] nmea_byte = Encoding.ASCII.GetBytes(lastNmea.NmeaString.PadRight(NMEA_LENGTH, ' ')); idxWriter.Write(nmea_byte); if (indexId % 100 == 0) { ProgressReportEventArgs args = new ProgressReportEventArgs((((double)sumBytes / (double)fileSize) * 100.0), sumBytes, utcPacketTimestamp); OnReportProgress(args); } lastNmea = null; } } break; case PacketCommunicatorReceiveResult.Eof: isEof = true; break; default: throw new InvalidOperationException("The result " + result + " should never be reached here"); } } } idxWriter.Close(); } } }
38.994048
199
0.512136
[ "MIT" ]
zkoppanyi/spin-stream-viewer
SharpVelodyne/VelodyneConverter.cs
6,553
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Windows.Forms { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.ComponentModel; using System.Drawing; using Microsoft.Win32; using System.Windows.Forms.Layout; /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel"]/*' /> /// <devdoc> /// <para> /// Represents a <see cref='System.Windows.Forms.Panel'/> /// control.</para> /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty(nameof(BorderStyle)), DefaultEvent(nameof(Paint)), Docking(DockingBehavior.Ask), Designer("System.Windows.Forms.Design.PanelDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionPanel)) ] public class Panel : ScrollableControl { private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.Panel"]/*' /> /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Panel'/> class.</para> /// </devdoc> public Panel() : base() { // this class overrides GetPreferredSizeCore, let Control automatically cache the result SetState2(STATE2_USEPREFERREDSIZECACHE, true); TabStop = false; SetStyle(ControlStyles.Selectable | ControlStyles.AllPaintingInWmPaint, false); SetStyle(ControlStyles.SupportsTransparentBackColor, true); } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.AutoSize"]/*' /> /// <devdoc> /// <para> Override to re-expose AutoSize.</para> /// </devdoc> [Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.AutoSizeChanged"]/*' /> [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))] [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] new public event EventHandler AutoSizeChanged { add { base.AutoSizeChanged += value; } remove { base.AutoSizeChanged -= value; } } /// <devdoc> /// Allows the control to optionally shrink when AutoSize is true. /// </devdoc> [ SRDescription(nameof(SR.ControlAutoSizeModeDescr)), SRCategory(nameof(SR.CatLayout)), Browsable(true), DefaultValue(AutoSizeMode.GrowOnly), Localizable(true) ] public virtual AutoSizeMode AutoSizeMode { get { return GetAutoSizeMode(); } set { if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){ throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } if (GetAutoSizeMode() != value) { SetAutoSizeMode(value); if(ParentInternal != null) { // DefaultLayout does not keep anchor information until it needs to. When // AutoSize became a common property, we could no longer blindly call into // DefaultLayout, so now we do a special InitLayout just for DefaultLayout. if(ParentInternal.LayoutEngine == DefaultLayout.Instance) { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize); } } } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.BorderStyle"]/*' /> /// <devdoc> /// <para> Indicates the /// border style for the control.</para> /// </devdoc> [ SRCategory(nameof(SR.CatAppearance)), DefaultValue(BorderStyle.None), DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.PanelBorderStyleDescr)) ] public BorderStyle BorderStyle { get { return borderStyle; } set { if (borderStyle != value) { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } borderStyle = value; UpdateStyles(); } } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.CreateParams"]/*' /> /// <internalonly/> /// <devdoc> /// Returns the parameters needed to create the handle. Inheriting classes /// can override this to provide extra functionality. They should not, /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// </devdoc> protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); switch (borderStyle) { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; case BorderStyle.FixedSingle: cp.Style |= NativeMethods.WS_BORDER; break; } return cp; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.DefaultSize"]/*' /> /// <devdoc> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </devdoc> protected override Size DefaultSize { get { return new Size(200, 100); } } internal override Size GetPreferredSizeCore(Size proposedSize) { // Translating 0,0 from ClientSize to actual Size tells us how much space // is required for the borders. Size borderSize = SizeFromClientSize(Size.Empty); Size totalPadding = borderSize + Padding.Size; return LayoutEngine.GetPreferredSize(this, proposedSize - totalPadding) + totalPadding; } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.KeyUp"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyUp { add { base.KeyUp += value; } remove { base.KeyUp -= value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.KeyDown"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyDown { add { base.KeyDown += value; } remove { base.KeyDown -= value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.KeyPress"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyPressEventHandler KeyPress { add { base.KeyPress += value; } remove { base.KeyPress -= value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.TabStop"]/*' /> /// <devdoc> /// </devdoc> [DefaultValue(false)] new public bool TabStop { get { return base.TabStop; } set { base.TabStop = value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.Text"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.OnResize"]/*' /> /// <internalonly/> /// <devdoc> /// <para>Fires the event indicating that the panel has been resized. /// Inheriting controls should use this in favour of actually listening to /// the event, but should not forget to call base.onResize() to /// ensure that the event is still fired for external listeners.</para> /// </devdoc> protected override void OnResize(EventArgs eventargs) { if (DesignMode && borderStyle == BorderStyle.None) { Invalidate(); } base.OnResize(eventargs); } internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) { base.PrintToMetaFileRecursive(hDC, lParam, bounds); using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) { using(Graphics g = Graphics.FromHdcInternal(hDC.Handle)) { ControlPaint.PrintBorder(g, new Rectangle(Point.Empty, Size), BorderStyle, Border3DStyle.Sunken); } } } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.StringFromBorderStyle"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> private static string StringFromBorderStyle(BorderStyle value) { Type borderStyleType = typeof(BorderStyle); return (ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) ? (borderStyleType.ToString() + "." + value.ToString()) : "[Invalid BorderStyle]"; } /// <include file='doc\Panel.uex' path='docs/doc[@for="Panel.ToString"]/*' /> /// <devdoc> /// Returns a string representation for this control. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); return s + ", BorderStyle: " + StringFromBorderStyle(borderStyle); } } }
38.311321
195
0.549947
[ "MIT" ]
0xflotus/winforms
src/System.Windows.Forms/src/System/Windows/Forms/Panel.cs
12,183
C#
// Copyright (c) MicroElements. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace MicroElements.Metadata.Formatters { /// <summary> /// Default format provider. /// </summary> public class DefaultFormatProvider : IValueFormatterProvider { /// <inheritdoc /> public IEnumerable<IValueFormatter> GetFormatters() { // String yield return SimpleStringFormatter.Instance; // Floating numbers yield return FloatFormatter.Instance; yield return DoubleFormatter.Instance; yield return DecimalFormatter.Instance; // Date and Time yield return DateTimeFormatter.IsoShort; yield return DateTimeOffsetFormatter.Iso; // NodaTime Formatters foreach (var nodaTimeFormatter in new NodaTimeIsoFormatters().GetFormatters()) { yield return nodaTimeFormatter; } } } }
30.527778
101
0.631483
[ "MIT" ]
micro-elements/MicroElements.Metadata
src/MicroElements.Metadata/Metadata/Formatters/DefaultFormatProvider.cs
1,101
C#
namespace SpotifyHotkeys.Core { /// <summary> /// Service that is responsible for performing various actions on the Spotify client. /// </summary> public interface ISpotifyActionService { /// <summary> /// Either starts playing a track or pauses the currently playing track. /// </summary> void TogglePlay(); /// <summary> /// Mutes Spotify. /// </summary> void Mute(); /// <summary> /// Increases the volume of Spotify. /// </summary> void IncreaseVolume(); /// <summary> /// Decreases the volume of Spotify. /// </summary> void DecreaseVolume(); /// <summary> /// Stops the track playing. /// </summary> void Stop(); /// <summary> /// Changes to the next track. /// </summary> void NextTrack(); /// <summary> /// Changes to the previous track. /// </summary> void PreviousTrack(); } }
24.209302
89
0.508165
[ "MIT" ]
joakimskoog/SpotifyHotkeys
SpotifyActionService/ISpotifyActionService.cs
1,043
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.IoTSiteWise")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT SiteWise. AWS IoT SiteWise is a managed service that makes it easy to collect, store, organize and monitor data from industrial equipment at scale. You can use AWS IoT SiteWise to model your physical assets, processes and facilities, quickly compute common industrial performance metrics, and create fully managed web applications to help analyze industrial equipment data, prevent costly equipment issues, and reduce production inefficiencies.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.5.1.1")]
56.4375
532
0.765781
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/IoTSiteWise/Properties/AssemblyInfo.cs
1,806
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2/audio_config.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Dialogflow.V2 { /// <summary>Holder for reflection information generated from google/cloud/dialogflow/v2/audio_config.proto</summary> public static partial class AudioConfigReflection { #region Descriptor /// <summary>File descriptor for google/cloud/dialogflow/v2/audio_config.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AudioConfigReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvY2xvdWQvZGlhbG9nZmxvdy92Mi9hdWRpb19jb25maWcucHJv", "dG8SGmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyGh9nb29nbGUvYXBpL2Zp", "ZWxkX2JlaGF2aW9yLnByb3RvGhlnb29nbGUvYXBpL3Jlc291cmNlLnByb3Rv", "Gh5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8aH2dvb2dsZS9wcm90", "b2J1Zi90aW1lc3RhbXAucHJvdG8aHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMu", "cHJvdG8iLwoNU3BlZWNoQ29udGV4dBIPCgdwaHJhc2VzGAEgAygJEg0KBWJv", "b3N0GAIgASgCIpIBCg5TcGVlY2hXb3JkSW5mbxIMCgR3b3JkGAMgASgJEi8K", "DHN0YXJ0X29mZnNldBgBIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlv", "bhItCgplbmRfb2Zmc2V0GAIgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0", "aW9uEhIKCmNvbmZpZGVuY2UYBCABKAIimwMKEElucHV0QXVkaW9Db25maWcS", "QQoOYXVkaW9fZW5jb2RpbmcYASABKA4yKS5nb29nbGUuY2xvdWQuZGlhbG9n", "Zmxvdy52Mi5BdWRpb0VuY29kaW5nEhkKEXNhbXBsZV9yYXRlX2hlcnR6GAIg", "ASgFEhUKDWxhbmd1YWdlX2NvZGUYAyABKAkSGAoQZW5hYmxlX3dvcmRfaW5m", "bxgNIAEoCBIYCgxwaHJhc2VfaGludHMYBCADKAlCAhgBEkIKD3NwZWVjaF9j", "b250ZXh0cxgLIAMoCzIpLmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLlNw", "ZWVjaENvbnRleHQSDQoFbW9kZWwYByABKAkSRQoNbW9kZWxfdmFyaWFudBgK", "IAEoDjIuLmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLlNwZWVjaE1vZGVs", "VmFyaWFudBIYChBzaW5nbGVfdXR0ZXJhbmNlGAggASgIEioKImRpc2FibGVf", "bm9fc3BlZWNoX3JlY29nbml6ZWRfZXZlbnQYDiABKAgiZgoUVm9pY2VTZWxl", "Y3Rpb25QYXJhbXMSDAoEbmFtZRgBIAEoCRJACgtzc21sX2dlbmRlchgCIAEo", "DjIrLmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLlNzbWxWb2ljZUdlbmRl", "ciKzAQoWU3ludGhlc2l6ZVNwZWVjaENvbmZpZxIVCg1zcGVha2luZ19yYXRl", "GAEgASgBEg0KBXBpdGNoGAIgASgBEhYKDnZvbHVtZV9nYWluX2RiGAMgASgB", "EhoKEmVmZmVjdHNfcHJvZmlsZV9pZBgFIAMoCRI/CgV2b2ljZRgEIAEoCzIw", "Lmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLlZvaWNlU2VsZWN0aW9uUGFy", "YW1zItIBChFPdXRwdXRBdWRpb0NvbmZpZxJMCg5hdWRpb19lbmNvZGluZxgB", "IAEoDjIvLmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLk91dHB1dEF1ZGlv", "RW5jb2RpbmdCA+BBAhIZChFzYW1wbGVfcmF0ZV9oZXJ0ehgCIAEoBRJUChhz", "eW50aGVzaXplX3NwZWVjaF9jb25maWcYAyABKAsyMi5nb29nbGUuY2xvdWQu", "ZGlhbG9nZmxvdy52Mi5TeW50aGVzaXplU3BlZWNoQ29uZmlnImcKElNwZWVj", "aFRvVGV4dENvbmZpZxJRChRzcGVlY2hfbW9kZWxfdmFyaWFudBgBIAEoDjIu", "Lmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyLlNwZWVjaE1vZGVsVmFyaWFu", "dEID4EEBKvsBCg1BdWRpb0VuY29kaW5nEh4KGkFVRElPX0VOQ09ESU5HX1VO", "U1BFQ0lGSUVEEAASHAoYQVVESU9fRU5DT0RJTkdfTElORUFSXzE2EAESFwoT", "QVVESU9fRU5DT0RJTkdfRkxBQxACEhgKFEFVRElPX0VOQ09ESU5HX01VTEFX", "EAMSFgoSQVVESU9fRU5DT0RJTkdfQU1SEAQSGQoVQVVESU9fRU5DT0RJTkdf", "QU1SX1dCEAUSGwoXQVVESU9fRU5DT0RJTkdfT0dHX09QVVMQBhIpCiVBVURJ", "T19FTkNPRElOR19TUEVFWF9XSVRIX0hFQURFUl9CWVRFEAcqdgoSU3BlZWNo", "TW9kZWxWYXJpYW50EiQKIFNQRUVDSF9NT0RFTF9WQVJJQU5UX1VOU1BFQ0lG", "SUVEEAASFgoSVVNFX0JFU1RfQVZBSUxBQkxFEAESEAoMVVNFX1NUQU5EQVJE", "EAISEAoMVVNFX0VOSEFOQ0VEEAMqjQEKD1NzbWxWb2ljZUdlbmRlchIhCh1T", "U01MX1ZPSUNFX0dFTkRFUl9VTlNQRUNJRklFRBAAEhoKFlNTTUxfVk9JQ0Vf", "R0VOREVSX01BTEUQARIcChhTU01MX1ZPSUNFX0dFTkRFUl9GRU1BTEUQAhId", "ChlTU01MX1ZPSUNFX0dFTkRFUl9ORVVUUkFMEAMq7AEKE091dHB1dEF1ZGlv", "RW5jb2RpbmcSJQohT1VUUFVUX0FVRElPX0VOQ09ESU5HX1VOU1BFQ0lGSUVE", "EAASIwofT1VUUFVUX0FVRElPX0VOQ09ESU5HX0xJTkVBUl8xNhABEh0KGU9V", "VFBVVF9BVURJT19FTkNPRElOR19NUDMQAhIlCiFPVVRQVVRfQVVESU9fRU5D", "T0RJTkdfTVAzXzY0X0tCUFMQBBIiCh5PVVRQVVRfQVVESU9fRU5DT0RJTkdf", "T0dHX09QVVMQAxIfChtPVVRQVVRfQVVESU9fRU5DT0RJTkdfTVVMQVcQBUKf", "AQoeY29tLmdvb2dsZS5jbG91ZC5kaWFsb2dmbG93LnYyQhBBdWRpb0NvbmZp", "Z1Byb3RvUAFaRGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFw", "aXMvY2xvdWQvZGlhbG9nZmxvdy92MjtkaWFsb2dmbG93+AEBogICREaqAhpH", "b29nbGUuQ2xvdWQuRGlhbG9nZmxvdy5WMmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Cloud.Dialogflow.V2.AudioEncoding), typeof(global::Google.Cloud.Dialogflow.V2.SpeechModelVariant), typeof(global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender), typeof(global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding), }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.SpeechContext), global::Google.Cloud.Dialogflow.V2.SpeechContext.Parser, new[]{ "Phrases", "Boost" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.SpeechWordInfo), global::Google.Cloud.Dialogflow.V2.SpeechWordInfo.Parser, new[]{ "Word", "StartOffset", "EndOffset", "Confidence" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.InputAudioConfig), global::Google.Cloud.Dialogflow.V2.InputAudioConfig.Parser, new[]{ "AudioEncoding", "SampleRateHertz", "LanguageCode", "EnableWordInfo", "PhraseHints", "SpeechContexts", "Model", "ModelVariant", "SingleUtterance", "DisableNoSpeechRecognizedEvent" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams), global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams.Parser, new[]{ "Name", "SsmlGender" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig), global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig.Parser, new[]{ "SpeakingRate", "Pitch", "VolumeGainDb", "EffectsProfileId", "Voice" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.OutputAudioConfig), global::Google.Cloud.Dialogflow.V2.OutputAudioConfig.Parser, new[]{ "AudioEncoding", "SampleRateHertz", "SynthesizeSpeechConfig" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dialogflow.V2.SpeechToTextConfig), global::Google.Cloud.Dialogflow.V2.SpeechToTextConfig.Parser, new[]{ "SpeechModelVariant" }, null, null, null, null) })); } #endregion } #region Enums /// <summary> /// Audio encoding of the audio content sent in the conversational query request. /// Refer to the /// [Cloud Speech API /// documentation](https://cloud.google.com/speech-to-text/docs/basics) for more /// details. /// </summary> public enum AudioEncoding { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Uncompressed 16-bit signed little-endian samples (Linear PCM). /// </summary> [pbr::OriginalName("AUDIO_ENCODING_LINEAR_16")] Linear16 = 1, /// <summary> /// [`FLAC`](https://xiph.org/flac/documentation.html) (Free Lossless Audio /// Codec) is the recommended encoding because it is lossless (therefore /// recognition is not compromised) and requires only about half the /// bandwidth of `LINEAR16`. `FLAC` stream encoding supports 16-bit and /// 24-bit samples, however, not all fields in `STREAMINFO` are supported. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_FLAC")] Flac = 2, /// <summary> /// 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_MULAW")] Mulaw = 3, /// <summary> /// Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_AMR")] Amr = 4, /// <summary> /// Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_AMR_WB")] AmrWb = 5, /// <summary> /// Opus encoded audio frames in Ogg container /// ([OggOpus](https://wiki.xiph.org/OggOpus)). /// `sample_rate_hertz` must be 16000. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_OGG_OPUS")] OggOpus = 6, /// <summary> /// Although the use of lossy encodings is not recommended, if a very low /// bitrate encoding is required, `OGG_OPUS` is highly preferred over /// Speex encoding. The [Speex](https://speex.org/) encoding supported by /// Dialogflow API has a header byte in each block, as in MIME type /// `audio/x-speex-with-header-byte`. /// It is a variant of the RTP Speex encoding defined in /// [RFC 5574](https://tools.ietf.org/html/rfc5574). /// The stream is a sequence of blocks, one block per RTP packet. Each block /// starts with a byte containing the length of the block, in bytes, followed /// by one or more frames of Speex data, padded to an integral number of /// bytes (octets) as specified in RFC 5574. In other words, each RTP header /// is replaced with a single byte containing the block length. Only Speex /// wideband is supported. `sample_rate_hertz` must be 16000. /// </summary> [pbr::OriginalName("AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE")] SpeexWithHeaderByte = 7, } /// <summary> /// Variant of the specified [Speech model][google.cloud.dialogflow.v2.InputAudioConfig.model] to use. /// /// See the [Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) /// for which models have different variants. For example, the "phone_call" model /// has both a standard and an enhanced variant. When you use an enhanced model, /// you will generally receive higher quality results than for a standard model. /// </summary> public enum SpeechModelVariant { /// <summary> /// No model variant specified. In this case Dialogflow defaults to /// USE_BEST_AVAILABLE. /// </summary> [pbr::OriginalName("SPEECH_MODEL_VARIANT_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Use the best available variant of the [Speech /// model][InputAudioConfig.model] that the caller is eligible for. /// /// Please see the [Dialogflow /// docs](https://cloud.google.com/dialogflow/docs/data-logging) for /// how to make your project eligible for enhanced models. /// </summary> [pbr::OriginalName("USE_BEST_AVAILABLE")] UseBestAvailable = 1, /// <summary> /// Use standard model variant even if an enhanced model is available. See the /// [Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) /// for details about enhanced models. /// </summary> [pbr::OriginalName("USE_STANDARD")] UseStandard = 2, /// <summary> /// Use an enhanced model variant: /// /// * If an enhanced variant does not exist for the given /// [model][google.cloud.dialogflow.v2.InputAudioConfig.model] and request language, Dialogflow falls /// back to the standard variant. /// /// The [Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) /// describes which models have enhanced variants. /// /// * If the API caller isn't eligible for enhanced models, Dialogflow returns /// an error. Please see the [Dialogflow /// docs](https://cloud.google.com/dialogflow/docs/data-logging) /// for how to make your project eligible. /// </summary> [pbr::OriginalName("USE_ENHANCED")] UseEnhanced = 3, } /// <summary> /// Gender of the voice as described in /// [SSML voice element](https://www.w3.org/TR/speech-synthesis11/#edef_voice). /// </summary> public enum SsmlVoiceGender { /// <summary> /// An unspecified gender, which means that the client doesn't care which /// gender the selected voice will have. /// </summary> [pbr::OriginalName("SSML_VOICE_GENDER_UNSPECIFIED")] Unspecified = 0, /// <summary> /// A male voice. /// </summary> [pbr::OriginalName("SSML_VOICE_GENDER_MALE")] Male = 1, /// <summary> /// A female voice. /// </summary> [pbr::OriginalName("SSML_VOICE_GENDER_FEMALE")] Female = 2, /// <summary> /// A gender-neutral voice. /// </summary> [pbr::OriginalName("SSML_VOICE_GENDER_NEUTRAL")] Neutral = 3, } /// <summary> /// Audio encoding of the output audio format in Text-To-Speech. /// </summary> public enum OutputAudioEncoding { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Uncompressed 16-bit signed little-endian samples (Linear PCM). /// Audio content returned as LINEAR16 also contains a WAV header. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_LINEAR_16")] Linear16 = 1, /// <summary> /// MP3 audio at 32kbps. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_MP3")] Mp3 = 2, /// <summary> /// MP3 audio at 64kbps. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_MP3_64_KBPS")] Mp364Kbps = 4, /// <summary> /// Opus encoded audio wrapped in an ogg container. The result will be a /// file which can be played natively on Android, and in browsers (at least /// Chrome and Firefox). The quality of the encoding is considerably higher /// than MP3 while using approximately the same bitrate. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_OGG_OPUS")] OggOpus = 3, /// <summary> /// 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. /// </summary> [pbr::OriginalName("OUTPUT_AUDIO_ENCODING_MULAW")] Mulaw = 5, } #endregion #region Messages /// <summary> /// Hints for the speech recognizer to help with recognition in a specific /// conversation state. /// </summary> public sealed partial class SpeechContext : pb::IMessage<SpeechContext> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechContext> _parser = new pb::MessageParser<SpeechContext>(() => new SpeechContext()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechContext> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext(SpeechContext other) : this() { phrases_ = other.phrases_.Clone(); boost_ = other.boost_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext Clone() { return new SpeechContext(this); } /// <summary>Field number for the "phrases" field.</summary> public const int PhrasesFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_phrases_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> phrases_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. A list of strings containing words and phrases that the speech /// recognizer should recognize with higher likelihood. /// /// This list can be used to: /// /// * improve accuracy for words and phrases you expect the user to say, /// e.g. typical commands for your Dialogflow agent /// * add additional words to the speech recognizer vocabulary /// * ... /// /// See the [Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/quotas) for usage /// limits. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Phrases { get { return phrases_; } } /// <summary>Field number for the "boost" field.</summary> public const int BoostFieldNumber = 2; private float boost_; /// <summary> /// Optional. Boost for this context compared to other contexts: /// /// * If the boost is positive, Dialogflow will increase the probability that /// the phrases in this context are recognized over similar sounding phrases. /// * If the boost is unspecified or non-positive, Dialogflow will not apply /// any boost. /// /// Dialogflow recommends that you use boosts in the range (0, 20] and that you /// find a value that fits your use case with binary search. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public float Boost { get { return boost_; } set { boost_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechContext); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechContext other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!phrases_.Equals(other.phrases_)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Boost, other.Boost)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= phrases_.GetHashCode(); if (Boost != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Boost); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else phrases_.WriteTo(output, _repeated_phrases_codec); if (Boost != 0F) { output.WriteRawTag(21); output.WriteFloat(Boost); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { phrases_.WriteTo(ref output, _repeated_phrases_codec); if (Boost != 0F) { output.WriteRawTag(21); output.WriteFloat(Boost); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += phrases_.CalculateSize(_repeated_phrases_codec); if (Boost != 0F) { size += 1 + 4; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechContext other) { if (other == null) { return; } phrases_.Add(other.phrases_); if (other.Boost != 0F) { Boost = other.Boost; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { phrases_.AddEntriesFrom(input, _repeated_phrases_codec); break; } case 21: { Boost = input.ReadFloat(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { phrases_.AddEntriesFrom(ref input, _repeated_phrases_codec); break; } case 21: { Boost = input.ReadFloat(); break; } } } } #endif } /// <summary> /// Information for a word recognized by the speech recognizer. /// </summary> public sealed partial class SpeechWordInfo : pb::IMessage<SpeechWordInfo> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechWordInfo> _parser = new pb::MessageParser<SpeechWordInfo>(() => new SpeechWordInfo()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechWordInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechWordInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechWordInfo(SpeechWordInfo other) : this() { word_ = other.word_; startOffset_ = other.startOffset_ != null ? other.startOffset_.Clone() : null; endOffset_ = other.endOffset_ != null ? other.endOffset_.Clone() : null; confidence_ = other.confidence_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechWordInfo Clone() { return new SpeechWordInfo(this); } /// <summary>Field number for the "word" field.</summary> public const int WordFieldNumber = 3; private string word_ = ""; /// <summary> /// The word this info is for. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Word { get { return word_; } set { word_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "start_offset" field.</summary> public const int StartOffsetFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Duration startOffset_; /// <summary> /// Time offset relative to the beginning of the audio that corresponds to the /// start of the spoken word. This is an experimental feature and the accuracy /// of the time offset can vary. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration StartOffset { get { return startOffset_; } set { startOffset_ = value; } } /// <summary>Field number for the "end_offset" field.</summary> public const int EndOffsetFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration endOffset_; /// <summary> /// Time offset relative to the beginning of the audio that corresponds to the /// end of the spoken word. This is an experimental feature and the accuracy of /// the time offset can vary. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration EndOffset { get { return endOffset_; } set { endOffset_ = value; } } /// <summary>Field number for the "confidence" field.</summary> public const int ConfidenceFieldNumber = 4; private float confidence_; /// <summary> /// The Speech confidence between 0.0 and 1.0 for this word. A higher number /// indicates an estimated greater likelihood that the recognized word is /// correct. The default of 0.0 is a sentinel value indicating that confidence /// was not set. /// /// This field is not guaranteed to be fully stable over time for the same /// audio input. Users should also not rely on it to always be provided. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public float Confidence { get { return confidence_; } set { confidence_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechWordInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechWordInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Word != other.Word) return false; if (!object.Equals(StartOffset, other.StartOffset)) return false; if (!object.Equals(EndOffset, other.EndOffset)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Word.Length != 0) hash ^= Word.GetHashCode(); if (startOffset_ != null) hash ^= StartOffset.GetHashCode(); if (endOffset_ != null) hash ^= EndOffset.GetHashCode(); if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (startOffset_ != null) { output.WriteRawTag(10); output.WriteMessage(StartOffset); } if (endOffset_ != null) { output.WriteRawTag(18); output.WriteMessage(EndOffset); } if (Word.Length != 0) { output.WriteRawTag(26); output.WriteString(Word); } if (Confidence != 0F) { output.WriteRawTag(37); output.WriteFloat(Confidence); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (startOffset_ != null) { output.WriteRawTag(10); output.WriteMessage(StartOffset); } if (endOffset_ != null) { output.WriteRawTag(18); output.WriteMessage(EndOffset); } if (Word.Length != 0) { output.WriteRawTag(26); output.WriteString(Word); } if (Confidence != 0F) { output.WriteRawTag(37); output.WriteFloat(Confidence); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Word.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Word); } if (startOffset_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartOffset); } if (endOffset_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndOffset); } if (Confidence != 0F) { size += 1 + 4; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechWordInfo other) { if (other == null) { return; } if (other.Word.Length != 0) { Word = other.Word; } if (other.startOffset_ != null) { if (startOffset_ == null) { StartOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } StartOffset.MergeFrom(other.StartOffset); } if (other.endOffset_ != null) { if (endOffset_ == null) { EndOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } EndOffset.MergeFrom(other.EndOffset); } if (other.Confidence != 0F) { Confidence = other.Confidence; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (startOffset_ == null) { StartOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(StartOffset); break; } case 18: { if (endOffset_ == null) { EndOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(EndOffset); break; } case 26: { Word = input.ReadString(); break; } case 37: { Confidence = input.ReadFloat(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (startOffset_ == null) { StartOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(StartOffset); break; } case 18: { if (endOffset_ == null) { EndOffset = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(EndOffset); break; } case 26: { Word = input.ReadString(); break; } case 37: { Confidence = input.ReadFloat(); break; } } } } #endif } /// <summary> /// Instructs the speech recognizer how to process the audio content. /// </summary> public sealed partial class InputAudioConfig : pb::IMessage<InputAudioConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<InputAudioConfig> _parser = new pb::MessageParser<InputAudioConfig>(() => new InputAudioConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<InputAudioConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InputAudioConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InputAudioConfig(InputAudioConfig other) : this() { audioEncoding_ = other.audioEncoding_; sampleRateHertz_ = other.sampleRateHertz_; languageCode_ = other.languageCode_; enableWordInfo_ = other.enableWordInfo_; phraseHints_ = other.phraseHints_.Clone(); speechContexts_ = other.speechContexts_.Clone(); model_ = other.model_; modelVariant_ = other.modelVariant_; singleUtterance_ = other.singleUtterance_; disableNoSpeechRecognizedEvent_ = other.disableNoSpeechRecognizedEvent_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InputAudioConfig Clone() { return new InputAudioConfig(this); } /// <summary>Field number for the "audio_encoding" field.</summary> public const int AudioEncodingFieldNumber = 1; private global::Google.Cloud.Dialogflow.V2.AudioEncoding audioEncoding_ = global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified; /// <summary> /// Required. Audio encoding of the audio content to process. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.AudioEncoding AudioEncoding { get { return audioEncoding_; } set { audioEncoding_ = value; } } /// <summary>Field number for the "sample_rate_hertz" field.</summary> public const int SampleRateHertzFieldNumber = 2; private int sampleRateHertz_; /// <summary> /// Required. Sample rate (in Hertz) of the audio content sent in the query. /// Refer to /// [Cloud Speech API /// documentation](https://cloud.google.com/speech-to-text/docs/basics) for /// more details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int SampleRateHertz { get { return sampleRateHertz_; } set { sampleRateHertz_ = value; } } /// <summary>Field number for the "language_code" field.</summary> public const int LanguageCodeFieldNumber = 3; private string languageCode_ = ""; /// <summary> /// Required. The language of the supplied audio. Dialogflow does not do /// translations. See [Language /// Support](https://cloud.google.com/dialogflow/docs/reference/language) /// for a list of the currently supported language codes. Note that queries in /// the same session do not necessarily need to specify the same language. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string LanguageCode { get { return languageCode_; } set { languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "enable_word_info" field.</summary> public const int EnableWordInfoFieldNumber = 13; private bool enableWordInfo_; /// <summary> /// If `true`, Dialogflow returns [SpeechWordInfo][google.cloud.dialogflow.v2.SpeechWordInfo] in /// [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] with information about the recognized speech /// words, e.g. start and end time offsets. If false or unspecified, Speech /// doesn't return any word-level information. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool EnableWordInfo { get { return enableWordInfo_; } set { enableWordInfo_ = value; } } /// <summary>Field number for the "phrase_hints" field.</summary> public const int PhraseHintsFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_phraseHints_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> phraseHints_ = new pbc::RepeatedField<string>(); /// <summary> /// A list of strings containing words and phrases that the speech /// recognizer should recognize with higher likelihood. /// /// See [the Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-hints) /// for more details. /// /// This field is deprecated. Please use [speech_contexts]() instead. If you /// specify both [phrase_hints]() and [speech_contexts](), Dialogflow will /// treat the [phrase_hints]() as a single additional [SpeechContext](). /// </summary> [global::System.ObsoleteAttribute] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> PhraseHints { get { return phraseHints_; } } /// <summary>Field number for the "speech_contexts" field.</summary> public const int SpeechContextsFieldNumber = 11; private static readonly pb::FieldCodec<global::Google.Cloud.Dialogflow.V2.SpeechContext> _repeated_speechContexts_codec = pb::FieldCodec.ForMessage(90, global::Google.Cloud.Dialogflow.V2.SpeechContext.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Dialogflow.V2.SpeechContext> speechContexts_ = new pbc::RepeatedField<global::Google.Cloud.Dialogflow.V2.SpeechContext>(); /// <summary> /// Context information to assist speech recognition. /// /// See [the Cloud Speech /// documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-hints) /// for more details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Dialogflow.V2.SpeechContext> SpeechContexts { get { return speechContexts_; } } /// <summary>Field number for the "model" field.</summary> public const int ModelFieldNumber = 7; private string model_ = ""; /// <summary> /// Which Speech model to select for the given request. Select the /// model best suited to your domain to get best results. If a model is not /// explicitly specified, then we auto-select a model based on the parameters /// in the InputAudioConfig. /// If enhanced speech model is enabled for the agent and an enhanced /// version of the specified model for the language does not exist, then the /// speech is recognized using the standard version of the specified model. /// Refer to /// [Cloud Speech API /// documentation](https://cloud.google.com/speech-to-text/docs/basics#select-model) /// for more details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Model { get { return model_; } set { model_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "model_variant" field.</summary> public const int ModelVariantFieldNumber = 10; private global::Google.Cloud.Dialogflow.V2.SpeechModelVariant modelVariant_ = global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified; /// <summary> /// Which variant of the [Speech model][google.cloud.dialogflow.v2.InputAudioConfig.model] to use. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.SpeechModelVariant ModelVariant { get { return modelVariant_; } set { modelVariant_ = value; } } /// <summary>Field number for the "single_utterance" field.</summary> public const int SingleUtteranceFieldNumber = 8; private bool singleUtterance_; /// <summary> /// If `false` (default), recognition does not cease until the /// client closes the stream. /// If `true`, the recognizer will detect a single spoken utterance in input /// audio. Recognition ceases when it detects the audio's voice has /// stopped or paused. In this case, once a detected intent is received, the /// client should close the stream and start a new request with a new stream as /// needed. /// Note: This setting is relevant only for streaming methods. /// Note: When specified, InputAudioConfig.single_utterance takes precedence /// over StreamingDetectIntentRequest.single_utterance. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool SingleUtterance { get { return singleUtterance_; } set { singleUtterance_ = value; } } /// <summary>Field number for the "disable_no_speech_recognized_event" field.</summary> public const int DisableNoSpeechRecognizedEventFieldNumber = 14; private bool disableNoSpeechRecognizedEvent_; /// <summary> /// Only used in [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] and /// [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]. /// If `false` and recognition doesn't return any result, trigger /// `NO_SPEECH_RECOGNIZED` event to Dialogflow agent. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool DisableNoSpeechRecognizedEvent { get { return disableNoSpeechRecognizedEvent_; } set { disableNoSpeechRecognizedEvent_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as InputAudioConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(InputAudioConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AudioEncoding != other.AudioEncoding) return false; if (SampleRateHertz != other.SampleRateHertz) return false; if (LanguageCode != other.LanguageCode) return false; if (EnableWordInfo != other.EnableWordInfo) return false; if(!phraseHints_.Equals(other.phraseHints_)) return false; if(!speechContexts_.Equals(other.speechContexts_)) return false; if (Model != other.Model) return false; if (ModelVariant != other.ModelVariant) return false; if (SingleUtterance != other.SingleUtterance) return false; if (DisableNoSpeechRecognizedEvent != other.DisableNoSpeechRecognizedEvent) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified) hash ^= AudioEncoding.GetHashCode(); if (SampleRateHertz != 0) hash ^= SampleRateHertz.GetHashCode(); if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode(); if (EnableWordInfo != false) hash ^= EnableWordInfo.GetHashCode(); hash ^= phraseHints_.GetHashCode(); hash ^= speechContexts_.GetHashCode(); if (Model.Length != 0) hash ^= Model.GetHashCode(); if (ModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) hash ^= ModelVariant.GetHashCode(); if (SingleUtterance != false) hash ^= SingleUtterance.GetHashCode(); if (DisableNoSpeechRecognizedEvent != false) hash ^= DisableNoSpeechRecognizedEvent.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) AudioEncoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (LanguageCode.Length != 0) { output.WriteRawTag(26); output.WriteString(LanguageCode); } phraseHints_.WriteTo(output, _repeated_phraseHints_codec); if (Model.Length != 0) { output.WriteRawTag(58); output.WriteString(Model); } if (SingleUtterance != false) { output.WriteRawTag(64); output.WriteBool(SingleUtterance); } if (ModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { output.WriteRawTag(80); output.WriteEnum((int) ModelVariant); } speechContexts_.WriteTo(output, _repeated_speechContexts_codec); if (EnableWordInfo != false) { output.WriteRawTag(104); output.WriteBool(EnableWordInfo); } if (DisableNoSpeechRecognizedEvent != false) { output.WriteRawTag(112); output.WriteBool(DisableNoSpeechRecognizedEvent); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) AudioEncoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (LanguageCode.Length != 0) { output.WriteRawTag(26); output.WriteString(LanguageCode); } phraseHints_.WriteTo(ref output, _repeated_phraseHints_codec); if (Model.Length != 0) { output.WriteRawTag(58); output.WriteString(Model); } if (SingleUtterance != false) { output.WriteRawTag(64); output.WriteBool(SingleUtterance); } if (ModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { output.WriteRawTag(80); output.WriteEnum((int) ModelVariant); } speechContexts_.WriteTo(ref output, _repeated_speechContexts_codec); if (EnableWordInfo != false) { output.WriteRawTag(104); output.WriteBool(EnableWordInfo); } if (DisableNoSpeechRecognizedEvent != false) { output.WriteRawTag(112); output.WriteBool(DisableNoSpeechRecognizedEvent); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AudioEncoding); } if (SampleRateHertz != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SampleRateHertz); } if (LanguageCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode); } if (EnableWordInfo != false) { size += 1 + 1; } size += phraseHints_.CalculateSize(_repeated_phraseHints_codec); size += speechContexts_.CalculateSize(_repeated_speechContexts_codec); if (Model.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Model); } if (ModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ModelVariant); } if (SingleUtterance != false) { size += 1 + 1; } if (DisableNoSpeechRecognizedEvent != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(InputAudioConfig other) { if (other == null) { return; } if (other.AudioEncoding != global::Google.Cloud.Dialogflow.V2.AudioEncoding.Unspecified) { AudioEncoding = other.AudioEncoding; } if (other.SampleRateHertz != 0) { SampleRateHertz = other.SampleRateHertz; } if (other.LanguageCode.Length != 0) { LanguageCode = other.LanguageCode; } if (other.EnableWordInfo != false) { EnableWordInfo = other.EnableWordInfo; } phraseHints_.Add(other.phraseHints_); speechContexts_.Add(other.speechContexts_); if (other.Model.Length != 0) { Model = other.Model; } if (other.ModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { ModelVariant = other.ModelVariant; } if (other.SingleUtterance != false) { SingleUtterance = other.SingleUtterance; } if (other.DisableNoSpeechRecognizedEvent != false) { DisableNoSpeechRecognizedEvent = other.DisableNoSpeechRecognizedEvent; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { AudioEncoding = (global::Google.Cloud.Dialogflow.V2.AudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { LanguageCode = input.ReadString(); break; } case 34: { phraseHints_.AddEntriesFrom(input, _repeated_phraseHints_codec); break; } case 58: { Model = input.ReadString(); break; } case 64: { SingleUtterance = input.ReadBool(); break; } case 80: { ModelVariant = (global::Google.Cloud.Dialogflow.V2.SpeechModelVariant) input.ReadEnum(); break; } case 90: { speechContexts_.AddEntriesFrom(input, _repeated_speechContexts_codec); break; } case 104: { EnableWordInfo = input.ReadBool(); break; } case 112: { DisableNoSpeechRecognizedEvent = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { AudioEncoding = (global::Google.Cloud.Dialogflow.V2.AudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { LanguageCode = input.ReadString(); break; } case 34: { phraseHints_.AddEntriesFrom(ref input, _repeated_phraseHints_codec); break; } case 58: { Model = input.ReadString(); break; } case 64: { SingleUtterance = input.ReadBool(); break; } case 80: { ModelVariant = (global::Google.Cloud.Dialogflow.V2.SpeechModelVariant) input.ReadEnum(); break; } case 90: { speechContexts_.AddEntriesFrom(ref input, _repeated_speechContexts_codec); break; } case 104: { EnableWordInfo = input.ReadBool(); break; } case 112: { DisableNoSpeechRecognizedEvent = input.ReadBool(); break; } } } } #endif } /// <summary> /// Description of which voice to use for speech synthesis. /// </summary> public sealed partial class VoiceSelectionParams : pb::IMessage<VoiceSelectionParams> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<VoiceSelectionParams> _parser = new pb::MessageParser<VoiceSelectionParams>(() => new VoiceSelectionParams()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<VoiceSelectionParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VoiceSelectionParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VoiceSelectionParams(VoiceSelectionParams other) : this() { name_ = other.name_; ssmlGender_ = other.ssmlGender_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VoiceSelectionParams Clone() { return new VoiceSelectionParams(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Optional. The name of the voice. If not set, the service will choose a /// voice based on the other parameters such as language_code and /// [ssml_gender][google.cloud.dialogflow.v2.VoiceSelectionParams.ssml_gender]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "ssml_gender" field.</summary> public const int SsmlGenderFieldNumber = 2; private global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender ssmlGender_ = global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified; /// <summary> /// Optional. The preferred gender of the voice. If not set, the service will /// choose a voice based on the other parameters such as language_code and /// [name][google.cloud.dialogflow.v2.VoiceSelectionParams.name]. Note that this is only a preference, not requirement. If a /// voice of the appropriate gender is not available, the synthesizer should /// substitute a voice with a different gender rather than failing the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender SsmlGender { get { return ssmlGender_; } set { ssmlGender_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as VoiceSelectionParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(VoiceSelectionParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (SsmlGender != other.SsmlGender) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (SsmlGender != global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified) hash ^= SsmlGender.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (SsmlGender != global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) SsmlGender); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (SsmlGender != global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) SsmlGender); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (SsmlGender != global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SsmlGender); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(VoiceSelectionParams other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.SsmlGender != global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender.Unspecified) { SsmlGender = other.SsmlGender; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 16: { SsmlGender = (global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender) input.ReadEnum(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 16: { SsmlGender = (global::Google.Cloud.Dialogflow.V2.SsmlVoiceGender) input.ReadEnum(); break; } } } } #endif } /// <summary> /// Configuration of how speech should be synthesized. /// </summary> public sealed partial class SynthesizeSpeechConfig : pb::IMessage<SynthesizeSpeechConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SynthesizeSpeechConfig> _parser = new pb::MessageParser<SynthesizeSpeechConfig>(() => new SynthesizeSpeechConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SynthesizeSpeechConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SynthesizeSpeechConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SynthesizeSpeechConfig(SynthesizeSpeechConfig other) : this() { speakingRate_ = other.speakingRate_; pitch_ = other.pitch_; volumeGainDb_ = other.volumeGainDb_; effectsProfileId_ = other.effectsProfileId_.Clone(); voice_ = other.voice_ != null ? other.voice_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SynthesizeSpeechConfig Clone() { return new SynthesizeSpeechConfig(this); } /// <summary>Field number for the "speaking_rate" field.</summary> public const int SpeakingRateFieldNumber = 1; private double speakingRate_; /// <summary> /// Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal /// native speed supported by the specific voice. 2.0 is twice as fast, and /// 0.5 is half as fast. If unset(0.0), defaults to the native 1.0 speed. Any /// other values &lt; 0.25 or > 4.0 will return an error. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public double SpeakingRate { get { return speakingRate_; } set { speakingRate_ = value; } } /// <summary>Field number for the "pitch" field.</summary> public const int PitchFieldNumber = 2; private double pitch_; /// <summary> /// Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 /// semitones from the original pitch. -20 means decrease 20 semitones from the /// original pitch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public double Pitch { get { return pitch_; } set { pitch_ = value; } } /// <summary>Field number for the "volume_gain_db" field.</summary> public const int VolumeGainDbFieldNumber = 3; private double volumeGainDb_; /// <summary> /// Optional. Volume gain (in dB) of the normal native volume supported by the /// specific voice, in the range [-96.0, 16.0]. If unset, or set to a value of /// 0.0 (dB), will play at normal native signal amplitude. A value of -6.0 (dB) /// will play at approximately half the amplitude of the normal native signal /// amplitude. A value of +6.0 (dB) will play at approximately twice the /// amplitude of the normal native signal amplitude. We strongly recommend not /// to exceed +10 (dB) as there's usually no effective increase in loudness for /// any value greater than that. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public double VolumeGainDb { get { return volumeGainDb_; } set { volumeGainDb_ = value; } } /// <summary>Field number for the "effects_profile_id" field.</summary> public const int EffectsProfileIdFieldNumber = 5; private static readonly pb::FieldCodec<string> _repeated_effectsProfileId_codec = pb::FieldCodec.ForString(42); private readonly pbc::RepeatedField<string> effectsProfileId_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. An identifier which selects 'audio effects' profiles that are /// applied on (post synthesized) text to speech. Effects are applied on top of /// each other in the order they are given. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> EffectsProfileId { get { return effectsProfileId_; } } /// <summary>Field number for the "voice" field.</summary> public const int VoiceFieldNumber = 4; private global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams voice_; /// <summary> /// Optional. The desired voice of the synthesized audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams Voice { get { return voice_; } set { voice_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SynthesizeSpeechConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SynthesizeSpeechConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(SpeakingRate, other.SpeakingRate)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(Pitch, other.Pitch)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(VolumeGainDb, other.VolumeGainDb)) return false; if(!effectsProfileId_.Equals(other.effectsProfileId_)) return false; if (!object.Equals(Voice, other.Voice)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (SpeakingRate != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(SpeakingRate); if (Pitch != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Pitch); if (VolumeGainDb != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(VolumeGainDb); hash ^= effectsProfileId_.GetHashCode(); if (voice_ != null) hash ^= Voice.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (SpeakingRate != 0D) { output.WriteRawTag(9); output.WriteDouble(SpeakingRate); } if (Pitch != 0D) { output.WriteRawTag(17); output.WriteDouble(Pitch); } if (VolumeGainDb != 0D) { output.WriteRawTag(25); output.WriteDouble(VolumeGainDb); } if (voice_ != null) { output.WriteRawTag(34); output.WriteMessage(Voice); } effectsProfileId_.WriteTo(output, _repeated_effectsProfileId_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (SpeakingRate != 0D) { output.WriteRawTag(9); output.WriteDouble(SpeakingRate); } if (Pitch != 0D) { output.WriteRawTag(17); output.WriteDouble(Pitch); } if (VolumeGainDb != 0D) { output.WriteRawTag(25); output.WriteDouble(VolumeGainDb); } if (voice_ != null) { output.WriteRawTag(34); output.WriteMessage(Voice); } effectsProfileId_.WriteTo(ref output, _repeated_effectsProfileId_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (SpeakingRate != 0D) { size += 1 + 8; } if (Pitch != 0D) { size += 1 + 8; } if (VolumeGainDb != 0D) { size += 1 + 8; } size += effectsProfileId_.CalculateSize(_repeated_effectsProfileId_codec); if (voice_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Voice); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SynthesizeSpeechConfig other) { if (other == null) { return; } if (other.SpeakingRate != 0D) { SpeakingRate = other.SpeakingRate; } if (other.Pitch != 0D) { Pitch = other.Pitch; } if (other.VolumeGainDb != 0D) { VolumeGainDb = other.VolumeGainDb; } effectsProfileId_.Add(other.effectsProfileId_); if (other.voice_ != null) { if (voice_ == null) { Voice = new global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams(); } Voice.MergeFrom(other.Voice); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 9: { SpeakingRate = input.ReadDouble(); break; } case 17: { Pitch = input.ReadDouble(); break; } case 25: { VolumeGainDb = input.ReadDouble(); break; } case 34: { if (voice_ == null) { Voice = new global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams(); } input.ReadMessage(Voice); break; } case 42: { effectsProfileId_.AddEntriesFrom(input, _repeated_effectsProfileId_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 9: { SpeakingRate = input.ReadDouble(); break; } case 17: { Pitch = input.ReadDouble(); break; } case 25: { VolumeGainDb = input.ReadDouble(); break; } case 34: { if (voice_ == null) { Voice = new global::Google.Cloud.Dialogflow.V2.VoiceSelectionParams(); } input.ReadMessage(Voice); break; } case 42: { effectsProfileId_.AddEntriesFrom(ref input, _repeated_effectsProfileId_codec); break; } } } } #endif } /// <summary> /// Instructs the speech synthesizer on how to generate the output audio content. /// If this audio config is supplied in a request, it overrides all existing /// text-to-speech settings applied to the agent. /// </summary> public sealed partial class OutputAudioConfig : pb::IMessage<OutputAudioConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<OutputAudioConfig> _parser = new pb::MessageParser<OutputAudioConfig>(() => new OutputAudioConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<OutputAudioConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OutputAudioConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OutputAudioConfig(OutputAudioConfig other) : this() { audioEncoding_ = other.audioEncoding_; sampleRateHertz_ = other.sampleRateHertz_; synthesizeSpeechConfig_ = other.synthesizeSpeechConfig_ != null ? other.synthesizeSpeechConfig_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OutputAudioConfig Clone() { return new OutputAudioConfig(this); } /// <summary>Field number for the "audio_encoding" field.</summary> public const int AudioEncodingFieldNumber = 1; private global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding audioEncoding_ = global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified; /// <summary> /// Required. Audio encoding of the synthesized audio content. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding AudioEncoding { get { return audioEncoding_; } set { audioEncoding_ = value; } } /// <summary>Field number for the "sample_rate_hertz" field.</summary> public const int SampleRateHertzFieldNumber = 2; private int sampleRateHertz_; /// <summary> /// The synthesis sample rate (in hertz) for this audio. If not /// provided, then the synthesizer will use the default sample rate based on /// the audio encoding. If this is different from the voice's natural sample /// rate, then the synthesizer will honor this request by converting to the /// desired sample rate (which might result in worse audio quality). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int SampleRateHertz { get { return sampleRateHertz_; } set { sampleRateHertz_ = value; } } /// <summary>Field number for the "synthesize_speech_config" field.</summary> public const int SynthesizeSpeechConfigFieldNumber = 3; private global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig synthesizeSpeechConfig_; /// <summary> /// Configuration of how speech should be synthesized. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig SynthesizeSpeechConfig { get { return synthesizeSpeechConfig_; } set { synthesizeSpeechConfig_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as OutputAudioConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(OutputAudioConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AudioEncoding != other.AudioEncoding) return false; if (SampleRateHertz != other.SampleRateHertz) return false; if (!object.Equals(SynthesizeSpeechConfig, other.SynthesizeSpeechConfig)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified) hash ^= AudioEncoding.GetHashCode(); if (SampleRateHertz != 0) hash ^= SampleRateHertz.GetHashCode(); if (synthesizeSpeechConfig_ != null) hash ^= SynthesizeSpeechConfig.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) AudioEncoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (synthesizeSpeechConfig_ != null) { output.WriteRawTag(26); output.WriteMessage(SynthesizeSpeechConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) AudioEncoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (synthesizeSpeechConfig_ != null) { output.WriteRawTag(26); output.WriteMessage(SynthesizeSpeechConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (AudioEncoding != global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AudioEncoding); } if (SampleRateHertz != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SampleRateHertz); } if (synthesizeSpeechConfig_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SynthesizeSpeechConfig); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(OutputAudioConfig other) { if (other == null) { return; } if (other.AudioEncoding != global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding.Unspecified) { AudioEncoding = other.AudioEncoding; } if (other.SampleRateHertz != 0) { SampleRateHertz = other.SampleRateHertz; } if (other.synthesizeSpeechConfig_ != null) { if (synthesizeSpeechConfig_ == null) { SynthesizeSpeechConfig = new global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig(); } SynthesizeSpeechConfig.MergeFrom(other.SynthesizeSpeechConfig); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { AudioEncoding = (global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { if (synthesizeSpeechConfig_ == null) { SynthesizeSpeechConfig = new global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig(); } input.ReadMessage(SynthesizeSpeechConfig); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { AudioEncoding = (global::Google.Cloud.Dialogflow.V2.OutputAudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { if (synthesizeSpeechConfig_ == null) { SynthesizeSpeechConfig = new global::Google.Cloud.Dialogflow.V2.SynthesizeSpeechConfig(); } input.ReadMessage(SynthesizeSpeechConfig); break; } } } } #endif } /// <summary> /// Configures speech transcription for [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile]. /// </summary> public sealed partial class SpeechToTextConfig : pb::IMessage<SpeechToTextConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechToTextConfig> _parser = new pb::MessageParser<SpeechToTextConfig>(() => new SpeechToTextConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechToTextConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Dialogflow.V2.AudioConfigReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechToTextConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechToTextConfig(SpeechToTextConfig other) : this() { speechModelVariant_ = other.speechModelVariant_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechToTextConfig Clone() { return new SpeechToTextConfig(this); } /// <summary>Field number for the "speech_model_variant" field.</summary> public const int SpeechModelVariantFieldNumber = 1; private global::Google.Cloud.Dialogflow.V2.SpeechModelVariant speechModelVariant_ = global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified; /// <summary> /// Optional. The speech model used in speech to text. /// `SPEECH_MODEL_VARIANT_UNSPECIFIED`, `USE_BEST_AVAILABLE` will be treated as /// `USE_ENHANCED`. It can be overridden in [AnalyzeContentRequest][google.cloud.dialogflow.v2.AnalyzeContentRequest] and /// [StreamingAnalyzeContentRequest][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest] request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Dialogflow.V2.SpeechModelVariant SpeechModelVariant { get { return speechModelVariant_; } set { speechModelVariant_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechToTextConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechToTextConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SpeechModelVariant != other.SpeechModelVariant) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (SpeechModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) hash ^= SpeechModelVariant.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (SpeechModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) SpeechModelVariant); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (SpeechModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) SpeechModelVariant); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (SpeechModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SpeechModelVariant); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechToTextConfig other) { if (other == null) { return; } if (other.SpeechModelVariant != global::Google.Cloud.Dialogflow.V2.SpeechModelVariant.Unspecified) { SpeechModelVariant = other.SpeechModelVariant; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { SpeechModelVariant = (global::Google.Cloud.Dialogflow.V2.SpeechModelVariant) input.ReadEnum(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { SpeechModelVariant = (global::Google.Cloud.Dialogflow.V2.SpeechModelVariant) input.ReadEnum(); break; } } } } #endif } #endregion } #endregion Designer generated code
40.304416
377
0.673982
[ "Apache-2.0" ]
amanda-tarafa/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2/AudioConfig.g.cs
102,212
C#
#region License /* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using NUnit.Framework; using Rhino.Mocks; using Spring.Core.TypeConversion; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; using Spring.Objects.Support; #endregion namespace Spring.Objects.Factory { /// <summary> /// Unit tests for the DefaultListableObjectFactory class. /// </summary> /// <author>Rod Johnson</author> /// <author>Simon White (.NET)</author> [TestFixture] public sealed class DefaultListableObjectFactoryTests { private MockRepository mocks; [SetUp] public void Setup() { mocks = new MockRepository(); } /// <summary> /// The setup logic executed before the execution of this test fixture. /// </summary> [TestFixtureSetUp] public void FixtureSetUp() { // enable (null appender) logging, just to ensure that the logging code is correct :D //XmlConfigurator.Configure(); } interface ICollaborator {} interface IStrategy {} class Collaborator : ICollaborator {} class Strategy1 : IStrategy {} class Strategy2 : IStrategy {} class Class1 { public readonly IStrategy TheStrategy; public Class1( ICollaborator collaborator, IStrategy strategy) { TheStrategy = strategy; } } class Class2 { private IStrategy _strategy; private ICollaborator _collaborator; public Class2() {} public IStrategy Strategy { get { return _strategy; } set { _strategy = value; } } public ICollaborator Collaborator { get { return _collaborator; } set { _collaborator = value; } } } [Test(Description = "http://jira.springframework.org/browse/SPRNET-985")] public void AutowireConstructorHonoresOverridesBeforeThrowingUnsatisfiedDependencyException() { RootObjectDefinition def = new RootObjectDefinition(typeof(Class1)); def.AutowireMode = AutoWiringMode.AutoDetect; def.ConstructorArgumentValues.AddNamedArgumentValue("strategy", new RuntimeObjectReference("Strategy1") ); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("Class", def); lof.RegisterObjectDefinition("ICollaborator", new RootObjectDefinition(typeof(Collaborator))); lof.RegisterObjectDefinition("Strategy1", new RootObjectDefinition(typeof(Strategy1))); lof.RegisterObjectDefinition("Strategy2", new RootObjectDefinition(typeof(Strategy1))); Class1 c1 = (Class1) lof.GetObject("Class"); Assert.IsNotNull(c1); Assert.AreEqual( typeof(Strategy1), c1.TheStrategy.GetType() ); } [Test(Description = "http://jira.springframework.org/browse/SPRNET-985")] public void AutowireByTypeHonoresOverridesBeforeThrowingUnsatisfiedDependencyException() { RootObjectDefinition def = new RootObjectDefinition(typeof(Class2)); def.AutowireMode = AutoWiringMode.AutoDetect; def.PropertyValues.Add("strategy", new RuntimeObjectReference("Strategy1") ); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("Class", def); lof.RegisterObjectDefinition("ICollaborator", new RootObjectDefinition(typeof(Collaborator))); lof.RegisterObjectDefinition("Strategy1", new RootObjectDefinition(typeof(Strategy1))); lof.RegisterObjectDefinition("Strategy2", new RootObjectDefinition(typeof(Strategy1))); Class2 c2 = (Class2) lof.GetObject("Class"); Assert.IsNotNull(c2); Assert.AreEqual( typeof(Strategy1), c2.Strategy.GetType() ); } [Test(Description = "http://jira.springframework.org/browse/SPRNET-112")] public void ObjectCreatedViaStaticFactoryMethodUsesReturnTypeOfFactoryMethodAsTheObjectType() { RootObjectDefinition def = new RootObjectDefinition(typeof(TestObjectCreator)); def.FactoryMethodName = "CreateTestObject"; DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("factoryObject", def); IDictionary objs = lof.GetObjectsOfType(typeof(TestObject)); Assert.AreEqual(1, objs.Count); } [Test(Description = "http://opensource2.atlassian.com/projects/spring/browse/SPRNET-112")] public void ObjectCreatedViaInstanceFactoryMethodUsesReturnTypeOfFactoryMethodAsTheObjectType() { RootObjectDefinition def = new RootObjectDefinition(typeof(TestObjectCreator)); def.FactoryMethodName = "InstanceCreateTestObject"; def.FactoryObjectName = "target"; DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("factoryObject", def); lof.RegisterObjectDefinition("target", new RootObjectDefinition(typeof(TestObjectCreator))); IDictionary objs = lof.GetObjectsOfType(typeof(TestObject)); Assert.AreEqual(1, objs.Count); } #if NET_2_0 [Test(Description = "http://opensource2.atlassian.com/projects/spring/browse/SPRNET-112")] public void ObjectCreatedViaStaticGenericFactoryMethodUsesReturnTypeOfGenericFactoryMethodAsTheObjectType() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition def = new RootObjectDefinition(typeof(TestGenericObject<int, string>)); def.FactoryMethodName = "CreateList<int>"; lof.RegisterObjectDefinition("foo", def); IDictionary objs = lof.GetObjectsOfType(typeof(System.Collections.Generic.List<int>)); Assert.AreEqual(1, objs.Count); } [Test(Description = "http://opensource2.atlassian.com/projects/spring/browse/SPRNET-112")] public void ObjectCreatedViaInstanceGenericFactoryMethodUsesReturnTypeOfGenericFactoryMethodAsTheObjectType() { RootObjectDefinition def = new RootObjectDefinition(typeof(TestObjectCreator)); def.FactoryMethodName = "CreateInstance<string,int>"; def.FactoryObjectName = "target"; DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("factoryObject", def); lof.RegisterObjectDefinition("target", new RootObjectDefinition(typeof(TestGenericObject<int, string>))); IDictionary objs = lof.GetObjectsOfType(typeof(TestGenericObject<string, int>)); Assert.AreEqual(1, objs.Count); } #endif /// <summary> /// Object instantiation through factory method should not require type attribute. /// </summary> [Test(Description = "http://opensource.atlassian.com/projects/spring/browse/SPRNET-130")] public void SPRNET_130() { const string factoryObjectName = "factoryObject"; const string exampleObjectName = "exampleObject"; RootObjectDefinition factoryObjectDefinition = new RootObjectDefinition(typeof(TestObjectFactory)); RootObjectDefinition exampleObjectDefinition = new RootObjectDefinition(); exampleObjectDefinition.FactoryObjectName = factoryObjectName; exampleObjectDefinition.FactoryMethodName = "GetObject"; DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition(factoryObjectName, factoryObjectDefinition); lof.RegisterObjectDefinition(exampleObjectName, exampleObjectDefinition); object exampleObject = lof.GetObject(exampleObjectName); Assert.IsNotNull(exampleObject); object factoryObject = lof.GetObject(factoryObjectName); Assert.IsNotNull(factoryObject); } [Test(Description = "http://opensource.atlassian.com/projects/spring/browse/SPR-1011")] public void SPR_1011() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition def = new RootObjectDefinition( typeof(StaticFactoryMethodObject)); def.FactoryMethodName = "CreateObject"; lof.RegisterObjectDefinition("foo", def); IDictionary objs = lof.GetObjectsOfType(typeof(DBNull)); Assert.AreEqual(1, objs.Count, "Must be looking at the RETURN TYPE of the factory method, " + "and hence get one DBNull object back."); } private sealed class StaticFactoryMethodObject { private StaticFactoryMethodObject() { } public static DBNull CreateObject() { return DBNull.Value; } } [Test(Description = "http://opensource.atlassian.com/projects/spring/browse/SPR-1077")] public void SPR_1077() { DisposableTestObject sing = null; using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition singleton = new RootObjectDefinition(typeof(DisposableTestObject)); MutablePropertyValues sprops = new MutablePropertyValues(); sprops.Add("name", "Rick"); singleton.PropertyValues = sprops; lof.RegisterObjectDefinition("singleton", singleton); RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); MutablePropertyValues pprops = new MutablePropertyValues(); pprops.Add("name", "Jenny"); // prototype has dependency on a singleton... pprops.Add("spouse", new RuntimeObjectReference("singleton")); prototype.PropertyValues = pprops; prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); sing = (DisposableTestObject)lof.GetObject("singleton"); lof.GetObject("prototype"); lof.GetObject("prototype"); lof.GetObject("prototype"); lof.GetObject("prototype"); } Assert.AreEqual(1, sing.NumTimesDisposed); } private sealed class DisposableTestObject : TestObject, IDisposable { private int _numTimesDisposed; public int NumTimesDisposed { get { return _numTimesDisposed; } } public void Dispose() { ++_numTimesDisposed; } } [Test] public void GetObjectPostProcessorCount() { IObjectPostProcessor proc1 = (IObjectPostProcessor) mocks.CreateMock(typeof (IObjectPostProcessor)); IObjectPostProcessor proc2 = (IObjectPostProcessor)mocks.CreateMock(typeof(IObjectPostProcessor)); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); const string errMsg = "Wrong number of IObjectPostProcessors being reported by the ObjectPostProcessorCount property."; Assert.AreEqual(0, lof.ObjectPostProcessorCount, errMsg); lof.AddObjectPostProcessor(proc1); Assert.AreEqual(1, lof.ObjectPostProcessorCount, errMsg); lof.AddObjectPostProcessor(proc2); Assert.AreEqual(2, lof.ObjectPostProcessorCount, errMsg); } /// <summary> /// The ObjectPostProcessorCount property must only return the count of /// processors registered with the current factory, and not /// surf up any hierarchy. /// </summary> [Test] public void GetObjectPostProcessorCountDoesntRespectHierarchy() { IObjectPostProcessor proc1 = (IObjectPostProcessor)mocks.CreateMock(typeof(IObjectPostProcessor)); IObjectPostProcessor proc2 = (IObjectPostProcessor)mocks.CreateMock(typeof(IObjectPostProcessor)); DefaultListableObjectFactory child = new DefaultListableObjectFactory(); DefaultListableObjectFactory parent = new DefaultListableObjectFactory(child); const string errMsg = "Wrong number of IObjectPostProcessors being reported by the ObjectPostProcessorCount property."; Assert.AreEqual(0, child.ObjectPostProcessorCount, errMsg); Assert.AreEqual(0, parent.ObjectPostProcessorCount, errMsg); child.AddObjectPostProcessor(proc1); Assert.AreEqual(1, child.ObjectPostProcessorCount, errMsg); Assert.AreEqual(0, parent.ObjectPostProcessorCount, errMsg); parent.AddObjectPostProcessor(proc2); Assert.AreEqual(1, child.ObjectPostProcessorCount, errMsg); Assert.AreEqual(1, parent.ObjectPostProcessorCount, errMsg); child.AddObjectPostProcessor(proc2); Assert.AreEqual(2, child.ObjectPostProcessorCount, errMsg); Assert.AreEqual(1, parent.ObjectPostProcessorCount, errMsg); } [Test] public void TestIInstantiationAwareObjectPostProcessorsInterception() { ProxyingInstantiationAwareObjectPostProcessorStub proc = new ProxyingInstantiationAwareObjectPostProcessorStub("TheAgony"); MutablePropertyValues props = new MutablePropertyValues(); props.Add("Name", "Rick"); RootObjectDefinition toBeProxied = new RootObjectDefinition(typeof(TestObject), props); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.AddObjectPostProcessor(proc); lof.RegisterObjectDefinition("toBeProxied", toBeProxied); object proxy = lof["toBeProxied"]; Assert.IsNotNull(proxy); Assert.AreEqual("TheAgony", proxy); } [Test] public void TestIInstantiationAwareObjectPostProcessorsPassThrough() { NullInstantiationAwareObjectPostProcessorStub proc = new NullInstantiationAwareObjectPostProcessorStub(); MutablePropertyValues props = new MutablePropertyValues(); props.Add("Name", "Rick"); RootObjectDefinition not = new RootObjectDefinition(typeof(TestObject), props); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.AddObjectPostProcessor(proc); lof.RegisterObjectDefinition("notToBeProxied", not); object foo = lof["notToBeProxied"]; Assert.IsNotNull(foo); Assert.AreEqual(typeof(TestObject), foo.GetType()); TestObject to = (TestObject)foo; Assert.AreEqual("Rick", to.Name); } private sealed class NullInstantiationAwareObjectPostProcessorStub : IInstantiationAwareObjectPostProcessor { public NullInstantiationAwareObjectPostProcessorStub() { } public object PostProcessBeforeInitialization(object obj, string name) { return obj; } public object PostProcessBeforeInstantiation(Type objectType, string objectName) { //proceed with default instantiation return null; } public bool PostProcessAfterInstantiation(object objectInstance, string objectName) { //proceed to set properties on the object return true; } #region IInstantiationAwareObjectPostProcessor Members public IPropertyValues PostProcessPropertyValues(IPropertyValues pvs, PropertyInfo[] pis, object objectInstance, string objectName) { return pvs; } #endregion public object PostProcessAfterInitialization(object obj, string objectName) { return obj; } } private sealed class ProxyingInstantiationAwareObjectPostProcessorStub : IInstantiationAwareObjectPostProcessor { public ProxyingInstantiationAwareObjectPostProcessorStub() { } public ProxyingInstantiationAwareObjectPostProcessorStub(object proxy) { _proxy = proxy; } private object _proxy; public object Proxy { get { return _proxy; } set { _proxy = value; } } public object PostProcessBeforeInitialization(object obj, string name) { throw new NotImplementedException(); } public object PostProcessBeforeInstantiation(Type objectType, string objectName) { return _proxy; } public bool PostProcessAfterInstantiation(object objectInstance, string objectName) { return true; } #region IInstantiationAwareObjectPostProcessor Members public IPropertyValues PostProcessPropertyValues(IPropertyValues pvs, PropertyInfo[] pis, object objectInstance, string objectName) { return pvs; } #endregion public object PostProcessAfterInitialization(object obj, string objectName) { throw new NotImplementedException(); } } [Test] public void PreInstantiateSingletonsMustNotIgnoreObjectsWithUnresolvedObjectTypes() { KnowsIfInstantiated.ClearInstantiationRecord(); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); Assert.IsTrue(!KnowsIfInstantiated.WasInstantiated, "Singleton appears to be instantiated before the test is even run."); RootObjectDefinition def = new RootObjectDefinition(); def.ObjectTypeName = typeof(KnowsIfInstantiated).FullName; lof.RegisterObjectDefinition("x1", def); Assert.IsTrue(!KnowsIfInstantiated.WasInstantiated, "Singleton appears to be instantiated before PreInstantiateSingletons() is invoked."); lof.PreInstantiateSingletons(); Assert.IsTrue(KnowsIfInstantiated.WasInstantiated, "Singleton was not instantiated by the container (it must be)."); } [Test] public void LazyInitialization() { KnowsIfInstantiated.ClearInstantiationRecord(); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition def = new RootObjectDefinition(); def.ObjectTypeName = typeof(KnowsIfInstantiated).FullName; def.IsLazyInit = true; lof.RegisterObjectDefinition("x1", def); Assert.IsTrue(!KnowsIfInstantiated.WasInstantiated, "Singleton appears to be instantiated before the test is even run."); lof.RegisterObjectDefinition("x1", def); Assert.IsTrue(!KnowsIfInstantiated.WasInstantiated, "Singleton appears to be instantiated before PreInstantiateSingletons() is invoked."); lof.PreInstantiateSingletons(); Assert.IsFalse(KnowsIfInstantiated.WasInstantiated, "Singleton was instantiated by the container (it must NOT be 'cos LazyInit was set to TRUE)."); lof.GetObject("x1"); Assert.IsTrue(KnowsIfInstantiated.WasInstantiated, "Singleton was not instantiated by the container (it must be)."); } [Test] public void SingletonFactoryObjectMustNotCreatePrototypeOnPreInstantiateSingletonsCall() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition def = new RootObjectDefinition(); def.ObjectType = typeof(DummyFactory); def.IsSingleton = true; def.PropertyValues.Add("IsSingleton", false); DummyFactory.Reset(); Assert.IsFalse(DummyFactory.WasPrototypeCreated, "Prototype appears to be instantiated before the test is even run."); lof.RegisterObjectDefinition("x1", def); Assert.IsFalse(DummyFactory.WasPrototypeCreated, "Prototype instantiated after object definition registration (must NOT be)."); lof.PreInstantiateSingletons(); Assert.IsFalse(DummyFactory.WasPrototypeCreated, "Prototype instantiated after call to PreInstantiateSingletons(); must NOT be."); lof.GetObject("x1"); Assert.IsTrue(DummyFactory.WasPrototypeCreated, "Prototype was not instantiated."); } [Test] public void Empty() { IListableObjectFactory lof = new DefaultListableObjectFactory(); Assert.IsTrue(lof.GetObjectDefinitionNames() != null, "No objects defined --> array != null"); Assert.IsTrue(lof.GetObjectDefinitionNames().Length == 0, "No objects defined after no arg constructor"); Assert.IsTrue(lof.ObjectDefinitionCount == 0, "No objects defined after no arg constructor"); } [Test] public void ObjectDefinitionCountIsZeroBeforeAnythingIsRegistered() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); Assert.AreEqual(0, lof.ObjectDefinitionCount, "No objects must be defined straight off the bat."); } [Test] public void ObjectDefinitionOverriding() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.RegisterObjectDefinition("test", new RootObjectDefinition(typeof(TestObject), null)); lof.RegisterObjectDefinition("test", new RootObjectDefinition(typeof(NestedTestObject), null)); Assert.IsTrue(lof.GetObject("test") is NestedTestObject); } [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void ObjectDefinitionOverridingNotAllowed() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.AllowObjectDefinitionOverriding = false; lof.RegisterObjectDefinition("test", new RootObjectDefinition(typeof(TestObject), null)); lof.RegisterObjectDefinition("test", new RootObjectDefinition(typeof(NestedTestObject), null)); } [Test] public void CustomEditor() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); NumberFormatInfo nfi = new CultureInfo("en-GB", false).NumberFormat; lof.RegisterCustomConverter(typeof(Single), new CustomNumberConverter(typeof(Single), nfi, true)); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add("myFloat", "1.1"); lof.RegisterObjectDefinition("testObject", new RootObjectDefinition(typeof(TestObject), pvs)); TestObject testObject = (TestObject)lof.GetObject("testObject"); Assert.IsTrue(testObject.MyFloat == 1.1f); } [Test] public void RegisterExistingSingletonWithReference() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition def = new RootObjectDefinition(); def.ObjectType = typeof(TestObject); def.PropertyValues.Add("Name", "Rick"); def.PropertyValues.Add("Age", 30); def.PropertyValues.Add("Spouse", new RuntimeObjectReference("singletonObject")); lof.RegisterObjectDefinition("test", def); object singletonObject = new TestObject(); lof.RegisterSingleton("singletonObject", singletonObject); Assert.IsTrue(lof.IsSingleton("singletonObject")); TestObject test = (TestObject)lof.GetObject("test"); Assert.AreEqual(singletonObject, lof.GetObject("singletonObject")); Assert.AreEqual(singletonObject, test.Spouse); Hashtable objectsOfType = (Hashtable)lof.GetObjectsOfType(typeof(TestObject), false, true); Assert.AreEqual(2, objectsOfType.Count); Assert.IsTrue(objectsOfType.ContainsValue(test)); Assert.IsTrue(objectsOfType.ContainsValue(singletonObject)); } [Test] public void ApplyPropertyValues() { DefaultListableObjectFactory factory = new DefaultListableObjectFactory(); MutablePropertyValues properties = new MutablePropertyValues(); properties.Add("age", "99"); factory.RegisterObjectDefinition("test", new RootObjectDefinition(typeof(TestObject), properties)); TestObject obj = new TestObject(); Assert.AreEqual(0, obj.Age); factory.ApplyObjectPropertyValues(obj, "test"); Assert.AreEqual(99, obj.Age, "Property values were not applied to the existing instance."); } [Test] public void ApplyPropertyValuesWithIncompleteDefinition() { DefaultListableObjectFactory factory = new DefaultListableObjectFactory(); MutablePropertyValues properties = new MutablePropertyValues(); properties.Add("age", "99"); factory.RegisterObjectDefinition("test", new RootObjectDefinition(null, properties)); TestObject obj = new TestObject(); Assert.AreEqual(0, obj.Age); factory.ApplyObjectPropertyValues(obj, "test"); Assert.AreEqual(99, obj.Age, "Property values were not applied to the existing instance."); } [Test] public void RegisterExistingSingletonWithAutowire() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add("name", "Tony"); pvs.Add("age", "48"); RootObjectDefinition rod = new RootObjectDefinition(typeof(DependenciesObject), pvs, true); rod.DependencyCheck = DependencyCheckingMode.Objects; rod.AutowireMode = AutoWiringMode.ByType; lof.RegisterObjectDefinition("test", rod); object singletonObject = new TestObject(); lof.RegisterSingleton("singletonObject", singletonObject); Assert.IsTrue(lof.ContainsObject("singletonObject")); Assert.IsTrue(lof.IsSingleton("singletonObject")); Assert.AreEqual(0, lof.GetAliases("singletonObject").Length); DependenciesObject test = (DependenciesObject)lof.GetObject("test"); Assert.AreEqual(singletonObject, lof.GetObject("singletonObject")); Assert.AreEqual(singletonObject, test.Spouse); } [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void RegisterExistingSingletonWithAlreadyBound() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); object singletonObject = new TestObject(); lof.RegisterSingleton("singletonObject", singletonObject); lof.RegisterSingleton("singletonObject", singletonObject); } [Test] public void AutowireConstructor() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("spouse", rod); ConstructorDependenciesObject cdo = (ConstructorDependenciesObject)lof.Autowire(typeof(ConstructorDependenciesObject), AutoWiringMode.Constructor, true); object spouse = lof.GetObject("spouse"); Assert.IsTrue(cdo.Spouse1 == spouse); Assert.IsTrue(ObjectFactoryUtils.ObjectOfType(lof, typeof(TestObject)) == spouse); } [Test] public void AutowireObjectByName() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rodDefinition = new RootObjectDefinition(typeof(TestObject)); rodDefinition.PropertyValues.Add("name", "Rod"); rodDefinition.AutowireMode = AutoWiringMode.ByName; RootObjectDefinition kerryDefinition = new RootObjectDefinition(typeof(TestObject)); kerryDefinition.PropertyValues.Add("name", "Kerry"); lof.RegisterObjectDefinition("rod", rodDefinition); lof.RegisterObjectDefinition("Spouse", kerryDefinition); DependenciesObject obj = (DependenciesObject)lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByName, true); TestObject objRod = (TestObject)lof.GetObject("rod"); Assert.AreEqual(obj.Spouse, objRod.Spouse); } [Test] public void AutowireObjectByNameIsNotCaseInsensitive() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rodDefinition = new RootObjectDefinition(typeof(TestObject)); rodDefinition.PropertyValues.Add("name", "Rod"); rodDefinition.AutowireMode = AutoWiringMode.ByName; RootObjectDefinition kerryDefinition = new RootObjectDefinition(typeof(TestObject)); kerryDefinition.PropertyValues.Add("name", "Kerry"); lof.RegisterObjectDefinition("rod", rodDefinition); lof.RegisterObjectDefinition("spouse", kerryDefinition); // property name is Spouse (capital S) TestObject objRod = (TestObject)lof.GetObject("rod"); Assert.IsNull(objRod.Spouse, "Mmm, Spouse property appears to have been autowired by name, even though there is no object in the factory with a name 'Spouse'."); } [Test] [ExpectedException(typeof(UnsatisfiedDependencyException))] public void AutowireObjectByNameWithDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("Spous", rod); lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByName, true); } [Test] public void AutowireObjectByNameWithNoDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("Spous", rod); DependenciesObject obj = (DependenciesObject)lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByName, false); Assert.IsNull(obj.Spouse); } [Test] public void AutowireObjectByType() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("test", rod); DependenciesObject obj = (DependenciesObject)lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByType, true); TestObject test = (TestObject)lof.GetObject("test"); Assert.AreEqual(obj.Spouse, test); } [Test] [ExpectedException(typeof(UnsatisfiedDependencyException))] public void AutowireObjectByTypeWithDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByType, true); Assert.Fail("Should have thrown UnsatisfiedDependencyException"); } [Test] public void AutowireObjectByTypeWithNoDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); DependenciesObject obj = (DependenciesObject)lof.Autowire(typeof(DependenciesObject), AutoWiringMode.ByType, false); Assert.IsNull(obj.Spouse); } [Test] public void AutowireExistingObjectByName() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("Spouse", rod); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByName, true); TestObject spouse = (TestObject)lof.GetObject("Spouse"); Assert.AreEqual(existingObj.Spouse, spouse); Assert.IsTrue(ObjectFactoryUtils.ObjectOfType(lof, typeof(TestObject)) == spouse); } [Test] [ExpectedException(typeof(UnsatisfiedDependencyException))] public void AutowireExistingObjectByNameWithDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("Spous", rod); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByName, true); Assert.Fail("Should have thrown UnsatisfiedDependencyException"); } [Test] public void AutowireExistingObjectByNameWithNoDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("Spous", rod); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByName, false); Assert.IsNull(existingObj.Spouse); } [Test] public void AutowireExistingObjectByType() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("test", rod); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByType, true); TestObject test = (TestObject)lof.GetObject("test"); Assert.AreEqual(existingObj.Spouse, test); } [Test] [ExpectedException(typeof(ArgumentException))] public void AutowireByTypeWithInvalidAutowireMode() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); DependenciesObject obj = new DependenciesObject(); lof.AutowireObjectProperties(obj, AutoWiringMode.Constructor, true); } [Test] [ExpectedException(typeof(UnsatisfiedDependencyException))] public void AutowireExistingObjectByTypeWithDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByType, true); } [Test] public void AutowireExistingObjectByTypeWithNoDependencyCheck() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); DependenciesObject existingObj = new DependenciesObject(); lof.AutowireObjectProperties(existingObj, AutoWiringMode.ByType, false); Assert.IsNull(existingObj.Spouse); } [Test] public void AutowireWithNoDependencies() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject)); lof.RegisterObjectDefinition("rod", rod); Assert.AreEqual(1, lof.ObjectDefinitionCount); object registered = lof.Autowire(typeof(NoDependencies), AutoWiringMode.AutoDetect, false); Assert.AreEqual(1, lof.ObjectDefinitionCount); Assert.IsTrue(registered is NoDependencies); } [Test] public void AutowireWithSatisfiedObjectDependency() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("name", "Rod")); RootObjectDefinition rood = new RootObjectDefinition(typeof(TestObject), pvs); lof.RegisterObjectDefinition("rod", rood); Assert.AreEqual(1, lof.ObjectDefinitionCount); // Depends on age, name and spouse (TestObject) object registered = lof.Autowire(typeof(DependenciesObject), AutoWiringMode.AutoDetect, true); Assert.AreEqual(1, lof.ObjectDefinitionCount); DependenciesObject kerry = (DependenciesObject)registered; TestObject rod = (TestObject)lof.GetObject("rod"); Assert.AreSame(rod, kerry.Spouse); } [Test] public void AutowireWithSatisfiedConstructorDependency() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("name", "Rod")); RootObjectDefinition rood = new RootObjectDefinition(typeof(TestObject), pvs); lof.RegisterObjectDefinition("rod", rood); Assert.AreEqual(1, lof.ObjectDefinitionCount); object registered = lof.Autowire(typeof(ConstructorDependency), AutoWiringMode.AutoDetect, false); Assert.AreEqual(1, lof.ObjectDefinitionCount); ConstructorDependency kerry = (ConstructorDependency)registered; TestObject rod = (TestObject)lof.GetObject("rod"); Assert.AreSame(rod, kerry._spouse); } [Test] [ExpectedException(typeof(UnsatisfiedDependencyException))] public void AutowireWithUnsatisfiedConstructorDependency() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("name", "Rod")); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject), pvs); lof.RegisterObjectDefinition("rod", rod); Assert.AreEqual(1, lof.ObjectDefinitionCount); lof.Autowire(typeof(UnsatisfiedConstructorDependency), AutoWiringMode.AutoDetect, true); Assert.Fail("Should have unsatisfied constructor dependency on SideEffectObject"); } [Test] public void ExtensiveCircularReference() { DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); for (int i = 0; i < 1000; i++) { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("Spouse", new RuntimeObjectReference("object" + (i < 99 ? i + 1 : 0)))); RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject), pvs); lof.RegisterObjectDefinition("object" + i, rod); } lof.PreInstantiateSingletons(); for (int i = 0; i < 1000; i++) { TestObject obj = (TestObject)lof.GetObject("object" + i); TestObject otherObj = (TestObject)lof.GetObject("object" + (i < 99 ? i + 1 : 0)); Assert.IsTrue(obj.Spouse == otherObj); } } [Test] public void PullingObjectWithFactoryMethodAlsoInjectsDependencies() { string expectedName = "Terese Raquin"; MutablePropertyValues props = new MutablePropertyValues(); props.Add(new PropertyValue("Name", expectedName)); RootObjectDefinition def = new RootObjectDefinition(typeof(MySingleton), props); def.FactoryMethodName = "GetInstance"; DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); object foo = fac["foo"]; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory using factory method instantiation."); MySingleton sing = (MySingleton)foo; Assert.AreEqual(expectedName, sing.Name, "Dependency was not resolved pulling manually registered instance out of the factory using factory method instantiation."); } [Test] public void GetObjectWithArgsOnFactoryObject() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { // DummyFactory produces a TestObject RootObjectDefinition factoryObjectDef = new RootObjectDefinition(typeof(DummyFactory)); factoryObjectDef.IsSingleton = true; lof.RegisterObjectDefinition("factoryObject", factoryObjectDef); // verify preconditions TestObject to = lof.GetObject("factoryObject", null, null) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(25, to.Age); Assert.AreEqual(DummyFactory.SINGLETON_NAME, to.Name); try { to = lof.GetObject("factoryObject", new object[] {}) as TestObject; Assert.Fail("should throw ObjectDefinitionStoreException"); } catch (ObjectDefinitionStoreException ex) { Assert.IsTrue( ex.Message.IndexOf("Cannot specify arguments in the GetObject () method when referring to a factory object definition") > -1); } try { to = lof.GetObject("factoryObject", new object[] { "Mark", "35" }) as TestObject; Assert.Fail("should throw ObjectDefinitionStoreException"); } catch (ObjectDefinitionStoreException ex) { Assert.IsTrue( ex.Message.IndexOf("Cannot specify arguments in the GetObject () method when referring to a factory object definition") > -1); } } } [Test(Description = "http://opensource.atlassian.com/projects/spring/browse/SPRNET-368")] public void GetObjectWithCtorArgsAndCtorAutowiring() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); TestObject to = lof.GetObject("prototype", new object[] { "Bruno", 26, new NestedTestObject("Home") }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(26, to.Age); Assert.AreEqual("Bruno", to.Name); Assert.AreEqual("Home", to.Doctor.Company); } } [Test] public void GetObjectWithCtorArgsOnPrototype() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); TestObject to = lof.GetObject("prototype", new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); } } [Test] [Ignore("Ordering must now be strict when providing array of arguments for ctors")] public void GetObjectWithCtorArgsOnPrototypeOutOfOrderArgs() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); try { TestObject to2 = lof.GetObject("prototype", new object[] { 35, "Mark" }) as TestObject; Assert.IsNotNull(to2); Assert.AreEqual(35, to2.Age); Assert.AreEqual("Mark", to2.Name); } catch (ObjectCreationException ex) { Assert.IsTrue(ex.Message.IndexOf("'Object of type 'System.Int32' cannot be converted to type 'System.String'") >= 0); } } } [Test] public void GetObjectWithCtorArgsOnSingleton() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject)); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); TestObject to = lof.GetObject("singleton", new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); } } [Test] public void GetObjectWithCtorArgsOverrided() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { ConstructorArgumentValues arguments = new ConstructorArgumentValues(); arguments.AddNamedArgumentValue("age", 27); arguments.AddNamedArgumentValue("name", "Bruno"); RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), arguments, new MutablePropertyValues()); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); TestObject to = lof.GetObject("singleton", new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); TestObject to2 = lof.GetObject("singleton") as TestObject; Assert.IsNotNull(to2); Assert.AreEqual(27, to2.Age); Assert.AreEqual("Bruno", to2.Name); } } [Test(Description = "http://opensource.atlassian.com/projects/spring/browse/SPRNET-368")] public void CreateObjectWithCtorArgsAndCtorAutowiring() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); TestObject to = lof.CreateObject("prototype", typeof(TestObject), new object[] { "Bruno", 26, new NestedTestObject("Home") }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(26, to.Age); Assert.AreEqual("Bruno", to.Name); Assert.AreEqual("Home", to.Doctor.Company); } } [Test] public void CreateObjectWithCtorArgsOnPrototype() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); TestObject to = lof.CreateObject("prototype", typeof(TestObject), new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); } } [Test] [Ignore("Ordering must now be strict when providing array of arguments for ctors")] public void CreateObjectWithCtorArgsOnPrototypeOutOfOrderArgs() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition prototype = new RootObjectDefinition(typeof(TestObject)); prototype.IsSingleton = false; lof.RegisterObjectDefinition("prototype", prototype); try { TestObject to2 = lof.CreateObject("prototype", typeof(TestObject), new object[] { 35, "Mark" }) as TestObject; Assert.IsNotNull(to2); Assert.AreEqual(35, to2.Age); Assert.AreEqual("Mark", to2.Name); } catch (ObjectCreationException ex) { Assert.IsTrue(ex.Message.IndexOf("'Object of type 'System.Int32' cannot be converted to type 'System.String'") >= 0); } } } [Test] public void CreateObjectWithCtorArgsOnSingleton() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject)); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); TestObject to = lof.CreateObject("singleton", typeof(TestObject), new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); } } [Test] public void CreateObjectWithCtorArgsOverrided() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { ConstructorArgumentValues arguments = new ConstructorArgumentValues(); arguments.AddNamedArgumentValue("age", 27); arguments.AddNamedArgumentValue("name", "Bruno"); RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), arguments, new MutablePropertyValues()); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); TestObject to = lof.CreateObject("singleton", typeof(TestObject), new object[] { "Mark", 35 }) as TestObject; Assert.IsNotNull(to); Assert.AreEqual(35, to.Age); Assert.AreEqual("Mark", to.Name); TestObject to2 = lof.CreateObject("singleton", null, null) as TestObject; Assert.IsNotNull(to2); Assert.AreEqual(27, to2.Age); Assert.AreEqual("Bruno", to2.Name); } } [Test] public void CreateObjectDoesNotConfigure() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { MutablePropertyValues properties = new MutablePropertyValues(); properties.Add(new PropertyValue("Age", 27)); properties.Add(new PropertyValue("Name", "Bruno")); RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), null, properties); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); TestObject to2 = lof.CreateObject("singleton", typeof(TestObject), null) as TestObject; Assert.IsNotNull(to2); // no props set Assert.AreEqual(0, to2.Age); Assert.AreEqual(null, to2.Name); // no object postprocessors executed! Assert.AreEqual(null, to2.ObjectName); Assert.AreEqual(null, to2.ObjectFactory); Assert.AreEqual(null, to2.SharedState); } } [Test] public void CreateObjectDoesAffectContainerManagedSingletons() { using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory()) { lof.AddObjectPostProcessor(new SharedStateAwareProcessor(new ISharedStateFactory[] { new ByTypeSharedStateFactory() }, Int32.MaxValue )); MutablePropertyValues properties = new MutablePropertyValues(); properties.Add(new PropertyValue("Age", 27)); properties.Add(new PropertyValue("Name", "Bruno")); RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), null, properties); singleton.IsSingleton = true; lof.RegisterObjectDefinition("singleton", singleton); // a call to GetObject() results in a normally configured instance TestObject to = lof.GetObject("singleton") as TestObject; Assert.IsNotNull(to); // props set Assert.AreEqual(27, to.Age); Assert.AreEqual("Bruno", to.Name); // object postprocessors executed! Assert.AreEqual("singleton", to.ObjectName); Assert.AreEqual(lof, to.ObjectFactory); Assert.IsNotNull(to.SharedState); // altough configured as singleton, calling CreateObject prevents the instance from being cached // otherwise the container could not guarantee the results of calling GetObject() to other clients. TestObject to2 = lof.CreateObject("singleton", typeof(TestObject), null) as TestObject; Assert.IsNotNull(to2); // no props set Assert.AreEqual(0, to2.Age); Assert.AreEqual(null, to2.Name); // no object postprocessors executed! Assert.AreEqual(null, to2.ObjectName); Assert.AreEqual(null, to2.ObjectFactory); Assert.AreEqual(null, to2.SharedState); // a call to GetObject() results in a normally configured instance TestObject to3 = lof.GetObject("singleton") as TestObject; Assert.IsNotNull(to3); // props set Assert.AreEqual(27, to3.Age); Assert.AreEqual("Bruno", to3.Name); // object postprocessors executed! Assert.AreEqual("singleton", to3.ObjectName); Assert.AreEqual(lof, to3.ObjectFactory); Assert.IsNotNull(to3.SharedState); } } [Test] public void CreateObjectWithAllNamedCtorArguments() { string expectedName = "Bingo"; int expectedAge = 1023; ConstructorArgumentValues values = new ConstructorArgumentValues(); values.AddNamedArgumentValue("age", expectedAge); values.AddNamedArgumentValue("name", expectedName); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues()); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); ITestObject foo = fac["foo"] as ITestObject; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory."); Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved using a named ctor arg."); Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg."); } [Test] public void CreateObjectWithAllNamedCtorArgumentsIsCaseInsensitive() { string expectedName = "Bingo"; int expectedAge = 1023; ConstructorArgumentValues values = new ConstructorArgumentValues(); values.AddNamedArgumentValue("aGe", expectedAge); values.AddNamedArgumentValue("naME", expectedName); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues()); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); ITestObject foo = fac["foo"] as ITestObject; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory."); Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved using a named ctor arg."); Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg."); } [Test] public void CreateObjectWithMixOfNamedAndIndexedCtorArguments() { string expectedName = "Bingo"; int expectedAge = 1023; ConstructorArgumentValues values = new ConstructorArgumentValues(); values.AddNamedArgumentValue("age", expectedAge); values.AddIndexedArgumentValue(0, expectedName); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues()); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); ITestObject foo = fac["foo"] as ITestObject; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory."); Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved an indexed ctor arg."); Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg."); } [Test] public void CreateObjectWithMixOfNamedAndIndexedAndAutowiredCtorArguments() { string expectedCompany = "Griffin's Foosball Arcade"; MutablePropertyValues autoProps = new MutablePropertyValues(); autoProps.Add(new PropertyValue("Company", expectedCompany)); RootObjectDefinition autowired = new RootObjectDefinition(typeof(NestedTestObject), autoProps); string expectedName = "Bingo"; int expectedAge = 1023; ConstructorArgumentValues values = new ConstructorArgumentValues(); values.AddNamedArgumentValue("age", expectedAge); values.AddIndexedArgumentValue(0, expectedName); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues()); def.AutowireMode = AutoWiringMode.Constructor; DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); fac.RegisterObjectDefinition("doctor", autowired); ITestObject foo = fac["foo"] as ITestObject; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory."); Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved an indexed ctor arg."); Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg."); Assert.AreEqual(expectedCompany, foo.Doctor.Company, "Dependency 'doctor.Company' was not resolved using autowiring."); } [Test] public void CreateObjectWithMixOfIndexedAndTwoNamedSameTypeCtorArguments() { // this object will be passed in as a named constructor argument string expectedCompany = "Griffin's Foosball Arcade"; MutablePropertyValues autoProps = new MutablePropertyValues(); autoProps.Add(new PropertyValue("Company", expectedCompany)); RootObjectDefinition autowired = new RootObjectDefinition(typeof(NestedTestObject), autoProps); // this object will be passed in as a named constructor argument string expectedLawyersCompany = "Pollack, Pounce, & Pulverise"; MutablePropertyValues lawyerProps = new MutablePropertyValues(); lawyerProps.Add(new PropertyValue("Company", expectedLawyersCompany)); RootObjectDefinition lawyer = new RootObjectDefinition(typeof(NestedTestObject), lawyerProps); // this simple string object will be passed in as an indexed constructor argument string expectedName = "Bingo"; // this simple integer object will be passed in as a named constructor argument int expectedAge = 1023; ConstructorArgumentValues values = new ConstructorArgumentValues(); // lets mix the order up a little... values.AddNamedArgumentValue("age", expectedAge); values.AddIndexedArgumentValue(0, expectedName); values.AddNamedArgumentValue("doctor", new RuntimeObjectReference("a_doctor")); values.AddNamedArgumentValue("lawyer", new RuntimeObjectReference("a_lawyer")); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues()); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); // the object we're attempting to resolve... fac.RegisterObjectDefinition("foo", def); // the object that will be looked up and passed as a named parameter to a ctor call... fac.RegisterObjectDefinition("a_doctor", autowired); // another object that will be looked up and passed as a named parameter to a ctor call... fac.RegisterObjectDefinition("a_lawyer", lawyer); ITestObject foo = fac["foo"] as ITestObject; Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory."); Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved an indexed ctor arg."); Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg."); Assert.AreEqual(expectedCompany, foo.Doctor.Company, "Dependency 'doctor.Company' was not resolved using autowiring."); Assert.AreEqual(expectedLawyersCompany, foo.Lawyer.Company, "Dependency 'lawyer.Company' was not resolved using another named ctor arg."); } [Test] public void CircularDependencyIsCorrectlyDetected() { RootObjectDefinition foo = new RootObjectDefinition(typeof(TestObject)); foo.ConstructorArgumentValues.AddNamedArgumentValue("spouse", new RuntimeObjectReference("bar")); RootObjectDefinition bar = new RootObjectDefinition(typeof(TestObject)); bar.ConstructorArgumentValues.AddNamedArgumentValue("spouse", new RuntimeObjectReference("foo")); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", foo); fac.RegisterObjectDefinition("bar", bar); try { fac.GetObject("foo"); } catch (ObjectCreationException ex) { Assert.AreEqual(typeof(ObjectCurrentlyInCreationException), ex.GetBaseException().GetType(), "Circular dependency was set up; should have caught an ObjectCurrentlyInCreationException instance."); } } [Test] public void ConfigurableFactoryObjectInline() { DefaultListableObjectFactory dlof = new DefaultListableObjectFactory(); RootObjectDefinition everyman = new RootObjectDefinition(); everyman.PropertyValues = new MutablePropertyValues(); everyman.PropertyValues.Add("name", "Noone"); everyman.PropertyValues.Add("age", 9781); RootObjectDefinition factory = new RootObjectDefinition(); factory.ObjectType = typeof(DummyConfigurableFactory); factory.PropertyValues = new MutablePropertyValues(); factory.PropertyValues.Add("ProductTemplate", everyman); dlof.RegisterObjectDefinition("factory", factory); TestObject instance = dlof.GetObject("factory") as TestObject; Assert.IsNotNull(instance); Assert.AreEqual("Noone", instance.Name, "Name dependency injected via IConfigurableObjectFactory (instance) failed (was 'Factory singleton')."); Assert.AreEqual(9781, instance.Age, "Age dependency injected via IObjectFactory.ConfigureObject(instance) failed (was 25)."); } [Test] public void ConfigurableFactoryObjectReference() { DefaultListableObjectFactory dlof = new DefaultListableObjectFactory(); RootObjectDefinition everyman = new RootObjectDefinition(); everyman.IsAbstract = true; everyman.PropertyValues = new MutablePropertyValues(); everyman.PropertyValues.Add("name", "Noone"); everyman.PropertyValues.Add("age", 9781); dlof.RegisterObjectDefinition("everyman", everyman); RootObjectDefinition factory = new RootObjectDefinition(); factory.ObjectType = typeof(DummyConfigurableFactory); factory.PropertyValues = new MutablePropertyValues(); factory.PropertyValues.Add("ProductTemplate", new RuntimeObjectReference("everyman")); dlof.RegisterObjectDefinition("factory", factory); TestObject instance = dlof.GetObject("factory") as TestObject; Assert.IsNotNull(instance); Assert.AreEqual("Noone", instance.Name, "Name dependency injected via IConfigurableObjectFactory (instance) failed (was 'Factory singleton')."); Assert.AreEqual(9781, instance.Age, "Age dependency injected via IObjectFactory.ConfigureObject(instance) failed (was 25)."); } [Test] public void ConfigureObject() { TestObject instance = new TestObject(); RootObjectDefinition everyman = new RootObjectDefinition(); everyman.IsAbstract = true; everyman.PropertyValues = new MutablePropertyValues(); everyman.PropertyValues.Add("name", "Noone"); everyman.PropertyValues.Add("age", 9781); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition(instance.GetType().FullName, everyman); fac.ConfigureObject(instance, instance.GetType().FullName); Assert.AreEqual("Noone", instance.Name, "Name dependency injected via IObjectFactory.ConfigureObject(instance) failed (was null)."); Assert.AreEqual(9781, instance.Age, "Age dependency injected via IObjectFactory.ConfigureObject(instance) failed (was null)."); } [Test] public void ConfigureObjectViaExplicitName() { TestObject instance = new TestObject(); RootObjectDefinition everyman = new RootObjectDefinition(); everyman.IsAbstract = true; everyman.PropertyValues = new MutablePropertyValues(); everyman.PropertyValues.Add("name", "Noone"); everyman.PropertyValues.Add("age", 9781); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("everyman", everyman); fac.ConfigureObject(instance, "everyman"); Assert.AreEqual(true, instance.InitCompleted, "AfterPropertiesSet() was not invoked by IObjectFactory.ConfigureObject(instance)."); Assert.AreEqual("Noone", instance.Name, "Name dependency injected via IObjectFactory.ConfigureObject(instance) failed (was null)."); Assert.AreEqual(9781, instance.Age, "Age dependency injected via IObjectFactory.ConfigureObject(instance) failed (was null)."); } [Test] [ExpectedException(typeof(ArgumentException))] public void ConfigureObjectViaNullName() { TestObject instance = new TestObject(); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.ConfigureObject(instance, null); } [Test] [ExpectedException(typeof(ArgumentException))] public void ConfigureObjectViaLoadOfOldWhitespaceName() { TestObject instance = new TestObject(); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.ConfigureObject(instance, " \t"); } [Test] [ExpectedException(typeof(ArgumentException))] public void ConfigureObjectViaEmptyName() { TestObject instance = new TestObject(); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.ConfigureObject(instance, string.Empty); } [Test] public void DisposeCyclesThroughAllSingletonsEvenIfTheirDisposeThrowsAnException() { RootObjectDefinition foo = new RootObjectDefinition(typeof(GoodDisposable)); foo.IsSingleton = true; RootObjectDefinition bar = new RootObjectDefinition(typeof(BadDisposable)); bar.IsSingleton = true; RootObjectDefinition baz = new RootObjectDefinition(typeof(GoodDisposable)); baz.IsSingleton = true; using (DefaultListableObjectFactory fac = new DefaultListableObjectFactory()) { fac.RegisterObjectDefinition("foo", foo); fac.RegisterObjectDefinition("bar", bar); fac.RegisterObjectDefinition("baz", baz); fac.PreInstantiateSingletons(); } Assert.AreEqual(2, GoodDisposable.DisposeCount, "All IDisposable singletons must have their Dispose() method called... one of them bailed, and as a result the rest were (apparently) not Dispose()d."); GoodDisposable.DisposeCount = 0; } [Test] public void StaticInitializationViaDependsOnSingletonMethodInvokingFactoryObject() { RootObjectDefinition initializer = new RootObjectDefinition(typeof(MethodInvokingFactoryObject)); initializer.PropertyValues.Add("TargetMethod", "Init"); initializer.PropertyValues.Add("TargetType", typeof(StaticInitializer).AssemblyQualifiedName); RootObjectDefinition foo = new RootObjectDefinition(typeof(TestObject)); foo.DependsOn = new string[] { "force-init" }; DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", foo); fac.RegisterObjectDefinition("force-init", initializer); fac.GetObject("foo"); Assert.IsTrue(StaticInitializer.InitWasCalled, "Boing"); } /// <summary> /// There is a similar test in XmlObjectFactoryTests that actually supplies another boolean /// object in the factory that is used to autowire the object; this test puts no such second /// object in the factory, so when the factory tries to autowire the second (missing) argument /// to the ctor, it should (must) choke. /// </summary> [Test] [ExpectedException(typeof(UnsatisfiedDependencyException), ExpectedMessage="Error creating object with name 'foo' : Unsatisfied dependency " + "expressed through constructor argument with index 1 of type [System.Boolean] : " + "No unique object of type [System.Boolean] is defined : Unsatisfied dependency of type [System.Boolean]: expected at least 1 matching object to wire the [b2] parameter on the constructor of object [foo]")] public void DoubleBooleanAutowire() { RootObjectDefinition def = new RootObjectDefinition(typeof(DoubleBooleanConstructorObject)); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.AddGenericArgumentValue(true, "bool"); def.ConstructorArgumentValues = args; def.AutowireMode = AutoWiringMode.Constructor; def.IsSingleton = true; DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); fac.GetObject("foo"); } [Test] public void CanSetPropertyThatUsesNewModifierOnDerivedClass() { string nick = "Banjo"; string expectedNickname = DerivedTestObject.NicknamePrefix + nick; RootObjectDefinition def = new RootObjectDefinition(typeof(DerivedTestObject)); def.PropertyValues.Add("Nickname", nick); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); DerivedTestObject tob = (DerivedTestObject)fac.GetObject("foo"); Assert.AreEqual(expectedNickname, tob.Nickname, "Property is not being set to the NEWed property on the subclass."); } [Test] public void CanSetPropertyThatUsesOddNewModifierOnDerivedClass() { RootObjectDefinition def = new RootObjectDefinition(typeof(DerivedFoo)); def.PropertyValues.Add("Bar", new DerivedBar()); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); DerivedFoo foo = (DerivedFoo)fac.GetObject("foo"); Assert.AreEqual(typeof(DerivedBar), foo.Bar.GetType()); } [Test] public void ChildReferencesParentByAnAliasOfTheParent() { const string TheParentsAlias = "theParentsAlias"; const int ExpectedAge = 31; const string ExpectedName = "Rick Evans"; RootObjectDefinition parentDef = new RootObjectDefinition(typeof(TestObject)); parentDef.IsAbstract = true; parentDef.PropertyValues.Add("name", ExpectedName); parentDef.PropertyValues.Add("age", ExpectedAge); ChildObjectDefinition childDef = new ChildObjectDefinition(TheParentsAlias); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("parent", parentDef); fac.RegisterAlias("parent", TheParentsAlias); fac.RegisterObjectDefinition("child", childDef); TestObject child = (TestObject)fac.GetObject("child"); Assert.AreEqual(ExpectedName, child.Name); Assert.AreEqual(ExpectedAge, child.Age); } [Test] public void GetObjectDefinitionResolvesAliases() { const string TheParentsAlias = "theParentsAlias"; const int ExpectedAge = 31; const string ExpectedName = "Rick Evans"; RootObjectDefinition parentDef = new RootObjectDefinition(typeof(TestObject)); parentDef.IsAbstract = true; parentDef.PropertyValues.Add("name", ExpectedName); parentDef.PropertyValues.Add("age", ExpectedAge); ChildObjectDefinition childDef = new ChildObjectDefinition(TheParentsAlias); DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("parent", parentDef); fac.RegisterAlias("parent", TheParentsAlias); IObjectDefinition od = fac.GetObjectDefinition(TheParentsAlias); Assert.IsNotNull(od); } [Test] public void IgnoreObjectPostProcessorDuplicates() { IObjectPostProcessor proc1 = (IObjectPostProcessor)mocks.CreateMock(typeof(IObjectPostProcessor)); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); const string errMsg = "Wrong number of IObjectPostProcessors being reported by the ObjectPostProcessorCount property."; Assert.AreEqual(0, lof.ObjectPostProcessorCount, errMsg); lof.AddObjectPostProcessor(proc1); Assert.AreEqual(1, lof.ObjectPostProcessorCount, errMsg); lof.AddObjectPostProcessor(proc1); Assert.AreEqual(1, lof.ObjectPostProcessorCount, errMsg); } [Test] public void ConfigureObjectReturnsOriginalInstanceIfNoDefinitionFound() { IConfigurableObjectFactory of = new DefaultListableObjectFactory(); object testObject = new object(); object resultObject = of.ConfigureObject(testObject, "non-existing object definition name"); Assert.AreSame(testObject, resultObject); } #region TestObjectPostProcessor private class TestObjectPostProcessor : IObjectPostProcessor { private object other; public TestObjectPostProcessor(object other) { this.other = other; } public object PostProcessBeforeInitialization(object instance, string name) { return instance; } public object PostProcessAfterInitialization(object instance, string objectName) { return other; } } #endregion [Test] public void ConfigureObjectAppliesObjectPostProcessorsUsingDefinition() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); object wrapperObject = "WrapperObject"; of.AddObjectPostProcessor( new TestObjectPostProcessor(wrapperObject)); of.RegisterObjectDefinition("myObjectDefinition", new RootObjectDefinition()); object testObject = "TestObject"; object resultObject = of.ConfigureObject(testObject, "myObjectDefinition"); Assert.AreSame(wrapperObject, resultObject); } [Test] public void ConfigureObjectDoesNotApplyObjectPostProcessorsIfNoDefinition() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); object wrapperObject = "WrapperObject"; of.AddObjectPostProcessor( new TestObjectPostProcessor(wrapperObject)); object testObject = "TestObject"; object resultObject = of.ConfigureObject(testObject, "non-existant definition"); Assert.AreSame(testObject, resultObject); } [Test] public void HierarchicalObjectFactoryChildParentResolution() { DefaultListableObjectFactory parent = new DefaultListableObjectFactory(); DefaultListableObjectFactory child = new DefaultListableObjectFactory(parent); parent.RegisterSingleton("parent", new Parent()); child.RegisterObjectDefinition("child", new RootObjectDefinition(typeof (Child), AutoWiringMode.AutoDetect)); Child c = (Child) child.GetObject("child"); Assert.IsNotNull(c); } #region GetObjectNamesForTypeFindsFactoryObjects private class A : IFactoryObject, ISerializable { public object GetObject() { throw new NotImplementedException(); } public Type ObjectType { get { throw new NotImplementedException(); } } public bool IsSingleton { get { throw new NotImplementedException(); } } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } } #endregion [Test] public void GetObjectNamesForTypeFindsFactoryObjects() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); of.RegisterObjectDefinition("mod", new RootObjectDefinition(typeof(A))); string[] names = of.GetObjectNamesForType(typeof (ISerializable), false, false); Assert.IsNotEmpty(names); Assert.AreEqual("&mod", names[0]); } #region Helper Classes public interface IParent { } public class Parent : IParent { } public interface IChild { } public class Child : IChild { public Child(Parent parent) { } } public class GoodDisposable : IDisposable { public static int DisposeCount = 0; public void Dispose() { ++DisposeCount; } } public class BadDisposable : IDisposable { public void Dispose() { throw new FormatException(); } } public sealed class MySingleton { private MySingleton() { } private static MySingleton _instance = new MySingleton(); public static MySingleton GetInstance() { return _instance; } public string Name { get { return _name; } set { _name = value; } } private string _name; } public class NoDependencies { } public class ConstructorDependency { public TestObject _spouse; public ConstructorDependency(TestObject spouse) { this._spouse = spouse; } } public class UnsatisfiedConstructorDependency { public UnsatisfiedConstructorDependency(TestObject to, SideEffectObject seo) { _to = to; _seo = seo; } public object Seo { get { return _seo; } } public TestObject To { get { return _to; } } private object _seo; private TestObject _to; } private sealed class StaticInitializer { public static bool InitWasCalled = false; public static void Init() { InitWasCalled = true; } } #endregion } public class Foo { private IBar bar; public IBar Bar { get { return bar; } set { bar = value; } } } public class DerivedFoo : Foo { public new IDerivedBar Bar { get { return (IDerivedBar)base.Bar; } set { base.Bar = value; } } } public interface IBar { } public interface IDerivedBar : IBar { } public class Bar : IBar { } public class DerivedBar : IDerivedBar { } }
45.036412
221
0.631234
[ "Apache-2.0" ]
MaferYangPointJun/Spring.net
test/Spring/Spring.Core.Tests/Objects/Factory/DefaultListableObjectFactoryTests.cs
85,344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Media.SpeechSynthesis; using Windows.UI.Core; using Windows.UI.Xaml.Controls; namespace ZigbeeAdapterLib { public sealed class SpeechHelper { private static SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(); private static MediaElement mediaElement = new MediaElement(); public static async void Speak(string textToSpeech) { if (!string.IsNullOrEmpty(textToSpeech)) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { VoiceInformation voiceInfo = ( from voice in SpeechSynthesizer.AllVoices where voice.Gender == VoiceGender.Female select voice ).FirstOrDefault() ?? SpeechSynthesizer.DefaultVoice; speechSynthesizer.Voice = voiceInfo; var speechSynthesisStream = await speechSynthesizer.SynthesizeTextToStreamAsync(textToSpeech); mediaElement.SetSource(speechSynthesisStream, speechSynthesisStream.ContentType); mediaElement.Play(); }); } } } }
35.341463
150
0.615597
[ "MIT" ]
iotoi-project/winiot-app
Common/AllJoyn/ZigBeeAdapter/ZigBeeAdapterLib/SpeechHelper.cs
1,451
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.IO; using System.Xml; using System.Diagnostics; using System.Text; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace System.Xml { public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader); public abstract class XmlDictionaryReader : XmlReader { internal const int MaxInitialArrayLength = 65535; public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader!!) { XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; if (dictionaryReader == null) { dictionaryReader = new XmlWrappedReader(reader, null); } return dictionaryReader; } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer!!, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, 0, buffer.Length, quotas); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, offset, count, null, quotas); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, onClose: null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { XmlBinaryReader reader = new XmlBinaryReader(); reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose); return reader; } public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(stream, null, quotas); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(stream, dictionary, quotas, null); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session) { return CreateBinaryReader(stream, dictionary, quotas, session, onClose: null); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { XmlBinaryReader reader = new XmlBinaryReader(); reader.SetInput(stream, dictionary, quotas, session, onClose); return reader; } public static XmlDictionaryReader CreateTextReader(byte[] buffer!!, XmlDictionaryReaderQuotas quotas) { return CreateTextReader(buffer, 0, buffer.Length, quotas); } public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas) { return CreateTextReader(buffer, offset, count, null, quotas, null); } public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { XmlUTF8TextReader reader = new XmlUTF8TextReader(); reader.SetInput(buffer, offset, count, encoding, quotas, onClose); return reader; } public static XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas) { return CreateTextReader(stream, null, quotas, null); } public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { XmlUTF8TextReader reader = new XmlUTF8TextReader(); reader.SetInput(stream, encoding, quotas, onClose); return reader; } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding!!, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, encodings, null, quotas); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding!!, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, encodings, null, quotas); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } public virtual bool CanCanonicalize { get { return false; } } public virtual XmlDictionaryReaderQuotas Quotas { get { return XmlDictionaryReaderQuotas.Max; } } public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual void EndCanonicalization() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual void MoveToStartElement() { if (!IsStartElement()) XmlExceptionHelper.ThrowStartElementExpected(this); } public virtual void MoveToStartElement(string name) { if (!IsStartElement(name)) XmlExceptionHelper.ThrowStartElementExpected(this, name); } public virtual void MoveToStartElement(string localName, string namespaceUri) { if (!IsStartElement(localName, namespaceUri)) XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri); } public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (!IsStartElement(localName, namespaceUri)) XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri); } public virtual bool IsLocalName(string localName) { return this.LocalName == localName; } public virtual bool IsLocalName(XmlDictionaryString localName!!) { return IsLocalName(localName.Value); } public virtual bool IsNamespaceUri(string namespaceUri!!) { return this.NamespaceURI == namespaceUri; } public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri!!) { return IsNamespaceUri(namespaceUri.Value); } public virtual void ReadFullStartElement() { MoveToStartElement(); if (IsEmptyElement) XmlExceptionHelper.ThrowFullStartElementExpected(this); Read(); } public virtual void ReadFullStartElement(string name) { MoveToStartElement(name); if (IsEmptyElement) XmlExceptionHelper.ThrowFullStartElementExpected(this, name); Read(); } public virtual void ReadFullStartElement(string localName, string namespaceUri) { MoveToStartElement(localName, namespaceUri); if (IsEmptyElement) XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri); Read(); } public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { MoveToStartElement(localName, namespaceUri); if (IsEmptyElement) XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri); Read(); } public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { MoveToStartElement(localName, namespaceUri); Read(); } public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public virtual int IndexOfLocalName(string[] localNames!!, string namespaceUri!!) { if (this.NamespaceURI == namespaceUri) { string localName = this.LocalName; for (int i = 0; i < localNames.Length; i++) { string value = localNames[i]; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value) { return i; } } } return -1; } public virtual int IndexOfLocalName(XmlDictionaryString[] localNames!!, XmlDictionaryString namespaceUri!!) { if (this.NamespaceURI == namespaceUri.Value) { string localName = this.LocalName; for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString value = localNames[i]; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value.Value) { return i; } } } return -1; } public virtual string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public virtual bool TryGetBase64ContentLength(out int length) { length = 0; return false; } public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual byte[] ReadContentAsBase64() { return ReadContentAsBase64(Quotas.MaxArrayLength, MaxInitialArrayLength); } internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount) { int length; if (TryGetBase64ContentLength(out length)) { if (length <= maxInitialCount) { byte[] buffer = new byte[length]; int read = 0; while (read < length) { int actual = ReadContentAsBase64(buffer, read, length - read); if (actual == 0) XmlExceptionHelper.ThrowBase64DataExpected(this); read += actual; } return buffer; } } return ReadContentAsBytes(true, maxByteArrayContentLength); } public override string ReadContentAsString() { return ReadContentAsString(Quotas.MaxStringContentLength); } protected string ReadContentAsString(int maxStringContentLength) { StringBuilder? sb = null; string result = string.Empty; bool done = false; while (true) { switch (this.NodeType) { case XmlNodeType.Attribute: result = this.Value; break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: // merge text content string value = this.Value; if (result.Length == 0) { result = value; } else { if (sb == null) sb = new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); sb.Append(value); } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (this.CanResolveEntity) { this.ResolveEntity(); break; } goto default; case XmlNodeType.Element: case XmlNodeType.EndElement: default: done = true; break; } if (done) break; if (this.AttributeCount != 0) ReadAttributeValue(); else Read(); } if (sb != null) result = sb.ToString(); if (result.Length > maxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); return result; } public override string ReadString() { return ReadString(Quotas.MaxStringContentLength); } protected string ReadString(int maxStringContentLength) { if (this.ReadState != ReadState.Interactive) return string.Empty; if (this.NodeType != XmlNodeType.Element) MoveToElement(); if (this.NodeType == XmlNodeType.Element) { if (this.IsEmptyElement) return string.Empty; if (!Read()) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation)); if (this.NodeType == XmlNodeType.EndElement) return string.Empty; } StringBuilder? sb = null; string result = string.Empty; while (IsTextNode(this.NodeType)) { string value = this.Value; if (result.Length == 0) { result = value; } else { if (sb == null) sb = new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); sb.Append(value); } if (!Read()) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation)); } if (sb != null) result = sb.ToString(); if (result.Length > maxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); return result; } public virtual byte[] ReadContentAsBinHex() { return ReadContentAsBinHex(Quotas.MaxArrayLength); } protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { return ReadContentAsBytes(false, maxByteArrayContentLength); } private byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength) { byte[][] buffers = new byte[32][]; byte[] buffer; // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text int count = 384; int bufferCount = 0; int totalRead = 0; while (true) { buffer = new byte[count]; buffers[bufferCount++] = buffer; int read = 0; while (read < buffer.Length) { int actual; if (base64) actual = ReadContentAsBase64(buffer, read, buffer.Length - read); else actual = ReadContentAsBinHex(buffer, read, buffer.Length - read); if (actual == 0) break; read += actual; } totalRead += read; if (read < buffer.Length) break; count = count * 2; } buffer = new byte[totalRead]; int offset = 0; for (int i = 0; i < bufferCount - 1; i++) { Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length); offset += buffers[i].Length; } Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset); return buffer; } protected bool IsTextNode(XmlNodeType nodeType) { return nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace || nodeType == XmlNodeType.CDATA || nodeType == XmlNodeType.Attribute; } public virtual int ReadContentAsChars(char[] chars, int offset, int count) { int read = 0; while (true) { XmlNodeType nodeType = this.NodeType; if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement) break; if (IsTextNode(nodeType)) { read = ReadValueChunk(chars, offset, count); if (read > 0) break; if (nodeType == XmlNodeType.Attribute /* || inAttributeText */) break; if (!Read()) break; } else { if (!Read()) break; } } return read; } public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver) { if (type == typeof(Guid[])) { string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver); Guid[] guids = new Guid[values.Length]; for (int i = 0; i < values.Length; i++) guids[i] = XmlConverter.ToGuid(values[i]); return guids; } if (type == typeof(UniqueId[])) { string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver); UniqueId[] uniqueIds = new UniqueId[values.Length]; for (int i = 0; i < values.Length; i++) uniqueIds[i] = XmlConverter.ToUniqueId(values[i]); return uniqueIds; } return base.ReadContentAs(type, namespaceResolver); } public virtual string ReadContentAsString(string[] strings!!, out int index) { string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { string value = strings[i]; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"strings[{i}]"); if (value == s) { index = i; return value; } } return s; } public virtual string ReadContentAsString(XmlDictionaryString[] strings!!, out int index) { string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { XmlDictionaryString value = strings[i]; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"strings[{i}]"); if (value.Value == s) { index = i; return value.Value; } } return s; } public override decimal ReadContentAsDecimal() { return XmlConverter.ToDecimal(ReadContentAsString()); } public override float ReadContentAsFloat() { return XmlConverter.ToSingle(ReadContentAsString()); } public virtual UniqueId ReadContentAsUniqueId() { return XmlConverter.ToUniqueId(ReadContentAsString()); } public virtual Guid ReadContentAsGuid() { return XmlConverter.ToGuid(ReadContentAsString()); } public virtual TimeSpan ReadContentAsTimeSpan() { return XmlConverter.ToTimeSpan(ReadContentAsString()); } public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { string prefix; XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName); namespaceUri = LookupNamespace(prefix)!; if (namespaceUri == null) XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix); } /* string, bool, int, long, float, double, decimal, DateTime, base64, binhex, uniqueID, object, list*/ public override string ReadElementContentAsString() { bool isEmptyElement = IsStartElement() && IsEmptyElement; string value; if (isEmptyElement) { Read(); value = string.Empty; } else { ReadStartElement(); value = ReadContentAsString(); ReadEndElement(); } return value; } public override bool ReadElementContentAsBoolean() { bool isEmptyElement = IsStartElement() && IsEmptyElement; bool value; if (isEmptyElement) { Read(); value = XmlConverter.ToBoolean(string.Empty); } else { ReadStartElement(); value = ReadContentAsBoolean(); ReadEndElement(); } return value; } public override int ReadElementContentAsInt() { bool isEmptyElement = IsStartElement() && IsEmptyElement; int value; if (isEmptyElement) { Read(); value = XmlConverter.ToInt32(string.Empty); } else { ReadStartElement(); value = ReadContentAsInt(); ReadEndElement(); } return value; } public override long ReadElementContentAsLong() { bool isEmptyElement = IsStartElement() && IsEmptyElement; long value; if (isEmptyElement) { Read(); value = XmlConverter.ToInt64(string.Empty); } else { ReadStartElement(); value = ReadContentAsLong(); ReadEndElement(); } return value; } public override float ReadElementContentAsFloat() { bool isEmptyElement = IsStartElement() && IsEmptyElement; float value; if (isEmptyElement) { Read(); value = XmlConverter.ToSingle(string.Empty); } else { ReadStartElement(); value = ReadContentAsFloat(); ReadEndElement(); } return value; } public override double ReadElementContentAsDouble() { bool isEmptyElement = IsStartElement() && IsEmptyElement; double value; if (isEmptyElement) { Read(); value = XmlConverter.ToDouble(string.Empty); } else { ReadStartElement(); value = ReadContentAsDouble(); ReadEndElement(); } return value; } public override decimal ReadElementContentAsDecimal() { bool isEmptyElement = IsStartElement() && IsEmptyElement; decimal value; if (isEmptyElement) { Read(); value = XmlConverter.ToDecimal(string.Empty); } else { ReadStartElement(); value = ReadContentAsDecimal(); ReadEndElement(); } return value; } public override DateTime ReadElementContentAsDateTime() { bool isEmptyElement = IsStartElement() && IsEmptyElement; DateTime value; if (isEmptyElement) { Read(); try { value = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception)); } } else { ReadStartElement(); value = ReadContentAsDateTime(); ReadEndElement(); } return value; } public virtual UniqueId ReadElementContentAsUniqueId() { bool isEmptyElement = IsStartElement() && IsEmptyElement; UniqueId value; if (isEmptyElement) { Read(); try { value = new UniqueId(string.Empty); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception)); } } else { ReadStartElement(); value = ReadContentAsUniqueId(); ReadEndElement(); } return value; } public virtual Guid ReadElementContentAsGuid() { bool isEmptyElement = IsStartElement() && IsEmptyElement; Guid value; if (isEmptyElement) { Read(); try { value = new Guid(string.Empty); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception)); } } else { ReadStartElement(); value = ReadContentAsGuid(); ReadEndElement(); } return value; } public virtual TimeSpan ReadElementContentAsTimeSpan() { bool isEmptyElement = IsStartElement() && IsEmptyElement; TimeSpan value; if (isEmptyElement) { Read(); value = XmlConverter.ToTimeSpan(string.Empty); } else { ReadStartElement(); value = ReadContentAsTimeSpan(); ReadEndElement(); } return value; } public virtual byte[] ReadElementContentAsBase64() { bool isEmptyElement = IsStartElement() && IsEmptyElement; byte[] buffer; if (isEmptyElement) { Read(); buffer = Array.Empty<byte>(); } else { ReadStartElement(); buffer = ReadContentAsBase64(); ReadEndElement(); } return buffer; } public virtual byte[] ReadElementContentAsBinHex() { bool isEmptyElement = IsStartElement() && IsEmptyElement; byte[] buffer; if (isEmptyElement) { Read(); buffer = Array.Empty<byte>(); } else { ReadStartElement(); buffer = ReadContentAsBinHex(); ReadEndElement(); } return buffer; } public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { localName = LocalName; namespaceUri = NamespaceURI; } public virtual bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName) { localName = null; return false; } public virtual bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? namespaceUri) { namespaceUri = null; return false; } public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { value = null; return false; } private void CheckArray(Array array!!, int offset, int count) { if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative)); if (count > array.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } public virtual bool IsStartArray([NotNullWhen(true)] out Type? type) { type = null; return false; } public virtual bool TryGetArrayLength(out int count) { count = 0; return false; } // Boolean public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsBoolean(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int16 public virtual short[] ReadInt16Array(string localName, string namespaceUri) { return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual short[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { int i = ReadElementContentAsInt(); if (i < short.MinValue || i > short.MaxValue) XmlExceptionHelper.ThrowConversionOverflow(this, i.ToString(NumberFormatInfo.CurrentInfo), "Int16"); array[offset + actual] = (short)i; actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int32 public virtual int[] ReadInt32Array(string localName, string namespaceUri) { return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsInt(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int64 public virtual long[] ReadInt64Array(string localName, string namespaceUri) { return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual long[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsLong(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Single public virtual float[] ReadSingleArray(string localName, string namespaceUri) { return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsFloat(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Double public virtual double[] ReadDoubleArray(string localName, string namespaceUri) { return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsDouble(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Decimal public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri) { return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsDecimal(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // DateTime public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsDateTime(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Guid public virtual Guid[] ReadGuidArray(string localName, string namespaceUri) { return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsGuid(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // TimeSpan public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int actual = 0; while (actual < count && IsStartElement(localName, namespaceUri)) { array[offset + actual] = ReadElementContentAsTimeSpan(); actual++; } return actual; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } private sealed class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo { private readonly XmlReader _reader; private XmlNamespaceManager? _nsMgr; public XmlWrappedReader(XmlReader reader, XmlNamespaceManager? nsMgr) { _reader = reader; _nsMgr = nsMgr; } public override int AttributeCount { get { return _reader.AttributeCount; } } public override string BaseURI { get { return _reader.BaseURI; } } public override bool CanReadBinaryContent { get { return _reader.CanReadBinaryContent; } } public override bool CanReadValueChunk { get { return _reader.CanReadValueChunk; } } public override void Close() { _reader.Dispose(); _nsMgr = null; } public override int Depth { get { return _reader.Depth; } } public override bool EOF { get { return _reader.EOF; } } public override string GetAttribute(int index) { return _reader.GetAttribute(index); } public override string? GetAttribute(string name) { return _reader.GetAttribute(name); } public override string? GetAttribute(string name, string? namespaceUri) { return _reader.GetAttribute(name, namespaceUri); } public override bool HasValue { get { return _reader.HasValue; } } public override bool IsDefault { get { return _reader.IsDefault; } } public override bool IsEmptyElement { get { return _reader.IsEmptyElement; } } public override bool IsStartElement(string name) { return _reader.IsStartElement(name); } public override bool IsStartElement(string localName, string namespaceUri) { return _reader.IsStartElement(localName, namespaceUri); } public override string LocalName { get { return _reader.LocalName; } } public override string? LookupNamespace(string namespaceUri) { return _reader.LookupNamespace(namespaceUri); } public override void MoveToAttribute(int index) { _reader.MoveToAttribute(index); } public override bool MoveToAttribute(string name) { return _reader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string? namespaceUri) { return _reader.MoveToAttribute(name, namespaceUri); } public override bool MoveToElement() { return _reader.MoveToElement(); } public override bool MoveToFirstAttribute() { return _reader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return _reader.MoveToNextAttribute(); } public override string Name { get { return _reader.Name; } } public override string NamespaceURI { get { return _reader.NamespaceURI; } } public override XmlNameTable NameTable { get { return _reader.NameTable; } } public override XmlNodeType NodeType { get { return _reader.NodeType; } } public override string Prefix { get { return _reader.Prefix; } } public override bool Read() { return _reader.Read(); } public override bool ReadAttributeValue() { return _reader.ReadAttributeValue(); } public override string ReadInnerXml() { return _reader.ReadInnerXml(); } public override string ReadOuterXml() { return _reader.ReadOuterXml(); } public override void ReadStartElement(string name) { _reader.ReadStartElement(name); } public override void ReadStartElement(string localName, string namespaceUri) { _reader.ReadStartElement(localName, namespaceUri); } public override void ReadEndElement() { _reader.ReadEndElement(); } public override ReadState ReadState { get { return _reader.ReadState; } } public override void ResolveEntity() { _reader.ResolveEntity(); } public override string this[int index] { get { return _reader[index]; } } public override string? this[string name] { get { return _reader[name]; } } public override string? this[string name, string? namespaceUri] { get { return _reader[name, namespaceUri]; } } public override string Value { get { return _reader.Value; } } public override string XmlLang { get { return _reader.XmlLang; } } public override XmlSpace XmlSpace { get { return _reader.XmlSpace; } } public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count) { return _reader.ReadElementContentAsBase64(buffer, offset, count); } public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { return _reader.ReadContentAsBase64(buffer, offset, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count) { return _reader.ReadElementContentAsBinHex(buffer, offset, count); } public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { return _reader.ReadContentAsBinHex(buffer, offset, count); } public override int ReadValueChunk(char[] chars, int offset, int count) { return _reader.ReadValueChunk(chars, offset, count); } public override Type ValueType { get { return _reader.ValueType; } } public override bool ReadContentAsBoolean() { try { return _reader.ReadContentAsBoolean(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Boolean), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Boolean), exception)); } } public override DateTime ReadContentAsDateTime() { return _reader.ReadContentAsDateTime(); } public override decimal ReadContentAsDecimal() { try { return (decimal)_reader.ReadContentAs(typeof(decimal), null); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Decimal), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Decimal), exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Decimal), exception)); } } public override double ReadContentAsDouble() { try { return _reader.ReadContentAsDouble(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Double), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Double), exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Double), exception)); } } public override int ReadContentAsInt() { try { return _reader.ReadContentAsInt(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int32), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int32), exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int32), exception)); } } public override long ReadContentAsLong() { try { return _reader.ReadContentAsLong(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int64), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int64), exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Int64), exception)); } } public override float ReadContentAsFloat() { try { return _reader.ReadContentAsFloat(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Single), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Single), exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(Single), exception)); } } public override string ReadContentAsString() { try { return _reader.ReadContentAsString(); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(String), exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(nameof(String), exception)); } } public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver) { return _reader.ReadContentAs(type, namespaceResolver); } public bool HasLineInfo() { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return false; return lineInfo.HasLineInfo(); } public int LineNumber { get { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return 1; return lineInfo.LineNumber; } } public int LinePosition { get { IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return 1; return lineInfo.LinePosition; } } } } }
36.199219
221
0.545823
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs
64,869
C#
using System; using FreeSql.DataAnnotations; using mbill_service.Core.Domains.Common.Consts; namespace mbill_service.Core.Domains.Entities.Core { /// <summary> /// 日志表 /// </summary> [Table(DisableSyncStructure = true, Name = SystemConst.DbTablePrefix + "_serilog")] public class SeriLogEntity { public long Id { get; set; } /// <summary> /// 异常信息 /// </summary> public string Exception { get; set; } /// <summary> /// 级别 /// </summary> public int Level { get; set; } /// <summary> /// 信息 /// </summary> public string Message { get; set; } /// <summary> /// 信息模板 /// </summary> public string MessageTemplate { get; set; } /// <summary> /// 属性 /// </summary> public string Properties { get; set; } /// <summary> /// 时间戳 /// </summary> public DateTime Timestamp { get; set; } } }
21.595745
87
0.503448
[ "MIT" ]
Memoyu/Mbill
src/mbill_service.Core/Domains/Entities/Core/SeriLogEntity.cs
1,057
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Xml; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Data; using Nop.Services.Directory; using Nop.Services.Localization; using Nop.Services.Media; namespace Nop.Services.Catalog { /// <summary> /// Product attribute parser /// </summary> public partial class ProductAttributeParser : IProductAttributeParser { #region Fields private readonly ICurrencyService _currencyService; private readonly IDownloadService _downloadService; private readonly ILocalizationService _localizationService; private readonly IProductAttributeService _productAttributeService; private readonly IRepository<ProductAttributeValue> _productAttributeValueRepository; private readonly IWorkContext _workContext; #endregion #region Ctor public ProductAttributeParser(ICurrencyService currencyService, IDownloadService downloadService, ILocalizationService localizationService, IProductAttributeService productAttributeService, IRepository<ProductAttributeValue> productAttributeValueRepository, IWorkContext workContext) { _currencyService = currencyService; _downloadService = downloadService; _productAttributeService = productAttributeService; _productAttributeValueRepository = productAttributeValueRepository; _workContext = workContext; _localizationService = localizationService; } #endregion #region Utilities /// <summary> /// Returns a list which contains all possible combinations of elements /// </summary> /// <typeparam name="T">Type of element</typeparam> /// <param name="elements">Elements to make combinations</param> /// <returns>All possible combinations of elements</returns> protected virtual IList<IList<T>> CreateCombination<T>(IList<T> elements) { var rez = new List<IList<T>>(); for (var i = 1; i < Math.Pow(2, elements.Count); i++) { var current = new List<T>(); var index = -1; //transform int to binary string var binaryMask = Convert.ToString(i, 2).PadLeft(elements.Count, '0'); foreach (var flag in binaryMask) { index++; if (flag == '0') continue; //add element if binary mask in the position of element has 1 current.Add(elements[index]); } rez.Add(current); } return rez; } /// <summary> /// Gets selected product attribute mapping identifiers /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected product attribute mapping identifiers</returns> protected virtual IList<int> ParseProductAttributeMappingIds(string attributesXml) { var ids = new List<int>(); if (string.IsNullOrEmpty(attributesXml)) return ids; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes?["ID"] == null) continue; var str1 = node1.Attributes["ID"].InnerText.Trim(); if (int.TryParse(str1, out var id)) { ids.Add(id); } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return ids; } /// <summary> /// Gets selected product attribute values with the quantity entered by the customer /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMappingId">Product attribute mapping identifier</param> /// <returns>Collections of pairs of product attribute values and their quantity</returns> protected IList<Tuple<string, string>> ParseValuesWithQuantity(string attributesXml, int productAttributeMappingId) { var selectedValues = new List<Tuple<string, string>>(); if (string.IsNullOrEmpty(attributesXml)) return selectedValues; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); foreach (XmlNode attributeNode in xmlDoc.SelectNodes(@"//Attributes/ProductAttribute")) { if (attributeNode.Attributes?["ID"] == null) continue; if (!int.TryParse(attributeNode.Attributes["ID"].InnerText.Trim(), out var attributeId) || attributeId != productAttributeMappingId) continue; foreach (XmlNode attributeValue in attributeNode.SelectNodes("ProductAttributeValue")) { var value = attributeValue.SelectSingleNode("Value").InnerText.Trim(); var quantityNode = attributeValue.SelectSingleNode("Quantity"); selectedValues.Add(new Tuple<string, string>(value, quantityNode != null ? quantityNode.InnerText.Trim() : string.Empty)); } } } catch { // ignored } return selectedValues; } /// <summary> /// Adds gift cards attributes in XML format /// </summary> /// <param name="product">Product</param> /// <param name="form">Form</param> /// <param name="attributesXml">Attributes in XML format</param> protected virtual void AddGiftCardsAttributesXml(Product product, IFormCollection form, ref string attributesXml) { if (!product.IsGiftCard) return; var recipientName = ""; var recipientEmail = ""; var senderName = ""; var senderEmail = ""; var giftCardMessage = ""; foreach (var formKey in form.Keys) { if (formKey.Equals($"giftcard_{product.Id}.RecipientName", StringComparison.InvariantCultureIgnoreCase)) { recipientName = form[formKey]; continue; } if (formKey.Equals($"giftcard_{product.Id}.RecipientEmail", StringComparison.InvariantCultureIgnoreCase)) { recipientEmail = form[formKey]; continue; } if (formKey.Equals($"giftcard_{product.Id}.SenderName", StringComparison.InvariantCultureIgnoreCase)) { senderName = form[formKey]; continue; } if (formKey.Equals($"giftcard_{product.Id}.SenderEmail", StringComparison.InvariantCultureIgnoreCase)) { senderEmail = form[formKey]; continue; } if (formKey.Equals($"giftcard_{product.Id}.Message", StringComparison.InvariantCultureIgnoreCase)) { giftCardMessage = form[formKey]; } } attributesXml = AddGiftCardAttribute(attributesXml, recipientName, recipientEmail, senderName, senderEmail, giftCardMessage); } /// <summary> /// Gets product attributes in XML format /// </summary> /// <param name="product">Product</param> /// <param name="form">Form</param> /// <param name="errors">Errors</param> /// <returns>Attributes in XML format</returns> protected virtual string GetProductAttributesXml(Product product, IFormCollection form, List<string> errors) { var attributesXml = string.Empty; var productAttributes = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id); foreach (var attribute in productAttributes) { var controlId = $"{NopCatalogDefaults.ProductAttributePrefix}{attribute.Id}"; switch (attribute.AttributeControlType) { case AttributeControlType.DropdownList: case AttributeControlType.RadioList: case AttributeControlType.ColorSquares: case AttributeControlType.ImageSquares: { var ctrlAttributes = form[controlId]; if (!StringValues.IsNullOrEmpty(ctrlAttributes)) { var selectedAttributeId = int.Parse(ctrlAttributes); if (selectedAttributeId > 0) { //get quantity entered by customer var quantity = 1; var quantityStr = form[$"{NopCatalogDefaults.ProductAttributePrefix}{attribute.Id}_{selectedAttributeId}_qty"]; if (!StringValues.IsNullOrEmpty(quantityStr) && (!int.TryParse(quantityStr, out quantity) || quantity < 1)) errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive")); attributesXml = AddProductAttribute(attributesXml, attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null); } } } break; case AttributeControlType.Checkboxes: { var ctrlAttributes = form[controlId]; if (!StringValues.IsNullOrEmpty(ctrlAttributes)) { foreach (var item in ctrlAttributes.ToString() .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var selectedAttributeId = int.Parse(item); if (selectedAttributeId > 0) { //get quantity entered by customer var quantity = 1; var quantityStr = form[$"{NopCatalogDefaults.ProductAttributePrefix}{attribute.Id}_{item}_qty"]; if (!StringValues.IsNullOrEmpty(quantityStr) && (!int.TryParse(quantityStr, out quantity) || quantity < 1)) errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive")); attributesXml = AddProductAttribute(attributesXml, attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null); } } } } break; case AttributeControlType.ReadonlyCheckboxes: { //load read-only (already server-side selected) values var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id); foreach (var selectedAttributeId in attributeValues .Where(v => v.IsPreSelected) .Select(v => v.Id) .ToList()) { //get quantity entered by customer var quantity = 1; var quantityStr = form[$"{NopCatalogDefaults.ProductAttributePrefix}{attribute.Id}_{selectedAttributeId}_qty"]; if (!StringValues.IsNullOrEmpty(quantityStr) && (!int.TryParse(quantityStr, out quantity) || quantity < 1)) errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive")); attributesXml = AddProductAttribute(attributesXml, attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null); } } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: { var ctrlAttributes = form[controlId]; if (!StringValues.IsNullOrEmpty(ctrlAttributes)) { var enteredText = ctrlAttributes.ToString().Trim(); attributesXml = AddProductAttribute(attributesXml, attribute, enteredText); } } break; case AttributeControlType.Datepicker: { var day = form[controlId + "_day"]; var month = form[controlId + "_month"]; var year = form[controlId + "_year"]; DateTime? selectedDate = null; try { selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day)); } catch { } if (selectedDate.HasValue) attributesXml = AddProductAttribute(attributesXml, attribute, selectedDate.Value.ToString("D")); } break; case AttributeControlType.FileUpload: { Guid.TryParse(form[controlId], out var downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { attributesXml = AddProductAttribute(attributesXml, attribute, download.DownloadGuid.ToString()); } } break; default: break; } } //validate conditional attributes (if specified) foreach (var attribute in productAttributes) { var conditionMet = IsConditionMet(attribute, attributesXml); if (conditionMet.HasValue && !conditionMet.Value) { attributesXml = RemoveProductAttribute(attributesXml, attribute); } } return attributesXml; } #endregion #region Product attributes /// <summary> /// Gets selected product attribute mappings /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected product attribute mappings</returns> public virtual IList<ProductAttributeMapping> ParseProductAttributeMappings(string attributesXml) { var result = new List<ProductAttributeMapping>(); if (string.IsNullOrEmpty(attributesXml)) return result; var ids = ParseProductAttributeMappingIds(attributesXml); foreach (var id in ids) { var attribute = _productAttributeService.GetProductAttributeMappingById(id); if (attribute != null) { result.Add(attribute); } } return result; } /// <summary> /// /// Get product attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMappingId">Product attribute mapping identifier; pass 0 to load all values</param> /// <returns>Product attribute values</returns> public virtual IList<ProductAttributeValue> ParseProductAttributeValues(string attributesXml, int productAttributeMappingId = 0) { var values = new List<ProductAttributeValue>(); if (string.IsNullOrEmpty(attributesXml)) return values; var attributes = ParseProductAttributeMappings(attributesXml); //to load values only for the passed product attribute mapping if (productAttributeMappingId > 0) attributes = attributes.Where(attribute => attribute.Id == productAttributeMappingId).ToList(); foreach (var attribute in attributes) { if (!attribute.ShouldHaveValues()) continue; foreach (var attributeValue in ParseValuesWithQuantity(attributesXml, attribute.Id)) { if (string.IsNullOrEmpty(attributeValue.Item1) || !int.TryParse(attributeValue.Item1, out var attributeValueId)) continue; var value = _productAttributeService.GetProductAttributeValueById(attributeValueId); if (value == null) continue; if (!string.IsNullOrEmpty(attributeValue.Item2) && int.TryParse(attributeValue.Item2, out var quantity) && quantity != value.Quantity) { //if customer enters quantity, use new entity with new quantity var oldValue = _productAttributeValueRepository.LoadOriginalCopy(value); oldValue.ProductAttributeMappingId = attribute.Id; oldValue.Quantity = quantity; values.Add(oldValue); } else values.Add(value); } } return values; } /// <summary> /// Gets selected product attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMappingId">Product attribute mapping identifier</param> /// <returns>Product attribute values</returns> public virtual IList<string> ParseValues(string attributesXml, int productAttributeMappingId) { var selectedValues = new List<string>(); if (string.IsNullOrEmpty(attributesXml)) return selectedValues; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes?["ID"] == null) continue; var str1 = node1.Attributes["ID"].InnerText.Trim(); if (!int.TryParse(str1, out var id)) continue; if (id != productAttributeMappingId) continue; var nodeList2 = node1.SelectNodes(@"ProductAttributeValue/Value"); foreach (XmlNode node2 in nodeList2) { var value = node2.InnerText.Trim(); selectedValues.Add(value); } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return selectedValues; } /// <summary> /// Adds an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMapping">Product attribute mapping</param> /// <param name="value">Value</param> /// <param name="quantity">Quantity (used with AttributeValueType.AssociatedToProduct to specify the quantity entered by the customer)</param> /// <returns>Updated result (XML format)</returns> public virtual string AddProductAttribute(string attributesXml, ProductAttributeMapping productAttributeMapping, string value, int? quantity = null) { var result = string.Empty; try { var xmlDoc = new XmlDocument(); if (string.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes?["ID"] == null) continue; var str1 = node1.Attributes["ID"].InnerText.Trim(); if (!int.TryParse(str1, out var id)) continue; if (id != productAttributeMapping.Id) continue; attributeElement = (XmlElement)node1; break; } //create new one if not found if (attributeElement == null) { attributeElement = xmlDoc.CreateElement("ProductAttribute"); attributeElement.SetAttribute("ID", productAttributeMapping.Id.ToString()); rootElement.AppendChild(attributeElement); } var attributeValueElement = xmlDoc.CreateElement("ProductAttributeValue"); attributeElement.AppendChild(attributeValueElement); var attributeValueValueElement = xmlDoc.CreateElement("Value"); attributeValueValueElement.InnerText = value; attributeValueElement.AppendChild(attributeValueValueElement); //the quantity entered by the customer if (quantity.HasValue) { var attributeValueQuantity = xmlDoc.CreateElement("Quantity"); attributeValueQuantity.InnerText = quantity.ToString(); attributeValueElement.AppendChild(attributeValueQuantity); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Remove an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMapping">Product attribute mapping</param> /// <returns>Updated result (XML format)</returns> public virtual string RemoveProductAttribute(string attributesXml, ProductAttributeMapping productAttributeMapping) { var result = string.Empty; try { var xmlDoc = new XmlDocument(); if (string.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes?["ID"] == null) continue; var str1 = node1.Attributes["ID"].InnerText.Trim(); if (!int.TryParse(str1, out var id)) continue; if (id != productAttributeMapping.Id) continue; attributeElement = (XmlElement)node1; break; } //found if (attributeElement != null) { rootElement.RemoveChild(attributeElement); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Are attributes equal /// </summary> /// <param name="attributesXml1">The attributes of the first product</param> /// <param name="attributesXml2">The attributes of the second product</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <param name="ignoreQuantity">A value indicating whether we should ignore the quantity of attribute value entered by the customer</param> /// <returns>Result</returns> public virtual bool AreProductAttributesEqual(string attributesXml1, string attributesXml2, bool ignoreNonCombinableAttributes, bool ignoreQuantity = true) { var attributes1 = ParseProductAttributeMappings(attributesXml1); if (ignoreNonCombinableAttributes) { attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList(); } var attributes2 = ParseProductAttributeMappings(attributesXml2); if (ignoreNonCombinableAttributes) { attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList(); } if (attributes1.Count != attributes2.Count) return false; var attributesEqual = true; foreach (var a1 in attributes1) { var hasAttribute = false; foreach (var a2 in attributes2) { if (a1.Id != a2.Id) continue; hasAttribute = true; var values1Str = ParseValuesWithQuantity(attributesXml1, a1.Id); var values2Str = ParseValuesWithQuantity(attributesXml2, a2.Id); if (values1Str.Count == values2Str.Count) { foreach (var str1 in values1Str) { var hasValue = false; foreach (var str2 in values2Str) { //case insensitive? //if (str1.Trim().ToLower() == str2.Trim().ToLower()) if (str1.Item1.Trim() != str2.Item1.Trim()) continue; hasValue = ignoreQuantity || str1.Item2.Trim() == str2.Item2.Trim(); break; } if (hasValue) continue; attributesEqual = false; break; } } else { attributesEqual = false; break; } } if (hasAttribute) continue; attributesEqual = false; break; } return attributesEqual; } /// <summary> /// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified /// </summary> /// <param name="pam">Product attribute</param> /// <param name="selectedAttributesXml">Selected attributes (XML format)</param> /// <returns>Result</returns> public virtual bool? IsConditionMet(ProductAttributeMapping pam, string selectedAttributesXml) { if (pam == null) throw new ArgumentNullException(nameof(pam)); var conditionAttributeXml = pam.ConditionAttributeXml; if (string.IsNullOrEmpty(conditionAttributeXml)) //no condition return null; //load an attribute this one depends on var dependOnAttribute = ParseProductAttributeMappings(conditionAttributeXml).FirstOrDefault(); if (dependOnAttribute == null) return true; var valuesThatShouldBeSelected = ParseValues(conditionAttributeXml, dependOnAttribute.Id) //a workaround here: //ConditionAttributeXml can contain "empty" values (nothing is selected) //but in other cases (like below) we do not store empty values //that's why we remove empty values here .Where(x => !string.IsNullOrEmpty(x)) .ToList(); var selectedValues = ParseValues(selectedAttributesXml, dependOnAttribute.Id); if (valuesThatShouldBeSelected.Count != selectedValues.Count) return false; //compare values var allFound = true; foreach (var t1 in valuesThatShouldBeSelected) { var found = false; foreach (var t2 in selectedValues) if (t1 == t2) found = true; if (!found) allFound = false; } return allFound; } /// <summary> /// Finds a product attribute combination by attributes stored in XML /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <returns>Found product attribute combination</returns> public virtual ProductAttributeCombination FindProductAttributeCombination(Product product, string attributesXml, bool ignoreNonCombinableAttributes = true) { if (product == null) throw new ArgumentNullException(nameof(product)); //anyway combination cannot contains non combinable attributes if (string.IsNullOrEmpty(attributesXml)) return null; var combinations = _productAttributeService.GetAllProductAttributeCombinations(product.Id); return combinations.FirstOrDefault(x => AreProductAttributesEqual(x.AttributesXml, attributesXml, ignoreNonCombinableAttributes)); } /// <summary> /// Generate all combinations /// </summary> /// <param name="product">Product</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <param name="allowedAttributeIds">List of allowed attribute identifiers. If null or empty then all attributes would be used.</param> /// <returns>Attribute combinations in XML format</returns> public virtual IList<string> GenerateAllCombinations(Product product, bool ignoreNonCombinableAttributes = false, IList<int> allowedAttributeIds = null) { if (product == null) throw new ArgumentNullException(nameof(product)); var allProductAttributMappings = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id); if (ignoreNonCombinableAttributes) { allProductAttributMappings = allProductAttributMappings.Where(x => !x.IsNonCombinable()).ToList(); } //get all possible attribute combinations var allPossibleAttributeCombinations = CreateCombination(allProductAttributMappings); var allAttributesXml = new List<string>(); foreach (var combination in allPossibleAttributeCombinations) { var attributesXml = new List<string>(); foreach (var productAttributeMapping in combination) { if (!productAttributeMapping.ShouldHaveValues()) continue; //get product attribute values var attributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id); //filter product attribute values if (allowedAttributeIds?.Any() ?? false) { attributeValues = attributeValues.Where(attributeValue => allowedAttributeIds.Contains(attributeValue.Id)).ToList(); } if (!attributeValues.Any()) continue; var isCheckbox = productAttributeMapping.AttributeControlType == AttributeControlType.Checkboxes || productAttributeMapping.AttributeControlType == AttributeControlType.ReadonlyCheckboxes; var currentAttributesXml = new List<string>(); if (isCheckbox) { //add several values attribute types (checkboxes) //checkboxes could have several values ticked foreach (var oldXml in attributesXml.Any() ? attributesXml : new List<string> { string.Empty }) { foreach (var checkboxCombination in CreateCombination(attributeValues)) { var newXml = oldXml; foreach (var checkboxValue in checkboxCombination) { newXml = AddProductAttribute(newXml, productAttributeMapping, checkboxValue.Id.ToString()); } if (!string.IsNullOrEmpty(newXml)) { currentAttributesXml.Add(newXml); } } } } else { //add one value attribute types (dropdownlist, radiobutton, color squares) foreach (var oldXml in attributesXml.Any() ? attributesXml : new List<string> { string.Empty }) { currentAttributesXml.AddRange(attributeValues.Select(attributeValue => AddProductAttribute(oldXml, productAttributeMapping, attributeValue.Id.ToString()))); } } attributesXml.Clear(); attributesXml.AddRange(currentAttributesXml); } allAttributesXml.AddRange(attributesXml); } //validate conditional attributes (if specified) //minor workaround: //once it's done (validation), then we could have some duplicated combinations in result //we don't remove them here (for performance optimization) because anyway it'll be done in the "GenerateAllAttributeCombinations" method of ProductController for (var i = 0; i < allAttributesXml.Count; i++) { var attributesXml = allAttributesXml[i]; foreach (var attribute in allProductAttributMappings) { var conditionMet = IsConditionMet(attribute, attributesXml); if (conditionMet.HasValue && !conditionMet.Value) { allAttributesXml[i] = RemoveProductAttribute(attributesXml, attribute); } } } return allAttributesXml; } /// <summary> /// Parse a customer entered price of the product /// </summary> /// <param name="product">Product</param> /// <param name="form">Form</param> /// <returns>Customer entered price of the product</returns> public virtual decimal ParseCustomerEnteredPrice(Product product, IFormCollection form) { if (product == null) throw new ArgumentNullException(nameof(product)); if (form == null) throw new ArgumentNullException(nameof(form)); var customerEnteredPriceConverted = decimal.Zero; if (product.CustomerEntersPrice) { foreach (var formKey in form.Keys) { if (formKey.Equals($"addtocart_{product.Id}.CustomerEnteredPrice", StringComparison.InvariantCultureIgnoreCase)) { if (decimal.TryParse(form[formKey], out var customerEnteredPrice)) customerEnteredPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency); break; } } } return customerEnteredPriceConverted; } /// <summary> /// Parse a entered quantity of the product /// </summary> /// <param name="product">Product</param> /// <param name="form">Form</param> /// <returns>Customer entered price of the product</returns> public virtual int ParseEnteredQuantity(Product product, IFormCollection form) { if (product == null) throw new ArgumentNullException(nameof(product)); if (form == null) throw new ArgumentNullException(nameof(form)); var quantity = 1; foreach (var formKey in form.Keys) { if (formKey.Equals($"addtocart_{product.Id}.EnteredQuantity", StringComparison.InvariantCultureIgnoreCase)) { int.TryParse(form[formKey], out quantity); break; } } return quantity; } /// <summary> /// Parse product rental dates on the product details page /// </summary> /// <param name="product">Product</param> /// <param name="form">Form</param> /// <param name="startDate">Start date</param> /// <param name="endDate">End date</param> public virtual void ParseRentalDates(Product product, IFormCollection form, out DateTime? startDate, out DateTime? endDate) { if (product == null) throw new ArgumentNullException(nameof(product)); if (form == null) throw new ArgumentNullException(nameof(form)); startDate = null; endDate = null; if (product.IsRental) { var startControlId = $"rental_start_date_{product.Id}"; var endControlId = $"rental_end_date_{product.Id}"; var ctrlStartDate = form[startControlId]; var ctrlEndDate = form[endControlId]; try { //currently we support only this format (as in the \Views\Product\_RentalInfo.cshtml file) const string datePickerFormat = "d"; startDate = DateTime.ParseExact(ctrlStartDate, datePickerFormat, CultureInfo.InvariantCulture); endDate = DateTime.ParseExact(ctrlEndDate, datePickerFormat, CultureInfo.InvariantCulture); } catch { } } } /// <summary> /// Get product attributes from the passed form /// </summary> /// <param name="product">Product</param> /// <param name="form">Form values</param> /// <param name="errors">Errors</param> /// <returns>Attributes in XML format</returns> public virtual string ParseProductAttributes(Product product, IFormCollection form, List<string> errors) { if (product == null) throw new ArgumentNullException(nameof(product)); if (form == null) throw new ArgumentNullException(nameof(form)); //product attributes var attributesXml = GetProductAttributesXml(product, form, errors); //gift cards AddGiftCardsAttributesXml(product, form, ref attributesXml); return attributesXml; } #endregion #region Gift card attributes /// <summary> /// Add gift card attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="recipientName">Recipient name</param> /// <param name="recipientEmail">Recipient email</param> /// <param name="senderName">Sender name</param> /// <param name="senderEmail">Sender email</param> /// <param name="giftCardMessage">Message</param> /// <returns>Attributes</returns> public string AddGiftCardAttribute(string attributesXml, string recipientName, string recipientEmail, string senderName, string senderEmail, string giftCardMessage) { var result = string.Empty; try { recipientName = recipientName.Trim(); recipientEmail = recipientEmail.Trim(); senderName = senderName.Trim(); senderEmail = senderEmail.Trim(); var xmlDoc = new XmlDocument(); if (string.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); var giftCardElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo"); if (giftCardElement == null) { giftCardElement = xmlDoc.CreateElement("GiftCardInfo"); rootElement.AppendChild(giftCardElement); } var recipientNameElement = xmlDoc.CreateElement("RecipientName"); recipientNameElement.InnerText = recipientName; giftCardElement.AppendChild(recipientNameElement); var recipientEmailElement = xmlDoc.CreateElement("RecipientEmail"); recipientEmailElement.InnerText = recipientEmail; giftCardElement.AppendChild(recipientEmailElement); var senderNameElement = xmlDoc.CreateElement("SenderName"); senderNameElement.InnerText = senderName; giftCardElement.AppendChild(senderNameElement); var senderEmailElement = xmlDoc.CreateElement("SenderEmail"); senderEmailElement.InnerText = senderEmail; giftCardElement.AppendChild(senderEmailElement); var messageElement = xmlDoc.CreateElement("Message"); messageElement.InnerText = giftCardMessage; giftCardElement.AppendChild(messageElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Get gift card attributes /// </summary> /// <param name="attributesXml">Attributes</param> /// <param name="recipientName">Recipient name</param> /// <param name="recipientEmail">Recipient email</param> /// <param name="senderName">Sender name</param> /// <param name="senderEmail">Sender email</param> /// <param name="giftCardMessage">Message</param> public void GetGiftCardAttribute(string attributesXml, out string recipientName, out string recipientEmail, out string senderName, out string senderEmail, out string giftCardMessage) { recipientName = string.Empty; recipientEmail = string.Empty; senderName = string.Empty; senderEmail = string.Empty; giftCardMessage = string.Empty; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var recipientNameElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/RecipientName"); var recipientEmailElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/RecipientEmail"); var senderNameElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/SenderName"); var senderEmailElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/SenderEmail"); var messageElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/Message"); if (recipientNameElement != null) recipientName = recipientNameElement.InnerText; if (recipientEmailElement != null) recipientEmail = recipientEmailElement.InnerText; if (senderNameElement != null) senderName = senderNameElement.InnerText; if (senderEmailElement != null) senderEmail = senderEmailElement.InnerText; if (messageElement != null) giftCardMessage = messageElement.InnerText; } catch (Exception exc) { Debug.Write(exc.ToString()); } } #endregion } }
43.020665
169
0.529009
[ "MIT" ]
ASP-WAF/FireWall
Samples/NopeCommerce/Libraries/Nop.Services/Catalog/ProductAttributeParser.cs
47,884
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Composition; using VVVV.PluginInterfaces.V2; using VVVV.PluginInterfaces.V1; using FeralTic.DX11; using FeralTic.DX11.Queries; namespace VVVV.DX11.Nodes { [PluginInfo(Name="Group",Category="DX11.Layer",Author="vux")] public class DX11LayerGroupNode : IPluginEvaluate, IDX11LayerHost, IDX11Queryable, IPartImportsSatisfiedNotification, IDX11UpdateBlocker { [Config("Input Count", DefaultValue = 2, MinValue = 2)] protected IDiffSpread<int> FInputCount; [Input("Render State", IsSingle=true)] protected Pin<DX11RenderState> FInState; [Input("Custom Semantics", Order = 5000, Visibility = PinVisibility.OnlyInspector)] protected Pin<IDX11RenderSemantic> FInSemantics; [Input("Resource Semantics", Order = 5001, Visibility = PinVisibility.OnlyInspector)] protected Pin<DX11Resource<IDX11RenderSemantic>> FInResSemantics; [Input("Validators", Order = 5001, Visibility = PinVisibility.OnlyInspector)] protected Pin<IDX11ObjectValidator> FInVal; [Input("Enabled",DefaultValue=1, Order = 100000)] protected IDiffSpread<bool> FEnabled; [Output("Layer Out")] protected ISpread<DX11Resource<DX11Layer>> FOutLayer; [Output("Query", Order = 200, IsSingle = true)] protected ISpread<IDX11Queryable> FOutQueryable; private List<IIOContainer<Pin<DX11Resource<DX11Layer>>>> FLayers = new List<IIOContainer<Pin<DX11Resource<DX11Layer>>>>(); private IPluginHost FHost; private IIOFactory FIOFactory; private int spmax; [ImportingConstructor()] public DX11LayerGroupNode(IPluginHost host,IIOFactory iofactory) { this.FHost = host; this.FIOFactory = iofactory; } public void Evaluate(int SpreadMax) { this.spmax = SpreadMax; if (SpreadMax > 0) { if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource<DX11Layer>(); } if (this.FOutQueryable[0] == null) { this.FOutQueryable[0] = this; } if (this.FEnabled[0]) { foreach (IIOContainer<Pin<DX11Resource<DX11Layer>>> lin in this.FLayers) { lin.IOObject.Sync(); } } } } private void SetInputs() { if (this.FInputCount[0] != FLayers.Count) { if (this.FInputCount[0] > FLayers.Count) { while (this.FInputCount[0] > FLayers.Count) { InputAttribute attr = new InputAttribute("Layer " + Convert.ToString(this.FLayers.Count + 1)); attr.IsSingle = false; attr.CheckIfChanged = true; attr.AutoValidate = false; //Create new layer Pin IIOContainer<Pin<DX11Resource<DX11Layer>>> newlayer = this.FIOFactory.CreateIOContainer<Pin<DX11Resource<DX11Layer>>>(attr); newlayer.IOObject.SliceCount = 1; this.FLayers.Add(newlayer); newlayer.IOObject[0] = new DX11Resource<DX11Layer>(); } } else { while (this.FInputCount[0] < FLayers.Count) { this.FLayers[this.FLayers.Count - 1].Dispose(); this.FLayers.RemoveAt(this.FLayers.Count - 1); } } } } #region IDX11ResourceProvider Members public void Update(DX11RenderContext context) { if (this.spmax > 0) { if (!this.FOutLayer[0].Contains(context)) { this.FOutLayer[0][context] = new DX11Layer(); this.FOutLayer[0][context].Render = this.Render; } } } public void Destroy(DX11RenderContext context, bool force) { this.FOutLayer.SafeDisposeAll(context); } public void Render(DX11RenderContext context, DX11RenderSettings settings) { if (this.spmax > 0) { if (this.FEnabled[0]) { bool popstate = false; if (this.FInState.IsConnected) { context.RenderStateStack.Push(this.FInState[0]); popstate = true; } List<IDX11RenderSemantic> semantics = new List<IDX11RenderSemantic>(); if (this.FInSemantics.PluginIO.IsConnected) { semantics.AddRange(this.FInSemantics); settings.CustomSemantics.AddRange(semantics); } List<DX11Resource<IDX11RenderSemantic>> ressemantics = new List<DX11Resource<IDX11RenderSemantic>>(); if (this.FInResSemantics.IsConnected) { ressemantics.AddRange(this.FInResSemantics); settings.ResourceSemantics.AddRange(ressemantics); } List<IDX11ObjectValidator> valids = new List<IDX11ObjectValidator>(); if (this.FInVal.IsConnected) { for (int i = 0; i < this.FInVal.SliceCount; i++) { if (this.FInVal[i].Enabled) { IDX11ObjectValidator v = this.FInVal[i]; //v.Reset(); v.SetGlobalSettings(settings); valids.Add(v); settings.ObjectValidators.Add(v); } } } if (this.BeginQuery != null) { this.BeginQuery(context); } for (int i = 0; i < this.FLayers.Count; i++) { var dxpin = this.FLayers[i]; if (dxpin.IOObject.IsConnected) { dxpin.IOObject.RenderAll(context, settings); } } if (this.EndQuery != null) { this.EndQuery(context); } foreach (IDX11RenderSemantic semantic in semantics) { settings.CustomSemantics.Remove(semantic); } foreach (DX11Resource<IDX11RenderSemantic> rs in ressemantics) { settings.ResourceSemantics.Remove(rs); } foreach (IDX11ObjectValidator v in valids) { settings.ObjectValidators.Remove(v); } if (popstate) { context.RenderStateStack.Pop(); } } } } #endregion #region IPartImportsSatisfiedNotification Members public void OnImportsSatisfied() { this.FInputCount.Changed += new SpreadChangedEventHander<int>(FInputCount_Changed); this.SetInputs(); } void FInputCount_Changed(IDiffSpread<int> spread) { this.SetInputs(); } #endregion public event DX11QueryableDelegate BeginQuery; public event DX11QueryableDelegate EndQuery; public bool Enabled { get { if (this.spmax > 0) { return this.FEnabled[0]; } else { return false; } } } } }
33.449799
148
0.486133
[ "BSD-3-Clause" ]
mhusinsky/dx11-vvvv
Nodes/VVVV.DX11.Nodes/Nodes/Layers/DX11LayerGroupNode.cs
8,331
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Velusia.Server.Helpers { public static class AsyncEnumerableExtensions { public static Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return ExecuteAsync(); async Task<List<T>> ExecuteAsync() { var list = new List<T>(); await foreach (var element in source) { list.Add(element); } return list; } } } }
23.258065
83
0.50208
[ "Apache-2.0" ]
AngularAdvisers/openiddict-samples
samples/Velusia/Velusia.Server/Helpers/AsyncEnumerableExtensions.cs
723
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 apigateway-2015-07-09.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.APIGateway.Model { /// <summary> /// Container for the parameters to the DeleteIntegrationResponse operation. /// Represents a delete integration response. /// </summary> public partial class DeleteIntegrationResponseRequest : AmazonAPIGatewayRequest { private string _httpMethod; private string _resourceId; private string _restApiId; private string _statusCode; /// <summary> /// Gets and sets the property HttpMethod. /// <para> /// [Required] Specifies a delete integration response request's HTTP method. /// </para> /// </summary> [AWSProperty(Required=true)] public string HttpMethod { get { return this._httpMethod; } set { this._httpMethod = value; } } // Check to see if HttpMethod property is set internal bool IsSetHttpMethod() { return this._httpMethod != null; } /// <summary> /// Gets and sets the property ResourceId. /// <para> /// [Required] Specifies a delete integration response request's resource identifier. /// </para> /// </summary> [AWSProperty(Required=true)] public string ResourceId { get { return this._resourceId; } set { this._resourceId = value; } } // Check to see if ResourceId property is set internal bool IsSetResourceId() { return this._resourceId != null; } /// <summary> /// Gets and sets the property RestApiId. /// <para> /// [Required] The string identifier of the associated <a>RestApi</a>. /// </para> /// </summary> [AWSProperty(Required=true)] public string RestApiId { get { return this._restApiId; } set { this._restApiId = value; } } // Check to see if RestApiId property is set internal bool IsSetRestApiId() { return this._restApiId != null; } /// <summary> /// Gets and sets the property StatusCode. /// <para> /// [Required] Specifies a delete integration response request's status code. /// </para> /// </summary> [AWSProperty(Required=true)] public string StatusCode { get { return this._statusCode; } set { this._statusCode = value; } } // Check to see if StatusCode property is set internal bool IsSetStatusCode() { return this._statusCode != null; } } }
30.262712
108
0.597032
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/DeleteIntegrationResponseRequest.cs
3,571
C#
// Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using Nuke.Common.Tooling; namespace Nuke.Common.Tools.SonarScanner { partial class SonarScannerBeginSettings { private string GetToolPath() { return SonarScannerTasks.GetToolPath(Framework); } } partial class SonarScannerEndSettings { private string GetToolPath() { return SonarScannerTasks.GetToolPath(Framework); } } partial class SonarScannerTasks { internal static string GetToolPath(string framework = null) { return ToolPathResolver.GetPackageExecutable( packageId: "dotnet-sonarscanner|MSBuild.SonarQube.Runner.Tool", packageExecutable: "SonarScanner.MSBuild.dll|SonarScanner.MSBuild.exe", framework: framework); } } }
26.611111
87
0.647182
[ "MIT" ]
Ceaphyrel/nuke
source/Nuke.Common/Tools/SonarScanner/SonarScannerTasks.cs
958
C#
using System; namespace CodeCamp.Areas.HelpPage.ModelDescriptions { /// <summary> /// Use this attribute to change the name of the <see cref="ModelDescription"/> generated for a type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] public sealed class ModelNameAttribute : Attribute { public ModelNameAttribute(string name) { Name = name; } public string Name { get; private set; } } }
32
137
0.645833
[ "MIT" ]
Mohammad-Nour-Rezek/CodeCamp
CodeCamp/CodeCamp/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs
576
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("1000 Days After Birth")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1000 Days After Birth")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("04254ded-7aed-4f82-b78e-15dea59c7e32")] // 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.243243
84
0.74417
[ "MIT" ]
IvayloKovachev09/SoftUni
Programming Basic/WindowsFormsApplication1/1000 Days After Birth/Properties/AssemblyInfo.cs
1,418
C#
using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.LanguageServer.Server.Configuration { class DisposableConfiguration : IScopedConfiguration { private readonly ConfigurationRoot _configuration; private readonly WorkspaceConfigurationSource _configurationSource; private readonly IDisposable _disposable; public DisposableConfiguration(IConfigurationBuilder configurationBuilder, WorkspaceConfigurationSource configurationSource, IDisposable disposable) { _configuration = configurationBuilder.Add(configurationSource).Build() as ConfigurationRoot; _configurationSource = configurationSource; _disposable = disposable; } public IConfigurationSection GetSection(string key) => _configuration.GetSection(key); public IEnumerable<IConfigurationSection> GetChildren() => _configuration.GetChildren(); public IChangeToken GetReloadToken() => _configuration.GetReloadToken(); internal void Update(IEnumerable<(string key, JToken settings)> data) => _configurationSource.Update(data); public string this[string key] { get => _configuration[key]; set => _configuration[key] = value; } public void Dispose() { _configuration.Dispose(); _disposable.Dispose(); } } }
35.488372
156
0.711664
[ "MIT" ]
TanayParikh/csharp-language-server-protocol
src/Server/Configuration/DisposableConfiguration.cs
1,528
C#
using DCM.Interfaces; using Discord.WebSocket; namespace DCM.Events.Discord { public class MessageCommandExecutedEvent : Event { public MessageCommandExecutedEvent(SocketMessageCommand command) { Command = command; } public SocketMessageCommand Command { get; } } }
20.3125
72
0.667692
[ "MIT" ]
Michelle-99/DiscordManager
DiscordManager/Events/Discord/MessageCommandExecutedEvent.cs
327
C#
using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using HarmonyLib; using RimWorld; using Verse; namespace TurretExtensions { public static class Patch_Verb_Shoot { [HarmonyPatch(typeof(Verb_Shoot), nameof(Verb_Shoot.WarmupComplete))] public static class WarmupComplete { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { // Reason why this transpiler exists instead of just a postfix on the CasterPawn and CasterIsPawn properties is because CasterPawn gets referenced in several other places too, which causes other issues #if DEBUG Log.Message("Transpiler start: Verb_Shoot.WarmupComplete (3 matches)"); #endif var instructionList = instructions.ToList(); var getCasterIsPawnInfo = AccessTools.Property(typeof(Verb), nameof(Verb.CasterIsPawn)).GetGetMethod(); var casterIsActuallyPawn = AccessTools.Method(typeof(WarmupComplete), nameof(CasterIsActuallyPawn)); var getCasterPawnInfo = AccessTools.Property(typeof(Verb), nameof(Verb.CasterPawn)).GetGetMethod(); var actualCasterPawnInfo = AccessTools.Method(typeof(WarmupComplete), nameof(ActualCasterPawn)); foreach (var ci in instructionList) { var instruction = ci; // Update all 'CasterIsPawn' and 'CasterPawn' calls to factor in CompMannable if (instruction.opcode == OpCodes.Callvirt) { #if DEBUG Log.Message("Verb_Shoot.WarmupComplete match 1 of 3"); #endif // CasterIsPawn if (instruction.OperandIs(getCasterIsPawnInfo)) { #if DEBUG Log.Message("Verb_Shoot.WarmupComplete match 2 of 3"); #endif yield return instruction; // this.CasterIsPawn yield return new CodeInstruction(OpCodes.Ldarg_0); // this instruction = new CodeInstruction(OpCodes.Call, casterIsActuallyPawn); // CasterIsActuallyPawn(this.CasterIsPawn, this) } // CasterPawn else if (instruction.OperandIs(getCasterPawnInfo)) { #if DEBUG Log.Message("Verb_Shoot.WarmupComplete match 3 of 3"); #endif yield return instruction; // this.CasterPawn yield return new CodeInstruction(OpCodes.Ldarg_0); // this instruction = new CodeInstruction(OpCodes.Call, actualCasterPawnInfo); // ActualCasterPawn(this.CasterPawn, this) } } yield return instruction; } } private static bool CasterIsActuallyPawn(bool original, Verb instance) { // Factor in CompMannable for exp purposes return original || instance.Caster.TryGetComp<CompMannable>() is CompMannable mannableComp && mannableComp.MannedNow; } private static Pawn ActualCasterPawn(Pawn original, Verb instance) { // Factor in CompMannable for exp purposes if (original == null && instance.Caster.TryGetComp<CompMannable>() is CompMannable mannableComp) return mannableComp.ManningPawn; return original; } } [HarmonyPatch(typeof(Verb_Shoot), "TryCastShot")] public static class TryCastShot { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { // WarmupComplete transpiler can be reused return WarmupComplete.Transpiler(instructions); } } } }
40.666667
217
0.589667
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Dakraid/RW_TurretExtensions
Source/TurretExtensions/TurretExtensions/HarmonyPatches/Patch_Verb_Shoot.cs
4,028
C#
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.ViewModels { /// <summary> /// /// </summary> [DataContract] public partial class UserViewModel : IEquatable<UserViewModel> { /// <summary> /// Default constructor, required by entity framework /// </summary> public UserViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="UserViewModel" /> class. /// </summary> /// <param name="Id">Id (required).</param> /// <param name="Active">Active (required).</param> /// <param name="GivenName">GivenName.</param> /// <param name="Surname">Surname.</param> /// <param name="Email">Email.</param> /// <param name="SmUserId">SmUserId.</param> /// <param name="UserRoles">UserRoles.</param> /// <param name="GroupMemberships">GroupMemberships.</param> /// <param name="District">The District to which this User is affliated..</param> public UserViewModel(int Id, bool Active, string GivenName = null, string Surname = null, string Email = null, string SmUserId = null, List<UserRole> UserRoles = null, List<GroupMembership> GroupMemberships = null, District District = null) { this.Id = Id; this.Active = Active; this.GivenName = GivenName; this.Surname = Surname; this.Email = Email; this.SmUserId = SmUserId; this.UserRoles = UserRoles; this.GroupMemberships = GroupMemberships; this.District = District; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id")] public int Id { get; set; } /// <summary> /// Gets or Sets Active /// </summary> [DataMember(Name="active")] public bool Active { get; set; } /// <summary> /// Gets or Sets GivenName /// </summary> [DataMember(Name="givenName")] public string GivenName { get; set; } /// <summary> /// Gets or Sets Surname /// </summary> [DataMember(Name="surname")] public string Surname { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name="email")] public string Email { get; set; } /// <summary> /// Gets or Sets SmUserId /// </summary> [DataMember(Name="smUserId")] public string SmUserId { get; set; } /// <summary> /// Gets or Sets UserRoles /// </summary> [DataMember(Name="userRoles")] public List<UserRole> UserRoles { get; set; } /// <summary> /// Gets or Sets GroupMemberships /// </summary> [DataMember(Name="groupMemberships")] public List<GroupMembership> GroupMemberships { get; set; } /// <summary> /// The District to which this User is affliated. /// </summary> /// <value>The District to which this User is affliated.</value> [DataMember(Name="district")] [MetaDataExtension (Description = "The District to which this User is affliated.")] public District District { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" GivenName: ").Append(GivenName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" SmUserId: ").Append(SmUserId).Append("\n"); sb.Append(" UserRoles: ").Append(UserRoles).Append("\n"); sb.Append(" GroupMemberships: ").Append(GroupMemberships).Append("\n"); sb.Append(" District: ").Append(District).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((UserViewModel)obj); } /// <summary> /// Returns true if UserViewModel instances are equal /// </summary> /// <param name="other">Instance of UserViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserViewModel other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Active == other.Active || this.Active.Equals(other.Active) ) && ( this.GivenName == other.GivenName || this.GivenName != null && this.GivenName.Equals(other.GivenName) ) && ( this.Surname == other.Surname || this.Surname != null && this.Surname.Equals(other.Surname) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.SmUserId == other.SmUserId || this.SmUserId != null && this.SmUserId.Equals(other.SmUserId) ) && ( this.UserRoles == other.UserRoles || this.UserRoles != null && this.UserRoles.SequenceEqual(other.UserRoles) ) && ( this.GroupMemberships == other.GroupMemberships || this.GroupMemberships != null && this.GroupMemberships.SequenceEqual(other.GroupMemberships) ) && ( this.District == other.District || this.District != null && this.District.Equals(other.District) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); hash = hash * 59 + this.Active.GetHashCode(); if (this.GivenName != null) { hash = hash * 59 + this.GivenName.GetHashCode(); } if (this.Surname != null) { hash = hash * 59 + this.Surname.GetHashCode(); } if (this.Email != null) { hash = hash * 59 + this.Email.GetHashCode(); } if (this.SmUserId != null) { hash = hash * 59 + this.SmUserId.GetHashCode(); } if (this.UserRoles != null) { hash = hash * 59 + this.UserRoles.GetHashCode(); } if (this.GroupMemberships != null) { hash = hash * 59 + this.GroupMemberships.GetHashCode(); } if (this.District != null) { hash = hash * 59 + this.District.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(UserViewModel left, UserViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(UserViewModel left, UserViewModel right) { return !Equals(left, right); } #endregion Operators } }
36.135593
314
0.48743
[ "Apache-2.0" ]
BcGovBrian/schoolbus
Server/src/SchoolBusAPI/ViewModels/UserViewModel.cs
10,660
C#
namespace UnityStandardAssets.CrossPlatformInput.Inspector { using System.Collections.Generic; using UnityEditor; [InitializeOnLoad] public class CrossPlatformInitialize { // Custom compiler defines: // // CROSS_PLATFORM_INPUT : denotes that cross platform input package exists, so that other packages can use their CrossPlatformInput functions. // EDITOR_MOBILE_INPUT : denotes that mobile input should be used in editor, if a mobile build target is selected. (i.e. using Unity Remote app). // MOBILE_INPUT : denotes that mobile input should be used right now! static CrossPlatformInitialize() { var defines = GetDefinesList(buildTargetGroups[0]); if (!defines.Contains("CROSS_PLATFORM_INPUT")) { SetEnabled("CROSS_PLATFORM_INPUT", true, false); SetEnabled("MOBILE_INPUT", true, true); } } [MenuItem("Mobile Input/Enable")] private static void Enable() { SetEnabled("MOBILE_INPUT", true, true); switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.Android: case BuildTarget.iOS: case BuildTarget.WP8Player: case BuildTarget.BlackBerry: case BuildTarget.PSM: case BuildTarget.Tizen: case BuildTarget.WSAPlayer: EditorUtility.DisplayDialog("Mobile Input", "You have enabled Mobile Input. You'll need to use the Unity Remote app on a connected device to control your game in the Editor.", "OK"); break; default: EditorUtility.DisplayDialog("Mobile Input", "You have enabled Mobile Input, but you have a non-mobile build target selected in your build settings. The mobile control rigs won't be active or visible on-screen until you switch the build target to a mobile platform.", "OK"); break; } } [MenuItem("Mobile Input/Enable", true)] private static bool EnableValidate() { var defines = GetDefinesList(mobileBuildTargetGroups[0]); return !defines.Contains("MOBILE_INPUT"); } [MenuItem("Mobile Input/Disable")] private static void Disable() { SetEnabled("MOBILE_INPUT", false, true); switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.Android: case BuildTarget.iOS: case BuildTarget.WP8Player: case BuildTarget.BlackBerry: EditorUtility.DisplayDialog("Mobile Input", "You have disabled Mobile Input. Mobile control rigs won't be visible, and the Cross Platform Input functions will always return standalone controls.", "OK"); break; } } [MenuItem("Mobile Input/Disable", true)] private static bool DisableValidate() { var defines = GetDefinesList(mobileBuildTargetGroups[0]); return defines.Contains("MOBILE_INPUT"); } private static BuildTargetGroup[] buildTargetGroups = { BuildTargetGroup.Standalone, BuildTargetGroup.WebPlayer, BuildTargetGroup.Android, BuildTargetGroup.iOS, BuildTargetGroup.WP8, BuildTargetGroup.BlackBerry }; private static BuildTargetGroup[] mobileBuildTargetGroups = { BuildTargetGroup.Android, BuildTargetGroup.iOS, BuildTargetGroup.WP8, BuildTargetGroup.BlackBerry, BuildTargetGroup.PSM, BuildTargetGroup.Tizen, BuildTargetGroup.WSA }; private static void SetEnabled(string defineName, bool enable, bool mobile) { //Debug.Log("setting "+defineName+" to "+enable); foreach (var group in mobile ? mobileBuildTargetGroups : buildTargetGroups) { var defines = GetDefinesList(group); if (enable) { if (defines.Contains(defineName)) { return; } defines.Add(defineName); } else { if (!defines.Contains(defineName)) { return; } while (defines.Contains(defineName)) { defines.Remove(defineName); } } string definesString = string.Join(";", defines.ToArray()); PlayerSettings.SetScriptingDefineSymbolsForGroup(group, definesString); } } private static List<string> GetDefinesList(BuildTargetGroup group) { return new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(group).Split(';')); } } }
37.344828
270
0.537765
[ "MIT" ]
L4fter/CrocoDie
Assets/Editor/CrossPlatformInput/CrossPlatformInputInitialize.cs
5,415
C#
using AS.Domain.Interfaces; using System.IO; using System.Xml.Serialization; namespace AS.Infrastructure { /// <summary> /// Simple XMLSerializer class /// </summary> public class ASXmlSerializer : IXmlSerializer { /// <summary> /// Serialize object of generic type to XML /// </summary> /// <typeparam name="T">Type of value to be serialized</typeparam> /// <param name="value">Value to be serialized</param> /// <returns>XML string output of the value</returns> public string SerializeToXML<T>(T value) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (StringWriter writer = new StringWriter()) { xmlSerializer.Serialize(writer, value); return writer.ToString(); } } /// <summary> /// Serializes object to XML. /// </summary> /// <param name="value">object to be serialized</param> /// <returns>XML string output of the value</returns> public string SerializeToXML(object value) { if (value == null) return string.Empty; XmlSerializer xmlSerializer = new XmlSerializer(value.GetType()); using (StringWriter writer = new StringWriter()) { xmlSerializer.Serialize(writer, value); return writer.ToString(); } } /// <summary> /// Deserializes from XML to generic object /// </summary> /// <typeparam name="T">Type of the object</typeparam> /// <param name="xmlValue">XML representation of the object</param> /// <returns>Deserialzed object</returns> public T DeserializeFromXML<T>(string xmlValue) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xmlValue)) { return (T)xmlSerializer.Deserialize(reader); } } } }
33.015873
77
0.563942
[ "MIT" ]
bartizo12/ASAdmin
src/AS.Infrastructure/XML/ASXmlSerializer.cs
2,082
C#
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; using Cofoundry.Domain; namespace Cofoundry.Web { /// <summary> /// Data model representing a single image /// </summary> public class ImageDataModel : IPageBlockTypeDataModel { [Image] public int ImageId { get; set; } public string AltText { get; set; } public string LinkPath { get; set; } public string LinkTarget { get; set; } } }
25.6
57
0.658203
[ "MIT" ]
BOBO41/cofoundry
src/Cofoundry.Web/PageBlockTypes/Image/ImageDataModel.cs
514
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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.DotNet.Build.Tasks { /// <summary> /// Internal type used for JSON serialization of signing certificate data. /// </summary> internal sealed class SignTypeItem { /// <summary> /// Gets or sets the name of the Authenticode signature to apply. /// </summary> public string Authenticode { get; set; } /// <summary> /// Gets or sets the name of the strong-name signature to apply. /// </summary> public string StrongName { get; set; } } }
31.346154
78
0.656442
[ "MIT" ]
A-And/buildtools
src/Microsoft.DotNet.Build.Tasks/SignTypeItem.cs
815
C#
using System; using System.Windows; using System.Windows.Controls; namespace Configurator.WPF.Views { public partial class ConfiguratorView : Window { public ConfiguratorView() { try { InitializeComponent(); } catch (Exception e) { var logger = new Common.IO.Logger(Common.Paths.ConfiguratorLogFileName); logger.Log("ConfiguratorView init failed."); logger.Log(e); Application.Current.Shutdown(2); } } private void OnStatusChanged(object sender, TextChangedEventArgs e) { var statusTextBox = sender as TextBox; statusTextBox?.ScrollToEnd(); } } }
23.878788
88
0.544416
[ "MIT" ]
EtiamNullam/MaterialColor
Configurator.WPF/Views/ConfiguratorView.xaml.cs
790
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Serialization; using System.IO; using Trifolia.Shared; using System.Text; using LantanaGroup.ValidationUtility; namespace Trifolia.Terminology { public class VocabularyOutputTypeAdapter { private const string DYNAMIC_BINDING = "dynamic"; private VocabularyOutputType _vocabOutputType; private VocabularySystems _vocabSystems; private Encoding _encoding; public VocabularyOutputTypeAdapter(VocabularySystems aVocabSystems, VocabularyOutputType aOutputType) { _vocabOutputType = aOutputType; _vocabSystems = aVocabSystems; _encoding = Encoding.UTF8; } public VocabularyOutputTypeAdapter(VocabularySystems aVocabSystems, VocabularyOutputType aOutputType, Encoding aEncoding) : this(aVocabSystems, aOutputType) { _encoding = aEncoding; } public string AsXML() { //TODO: Refactor the AsDefaultXML, AsSVSXML and AsSVS_SingleValueSetXML into a more dynamic pattern. switch (_vocabOutputType) { case VocabularyOutputType.Default: return AsDefaultXML(); case VocabularyOutputType.SVS: return AsSVSXML(); case VocabularyOutputType.SVS_SingleValueSet: return AsSVS_SingleValueSetXML(); case VocabularyOutputType.FHIR: var svsXml = AsSVSXML(); return AsFHIRXML(svsXml); default: throw new ArgumentException(string.Format("No implementation for Vocabulary Type of '{0}'.", _vocabOutputType.ToString())); } } private string AsDefaultXML() { return CreateXML(typeof(VocabularySystems), _vocabSystems); } private string AsSVSXML() { return CreateXML(typeof(Schemas.VocabularyService.SVS.MultipleValueSet.RetrieveMultipleValueSetsResponseType), CreateRetrieveMultipleValueSetsResponse()); } private string AsSVS_SingleValueSetXML() { return CreateXML(typeof(Schemas.VocabularyService.SVS.SingleValueSet.RetrieveValueSetResponseType), CreateRetrieveValueSetResponse()); } private string AsFHIRXML(string svsXml) { string stylesheetContent = string.Empty; using (StreamReader sr = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Trifolia.Terminology.Transforms.Svs2FhirValueSet.xslt"))) { stylesheetContent = sr.ReadToEnd(); } return TransformFactory.Transform(svsXml, stylesheetContent, "http://www.w3.org/1999/XSL/Transform", new LantanaXmlResolver()); } private string CreateXML(Type aType, object aObjectToSerialize) { XmlSerializer serializer = new XmlSerializer(aType); using (StringWriterWithEncoding sw = new StringWriterWithEncoding(_encoding)) { serializer.Serialize(sw, aObjectToSerialize); return sw.ToString(); } } private Schemas.VocabularyService.SVS.SingleValueSet.RetrieveValueSetResponseType CreateRetrieveValueSetResponse() { var response = new Schemas.VocabularyService.SVS.SingleValueSet.RetrieveValueSetResponseType(); response.cacheExpirationHint = DateTime.Now.Date; response.cacheExpirationHintSpecified = true; if (_vocabSystems.Systems.Length > 0) { Schemas.VocabularyService.SVS.SingleValueSet.ValueSetResponseType valueSet = new Schemas.VocabularyService.SVS.SingleValueSet.ValueSetResponseType(); valueSet.displayName = _vocabSystems.Systems[0].ValueSetName; valueSet.id = _vocabSystems.Systems[0].ValueSetOid; valueSet.version = string.Empty; var concepts = new List<Schemas.VocabularyService.SVS.SingleValueSet.CE>(); foreach (var code in _vocabSystems.Systems[0].Codes) { concepts.Add(new Schemas.VocabularyService.SVS.SingleValueSet.CE() { code = code.Value, codeSystem = code.CodeSystem, codeSystemName = code.CodeSystemName, displayName = code.DisplayName }); } var conceptList = new Schemas.VocabularyService.SVS.SingleValueSet.ConceptListType() { Concept = concepts.ToArray() }; valueSet.ConceptList = new Schemas.VocabularyService.SVS.SingleValueSet.ConceptListType[] {conceptList}; response.ValueSet = valueSet; } return response; } private Schemas.VocabularyService.SVS.MultipleValueSet.RetrieveMultipleValueSetsResponseType CreateRetrieveMultipleValueSetsResponse() { var response = new Schemas.VocabularyService.SVS.MultipleValueSet.RetrieveMultipleValueSetsResponseType(); var valueSets = new List<Schemas.VocabularyService.SVS.MultipleValueSet.DescribedValueSet>(); foreach (var vocab in _vocabSystems.Systems) { if (vocab.Codes.Length > 0) { var valueSet = new Schemas.VocabularyService.SVS.MultipleValueSet.DescribedValueSet(); valueSet.Binding = Schemas.VocabularyService.SVS.MultipleValueSet.DescribedValueSetBinding.Static; if (vocab.Binding != null && vocab.Binding.ToLower() == DYNAMIC_BINDING) { valueSet.Binding = Schemas.VocabularyService.SVS.MultipleValueSet.DescribedValueSetBinding.Dynamic; } valueSet.BindingSpecified = true; valueSet.CreationDateSpecified = false; valueSet.displayName = vocab.ValueSetName; valueSet.EffectiveDateSpecified = false; valueSet.ExpirationDateSpecified = false; valueSet.ID = vocab.ValueSetOid; valueSet.RevisionDateSpecified = false; valueSet.Type = Schemas.VocabularyService.SVS.MultipleValueSet.DescribedValueSetType.Expanded; valueSet.version = ""; valueSet.Source = ""; valueSet.SourceURI = ""; var concepts = new List<Schemas.VocabularyService.SVS.MultipleValueSet.CE>(); foreach (var code in vocab.Codes) { concepts.Add(new Schemas.VocabularyService.SVS.MultipleValueSet.CE() { code = code.Value, codeSystem = code.CodeSystem, codeSystemName = code.CodeSystemName, displayName = code.DisplayName }); } valueSet.ConceptList = new Schemas.VocabularyService.SVS.MultipleValueSet.ConceptListType() { Concept = concepts.ToArray() }; valueSets.Add(valueSet); } } response.DescribedValueSet = valueSets.ToArray(); return response; } } }
44.964286
188
0.608684
[ "Apache-2.0" ]
BOBO41/trifolia
Trifolia.Terminology/VocabularyOutputTypeAdapter.cs
7,556
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associada a um assembly. [assembly: AssemblyTitle("ShutdownToolkit.Service")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShutdownToolkit.Service")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("bc3987cb-a36e-4a1b-8120-e8c415a748d5")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.756757
95
0.75523
[ "MIT" ]
jslucas22/ShutdownToolkit
ShutdownToolkit.Service/Properties/AssemblyInfo.cs
1,459
C#
namespace DataTanker { using System; /// <summary> /// Contains properties and methods of keys /// which is used to access the values in storage. /// </summary> public interface IComparableKey : IKey, IComparable { } }
19.461538
55
0.628458
[ "MIT" ]
VictorScherbakov/DataTanker
DataTanker/Core/IComparableKey.cs
255
C#
using System; using System.Collections.Generic; using System.Resources; using System.Text; using WhoPK.GameLogic.Character; using WhoPK.GameLogic.World.Area; using WhoPK.GameLogic.World.Room; namespace WhoPK.GameLogic.Commands.Movement { public interface ICommunication { //TODO: Add language void Say(Room room, Player character, string message); void Tell(Player fromCharacter, Player toCharacter, string message); void Yell(Area area, Player character, string message); } }
25.047619
76
0.73384
[ "MIT" ]
mbevier/ArchaicQuest-II
WhoPK.GameLogic/Commands/Communication/ICommunication.cs
528
C#
using System; using System.Collections.Generic; using System.Data.Entity.Core.Mapping; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using AutoMapper; using Itera.Fagdag.November.Domain.Models; using Itera.Fagdag.November.Helpers; using Itera.Fagdag.November.Logging.Contract; using Itera.Fagdag.November.Resources.Keys; using Itera.Fagdag.November.Services.Contracts; using Itera.Fagdag.November.Validation.Contracts; using Itera.Fagdag.November.ViewModels; using OfficeOpenXml; namespace Itera.Fagdag.November.Controllers { [Authorize] public class ManageProductsController : Common { private readonly ILogger _logger; private readonly IProductService _productService; private readonly IFileFormatValidation _fileFormatValidation; public ManageProductsController(ILogger logger, IProductService productService, IFileFormatValidation fileFormatValidation) { _logger = logger; _productService = productService; _fileFormatValidation = fileFormatValidation; } public ActionResult Index() { var products = _productService.GetProducts(); if (products == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() {ElementName = "Products"}); } var productViewModels = products.Select(Mapper.Map<Product, ProductViewModel>).ToList(); return View(productViewModels); } public ActionResult Add() { return View(); } public ActionResult AddMany() { return View(); } [HttpPost] public ActionResult AddProducts(ManageProductsViewModel manageProductsViewModel) { if (manageProductsViewModel == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() {ElementName = "Products"}); } if (ModelState.IsValid) { if (ModelState.Values.Any(x => x.Errors.Count >= 1)) { return View("AddMany", manageProductsViewModel); } } else { ModelState.AddModelError(string.Empty, "Please upload an Excel file with product information."); return View("AddMany", manageProductsViewModel); } return RedirectToAction("index"); } public ActionResult RemoveProduct(int id) { var product = _productService.GetProduct(id); if (product == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() { ElementName = "Product" }); } _productService.Remove(product); return RedirectToAction("Index", "ManageProducts"); } [HttpPost] public ActionResult AddProduct(ProductViewModel productViewModel) { if (productViewModel == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() {ElementName = "Product"}); } if (ModelState.IsValid) { var product = Mapper.Map<ProductViewModel, Product>(productViewModel); SaveCoverImageOnServer(productViewModel, product); if (ModelState.Values.Any(x => x.Errors.Count >= 1)) { return View("Add", productViewModel); } _productService.Add(product); } else { ModelState.AddModelError(string.Empty, "The fields below must be filled."); return View("Add", productViewModel); } return RedirectToAction("index"); } private void SaveCoverImageOnServer(ProductViewModel productViewModel, Product product) { var fileName = productViewModel.CoverImageBase.FileName; if (_fileFormatValidation.IsImageType(fileName)) { SaveOnServer(productViewModel.CoverImageBase.FileName, Keys.CoverImageBase); product.ImageName = String.Concat(Keys.PathUploads + "/", productViewModel.CoverImageBase.FileName); } else { ModelState.AddModelError(string.Empty, "Please upload a valid image file."); } } [HttpPost] public ActionResult UpdateProduct(string id) { var product = _productService.GetProduct(id.ToInt32()); if (product == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() { ElementName = "Product" }); } SaveCoverImageOnServer(product); _productService.Update(product); return RedirectToAction("Index"); } private void SaveCoverImageOnServer(Product product) { foreach (var file in from string item in Request.Files select Request.Files[item]) { SaveOnServer(file.FileName, Keys.CoverImageBase); product.ImageName = String.Concat(Keys.PathUploads + "/", file.FileName); break; } } } }
34.471338
116
0.584996
[ "MIT" ]
sirarsalih/Hackathons
Fagdag-2015---.Net-1/Itera.Fagdag.November/Controllers/ManageProductsController.cs
5,414
C#
using NBitcoin; using Nito.AsyncEx; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Crypto; using WalletWasabi.WabiSabi.Crypto; using WalletWasabi.WabiSabi.Backend.Banning; using WalletWasabi.WabiSabi.Backend.Models; using WalletWasabi.WabiSabi.Backend.PostRequests; using WalletWasabi.WabiSabi.Crypto.CredentialRequesting; using WalletWasabi.WabiSabi.Models; using WalletWasabi.WabiSabi.Models.MultipartyTransaction; using WalletWasabi.Logging; using WalletWasabi.Crypto.Randomness; using System; namespace WalletWasabi.WabiSabi.Backend.Rounds; public partial class Arena : IWabiSabiApiRequestHandler { public async Task<InputRegistrationResponse> RegisterInputAsync(InputRegistrationRequest request, CancellationToken cancellationToken) { try { return await RegisterInputCoreAsync(request, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (IsUserCheating(ex)) { Prison.Ban(request.Input, request.RoundId); throw; } } private async Task<InputRegistrationResponse> RegisterInputCoreAsync(InputRegistrationRequest request, CancellationToken cancellationToken) { var coin = await OutpointToCoinAsync(request, cancellationToken).ConfigureAwait(false); using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var round = GetRound(request.RoundId); var registeredCoins = Rounds.Where(x => !(x.Phase == Phase.Ended && x.EndRoundState != EndRoundState.TransactionBroadcasted)) .SelectMany(r => r.Alices.Select(a => a.Coin)); if (registeredCoins.Any(x => x.Outpoint == coin.Outpoint)) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AliceAlreadyRegistered); } if (round.IsInputRegistrationEnded(Config.MaxInputCountByRound)) { throw new WrongPhaseException(round, Phase.InputRegistration); } if (round is BlameRound blameRound && !blameRound.BlameWhitelist.Contains(coin.Outpoint)) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputNotWhitelisted); } // Compute but don't commit updated coinjoin to round state, it will // be re-calculated on input confirmation. This is computed in here // for validation purposes. _ = round.Assert<ConstructionState>().AddInput(coin); var coinJoinInputCommitmentData = new CoinJoinInputCommitmentData("CoinJoinCoordinatorIdentifier", round.Id); if (!OwnershipProof.VerifyCoinJoinInputProof(request.OwnershipProof, coin.TxOut.ScriptPubKey, coinJoinInputCommitmentData)) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongOwnershipProof); } // Generate a new GUID with the secure random source, to be sure // that it is not guessable (Guid.NewGuid() documentation does // not say anything about GUID version or randomness source, // only that the probability of duplicates is very low). var id = new Guid(SecureRandom.Instance.GetBytes(16)); var isPayingZeroCoordinationFee = CoinJoinIdStore.Contains(coin.Outpoint.Hash); if (!isPayingZeroCoordinationFee) { // If the coin comes from a tx that all of the tx inputs are coming from a CJ (1 hop - no pay). Transaction tx = await Rpc.GetRawTransactionAsync(coin.Outpoint.Hash, true, cancellationToken).ConfigureAwait(false); if (tx.Inputs.All(input => CoinJoinIdStore.Contains(input.PrevOut.Hash))) { isPayingZeroCoordinationFee = true; } } var alice = new Alice(coin, request.OwnershipProof, round, id, isPayingZeroCoordinationFee); if (alice.CalculateRemainingAmountCredentials(round.Parameters.MiningFeeRate, round.Parameters.CoordinationFeeRate) <= Money.Zero) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.UneconomicalInput); } if (alice.TotalInputAmount < round.Parameters.MinAmountCredentialValue) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.NotEnoughFunds); } if (alice.TotalInputAmount > round.Parameters.MaxAmountCredentialValue) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.TooMuchFunds); } if (alice.TotalInputVsize > round.Parameters.MaxVsizeAllocationPerAlice) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.TooMuchVsize); } var amountCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(request.ZeroAmountCredentialRequests, cancellationToken); var vsizeCredentialTask = round.VsizeCredentialIssuer.HandleRequestAsync(request.ZeroVsizeCredentialRequests, cancellationToken); if (round.RemainingInputVsizeAllocation < round.Parameters.MaxVsizeAllocationPerAlice) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.VsizeQuotaExceeded); } var commitAmountCredentialResponse = await amountCredentialTask.ConfigureAwait(false); var commitVsizeCredentialResponse = await vsizeCredentialTask.ConfigureAwait(false); alice.SetDeadlineRelativeTo(round.ConnectionConfirmationTimeFrame.Duration); round.Alices.Add(alice); return new(alice.Id, commitAmountCredentialResponse, commitVsizeCredentialResponse, alice.IsPayingZeroCoordinationFee); } } public async Task ReadyToSignAsync(ReadyToSignRequestRequest request, CancellationToken cancellationToken) { using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var round = GetRound(request.RoundId, Phase.OutputRegistration); var alice = GetAlice(request.AliceId, round); alice.ReadyToSign = true; } } public async Task RemoveInputAsync(InputsRemovalRequest request, CancellationToken cancellationToken) { using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var round = GetRound(request.RoundId, Phase.InputRegistration); round.Alices.RemoveAll(x => x.Id == request.AliceId); } } public async Task<ConnectionConfirmationResponse> ConfirmConnectionAsync(ConnectionConfirmationRequest request, CancellationToken cancellationToken) { try { return await ConfirmConnectionCoreAsync(request, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (IsUserCheating(ex)) { var round = GetRound(request.RoundId); var alice = GetAlice(request.AliceId, round); Prison.Ban(alice.Coin.Outpoint, round.Id); throw; } } private async Task<ConnectionConfirmationResponse> ConfirmConnectionCoreAsync(ConnectionConfirmationRequest request, CancellationToken cancellationToken) { Round round; Alice alice; var realAmountCredentialRequests = request.RealAmountCredentialRequests; var realVsizeCredentialRequests = request.RealVsizeCredentialRequests; using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { round = GetRound(request.RoundId, Phase.InputRegistration, Phase.ConnectionConfirmation); alice = GetAlice(request.AliceId, round); if (alice.ConfirmedConnection) { Prison.Ban(alice, round.Id); throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AliceAlreadyConfirmedConnection, $"Round ({request.RoundId}): Alice ({request.AliceId}) already confirmed connection."); } if (realVsizeCredentialRequests.Delta != alice.CalculateRemainingVsizeCredentials(round.Parameters.MaxVsizeAllocationPerAlice)) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.IncorrectRequestedVsizeCredentials, $"Round ({request.RoundId}): Incorrect requested vsize credentials."); } var remaining = alice.CalculateRemainingAmountCredentials(round.Parameters.MiningFeeRate, round.Parameters.CoordinationFeeRate); if (realAmountCredentialRequests.Delta != remaining) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.IncorrectRequestedAmountCredentials, $"Round ({request.RoundId}): Incorrect requested amount credentials."); } } var amountZeroCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(request.ZeroAmountCredentialRequests, cancellationToken); var vsizeZeroCredentialTask = round.VsizeCredentialIssuer.HandleRequestAsync(request.ZeroVsizeCredentialRequests, cancellationToken); Task<CredentialsResponse>? amountRealCredentialTask = null; Task<CredentialsResponse>? vsizeRealCredentialTask = null; if (round.Phase is Phase.ConnectionConfirmation) { amountRealCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(realAmountCredentialRequests, cancellationToken); vsizeRealCredentialTask = round.VsizeCredentialIssuer.HandleRequestAsync(realVsizeCredentialRequests, cancellationToken); } using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { alice = GetAlice(request.AliceId, round); switch (round.Phase) { case Phase.InputRegistration: { var commitAmountZeroCredentialResponse = await amountZeroCredentialTask.ConfigureAwait(false); var commitVsizeZeroCredentialResponse = await vsizeZeroCredentialTask.ConfigureAwait(false); alice.SetDeadlineRelativeTo(round.ConnectionConfirmationTimeFrame.Duration); return new( commitAmountZeroCredentialResponse, commitVsizeZeroCredentialResponse); } case Phase.ConnectionConfirmation: { // If the phase was InputRegistration before then we did not pre-calculate real credentials. amountRealCredentialTask ??= round.AmountCredentialIssuer.HandleRequestAsync(realAmountCredentialRequests, cancellationToken); vsizeRealCredentialTask ??= round.VsizeCredentialIssuer.HandleRequestAsync(realVsizeCredentialRequests, cancellationToken); ConnectionConfirmationResponse response = new( await amountZeroCredentialTask.ConfigureAwait(false), await vsizeZeroCredentialTask.ConfigureAwait(false), await amountRealCredentialTask.ConfigureAwait(false), await vsizeRealCredentialTask.ConfigureAwait(false)); // Update the coinjoin state, adding the confirmed input. round.CoinjoinState = round.Assert<ConstructionState>().AddInput(alice.Coin); alice.ConfirmedConnection = true; return response; } default: throw new WrongPhaseException(round, Phase.InputRegistration, Phase.ConnectionConfirmation); } } } public Task RegisterOutputAsync(OutputRegistrationRequest request, CancellationToken cancellationToken) { return RegisterOutputCoreAsync(request, cancellationToken); } public async Task<EmptyResponse> RegisterOutputCoreAsync(OutputRegistrationRequest request, CancellationToken cancellationToken) { using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var round = GetRound(request.RoundId, Phase.OutputRegistration); var credentialAmount = -request.AmountCredentialRequests.Delta; if (CoinJoinScriptStore?.Contains(request.Script) is true) { Logger.LogWarning($"Round ({request.RoundId}): Already registered script."); throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AlreadyRegisteredScript, $"Round ({request.RoundId}): Already registered script."); } var inputScripts = round.Alices.Select(a => a.Coin.ScriptPubKey).ToHashSet(); if (inputScripts.Contains(request.Script)) { Logger.LogWarning($"Round ({request.RoundId}): Already registered script in the round."); throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AlreadyRegisteredScript, $"Round ({request.RoundId}): Already registered script in round."); } Bob bob = new(request.Script, credentialAmount); var outputValue = bob.CalculateOutputAmount(round.Parameters.MiningFeeRate); var vsizeCredentialRequests = request.VsizeCredentialRequests; if (-vsizeCredentialRequests.Delta != bob.OutputVsize) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.IncorrectRequestedVsizeCredentials, $"Round ({request.RoundId}): Incorrect requested vsize credentials."); } // Update the current round state with the additional output to ensure it's valid. var newState = round.AddOutput(new TxOut(outputValue, bob.Script)); // Verify the credential requests and prepare their responses. await round.AmountCredentialIssuer.HandleRequestAsync(request.AmountCredentialRequests, cancellationToken).ConfigureAwait(false); await round.VsizeCredentialIssuer.HandleRequestAsync(vsizeCredentialRequests, cancellationToken).ConfigureAwait(false); // Update round state. round.Bobs.Add(bob); round.CoinjoinState = newState; } return EmptyResponse.Instance; } public async Task SignTransactionAsync(TransactionSignaturesRequest request, CancellationToken cancellationToken) { using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var round = GetRound(request.RoundId, Phase.TransactionSigning); var state = round.Assert<SigningState>().AddWitness((int)request.InputIndex, request.Witness); // at this point all of the witnesses have been verified and the state can be updated round.CoinjoinState = state; } } public async Task<ReissueCredentialResponse> ReissuanceAsync(ReissueCredentialRequest request, CancellationToken cancellationToken) { Round round; using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { round = GetRound(request.RoundId, Phase.ConnectionConfirmation, Phase.OutputRegistration); } if (request.RealAmountCredentialRequests.Delta != 0) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.DeltaNotZero, $"Round ({round.Id}): Amount credentials delta must be zero."); } if (request.RealVsizeCredentialRequests.Delta != 0) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.DeltaNotZero, $"Round ({round.Id}): Vsize credentials delta must be zero."); } if (request.RealAmountCredentialRequests.Requested.Count() != ProtocolConstants.CredentialNumber) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongNumberOfCreds, $"Round ({round.Id}): Incorrect requested number of amount credentials."); } if (request.RealVsizeCredentialRequests.Requested.Count() != ProtocolConstants.CredentialNumber) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongNumberOfCreds, $"Round ({round.Id}): Incorrect requested number of weight credentials."); } var realAmountTask = round.AmountCredentialIssuer.HandleRequestAsync(request.RealAmountCredentialRequests, cancellationToken); var realVsizeTask = round.VsizeCredentialIssuer.HandleRequestAsync(request.RealVsizeCredentialRequests, cancellationToken); var zeroAmountTask = round.AmountCredentialIssuer.HandleRequestAsync(request.ZeroAmountCredentialRequests, cancellationToken); var zeroVsizeTask = round.VsizeCredentialIssuer.HandleRequestAsync(request.ZeroVsizeCredentialsRequests, cancellationToken); return new( await realAmountTask.ConfigureAwait(false), await realVsizeTask.ConfigureAwait(false), await zeroAmountTask.ConfigureAwait(false), await zeroVsizeTask.ConfigureAwait(false)); } public async Task<Coin> OutpointToCoinAsync(InputRegistrationRequest request, CancellationToken cancellationToken) { OutPoint input = request.Input; if (Prison.TryGet(input, out var inmate)) { DateTimeOffset bannedUntil; if (inmate.Punishment == Punishment.LongBanned) { bannedUntil = inmate.Started + Config.ReleaseUtxoFromPrisonAfterLongBan; throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputLongBanned, exceptionData: new InputBannedExceptionData(bannedUntil)); } if (!Config.AllowNotedInputRegistration || inmate.Punishment != Punishment.Noted) { bannedUntil = inmate.Started + Config.ReleaseUtxoFromPrisonAfter; throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputBanned, exceptionData: new InputBannedExceptionData(bannedUntil)); } } var txOutResponse = await Rpc.GetTxOutAsync(input.Hash, (int)input.N, includeMempool: true, cancellationToken).ConfigureAwait(false); if (txOutResponse is null) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputSpent); } if (txOutResponse.Confirmations == 0) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputUnconfirmed); } if (txOutResponse.IsCoinBase && txOutResponse.Confirmations <= 100) { throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputImmature); } return new Coin(input, txOutResponse.TxOut); } public Task<RoundStateResponse> GetStatusAsync(RoundStateRequest request, CancellationToken cancellationToken) { var requestCheckPointDictionary = request.RoundCheckpoints.ToDictionary(r => r.RoundId, r => r); var responseRoundStates = RoundStates.Select(x => { if (requestCheckPointDictionary.TryGetValue(x.Id, out RoundStateCheckpoint? checkPoint) && checkPoint.StateId > 0) { return x.GetSubState(checkPoint.StateId); } return x; }).ToArray(); return Task.FromResult(new RoundStateResponse(responseRoundStates, Array.Empty<CoinJoinFeeRateMedian>())); } private Round GetRound(uint256 roundId) => Rounds.FirstOrDefault(x => x.Id == roundId) ?? throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.RoundNotFound, $"Round ({roundId}) not found."); private Round InPhase(Round round, Phase[] phases) => phases.Contains(round.Phase) ? round : throw new WrongPhaseException(round, phases); private Round GetRound(uint256 roundId, params Phase[] phases) => InPhase(GetRound(roundId), phases); private Alice GetAlice(Guid aliceId, Round round) => round.Alices.Find(x => x.Id == aliceId) ?? throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AliceNotFound, $"Round ({round.Id}): Alice ({aliceId}) not found."); private static bool IsUserCheating(Exception e) => e is WabiSabiCryptoException || (e is WabiSabiProtocolException wpe && wpe.ErrorCode.IsEvidencingClearMisbehavior()); }
41.655738
186
0.789453
[ "MIT" ]
CAnorbo/WalletWasabi
WalletWasabi/WabiSabi/Backend/Rounds/Arena.Partial.cs
17,787
C#
namespace AngleSharp.Css.Values { using AngleSharp.Css.Dom; using AngleSharp.Text; using System; /// <summary> /// Represents the skew transformation. /// </summary> sealed class CssSkewValue : ICssTransformFunctionValue { #region Fields private readonly ICssValue _alpha; private readonly ICssValue _beta; #endregion #region ctor /// <summary> /// Creates a new skew transform. /// </summary> /// <param name="alpha">The alpha skewing angle.</param> /// <param name="beta">The beta skewing angle.</param> public CssSkewValue(ICssValue alpha, ICssValue beta) { _alpha = alpha; _beta = beta; } #endregion #region Properties /// <summary> /// Gets the name of the function. /// </summary> public String Name { get { if (_alpha != _beta) { if (_alpha == null) { return FunctionNames.SkewY; } else if (_beta == null) { return FunctionNames.SkewX; } } return FunctionNames.Skew; } } /// <summary> /// Gets the arguments. /// </summary> public ICssValue[] Arguments => new ICssValue[] { }; /// <summary> /// Gets the CSS text representation. /// </summary> public String CssText { get { var args = _alpha?.CssText ?? String.Empty; if (_alpha != _beta) { if (_alpha == null) { args = _beta.CssText; } else if (_beta != null) { args = String.Concat(args, ", ", _beta.CssText); } } return Name.CssFunction(args); } } /// <summary> /// Gets the value of the first angle. /// </summary> public ICssValue Alpha => _alpha; /// <summary> /// Gets the value of the second angle. /// </summary> public ICssValue Beta => _beta; #endregion #region Methods /// <summary> /// Computes the matrix for the given transformation. /// </summary> /// <returns>The transformation matrix representation.</returns> public TransformMatrix ComputeMatrix(IRenderDimensions renderDimensions) { var a = Math.Tan((_alpha as Angle ? ?? Angle.Zero).ToRadian()); var b = Math.Tan((_beta as Angle? ?? Angle.Zero).ToRadian()); return new TransformMatrix(1.0, a, 0.0, b, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } #endregion } }
26.17094
110
0.450686
[ "MIT" ]
AngleSharp/AngleSharp.Css
src/AngleSharp.Css/Values/Functions/CssSkewValue.cs
3,062
C#
#region using using System.Collections.Generic; using System.Drawing; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; using VVVV.PluginInterfaces.V2; using VVVV.Utils.VMath; using System; using VVVV.Utils.VColor; using VVVV.CV.Core; #endregion namespace VVVV.CV.Nodes { [FilterInstance("Grayscale", Help = "Converts incoming images to respective grayscale versions", Author = "elliotwoods")] public class GrayscaleInstance : IFilterInstance { TColorFormat FOutFormat; public override void Allocate() { FOutFormat = ImageUtils.MakeGrayscale(FInput.ImageAttributes.ColorFormat); //if we can't convert or it's already grayscale, just pass through if (FOutFormat == TColorFormat.UnInitialised) FOutFormat = FInput.ImageAttributes.ColorFormat; FOutput.Image.Initialise(FInput.Image.ImageAttributes.Size, FOutFormat); } public override void Process() { FInput.GetImage(FOutput.Image); FOutput.Send(); } } }
24.075
122
0.760125
[ "MIT" ]
AchimTHISPLAY/VVVV.Packs.Image
src/nodes/plugins/Image/OpenCV/src/Filters/Grayscale.cs
965
C#
using System; namespace ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel { public class StDefaultKeywordToken : ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StToken, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.IStModifier { public StDefaultKeywordToken(ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.NodeFlags flags, System.Collections.Generic.List<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator> decorators, System.Collections.Generic.List<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.IStModifier> modifiers): base(flags, decorators, modifiers) { this.kind = ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.SyntaxKind.DefaultKeyword; } public StDefaultKeywordToken() { this.kind = ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.SyntaxKind.DefaultKeyword; } public override System.Object GetTransportModelNode() { return new ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.DefaultKeywordToken() {kind = this.kind, flags = this.flags, decorators = this.GetTransportModelNodes<ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.Decorator>(this.decorators), modifiers = this.GetTransportModelNodes<ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.IModifier>(this.modifiers)}; } } }
63.347826
371
0.775566
[ "MIT" ]
YevgenNabokov/ForgedOnce.TSLanguageServices
ForgedOnce.TsLanguageServices.FullSyntaxTree/AstModel/Generated/StDefaultKeywordToken.cs
1,457
C#
using log4net.Core; using System; namespace log4net.Filter { /// <summary> /// Simple filter to match a string in the event's logger name. /// </summary> /// <remarks> /// <para> /// The works very similar to the <see cref="T:log4net.Filter.LevelMatchFilter" />. It admits two /// options <see cref="P:log4net.Filter.LoggerMatchFilter.LoggerToMatch" /> and <see cref="P:log4net.Filter.LoggerMatchFilter.AcceptOnMatch" />. If the /// <see cref="P:log4net.Core.LoggingEvent.LoggerName" /> of the <see cref="T:log4net.Core.LoggingEvent" /> starts /// with the value of the <see cref="P:log4net.Filter.LoggerMatchFilter.LoggerToMatch" /> option, then the /// <see cref="M:log4net.Filter.LoggerMatchFilter.Decide(log4net.Core.LoggingEvent)" /> method returns <see cref="F:log4net.Filter.FilterDecision.Accept" /> in /// case the <see cref="P:log4net.Filter.LoggerMatchFilter.AcceptOnMatch" /> option value is set to <c>true</c>, /// if it is <c>false</c> then <see cref="F:log4net.Filter.FilterDecision.Deny" /> is returned. /// </para> /// </remarks> /// <author>Daniel Cazzulino</author> public class LoggerMatchFilter : FilterSkeleton { /// <summary> /// Flag to indicate the behavior when we have a match /// </summary> private bool m_acceptOnMatch = true; /// <summary> /// The logger name string to substring match against the event /// </summary> private string m_loggerToMatch; /// <summary> /// <see cref="F:log4net.Filter.FilterDecision.Accept" /> when matching <see cref="P:log4net.Filter.LoggerMatchFilter.LoggerToMatch" /> /// </summary> /// <remarks> /// <para> /// The <see cref="P:log4net.Filter.LoggerMatchFilter.AcceptOnMatch" /> property is a flag that determines /// the behavior when a matching <see cref="T:log4net.Core.Level" /> is found. If the /// flag is set to true then the filter will <see cref="F:log4net.Filter.FilterDecision.Accept" /> the /// logging event, otherwise it will <see cref="F:log4net.Filter.FilterDecision.Deny" /> the event. /// </para> /// <para> /// The default is <c>true</c> i.e. to <see cref="F:log4net.Filter.FilterDecision.Accept" /> the event. /// </para> /// </remarks> public bool AcceptOnMatch { get { return m_acceptOnMatch; } set { m_acceptOnMatch = value; } } /// <summary> /// The <see cref="P:log4net.Core.LoggingEvent.LoggerName" /> that the filter will match /// </summary> /// <remarks> /// <para> /// This filter will attempt to match this value against logger name in /// the following way. The match will be done against the beginning of the /// logger name (using <see cref="M:System.String.StartsWith(System.String)" />). The match is /// case sensitive. If a match is found then /// the result depends on the value of <see cref="P:log4net.Filter.LoggerMatchFilter.AcceptOnMatch" />. /// </para> /// </remarks> public string LoggerToMatch { get { return m_loggerToMatch; } set { m_loggerToMatch = value; } } /// <summary> /// Check if this filter should allow the event to be logged /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <returns>see remarks</returns> /// <remarks> /// <para> /// The rendered message is matched against the <see cref="P:log4net.Filter.LoggerMatchFilter.LoggerToMatch" />. /// If the <see cref="P:log4net.Filter.LoggerMatchFilter.LoggerToMatch" /> equals the beginning of /// the incoming <see cref="P:log4net.Core.LoggingEvent.LoggerName" /> (<see cref="M:System.String.StartsWith(System.String)" />) /// then a match will have occurred. If no match occurs /// this function will return <see cref="F:log4net.Filter.FilterDecision.Neutral" /> /// allowing other filters to check the event. If a match occurs then /// the value of <see cref="P:log4net.Filter.LoggerMatchFilter.AcceptOnMatch" /> is checked. If it is /// true then <see cref="F:log4net.Filter.FilterDecision.Accept" /> is returned otherwise /// <see cref="F:log4net.Filter.FilterDecision.Deny" /> is returned. /// </para> /// </remarks> public override FilterDecision Decide(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } if (m_loggerToMatch != null && m_loggerToMatch.Length != 0 && loggingEvent.LoggerName.StartsWith(m_loggerToMatch)) { if (m_acceptOnMatch) { return FilterDecision.Accept; } return FilterDecision.Deny; } return FilterDecision.Neutral; } } }
38.344538
161
0.681569
[ "MIT" ]
HuyTruong19x/DDTank4.1
Source Server/SourceQuest4.5/log4net/log4net.Filter/LoggerMatchFilter.cs
4,563
C#
using employers.domain.Requests; using System.Threading.Tasks; namespace employers.application.Interfaces.Departament { public interface IInsertDepartmentUseCaseAsync { Task<int?> RunAsync(DepartmentRequest departmentRequest); } }
23
65
0.774704
[ "MIT" ]
Carlinhao/crud-employee
src/employers.application/Interfaces/Departament/IInsertDepartmentUseCaseAsync.cs
255
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.IO; namespace APIStarter.Application.Resolvers { public class ResponseBodyResolver : IResponseBodyResolver { public RequestDelegate RequestDelegate { get; set; } private readonly IHttpContextAccessor _httpContextAccessor; private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager(); public ResponseBodyResolver(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; public async Task<string> ResolveAsync() { if (RequestDelegate is null) throw new ArgumentNullException(nameof(RequestDelegate)); var httpContext = _httpContextAccessor.HttpContext; var response = httpContext.Response; await using var responseStream = _recyclableMemoryStreamManager.GetStream(); var originalBody = response.Body; response.Body = responseStream; await RequestDelegate(httpContext); responseStream.Position = 0; using var streamReader = new StreamReader(responseStream); var responseBody = streamReader.ReadToEnd(); responseStream.Position = 0; await responseStream.CopyToAsync(originalBody); response.Body = originalBody; return responseBody == string.Empty ? null : responseBody; } } }
34.795455
124
0.694971
[ "MIT" ]
HaddadBenjamin/APIStarter
Write Model/WriteModel.Application/Resolvers/ResponseBodyResolver.cs
1,531
C#
using System.ComponentModel; namespace Reductech.Sequence.Connectors.Nuix.Enums; /// <summary> /// Method of deduplication to use for a top-level item export. /// </summary> public enum ExportDeduplication { /// <summary> /// No deduplication. /// </summary> [Description("none")] [Display(Name = "none")] None, /// <summary> /// If an item has no MD5, it is not removed. /// If two items have the same MD5, the first item by position is kept. /// </summary> [Description("md5")] [Display(Name = "md5")] // ReSharper disable once InconsistentNaming MD5, /// <summary> /// Same as MD5, except items assigned to different custodians are not treated as duplicates. /// </summary> [Description("md5_per_custodian")] [Display(Name = "md5_per_custodian")] // ReSharper disable once InconsistentNaming MD5PerCustodian }
26.529412
97
0.649667
[ "Apache-2.0" ]
reductech/Nuix
Nuix/Enums/ExportDeduplication.cs
904
C#
// Code generated by jtd-codegen for C# + System.Text.Json v0.2.1 using System; using System.Text.Json; using System.Text.Json.Serialization; namespace JtdCodegenE2E { [JsonConverter(typeof(RootJsonConverter))] public abstract class Root { } public class RootJsonConverter : JsonConverter<Root> { public override Root Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var readerCopy = reader; var tagValue = JsonDocument.ParseValue(ref reader).RootElement.GetProperty("foo").GetString(); switch (tagValue) { case "BAR_BAZ": return JsonSerializer.Deserialize<RootBarBaz>(ref readerCopy, options); case "QUUX": return JsonSerializer.Deserialize<RootQuux>(ref readerCopy, options); default: throw new ArgumentException(String.Format("Bad Foo value: {0}", tagValue)); } } public override void Write(Utf8JsonWriter writer, Root value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, value.GetType(), options); } } }
32.421053
111
0.625
[ "MIT" ]
AdamLeyshon/json-typedef-codegen
crates/target_csharp_system_text/output/basic_discriminator/Root.cs
1,232
C#
using Ao.ObjectDesign.Designing; using Ao.ObjectDesign.Designing.Annotations; using Ao.ObjectDesign.Wpf.Designing; using System.Windows.Media; namespace ObjectDesign.Wpf.Controls { [MappingFor(typeof(MoveId))] public class MoveIdSetting : NotifyableObject, IMiddlewareDesigner<MoveId> { public MoveIdSetting() { SetDefault(); } private string text; private BrushDesigner idBrush; private double idFontSize; public virtual double IdFontSize { get => idFontSize; set => Set(ref idFontSize, value); } public virtual BrushDesigner IdBrush { get => idBrush; set => Set(ref idBrush, value); } public virtual string Text { get => text; set => Set(ref text, value); } public void SetDefault() { IdFontSize = 12; IdBrush = new BrushDesigner { Brush = Brushes.Black }; Text = null; } public void Apply(MoveId value) { if (value is null) { SetDefault(); } else { IdFontSize = value.IdFontSize; IdBrush = new BrushDesigner { Brush = value.IdBrush }; Text = value.Text; } } public void WriteTo(MoveId value) { if (value != null) { value.IdFontSize = idFontSize; value.IdBrush = idBrush?.Brush; value.Text = text; } } } }
25.791045
79
0.478009
[ "Apache-2.0" ]
fossabot/Ao.ObjectDesign
samples/ObjectDesign.Wpf/Controls/MoveIdSetting.cs
1,730
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using DocumentFormat.OpenXml; namespace DocumentsGenerator.Core { internal class SourceData : ISourceData { public ISourceDataStep? Current => steps == null || steps.Count == 0 ? null : steps.Last(); public DataSet CommonData { get; private set; } object ISourceData.CommonData => this.CommonData; private readonly List<ISourceDataStep> steps = new List<ISourceDataStep>(); private readonly Dictionary<string, List<OpenXmlElement>> cacheChangeElements = new Dictionary<string, List<OpenXmlElement>>(); public SourceData(DataSet source) { CommonData = source; } private string GetKey(IProperty property) { return $"{property.Parent.Id}{property.Name}"; } public void AddCachedChangeElement(IProperty property, OpenXmlElement? element) { if (element == null) return; string key = GetKey(property); if (!cacheChangeElements.ContainsKey(key)) cacheChangeElements.Add(key, new List<OpenXmlElement>()); cacheChangeElements[key].Add(element); } public List<OpenXmlElement>? GetCachedChangeElements(IProperty property) { string key = GetKey(property); return cacheChangeElements.ContainsKey(key) ? cacheChangeElements[key] : null; } public void ClearCachedChangeElements(IProperty property) { string key = GetKey(property); if (cacheChangeElements.ContainsKey(key)) cacheChangeElements.Remove(key); } public void AddStep(ISourceDataStep step) { steps.Add(step); } public void RemoveLastStep() { if (steps.Count > 0) steps.RemoveAt(steps.Count - 1); } public ISourceDataStep? FindStepByTable(string tableName) { return steps.Reverse<ISourceDataStep>().FirstOrDefault(x => x.Tag.TableName == tableName); } } }
28.539474
135
0.610881
[ "MIT" ]
sowlks/DocumentsGenerator
DocumentsGenerator/Core/SourceData.cs
2,171
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Octokit { /// <summary> /// A client for GitHub's Pull Request Review API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/pulls/reviews/">Review API documentation</a> for more information. /// </remarks> public interface IPullRequestReviewsClient { /// <summary> /// Gets reviews for a specified pull request. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> Task<IReadOnlyList<PullRequestReview>> GetAll(string owner, string name, int number); /// <summary> /// Gets reviews for a specified pull request. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> Task<IReadOnlyList<PullRequestReview>> GetAll(long repositoryId, int number); /// <summary> /// Gets reviews for a specified pull request. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="options">Options for changing the API response</param> Task<IReadOnlyList<PullRequestReview>> GetAll(string owner, string name, int number, ApiOptions options); /// <summary> /// Gets reviews for a specified pull request. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="options">Options for changing the API response</param> Task<IReadOnlyList<PullRequestReview>> GetAll(long repositoryId, int number, ApiOptions options); /// <summary> /// Gets a single pull request review by ID. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-a-single-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task<PullRequestReview> Get(string owner, string name, int number, long reviewId); /// <summary> /// Gets a single pull request review by ID. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-a-single-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task<PullRequestReview> Get(long repositoryId, int number, long reviewId); /// <summary> /// Creates a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The Pull Request number</param> /// <param name="review">The review</param> Task<PullRequestReview> Create(string owner, string name, int number, PullRequestReviewCreate review); /// <summary> /// Creates a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The Pull Request number</param> /// <param name="review">The review</param> Task<PullRequestReview> Create(long repositoryId, int number, PullRequestReviewCreate review); /// <summary> /// Deletes a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#delete-a-pending-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task Delete(string owner, string name, int number, long reviewId); /// <summary> /// Deletes a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#delete-a-pending-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task Delete(long repositoryId, int number, long reviewId); /// <summary> /// Submits a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#submit-a-pull-request-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="submitMessage">The message and event being submitted for the review</param> Task<PullRequestReview> Submit(string owner, string name, int number, long reviewId, PullRequestReviewSubmit submitMessage); /// <summary> /// Submits a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#submit-a-pull-request-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="submitMessage">The message and event being submitted for the review</param> Task<PullRequestReview> Submit(long repositoryId, int number, long reviewId, PullRequestReviewSubmit submitMessage); /// <summary> /// Dismisses a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#dismiss-a-pull-request-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="dismissMessage">The message indicating why the review was dismissed</param> Task<PullRequestReview> Dismiss(string owner, string name, int number, long reviewId, PullRequestReviewDismiss dismissMessage); /// <summary> /// Dismisses a pull request review. /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#dismiss-a-pull-request-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="dismissMessage">The message indicating why the review was dismissed</param> Task<PullRequestReview> Dismiss(long repositoryId, int number, long reviewId, PullRequestReviewDismiss dismissMessage); /// <summary> /// Lists comments for a single review /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task<IReadOnlyList<PullRequestReviewComment>> GetAllComments(string owner, string name, int number, long reviewId); /// <summary> /// Lists comments for a single review /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> Task<IReadOnlyList<PullRequestReviewComment>> GetAllComments(long repositoryId, int number, long reviewId); /// <summary> /// Lists comments for a single review /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="options">Options for changing the API response</param> Task<IReadOnlyList<PullRequestReviewComment>> GetAllComments(string owner, string name, int number, long reviewId, ApiOptions options); /// <summary> /// Lists comments for a single review /// </summary> /// <remarks>https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="reviewId">The pull request review number</param> /// <param name="options">Options for changing the API response</param> Task<IReadOnlyList<PullRequestReviewComment>> GetAllComments(long repositoryId, int number, long reviewId, ApiOptions options); } }
56.740741
143
0.644629
[ "MIT" ]
3shape/octokit.net
Octokit/Clients/IPullRequestReviewsClient.cs
10,726
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace UFO.Server.WebService.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("DaoProviderFactory")] public string DaoProviderClassName { get { return ((string)(this["DaoProviderClassName"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("UFO.Server.Dal.MySql")] public string DaoProviderNameSpace { get { return ((string)(this["DaoProviderNameSpace"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("UFO.Server.Dal.MySql")] public string DaoProviderAssemblyName { get { return ((string)(this["DaoProviderAssemblyName"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Server=localhost;Database=ufo;Uid=root;Pwd=;")] public string DbConnectionString { get { return ((string)(this["DbConnectionString"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("MySQL Data Provider")] public string DbProviderName { get { return ((string)(this["DbProviderName"])); } } } }
42.597222
151
0.615585
[ "Apache-2.0" ]
untitled-no1/ufo
ufo/UFO.Server/UFO.Server.WebService/Properties/Settings.Designer.cs
3,069
C#
using System; using System.Linq; using FluentAssertions.Common; namespace FluentAssertions.Execution { /// <summary> /// Represents a chaining object returned from <see cref="AssertionScope.Given{T}"/> to continue the assertion using /// an object returned by a selector. /// </summary> public class GivenSelector<T> { #region Private Definitions private readonly T subject; private readonly bool predecessorSucceeded; private readonly AssertionScope predecessor; #endregion public GivenSelector(Func<T> selector, bool predecessorSucceeded, AssertionScope predecessor) { this.predecessorSucceeded = predecessorSucceeded; this.predecessor = predecessor; subject = predecessorSucceeded ? selector() : default; } /// <summary> /// Specify the condition that must be satisfied upon the subject selected through a prior selector. /// </summary> /// <param name="predicate"> /// If <c>true</c> the assertion will be treated as successful and no exceptions will be thrown. /// </param> /// <remarks> /// The condition will not be evaluated if the prior assertion failed, /// nor will <see cref="FailWith(string, System.Func{T, object}[])"/> throw any exceptions. /// </remarks> public GivenSelector<T> ForCondition(Func<T, bool> predicate) { Guard.ThrowIfArgumentIsNull(predicate, nameof(predicate)); predecessor.ForCondition(predicate(subject)); return this; } /// <summary> /// Allows to safely refine the subject for successive assertions, even when the prior assertion has failed. /// </summary> /// <paramref name="selector"> /// Selector which result is passed to successive calls to <see cref="ForCondition"/>. /// </paramref> /// <remarks> /// The selector will not be invoked if the prior assertion failed, /// nor will <see cref="FailWith(string,System.Func{T,object}[])"/> throw any exceptions. /// </remarks> public GivenSelector<TOut> Given<TOut>(Func<T, TOut> selector) { Guard.ThrowIfArgumentIsNull(selector, nameof(selector)); return new GivenSelector<TOut>(() => selector(subject), predecessorSucceeded, predecessor); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// If an expectation was set through a prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, /// then the failure message is appended to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> public ContinuationOfGiven<T> FailWith(string message) { return FailWith(message, new object[0]); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// In addition to the numbered <see cref="string.Format(string,object[])"/>-style placeholders, messages may contain a few /// specialized placeholders as well. For instance, {reason} will be replaced with the reason of the assertion as passed /// to <see cref="FluentAssertions.Execution.AssertionScope.BecauseOf"/>. Other named placeholders will be replaced with /// the <see cref="FluentAssertions.Execution.AssertionScope.Current"/> scope data passed through /// <see cref="FluentAssertions.Execution.AssertionScope.AddNonReportable"/> and /// <see cref="FluentAssertions.Execution.AssertionScope.AddReportable"/>. Finally, a description of the current subject /// can be passed through the {context:description} placeholder. This is used in the message if no explicit context /// is specified through the <see cref="AssertionScope"/> constructor. /// Note that only 10 <paramref name="args"/> are supported in combination with a {reason}. /// If an expectation was set through a prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, /// then the failure message is appended to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> /// <param name="args">Optional arguments to any numbered placeholders.</param> public ContinuationOfGiven<T> FailWith(string message, params Func<T, object>[] args) { object[] mappedArguments = args.Select(a => a(subject)).ToArray(); return FailWith(message, mappedArguments); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// In addition to the numbered <see cref="string.Format(string, object[])"/>-style placeholders, messages may contain /// a few specialized placeholders as well. For instance, {reason} will be replaced with the reason of the assertion as /// passed to <see cref="FluentAssertions.Execution.AssertionScope.BecauseOf"/>. Other named placeholders will be /// replaced with the <see cref="FluentAssertions.Execution.AssertionScope.Current"/> scope data passed through /// <see cref="FluentAssertions.Execution.AssertionScope.AddNonReportable"/> and /// <see cref="FluentAssertions.Execution.AssertionScope.AddReportable"/>. Finally, a description of the /// current subject can be passed through the {context:description} placeholder. This is used in the message if no /// explicit context is specified through the <see cref="AssertionScope"/> constructor. /// Note that only 10 <paramref name="args"/> are supported in combination with a {reason}. /// If an expectation was set through a prior call to /// <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, then the failure message is appended /// to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> /// <param name="args">Optional arguments to any numbered placeholders.</param> public ContinuationOfGiven<T> FailWith(string message, params object[] args) { bool succeeded = predecessorSucceeded; if (predecessorSucceeded) { Continuation continuation = predecessor.FailWith(message, args); succeeded = continuation.SourceSucceeded; } return new ContinuationOfGiven<T>(this, succeeded); } /// <summary> /// Clears the expectation set by <see cref="AssertionScope.WithExpectation"/>. /// </summary> public ContinuationOfGiven<T> ClearExpectation() { predecessor.ClearExpectation(); return new ContinuationOfGiven<T>(this, predecessorSucceeded); } } }
51.768707
134
0.655191
[ "Apache-2.0" ]
oboukli/fluentassertions
Src/FluentAssertions/Execution/GivenSelector.cs
7,610
C#
using System; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Param_RootNamespace.Views { // TODO WTS: Change the URL for your privacy policy in the Resource File, currently set to https://YourPrivacyUrlGoesHere public sealed partial class SettingsPagePage : Page { public SettingsPagePage() { InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { ViewModel.Initialize(); } } }
25.285714
125
0.664783
[ "MIT" ]
Acidburn0zzz/WindowsTemplateStudio
templates/Uwp/Pages/Settings/Views/SettingsPagePage.xaml.cs
533
C#
using System.Collections.Generic; using System.IO; using Unity; namespace APIHome { public static class Utility { public static string[] GetLocatonImages(string ImageFolder, string ImageSubFolder, string Location, string Filter) { string dir = Path.Combine(ImageFolder, ImageSubFolder, Location); return FileHelper.ListFile(dir, Filter); } } }
23.941176
122
0.675676
[ "Apache-2.0" ]
garysun1830/API74942
Helper/Utility.cs
409
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0.Asm { using System; using static core; using static WsAtoms; partial class AsmCmdService { [CmdOp(".emit-tokens")] Outcome EmitTokenSpecs(CmdArgs args) { var result = Outcome.Success; var svc = Wf.Symbolism(); var output = svc.EmitTokenSpecs(typeof(AsmOpCodeTokens.VexToken)); var input = svc.LoadTokenSpecs(nameof(AsmOpCodeTokens.VexToken)); var formatter = Tables.formatter<SymInfo>(SymInfo.RenderWidths); var count = input.Length; for(var i=0; i<count; i++) { ref readonly var row = ref skip(input,i); Write(formatter.Format(row)); } return result; } void EmitTokenSpecs() { var tokens = Wf.AsmTokens(); EmitTokenSet(tokens.RegTokens()); EmitTokenSet(tokens.OpCodeTokens()); EmitTokenSet(tokens.SigTokens()); EmitTokenSet(tokens.ConditonTokens()); EmitTokenSet(tokens.PrefixTokens()); } void EmitTokenSpecs(Type src) { var dst = Ws.Tables().TablePath<SymInfo>("tokens", src.Name); var tokens = Symbols.syminfo(src); TableEmit(tokens, SymInfo.RenderWidths, dst); } void EmitTokenSet(ITokenSet src) { var dst = Ws.Tables().TablePath<SymInfo>("tokens", src.Name); var tokens = Symbols.syminfo(src.Types()); TableEmit(tokens, SymInfo.RenderWidths, dst); } [CmdOp(".machine")] Outcome EmitMachineTables(CmdArgs args) { var result = Outcome.Success; var tables = Ws.Tables(); var tokens = Wf.AsmTokens(); var dir = Ws.Tables().Subdir(machine); Emitters.Emit(Loaders.ApiLiterals().View, dir); result = GenModRmBits(); if(result.Fail) return result; result = GenSibBits(); if(result.Fail) return result; result = AsmTables.ImportCpuIdSources(); if(result.Fail) return result; Wf.IntelIntrinsics().Emit(dir); EmitTokenSpecs(); EmitSymKinds(Symbols.index<AsmOpClass>(), tables.TablePath(machine,"classes.asm.operands")); EmitSymIndex<RegClassCode>(tables.TablePath(machine, "classes.asm.regs")); return result; } Outcome GenSibBits() { var result = Outcome.Success; var dst = Ws.Tables().Path(machine, "sib", FS.ext("bits") + FS.Csv); var rows = AsmBits.SibRows().View; TableEmit(rows, SibBitfieldRow.RenderWidths, dst); return result; } Outcome GenModRmBits() { var path = Ws.Tables().Path(machine, "modrm", FS.ext("bits") + FS.Csv); var flow = Wf.EmittingFile(path); using var writer = path.AsciWriter(); var dst = span<char>(256*128); var count = AsmBits.ModRmTable(dst); var rendered = slice(dst,0,count); writer.Write(rendered); Wf.EmittedFile(flow,count); return true; } ReadOnlySpan<SymLiteralRow> EmitSymLiterals<E>(FS.FilePath dst) where E : unmanaged, Enum { var svc = Wf.Symbolism(); return svc.EmitLiterals<E>(dst); } } }
32.059829
104
0.514529
[ "BSD-3-Clause" ]
0xCM/z0
src/asm.shell/src/commands/ops/.machine.cs
3,751
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Ditto.AsyncMvvm.Calculated")] [assembly: AssemblyDescription("AsyncMVVM library Calculated Properties integration")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
32.1
86
0.791277
[ "Apache-2.0" ]
dmitry-shechtman/AsyncMvvm
AsyncMvvm.Calculated/Shared/Properties/AssemblyInfo.cs
323
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 file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void PopCount_Vector128_SByte() { var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__PopCount_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__PopCount_Vector128_SByte testClass) { var result = AdvSimd.PopCount(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__PopCount_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar1; private Vector128<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__PopCount_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleUnaryOpTest__PopCount_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.PopCount( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.PopCount), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.PopCount), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.PopCount( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.PopCount(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.PopCount(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte(); var result = AdvSimd.PopCount(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.PopCount(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.PopCount(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.PopCount( AdvSimd.LoadVector128((SByte*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.BitCount(firstOp[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (Helpers.BitCount(firstOp[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.PopCount)}<SByte>(Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
37.561368
187
0.570763
[ "MIT" ]
AArnott/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/PopCount.Vector128.SByte.cs
18,668
C#
using CmlLib.Core.Version; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading.Tasks; namespace CmlLib.Core.Downloader { public class MParallelDownloader : MDownloader { public MParallelDownloader(MinecraftPath path, MVersion mVersion) : this(path, mVersion, 10, true) { } public MParallelDownloader(MinecraftPath path, MVersion mVersion, int maxThread, bool setConnectionLimit) : base(path, mVersion) { MaxThread = maxThread; if (setConnectionLimit) ServicePointManager.DefaultConnectionLimit = maxThread; } public int MaxThread { get; private set; } object lockEvent = new object(); public override void DownloadFiles(DownloadFile[] files) { TryDownloadFiles(files, 3, null); } private void TryDownloadFiles(DownloadFile[] files, int retry, Exception failEx) { if (retry == 0) { if (IgnoreInvalidFiles) return; else { if (failEx == null) failEx = new MDownloadFileException(failEx.Message, failEx, files[0]); throw failEx; } } var length = files.Length; if (length == 0) return; var progressed = 0; fireDownloadFileChangedEvent(files[0].Type, files[0].Name, length, 0); var option = new ParallelOptions() { MaxDegreeOfParallelism = MaxThread }; var failedFiles = new List<DownloadFile>(); Exception lastEx = null; Parallel.ForEach(files, option, (file) => { try { Directory.CreateDirectory(Path.GetDirectoryName(file.Path)); using (var wc = new WebClient()) { wc.DownloadFile(file.Url, file.Path); } lock (lockEvent) { progressed++; fireDownloadFileChangedEvent(file.Type, file.Name, length, progressed); } } catch (Exception ex) { failedFiles.Add(file); lastEx = ex; } }); TryDownloadFiles(failedFiles.ToArray(), retry - 1, lastEx); } } }
29.292135
136
0.496356
[ "MIT" ]
ArcanoxDragon/CmlLib.Core
CmlLib/Core/Downloader/MParallelDownloader.cs
2,609
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace GSoft.Dynamite.Navigation { /// <summary> /// Navigation search related settings. /// </summary> public class NavigationSearchSettings { /// <summary> /// The navigation filter managed property name /// </summary> public string NavigationManagedPropertyName { get; set; } /// <summary> /// The result source name /// </summary> public string ResultSourceName { get; set; } /// <summary> /// The list of selected properties from the search query. /// See https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.query.keywordquery.selectproperties.aspx /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Not making this property read-only helps facilitate setting the value.")] public ICollection<string> SelectedProperties { get; set; } /// <summary> /// Gets the filters to apply to the all search queries. /// ex: MyManagedPropertyOWSTEXT:myvalue /// </summary> /// <value> /// The filters. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Not making this property read-only helps facilitate setting the value.")] public ICollection<string> GlobalFilters { get; set; } /// <summary> /// Gets the filters to apply to the search queries related to target items. /// ex: ContentTypeId:0x01000210210* /// </summary> /// <value> /// The filters. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Not making this property read-only helps facilitate setting the value.")] public ICollection<string> TargetItemFilters { get; set; } /// <summary> /// Gets the filters to apply to the search queries related to catalog items. /// ex: ContentTypeId:0x010002102101* /// </summary> /// <value> /// The filters. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Not making this property read-only helps facilitate setting the value.")] public ICollection<string> CatalogItemFilters { get; set; } } }
39.671429
132
0.620454
[ "MIT" ]
GSoft-SharePoint/Dynamite
Source/GSoft.Dynamite/Navigation/NavigationSearchSettings.cs
2,779
C#
using Abp.Application.Editions; using Abp.Application.Features; using Abp.Domain.Repositories; namespace InvManSaas.Editions { public class EditionManager : AbpEditionManager { public const string DefaultEditionName = "Standard"; public EditionManager( IRepository<Edition> editionRepository, IAbpZeroFeatureValueStore featureValueStore) : base( editionRepository, featureValueStore) { } } }
24.190476
60
0.643701
[ "MIT" ]
cliffyllok/InvManSaas
aspnet-core/src/InvManSaas.Core/Editions/EditionManager.cs
510
C#