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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18052
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace DXInfo.Data.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.ModelConfiguration;
using DXInfo.Models;
using System.ComponentModel.DataAnnotations.Schema;
public class PTTypeConfiguration : EntityTypeConfiguration<PTType>
{
public PTTypeConfiguration()
{
this.HasKey(k => k.Code);
this.Property(o => o.Code).IsRequired();
this.Property(o => o.Code).HasMaxLength(50);
this.Property(o => o.Name).IsRequired();
this.Property(o => o.Name).IsUnicode();
this.Property(o => o.Name).HasMaxLength(200);
this.Property(o => o.RdCode).IsRequired();
this.Property(o => o.RdCode).HasMaxLength(50);
this.Property(o => o.IsDefault).IsRequired();
}
}
}
| 31.333333 | 80 | 0.520458 | [
"Apache-2.0"
] | zhenghua75/DXInfo | DXInfo.Data/Configuration/PTTypeConfiguration.cs | 1,328 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace DiscordOgerBot.Modules
{
public class GenericCommands : ModuleBase<SocketCommandContext>
{
private readonly Random _rand = new();
[Command("help")]
public async Task SendHelp()
{
var embed = new EmbedBuilder
{
Title = "Meddl Leudde!:metal:"
};
var buildEmbed = embed
.WithDescription(
"Ich versuche deutsche Sätze ins Meddlfrängische zu übersetzen! " + Environment.NewLine +
"Eine Discord Nachricht auf Hochdeutsch nervt dich? Kein Problem! **reagiere einfach auf die Nachricht mit :OgerBot: **" +
Environment.NewLine +
Environment.NewLine +
"**Der Server braucht ein Emoji mit dem Namen OgerBot!!** (Wende dich an die Server Admins die wissen das ganz bestimmt)" +
Environment.NewLine +
Environment.NewLine +
"Die Nachricht kann auch wieder gelöscht werden indem man die Reaction wieder entfernt")
.AddField("Sounds",
"Ich kann auch Sounds abspielen! Für eine Übersicht schreib einfach **og commands**")
.AddField("Willst du mich auf deinem eigenen Discord Server?",
"Das kannst du ganz einfach [hier](https://discord.com/api/oauth2/authorize?client_id=761895612291350538&permissions=383040&scope=bot) machen!")
.AddField("Weitere Hilfe",
"Sollte ich mal nicht richtig funktionieren, komm ins [DrachenlordKoreaDiscord](https://discord.gg/jNkTrsZvW3) oder wende dich bitte an meinen Erbauer:" +
Environment.NewLine +
"[Discord](https://discordapp.com/users/386989432148066306) | [Reddit](https://www.reddit.com/user/MoriPastaPizza)")
.AddField("Links",
"[Github](https://github.com/MoriPastaPizza/DiscordOgerBotWeb) | " +
"[Lade den Bot auf deinen Server ein!](https://discord.com/api/oauth2/authorize?client_id=761895612291350538&permissions=383040&scope=bot) | " +
"[DrachenlordKoreaDiscord](https://discord.gg/jNkTrsZvW3)")
.WithAuthor(Context.Client.CurrentUser)
.WithFooter(footer =>
footer.Text =
Controller.OgerBot.FooterDictionary[_rand.Next(Controller.OgerBot.FooterDictionary.Count)])
.WithColor(Color.Blue)
.WithCurrentTimestamp()
.Build();
await Context.Channel.SendMessageAsync(embed: buildEmbed);
}
[Command("commands")]
public async Task SendCommands()
{
var module = Controller.OgerBot.CommandService.Modules
.FirstOrDefault(m => m.Name == nameof(GenericCommands));
if (module == null) return;
var commands = module.Commands
.OrderBy(m => m.Name)
.ToList();
var commandList = commands
.Select(command => $"**{command.Aliases.Aggregate((i, j) => i + " " + j)}** {command.Summary}")
.ToList();
var fieldString = commandList.Aggregate((i, j) => i + " | " + j).ToString();
var embedBuilder = new EmbedBuilder
{
Title = "Commands"
};
embedBuilder
.WithDescription(fieldString)
.AddField("Links",
"[Github](https://github.com/MoriPastaPizza/DiscordOgerBotWeb) | " +
"[Lade den Bot auf deinen Server ein!](https://discord.com/api/oauth2/authorize?client_id=761895612291350538&permissions=383040&scope=bot) | " +
"[DrachenlordKoreaDiscord](https://discord.gg/jNkTrsZvW3)")
.WithAuthor(Context.Client.CurrentUser)
.WithFooter(footer =>
footer.Text =
Controller.OgerBot.FooterDictionary[_rand.Next(Controller.OgerBot.FooterDictionary.Count)])
.WithColor(Color.Red)
.WithCurrentTimestamp();
await Context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
[Command("sounds")]
public async Task SendSounds()
{
var module = Controller.OgerBot.CommandService.Modules
.FirstOrDefault(m => m.Name == nameof(SoundCommands));
if (module == null) return;
var commands = module.Commands
.Where(m => m.Name != "asia")
.OrderBy(m => m.Name)
.ToList();
var subCommandsCount = Math.Ceiling((double)commands.Count / 60);
for (var commandIndex = 0; commandIndex < subCommandsCount; commandIndex++)
{
var commandList = commands
.Select(command => $"**{command.Aliases.Aggregate((i, j) => i + " " + j)}** {command.Summary}")
.Skip(commandIndex * 60)
.Take(60)
.ToList();
var fieldString = commandList.Aggregate((i, j) => i + " | " + j).ToString();
var embedBuilder = new EmbedBuilder
{
Title = $"Sound Commands #{commandIndex + 1}"
};
embedBuilder
.WithDescription(fieldString)
.WithAuthor(Context.Client.CurrentUser)
.WithColor(Color.Red)
.WithCurrentTimestamp();
await Context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
}
[Command("videos")]
public async Task SendVideos()
{
var module = Controller.OgerBot.CommandService.Modules
.FirstOrDefault(m => m.Name == nameof(VideoCommands));
if (module == null) return;
var commands = module.Commands
.Where(m => m.Name != "oof")
.OrderBy(m => m.Name)
.ToList();
var subCommandsCount = Math.Ceiling((double)commands.Count / 60);
for (var commandIndex = 0; commandIndex < subCommandsCount; commandIndex++)
{
var commandList = commands
.Select(command => $"**{command.Aliases.Aggregate((i, j) => i + " " + j)}** {command.Summary}")
.Skip(commandIndex * 60)
.Take(60)
.ToList();
var fieldString = commandList.Aggregate((i, j) => i + " | " + j).ToString();
var embedBuilder = new EmbedBuilder
{
Title = $"Video Commands #{commandIndex + 1}"
};
embedBuilder
.WithDescription(fieldString)
.WithAuthor(Context.Client.CurrentUser)
.WithColor(Color.Red)
.WithCurrentTimestamp();
await Context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
}
[Command("images")]
public async Task SendImages()
{
var module = Controller.OgerBot.CommandService.Modules
.FirstOrDefault(m => m.Name == nameof(ImageCommands));
if (module == null) return;
var commands = module.Commands
.OrderBy(m => m.Name)
.ToList();
var subCommandsCount = Math.Ceiling((double)commands.Count / 60);
for (var commandIndex = 0; commandIndex < subCommandsCount; commandIndex++)
{
var commandList = commands
.Select(command => $"**{command.Aliases.Aggregate((i, j) => i + " " + j)}** {command.Summary}")
.Skip(commandIndex * 60)
.Take(60)
.ToList();
var fieldString = commandList.Aggregate((i, j) => i + " | " + j).ToString();
var embedBuilder = new EmbedBuilder
{
Title = $"Image Commands #{commandIndex + 1}"
};
embedBuilder
.WithDescription(fieldString)
.WithAuthor(Context.Client.CurrentUser)
.WithColor(Color.Red)
.WithCurrentTimestamp();
await Context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
}
}
}
| 40.231481 | 174 | 0.526928 | [
"MIT"
] | MoriPastaPizza/DiscordOgerBotWeb | DiscordOgerBot/Modules/GenericCommands.cs | 8,698 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace BuildXL.FrontEnd.Script.RuntimeModel.AstBridge
{
/// <summary>
/// Abstract base class for optional (user-configurable) DS Lint rules.
/// </summary>
internal abstract class PolicyRule : DiagnosticRule
{
/// <summary>
/// Name of the rule, which can be referenced from a configuration file
/// </summary>
public abstract string Name { get; }
/// <summary>
/// User-facing description of what the rule does
/// </summary>
public abstract string Description { get; }
/// <inheritdoc/>
public override string ToString()
{
return "'" + Name + "': " + Description;
}
/// <inheritdoc />
public override RuleType RuleType => RuleType.UserConfigurablePolicy;
}
}
| 32.193548 | 102 | 0.594188 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/FrontEnd/Script/RuntimeModel/AstBridge/Linter/PolicyRule.cs | 998 | C# |
using System;
using System.Collections.ObjectModel;
namespace A5Soft.CARMA.Domain.Metadata
{
/// <summary>
/// Common interface for entity (class) metadata localization provider.
/// </summary>
/// <remarks>Entity could be commonly described in:
/// 1) Web edit form header or winforms/WPF form caption for a new entity instance;
/// 2) Web edit form header or winforms/WPF form caption for an existing entity instance being edited;
/// 3) Menu item for a new instance of the entity or a tooltip for a button (in all types of interfaces);
/// 4) (Contextual) menu item for editing an entity or a tooltip for a button (in all types of interfaces);
/// 5) (Contextual) menu item for deleting an entity or a tooltip for a button (in all types of interfaces).
/// Paras 4 and 5 are actually actions (use cases), therefore not a part of entity metadata.
/// While creating a new instance (para 3) of an entity usually is not a use case
/// (does not require specific actions except for invoking constructor).</remarks>
public interface IEntityMetadata
{
/// <summary>
/// Gets a type of the entity described.
/// </summary>
Type EntityType { get; }
/// <summary>
/// Gets a collection of metadata descriptions for entity properties.
/// </summary>
ReadOnlyDictionary<string, IPropertyMetadata> Properties { get; }
/// <summary>
/// Gets an array of all the property names.
/// </summary>
string[] PropertyNames { get; }
/// <summary>
/// Gets a collection of metadata descriptions for entity methods.
/// </summary>
ReadOnlyDictionary<string, IMethodMetadata> Methods { get; }
/// <summary>
/// Gets a <see cref="IPropertyMetadata"/> instance for the property specified
/// (null if no metadata for the property).
/// </summary>
/// <param name="propertyName">a name of the property to get the metadata for</param>
/// <returns>a <see cref="IPropertyMetadata"/> instance for the property specified
/// (null if no metadata for the property)</returns>
IPropertyMetadata GetPropertyMetadata(string propertyName);
/// <summary>
/// Gets a localized value that is used for display in the UI
/// for a new instance of the entity (typically used as a form caption/header).
/// </summary>
/// <returns>a localized value that is used for display in the UI</returns>
string GetDisplayNameForNew();
/// <summary>
/// Gets a localized value that is used to display a description in the UI
/// for an old entity instance (typically used as a form caption/header).
/// </summary>
/// <returns>a localized value that is used for display in the UI</returns>
string GetDisplayNameForOld();
/// <summary>
/// Gets a localized value that is used to display a description in the UI
/// for a menu item or button (tooltip) that create a new instance of the entity.
/// </summary>
/// <returns>a localized value that is used for display in the UI</returns>
string GetDisplayNameForCreateNew();
/// <summary>
/// Gets an URI for help file and topic for the entity.
/// </summary>
string GetHelpUri();
}
}
| 43.278481 | 112 | 0.636736 | [
"MIT"
] | Apskaita5/CARMA | src/A5Soft.CARMA.Domain/Metadata/IEntityMetadata.cs | 3,421 | C# |
// Copyright Bastian Eicher
// Licensed under the MIT License
#if !NET20 && !NET40
using System.Threading.Tasks;
#endif
namespace NanoByte.Common.Collections
{
/// <summary>
/// Provides extension methods for <see cref="IEnumerable{T}"/>s.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Determines whether the enumeration contains an element or is null.
/// </summary>
/// <param name="enumeration">The list to check.</param>
/// <param name="element">The element to look for.</param>
/// <remarks>Useful for lists that contain an OR-ed list of restrictions, where an empty list means no restrictions.</remarks>
[Pure]
public static bool ContainsOrEmpty<T>([InstantHandle] this IEnumerable<T> enumeration, T element)
{
#region Sanity checks
if (enumeration == null) throw new ArgumentNullException(nameof(enumeration));
if (element == null) throw new ArgumentNullException(nameof(element));
#endregion
// ReSharper disable PossibleMultipleEnumeration
return enumeration.Contains(element) || !enumeration.Any();
// ReSharper restore PossibleMultipleEnumeration
}
/// <summary>
/// Determines whether one enumeration of elements contains any of the elements in another.
/// </summary>
/// <param name="first">The first of the two enumerations to compare.</param>
/// <param name="second">The first of the two enumerations to compare.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
/// <returns><c>true</c> if <paramref name="first"/> contains any element from <paramref name="second"/>. <c>false</c> if <paramref name="first"/> or <paramref name="second"/> is empty.</returns>
[Pure]
public static bool ContainsAny<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null)
{
#region Sanity checks
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
#endregion
var set =
#if !NET20
second as ISet<T> ??
#endif
new HashSet<T>(first, comparer ?? EqualityComparer<T>.Default);
return second.Any(set.Contains);
}
/// <summary>
/// Determines whether two enumerations contain the same elements in the same order.
/// </summary>
/// <param name="first">The first of the two enumerations to compare.</param>
/// <param name="second">The first of the two enumerations to compare.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
[Pure]
public static bool SequencedEquals<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null)
{
#region Sanity checks
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
#endregion
if (ReferenceEquals(first, second)) return true;
if (first is ICollection<T> a && second is ICollection<T> b && a.Count != b.Count) return false;
return first.SequenceEqual(second, comparer ?? EqualityComparer<T>.Default);
}
/// <summary>
/// Determines whether two enumerations contain the same elements disregarding the order they are in.
/// </summary>
/// <param name="first">The first of the two enumerations to compare.</param>
/// <param name="second">The first of the two enumerations to compare.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
[Pure]
public static bool UnsequencedEquals<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null)
{
#region Sanity checks
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
#endregion
if (ReferenceEquals(first, second)) return true;
if (first is ICollection<T> a && second is ICollection<T> b && a.Count != b.Count) return false;
var set = new HashSet<T>(first, comparer ?? EqualityComparer<T>.Default);
return second.All(set.Contains);
}
/// <summary>
/// Generates a hash code for the contents of the enumeration. Changing the elements' order will change the hash.
/// </summary>
/// <param name="enumeration">The enumeration to generate the hash for.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
/// <seealso cref="SequencedEquals{T}"/>
[Pure]
public static int GetSequencedHashCode<T>([InstantHandle] this IEnumerable<T> enumeration, IEqualityComparer<T>? comparer = null)
{
#region Sanity checks
if (enumeration == null) throw new ArgumentNullException(nameof(enumeration));
#endregion
var hash = new HashCode();
foreach (T item in enumeration)
hash.Add(item, comparer);
return hash.ToHashCode();
}
/// <summary>
/// Generates a hash code for the contents of the enumeration. Changing the elements' order will not change the hash.
/// </summary>
/// <param name="enumeration">The enumeration to generate the hash for.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
/// <seealso cref="UnsequencedEquals{T}"/>
[Pure]
public static int GetUnsequencedHashCode<T>([InstantHandle] this IEnumerable<T> enumeration, IEqualityComparer<T>? comparer = null)
{
#region Sanity checks
if (enumeration == null) throw new ArgumentNullException(nameof(enumeration));
#endregion
comparer ??= EqualityComparer<T>.Default;
int result = 397;
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (T item in enumeration)
{
if (item != null)
result ^= comparer.GetHashCode(item);
}
return result;
}
/// <summary>
/// Filters a sequence of elements to remove any that match the <paramref name="predicate"/>.
/// The opposite of <see cref="Enumerable.Where{TSource}(IEnumerable{TSource},Func{TSource,bool})"/>.
/// </summary>
[LinqTunnel]
public static IEnumerable<T> Except<T>(this IEnumerable<T> enumeration, Func<T, bool> predicate)
=> enumeration.Where(x => !predicate(x));
/// <summary>
/// Filters a sequence of elements to remove any that are equal to <paramref name="element"/>.
/// </summary>
[LinqTunnel]
public static IEnumerable<T> Except<T>(this IEnumerable<T> enumeration, T element)
=> enumeration.Except(new[] {element});
/// <summary>
/// Flattens a list of lists.
/// </summary>
[LinqTunnel]
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> enumeration)
=> enumeration.SelectMany(x => x);
/// <summary>
/// Filters a sequence of elements to remove any <c>null</c> values.
/// </summary>
[LinqTunnel]
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> enumeration)
where T : class
{
foreach (var element in enumeration)
{
if (element != null)
yield return element;
}
}
/// <summary>
/// Determines the element in a list that maximizes a specified expression.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <typeparam name="TValue">The type of the <paramref name="expression"/>.</typeparam>
/// <param name="enumeration">The elements to check.</param>
/// <param name="expression">The expression to maximize.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
/// <returns>The element that maximizes the expression.</returns>
/// <exception cref="InvalidOperationException"><paramref name="enumeration"/> contains no elements.</exception>
[Pure]
public static T MaxBy<T, TValue>([InstantHandle] this IEnumerable<T> enumeration, [InstantHandle] Func<T, TValue> expression, IComparer<TValue>? comparer = null)
{
#region Sanity checks
if (enumeration == null) throw new ArgumentNullException(nameof(enumeration));
if (expression == null) throw new ArgumentNullException(nameof(expression));
#endregion
comparer ??= Comparer<TValue>.Default;
using var enumerator = enumeration.GetEnumerator();
if (!enumerator.MoveNext()) throw new InvalidOperationException("Enumeration contains no elements");
var maxElement = enumerator.Current;
var maxValue = expression(maxElement);
while (enumerator.MoveNext())
{
var candidate = enumerator.Current;
var candidateValue = expression(candidate);
if (comparer.Compare(candidateValue, maxValue) > 0)
{
maxElement = candidate;
maxValue = candidateValue;
}
}
return maxElement;
}
/// <summary>
/// Determines the element in a list that minimizes a specified expression.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <typeparam name="TValue">The type of the <paramref name="expression"/>.</typeparam>
/// <param name="enumeration">The elements to check.</param>
/// <param name="expression">The expression to minimize.</param>
/// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param>
/// <returns>The element that minimizes the expression.</returns>
/// <exception cref="InvalidOperationException"><paramref name="enumeration"/> contains no elements.</exception>
[Pure]
public static T MinBy<T, TValue>([InstantHandle] this IEnumerable<T> enumeration, [InstantHandle] Func<T, TValue> expression, IComparer<TValue>? comparer = null)
{
#region Sanity checks
if (enumeration == null) throw new ArgumentNullException(nameof(enumeration));
if (expression == null) throw new ArgumentNullException(nameof(expression));
#endregion
comparer ??= Comparer<TValue>.Default;
using var enumerator = enumeration.GetEnumerator();
if (!enumerator.MoveNext()) throw new InvalidOperationException("Enumeration contains no elements");
var minElement = enumerator.Current;
var minValue = expression(minElement);
while (enumerator.MoveNext())
{
var candidate = enumerator.Current;
var candidateValue = expression(candidate);
if (comparer.Compare(candidateValue, minValue) < 0)
{
minElement = candidate;
minValue = candidateValue;
}
}
return minElement;
}
/// <summary>
/// Filters a sequence of elements to remove any duplicates based on the equality of a key extracted from the elements.
/// </summary>
/// <param name="enumeration">The sequence of elements to filter.</param>
/// <param name="keySelector">A function mapping elements to their respective equality keys.</param>
[LinqTunnel]
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumeration, Func<T, TKey> keySelector)
where T : notnull
where TKey : notnull
=> enumeration.Distinct(new KeyEqualityComparer<T, TKey>(keySelector));
/// <summary>
/// Maps elements using a selector. Calls a handler for specific exceptions, skips the element and continues enumerating with the element.
/// </summary>
/// <typeparam name="TSource">The type of the input elements.</typeparam>
/// <typeparam name="TResult">The type of the output elements.</typeparam>
/// <typeparam name="TException">The type of exceptions to handle..</typeparam>
/// <param name="source">The elements to map.</param>
/// <param name="selector">The selector to execute for each <paramref name="source"/> element.</param>
/// <param name="exceptionHandler">A Callback to be invoked when a <typeparamref name="TException"/> is caught.</param>
[LinqTunnel]
public static IEnumerable<TResult> TrySelect<TSource, TResult, TException>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, [InstantHandle] Action<TException> exceptionHandler)
where TException : Exception
{
#region Sanity checks
if (source == null) throw new ArgumentNullException(nameof(source));
if (selector == null) throw new ArgumentNullException(nameof(selector));
#endregion
foreach (var element in source)
{
TResult result;
try
{
result = selector(element);
}
catch (TException ex)
{
exceptionHandler(ex);
continue;
}
yield return result;
}
}
/// <summary>
/// Calls <see cref="ICloneable{T}.Clone"/> for every element in a enumeration and returns the results as a new enumeration.
/// </summary>
[LinqTunnel]
public static IEnumerable<T> CloneElements<T>(this IEnumerable<T> enumerable) where T : ICloneable<T>
=> (enumerable ?? throw new ArgumentNullException(nameof(enumerable))).Select(x => x.Clone());
/// <summary>
/// Performs a topological sort of an object graph.
/// </summary>
/// <param name="nodes">The set of nodes to sort.</param>
/// <param name="getDependencies">A function that retrieves all dependencies of a node.</param>
/// <exception cref="InvalidDataException">Cyclic dependency found.</exception>
[Pure]
public static IEnumerable<T> TopologicalSort<T>([InstantHandle] this IEnumerable<T> nodes, [InstantHandle] Func<T, IEnumerable<T>> getDependencies)
{
#region Sanity checks
if (nodes == null) throw new ArgumentNullException(nameof(nodes));
if (getDependencies == null) throw new ArgumentNullException(nameof(getDependencies));
#endregion
var sorted = new List<T>();
var visited = new HashSet<T>();
foreach (var item in nodes)
TopologicalSortVisit(item, visited, sorted, getDependencies);
return sorted;
}
private static void TopologicalSortVisit<T>(T node, HashSet<T> visited, List<T> sorted, Func<T, IEnumerable<T>> getDependencies)
{
if (visited.Contains(node))
{
if (!sorted.Contains(node))
throw new InvalidDataException($"Cyclic dependency found at: {node}");
}
else
{
visited.Add(node);
foreach (var dep in getDependencies(node))
TopologicalSortVisit(dep, visited, sorted, getDependencies);
sorted.Add(node);
}
}
#if !NET20 && !NET40
/// <summary>
/// Runs asynchronous operations for each element in an enumeration. Runs multiple tasks using cooperative multitasking.
/// </summary>
/// <param name="enumerable">The input elements to enumerate over.</param>
/// <param name="taskFactory">Creates a <see cref="Task"/> for each input element.</param>
/// <param name="maxParallel">The maximum number of <see cref="Task"/>s to run in parallel. Use 0 or lower for unbounded.</param>
/// <exception cref="InvalidOperationException"><see cref="TaskScheduler.Current"/> is equal to <see cref="TaskScheduler.Default"/>.</exception>
/// <remarks>
/// <see cref="SynchronizationContext.Current"/> must not be null.
/// The synchronization context is required to ensure that task continuations are scheduled sequentially and do not run in parallel.
/// </remarks>
public static async Task ForEachAsync<T>(this IEnumerable<T> enumerable, Func<T, Task> taskFactory, int maxParallel = 0)
{
if (TaskScheduler.Current == TaskScheduler.Default)
throw new InvalidOperationException("TaskScheduler.Current must not be equal to TaskScheduler.Default value when using ForEachAsync().");
var tasks = new List<Task>(maxParallel);
foreach (var task in enumerable.Select(taskFactory))
{
tasks.Add(task);
if (tasks.Count == maxParallel)
{
var completedTask = await Task.WhenAny(tasks.ToArray()).ConfigureAwait(true);
await completedTask.ConfigureAwait(true); // observe exceptions
tasks.Remove(completedTask);
}
}
await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);
}
#endif
/// <summary>
/// Generates all possible permutations of a set of <paramref name="elements"/>.
/// </summary>
[LinqTunnel]
public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> elements)
{
#region Sanity checks
if (elements == null) throw new ArgumentNullException(nameof(elements));
#endregion
static IEnumerable<T[]> Helper(T[] array, int index)
{
if (index >= array.Length - 1)
yield return array;
else
{
for (int i = index; i < array.Length; i++)
{
var subArray = array.ToArray();
var t1 = subArray[index];
subArray[index] = subArray[i];
subArray[i] = t1;
foreach (var element in Helper(subArray, index + 1))
yield return element;
}
}
}
return Helper(elements.ToArray(), index: 0);
}
}
}
| 48.093976 | 204 | 0.584047 | [
"MIT"
] | nano-byte/common | src/Common/Collections/EnumerableExtensions.cs | 19,959 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using AutoFixture;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json;
using Withywoods.AspNetCoreApiSample.Dto;
using Withywoods.AspNetCoreApiSample.IntegrationTests.Entities;
using Withywoods.Serialization.Json;
using Withywoods.WebTesting.Rest;
using Xunit;
namespace Withywoods.AspNetCoreApiSample.IntegrationTests.Resources
{
[Trait("Environment", "Localhost")]
public class TaskResourceTest : RestClient, IClassFixture<WebApplicationFactory<Startup>>
{
private const string ResourceEndpoint = "api/tasks";
private readonly Fixture _fixture;
private readonly RestRunner _restRunner;
public TaskResourceTest(WebApplicationFactory<Startup> factory)
: base(factory.CreateClient())
{
_fixture = new Fixture();
_restRunner = new RestRunner(_fixture, this, ResourceEndpoint);
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourcePost_ReturnsOk()
{
var input = _fixture.Create<TaskDto>();
var response = await PostAsync($"/{ResourceEndpoint}", input.ToJson(), HttpStatusCode.Created);
dynamic deserializedValue = JsonConvert.DeserializeObject(response);
await DeleteAsync($"/{ResourceEndpoint}/{deserializedValue["id"]}");
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourceFullCycle_IsOk()
{
var initialTasks = await GetAsync<List<TaskDto>>($"/{ResourceEndpoint}");
initialTasks.Count.Should().Be(0);
var created = await _restRunner.CreateResourceAsync<TaskDto>();
await _restRunner.GetResourceByIdAsync(created.Id, created);
await _restRunner.UpdateResourceAsync(created.Id, created);
var existingTasks = await _restRunner.GetResourcesAsync<TaskDto>();
existingTasks.Count.Should().Be(1);
await _restRunner.DeleteResourceAsync(created.Id);
var expectedNotFound = new ProblemDetails
{
Title = "Not Found",
Status = 404,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4"
};
await _restRunner.GetResourceByIdAsync(created.Id, expectedNotFound, HttpStatusCode.NotFound, config => config.Excluding(x => x.Extensions));
var finalTasks = await _restRunner.GetResourcesAsync<TaskDto>();
finalTasks.Count.Should().Be(0);
}
[Fact]
public Task AspNetCoreApiSampleTaskResourceDelete_WhenResourceDoesNotExist_ReturnsHttpNoContent()
{
return _restRunner.DeleteResourceAsync(new Guid().ToString());
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourceUpdate_WhenResourceDoesNotExist_ReturnsHttpNotFound()
{
var taskId = Guid.NewGuid().ToString();
var expectedNotFound = new ProblemDetails
{
Title = "Not Found",
Status = 404,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4"
};
await _restRunner.UpdateResourceAsync(taskId, new TaskDto { Id = taskId, Title = "Bla bla" }, expectedNotFound, HttpStatusCode.NotFound,
config => config.Excluding(x => x.Extensions));
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourceUpdate_WhenResourceDoesNotExistAndNewTitleIsNull_ReturnsHttpBadRequest()
{
var taskId = Guid.NewGuid().ToString();
var expectedError = new ValidationProblemDetails
{
Title = "One or more validation errors occurred.",
Status = 400,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
expectedError.Errors["Title"] = new string[1] { "The Title field is required." };
await _restRunner.UpdateResourceAsync(taskId, new TaskDto { Id = taskId }, expectedError, HttpStatusCode.BadRequest,
config => config.Excluding(x => x.Extensions));
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourceUpdate_WhenResourceDoesNotExistAndNewTitleIsNull_ReturnsHttpLighBadRequest()
{
var taskId = Guid.NewGuid().ToString();
var expectedError = new LightValidationProblemDetails
{
Title = "One or more validation errors occurred.",
Status = 400,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
expectedError.Errors["Title"] = new string[1] { "The Title field is required." };
await _restRunner.UpdateResourceAsync(taskId, new TaskDto { Id = taskId }, expectedError, HttpStatusCode.BadRequest);
}
[Theory]
[InlineData("dummy", null)]
[InlineData("dummy", "")]
[InlineData("dummy", "42")]
public async Task AspNetCoreApiSampleTaskResourceUpdate_WhenInvalidIdProvided_ReturnsHttpBadRequest(string id, string resourceId)
{
var expectedError = new ProblemDetails
{
Title = "Bad Request",
Status = 400,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
await _restRunner.UpdateResourceAsync(id, new TaskDto { Id = resourceId, Title = "Bla bla" }, expectedError, HttpStatusCode.BadRequest,
config => config.Excluding(x => x.Extensions));
}
[Fact]
public async Task AspNetCoreApiSampleTaskResourceUpdate_WhenNullDto_ReturnsHttpBadRequest()
{
var expectedError = new ProblemDetails
{
Title = "One or more validation errors occurred.",
Status = 400,
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
await _restRunner.UpdateResourceAsync("dummy", (TaskDto)null, expectedError, HttpStatusCode.BadRequest,
config => config.Excluding(x => x.Extensions));
}
}
}
| 41.217105 | 153 | 0.631764 | [
"Apache-2.0"
] | Net-Acheteur/withywoods | test/AspNetCoreApiSample.IntegrationTests/Resources/TaskResourceTest.cs | 6,267 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.SageMaker.Inputs
{
/// <summary>
/// The configuration object that specifies the monitoring schedule and defines the monitoring job.
/// </summary>
public sealed class MonitoringScheduleConfigArgs : Pulumi.ResourceArgs
{
[Input("monitoringJobDefinition")]
public Input<Inputs.MonitoringScheduleMonitoringJobDefinitionArgs>? MonitoringJobDefinition { get; set; }
/// <summary>
/// Name of the job definition
/// </summary>
[Input("monitoringJobDefinitionName")]
public Input<string>? MonitoringJobDefinitionName { get; set; }
[Input("monitoringType")]
public Input<Pulumi.AwsNative.SageMaker.MonitoringScheduleMonitoringType>? MonitoringType { get; set; }
[Input("scheduleConfig")]
public Input<Inputs.MonitoringScheduleScheduleConfigArgs>? ScheduleConfig { get; set; }
public MonitoringScheduleConfigArgs()
{
}
}
}
| 33.736842 | 113 | 0.695788 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/SageMaker/Inputs/MonitoringScheduleConfigArgs.cs | 1,282 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.IO;
using System.IO.Compression;
using System.Text;
using Newtonsoft.Json;
namespace rosette_api
{
public class RosetteResponse
{
public RosetteResponse(HttpResponseMessage responseMsg) {
Content = new Dictionary<string, object>();
Headers = new Dictionary<string, string>();
StatusCode = (int)responseMsg.StatusCode;
if (responseMsg.IsSuccessStatusCode) {
foreach (var header in responseMsg.Headers) {
Headers.Add(header.Key, string.Join("", header.Value));
}
foreach (var header in responseMsg.Content.Headers) {
Headers.Add(header.Key, string.Join("", header.Value));
}
byte[] byteArray = responseMsg.Content.ReadAsByteArrayAsync().Result;
if(byteArray[0] == '\x1f' && byteArray[1] == '\x8b' && byteArray[2] == '\x08') {
byteArray = Decompress(byteArray);
}
string result = string.Empty;
using (StreamReader reader = new StreamReader(new MemoryStream(byteArray), Encoding.UTF8)) {
result = reader.ReadToEnd();
}
Content = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
}
else {
throw new HttpRequestException(string.Format("{0}: {1}: {2}", (int)responseMsg.StatusCode, responseMsg.ReasonPhrase, ContentToString(responseMsg.Content)));
}
}
/// <summary>
/// Headers provides read access to the Response Headers collection
/// </summary>
/// <returns>IDictionary of string, string</returns>
public IDictionary<string, string> Headers {get; private set;}
/// <summary>
/// Content provides read access to the Response IDictionary
/// </summary>
/// <returns>IDictionary of string, object</returns>
public IDictionary<string, object> Content {get; private set;}
public object ContentAsJson(bool pretty=false) {
return pretty ?
JsonConvert.SerializeObject(Content, Formatting.Indented) :
JsonConvert.SerializeObject(Content); }
public int StatusCode {get; private set;}
/// <summary>Decompress decompresses GZIP files
/// Source: http://www.dotnetperls.com/decompress
/// </summary>
/// <param name="gzip">(byte[]): Data in byte form to decompress</param>
/// <returns>(byte[]) Decompressed data</returns>
private byte[] Decompress(byte[] gzip) {
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress)) {
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream()) {
int count = 0;
do {
count = stream.Read(buffer, 0, size);
if (count > 0) {
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
internal static string ContentToString(HttpContent httpContent) {
if (httpContent != null) {
var readAsStringAsync = httpContent.ReadAsStringAsync();
return readAsStringAsync.Result;
}
else {
return string.Empty;
}
}
}
} | 40.694737 | 172 | 0.552768 | [
"Apache-2.0"
] | rosette-api/dotnet | rosette_api/RosetteResponse.cs | 3,866 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace UserMaintenance
{
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());
}
}
}
| 22 | 65 | 0.60124 | [
"Apache-2.0"
] | wxd4cd/VersionControl | UserMaintenance/Program.cs | 486 | C# |
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using UNicoAPI2.Connect;
namespace UNicoAPI2.APIs.search
{
public class Accessor : IAccessor
{
public AccessorType Type
{
get
{
return AccessorType.Download;
}
}
CookieContainer cookieContainer;
string type = "";
string word = "";
string page = "";
string order = "";
string sort = "";
public void Setting(CookieContainer CookieContainer, string type, string word, string page, string order, string sort)
{
cookieContainer = CookieContainer;
this.type = type;
this.word = word;
this.page = page;
this.order = order;
this.sort = sort;
}
public byte[] GetUploadData()
{
throw new NotImplementedException();
}
public Task<Stream> GetUploadStreamAsync(int DataLength)
{
throw new NotImplementedException();
}
public Task<WebResponse> GetDownloadStreamAsync()
{
var request = (HttpWebRequest)WebRequest.Create(
"http://ext.nicovideo.jp/api/search/" + type
+ "/" + word
+ "?mode&page=" + page
+ "&order=" + order
+ "&sort=" + sort);
request.Method = ContentMethod.Get;
request.CookieContainer = cookieContainer;
return request.GetResponseAsync();
}
}
}
| 25.919355 | 126 | 0.522091 | [
"Unlicense"
] | cocop/UNicoAPI2 | UNicoAPI2/APIs/search/Accessor.cs | 1,609 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.EntityFrameworkCore.Migrations.Design;
public class MigrationsBundleTest
{
[ConditionalFact]
public void Short_names_are_unique()
{
foreach (var command in GetCommands())
{
foreach (var group in command.Options.GroupBy(o => o.ShortName))
{
Assert.True(
group.Key == null || group.Count() == 1,
"Duplicate short names on command '"
+ GetFullName(command)
+ "': "
+ string.Join("; ", group.Select(o => o.Template)));
}
}
}
[ConditionalFact]
public void Long_names_are_unique()
{
foreach (var command in GetCommands())
{
foreach (var group in command.Options.GroupBy(o => o.LongName))
{
Assert.True(
group.Key == null || group.Count() == 1,
"Duplicate option names on command '"
+ GetFullName(command)
+ "': "
+ string.Join("; ", group.Select(o => o.Template)));
}
}
}
[ConditionalFact]
public void HandleResponseFiles_is_true()
{
var app = new CommandLineApplication { Name = "efbundle" };
MigrationsBundle.Configure(app);
Assert.True(app.HandleResponseFiles);
}
[ConditionalFact]
public void AllowArgumentSeparator_is_true()
{
var app = new CommandLineApplication { Name = "efbundle" };
MigrationsBundle.Configure(app);
Assert.True(app.AllowArgumentSeparator);
}
private static IEnumerable<CommandLineApplication> GetCommands()
{
var app = new CommandLineApplication { Name = "efbundle" };
MigrationsBundle.Configure(app);
return GetCommands(app);
}
private static IEnumerable<CommandLineApplication> GetCommands(CommandLineApplication command)
{
var commands = new Stack<CommandLineApplication>();
commands.Push(command);
while (commands.Count != 0)
{
command = commands.Pop();
yield return command;
foreach (var subcommand in command.Commands)
{
commands.Push(subcommand);
}
}
}
private static string GetFullName(CommandLineApplication command)
{
var names = new Stack<string>();
while (command != null)
{
names.Push(command.Name);
command = command.Parent;
}
return string.Join(" ", names);
}
}
| 27.359223 | 98 | 0.559262 | [
"MIT"
] | AraHaan/efcore | test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs | 2,820 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type UnifiedRoleDefinitionRequest.
/// </summary>
public partial class UnifiedRoleDefinitionRequest : BaseRequest, IUnifiedRoleDefinitionRequest
{
/// <summary>
/// Constructs a new UnifiedRoleDefinitionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public UnifiedRoleDefinitionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified UnifiedRoleDefinition using POST.
/// </summary>
/// <param name="unifiedRoleDefinitionToCreate">The UnifiedRoleDefinition to create.</param>
/// <returns>The created UnifiedRoleDefinition.</returns>
public System.Threading.Tasks.Task<UnifiedRoleDefinition> CreateAsync(UnifiedRoleDefinition unifiedRoleDefinitionToCreate)
{
return this.CreateAsync(unifiedRoleDefinitionToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified UnifiedRoleDefinition using POST.
/// </summary>
/// <param name="unifiedRoleDefinitionToCreate">The UnifiedRoleDefinition to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created UnifiedRoleDefinition.</returns>
public async System.Threading.Tasks.Task<UnifiedRoleDefinition> CreateAsync(UnifiedRoleDefinition unifiedRoleDefinitionToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<UnifiedRoleDefinition>(unifiedRoleDefinitionToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified UnifiedRoleDefinition.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified UnifiedRoleDefinition.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<UnifiedRoleDefinition>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified UnifiedRoleDefinition.
/// </summary>
/// <returns>The UnifiedRoleDefinition.</returns>
public System.Threading.Tasks.Task<UnifiedRoleDefinition> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified UnifiedRoleDefinition.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The UnifiedRoleDefinition.</returns>
public async System.Threading.Tasks.Task<UnifiedRoleDefinition> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<UnifiedRoleDefinition>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified UnifiedRoleDefinition using PATCH.
/// </summary>
/// <param name="unifiedRoleDefinitionToUpdate">The UnifiedRoleDefinition to update.</param>
/// <returns>The updated UnifiedRoleDefinition.</returns>
public System.Threading.Tasks.Task<UnifiedRoleDefinition> UpdateAsync(UnifiedRoleDefinition unifiedRoleDefinitionToUpdate)
{
return this.UpdateAsync(unifiedRoleDefinitionToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified UnifiedRoleDefinition using PATCH.
/// </summary>
/// <param name="unifiedRoleDefinitionToUpdate">The UnifiedRoleDefinition to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated UnifiedRoleDefinition.</returns>
public async System.Threading.Tasks.Task<UnifiedRoleDefinition> UpdateAsync(UnifiedRoleDefinition unifiedRoleDefinitionToUpdate, CancellationToken cancellationToken)
{
if (unifiedRoleDefinitionToUpdate.AdditionalData != null)
{
if (unifiedRoleDefinitionToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
unifiedRoleDefinitionToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, unifiedRoleDefinitionToUpdate.GetType().Name)
});
}
}
if (unifiedRoleDefinitionToUpdate.AdditionalData != null)
{
if (unifiedRoleDefinitionToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
unifiedRoleDefinitionToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, unifiedRoleDefinitionToUpdate.GetType().Name)
});
}
}
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<UnifiedRoleDefinition>(unifiedRoleDefinitionToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUnifiedRoleDefinitionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IUnifiedRoleDefinitionRequest Expand(Expression<Func<UnifiedRoleDefinition, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUnifiedRoleDefinitionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IUnifiedRoleDefinitionRequest Select(Expression<Func<UnifiedRoleDefinition, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="unifiedRoleDefinitionToInitialize">The <see cref="UnifiedRoleDefinition"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(UnifiedRoleDefinition unifiedRoleDefinitionToInitialize)
{
if (unifiedRoleDefinitionToInitialize != null && unifiedRoleDefinitionToInitialize.AdditionalData != null)
{
if (unifiedRoleDefinitionToInitialize.InheritsPermissionsFrom != null && unifiedRoleDefinitionToInitialize.InheritsPermissionsFrom.CurrentPage != null)
{
unifiedRoleDefinitionToInitialize.InheritsPermissionsFrom.AdditionalData = unifiedRoleDefinitionToInitialize.AdditionalData;
object nextPageLink;
unifiedRoleDefinitionToInitialize.AdditionalData.TryGetValue("inheritsPermissionsFrom@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
unifiedRoleDefinitionToInitialize.InheritsPermissionsFrom.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| 45.46332 | 173 | 0.630743 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/UnifiedRoleDefinitionRequest.cs | 11,775 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HoneypotRuleCollection.cs" company="Web Advanced">
// Copyright 2012 Web Advanced (www.webadvanced.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleHoneypot.Core {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using SimpleHoneypot.Core.Common;
public class HoneypotRuleCollection : IEnumerable<Func<NameValueCollection, bool>> {
#region Constants and Fields
private readonly List<Func<NameValueCollection, bool>> rules = new List<Func<NameValueCollection, bool>>();
#endregion
#region Public Methods and Operators
/// <summary>
/// A func that returns true if request is a bot
/// </summary>
/// <param name="func"></param>
public void Add(Func<NameValueCollection, bool> func) {
Check.Argument.IsNotNull(func, "func");
this.rules.Add(func);
}
public void Clear() {
this.rules.Clear();
}
public IEnumerator<Func<NameValueCollection, bool>> GetEnumerator() {
return this.rules.GetEnumerator();
}
#endregion
#region Explicit Interface Methods
IEnumerator IEnumerable.GetEnumerator() {
return this.GetEnumerator();
}
#endregion
}
} | 36.131148 | 121 | 0.575771 | [
"Apache-2.0"
] | TechSmith/Honeypot-MVC | src/SimpleHoneypot/Core/HoneypotRuleCollection.cs | 2,206 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ejercicio8 : MonoBehaviour
{
public int dia;
// Start is called before the first frame update
void Start()
{
switch (dia)
{
case 1:
Debug.Log("Domingo");
break;
case 2:
Debug.Log("Lunes");
break;
case 3:
Debug.Log("Martes");
break;
case 4:
Debug.Log("Miercoles");
break;
case 5:
Debug.Log("Jueves");
break;
case 6:
Debug.Log("Viernes");
break;
case 7:
Debug.Log("Sabado");
break;
default:
Debug.Log("El dia ingresado no es valido");
break;
}
}
// Update is called once per frame
void Update()
{ }
}
| 20.16 | 59 | 0.417659 | [
"MIT"
] | DylanTsai1/Gu-a-de-programaci-n-1 | Assets/Ejercicio8.cs | 1,010 | C# |
using System.Collections.Generic;
using UnityEngine;
public class SpritedObserverBehaviour<T> : ObserverBehaviour<T> where T: Entity<T> {
List<SpriteRenderer> layers = new List<SpriteRenderer>();
public override void HandleEvent(string signal, object[] args) {
throw new System.NotImplementedException();
}
protected void CreateGraphics() {
if(Emitter.icon == null) {
return;
}
EnsureSize();
for (int i = 0; i < Emitter.Icon.Count; ++i) {
SpriteController.spriteLoader.LoadIntoSpriteRenderer(layers[i], Emitter.Icon.Get(i), Emitter);
}
}
private void EnsureSize() {
int oldCap = layers.Count;
layers.Capacity = Mathf.Max(oldCap, Emitter.Icon.Count);
for (int i = oldCap; i < Emitter.Icon.Count; ++i) {
GameObject layer = new GameObject("layer" + i);
layer.transform.SetParent(transform, false);
//layer.transform.localPosition = Vector3.zero;
layers.Add(layer.AddComponent<SpriteRenderer>());
}
}
protected void UpdateGraphics() {
EnsureSize();
for (int i = 0; i < Emitter.Icon.Count; ++i) {
SpriteController.spriteLoader.LoadIntoSpriteRenderer(layers[i], Emitter.Icon.Get(i), Emitter);
}
}
} | 34.789474 | 106 | 0.618003 | [
"Apache-2.0"
] | FilippoLeon/Shipwreck | Assets/Components/SpritedObserverBehaviour.cs | 1,324 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Drawing;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Diagnostics;
namespace SpotlightImages
{
public class ImageProcessor
{
private string spotlightImagesFolder;
private string defaultDestinationFolder;
private string destinationFolder;
private UiDrawer uiDrawer;
private IConfigurationRoot config;
public ImageProcessor(string spotlightImagesFolder, string defaultDestinationFolder)
{
this.spotlightImagesFolder = spotlightImagesFolder;
this.defaultDestinationFolder = defaultDestinationFolder.Replace('/', '\\');
this.GetConfiguration();
this.uiDrawer = new UiDrawer();
}
public void RetrieveImages()
{
var destFolder = this.uiDrawer.DrawFolderDialog(defaultDestinationFolder);
if (destFolder != string.Empty)
{
this.destinationFolder = destFolder;
}
List<FileInfo> existingLandscapeImages = new List<FileInfo>();
List<FileInfo> existingPortraitImages = new List<FileInfo>();
try
{
if (!Directory.Exists(this.destinationFolder))
{
Console.WriteLine("\"" + this.destinationFolder + "\" folder created.");
Directory.CreateDirectory(this.destinationFolder);
Directory.CreateDirectory(this.destinationFolder + "\\Landscape");
Directory.CreateDirectory(this.destinationFolder + "\\Portrait");
}
else
{
if (!Directory.Exists(this.destinationFolder + "\\Landscape"))
{
Console.WriteLine("\"" + this.destinationFolder + "\\Landscape" + "\" folder created.");
Directory.CreateDirectory(this.destinationFolder + "\\Landscape");
}
if (!Directory.Exists(this.destinationFolder + "\\Portrait"))
{
Console.WriteLine("\"" + this.destinationFolder + "\\Portrait" + "\" folder created.");
Directory.CreateDirectory(this.destinationFolder + "\\Portrait");
}
}
existingLandscapeImages = new DirectoryInfo(this.destinationFolder + "\\Landscape").EnumerateFiles().ToList();
existingPortraitImages = new DirectoryInfo(this.destinationFolder + "\\Portrait").EnumerateFiles().ToList();
}
catch (Exception e)
{
Console.WriteLine(e.Message + "Press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
}
if (destFolder != string.Empty)
{
this.SetConfiguration("destinationFolder", this.destinationFolder);
}
var copiedLandscapesCount = 0;
var copiedPortraitsCount = 0;
var existingLandscapesCount = 0;
var existingPortraitsCount = 0;
if (!Directory.Exists(this.spotlightImagesFolder))
{
Console.WriteLine("\"" + this.destinationFolder + "\" does not exist. Press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
}
IEnumerable<FileInfo> files = new DirectoryInfo(this.spotlightImagesFolder).EnumerateFiles();
foreach (var file in files)
{
if (existingLandscapeImages.Any(x => x.Name == file.Name + ".jpg"))
{
existingLandscapesCount++;
continue;
}
if (existingPortraitImages.Any(x => x.Name == file.Name + ".jpg"))
{
existingPortraitsCount++;
continue;
}
try
{
var size = this.GetJpegImageSize(file.FullName);
// todo: decide what's portrait and what's landscape
if (size.Height < size.Width)
{
this.CopyFile(file.FullName, destinationFolder + "\\Landscape\\" + file.Name + ".jpg");
copiedLandscapesCount++;
}
else
{
this.CopyFile(file.FullName, destinationFolder + "\\Portrait\\" + file.Name + ".jpg");
copiedPortraitsCount++;
}
}
catch (Exception)
{
continue;
}
}
Console.Clear();
this.uiDrawer.DrawResult(copiedLandscapesCount, existingLandscapesCount, copiedPortraitsCount, existingPortraitsCount);
if (uiDrawer.DrawOpenFolderDialog())
{
Process.Start("explorer.exe", this.destinationFolder);
}
}
// todo: handle exceptions
private void CopyFile(string sourceFileName, string destFileName)
{
File.Copy(sourceFileName, destFileName);
}
// todo: spotlightImagesFolder key
private void GetConfiguration()
{
var appsettingsPath = Directory.GetCurrentDirectory() + "\\appsettings.json";
if (!File.Exists(appsettingsPath))
{
var jsonContent = "{\n\r \"destinationFolder\" : \"" + this.defaultDestinationFolder.Replace('\\', '/') + "\",\n\r \"spotlightImagesFolder\" : \"" + this.spotlightImagesFolder.Replace('\\', '/') + "\"\n\r }";
File.WriteAllText(appsettingsPath, jsonContent);
}
try
{
config = new ConfigurationBuilder().AddJsonFile(appsettingsPath).Build();
if (!config.AsEnumerable().Any(x => x.Key == "destinationFolder"))
{
this.SetConfiguration("destinationFolder", this.defaultDestinationFolder);
}
this.destinationFolder = config["destinationFolder"].Replace('/', '\\');
}
//catch (FileNotFoundException)
//{
// Console.WriteLine("Missing appsettings.json");
// Console.ReadLine();
// return;
//}
catch (Exception)
{
Console.WriteLine("Invalid appsettings.json . Press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
}
}
// todo: validate json
private void SetConfiguration(string key, string value)
{
this.config[key] = value.Replace('\\', '/');
}
public Size GetJpegImageSize(string filename)
{
FileStream stream = null;
BinaryReader rdr = null;
try
{
stream = File.OpenRead(filename);
rdr = new BinaryReader(stream);
// keep reading packets until we find one that contains Size info
for (;;)
{
byte code = rdr.ReadByte();
if (code != 0xFF) throw new Exception("Unexpected value in file " + filename);
code = rdr.ReadByte();
switch (code)
{
// filler byte
case 0xFF:
stream.Position--;
break;
// packets without data
case 0xD0:
case 0xD1:
case 0xD2:
case 0xD3:
case 0xD4:
case 0xD5:
case 0xD6:
case 0xD7:
case 0xD8:
case 0xD9:
break;
// packets with size information
case 0xC0:
case 0xC1:
case 0xC2:
case 0xC3:
case 0xC4:
case 0xC5:
case 0xC6:
case 0xC7:
case 0xC8:
case 0xC9:
case 0xCA:
case 0xCB:
case 0xCC:
case 0xCD:
case 0xCE:
case 0xCF:
ReadBEUshort(rdr);
rdr.ReadByte();
ushort h = ReadBEUshort(rdr);
ushort w = ReadBEUshort(rdr);
return new Size(w, h);
// irrelevant variable-length packets
default:
int len = ReadBEUshort(rdr);
stream.Position += len - 2;
break;
}
}
}
finally
{
if (rdr != null) rdr.Dispose();
if (stream != null) stream.Dispose();
}
}
private static ushort ReadBEUshort(BinaryReader rdr)
{
ushort hi = rdr.ReadByte();
hi <<= 8;
ushort lo = rdr.ReadByte();
return (ushort)(hi | lo);
}
}
}
| 36.886364 | 224 | 0.465393 | [
"MIT"
] | mdraganov/SpotlightImages | SpotlightImages/src/SpotlightImages/ImageProcessor.cs | 9,740 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace rokWebsite.Models
{
public class KvkPlayers
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Update Time")]
[Display(Name = "Update Time", Description = "Update Time")]
public DateTime UpdateTime { get; set; }
public virtual Kvk Kvk { get; set; }
public virtual User User { get; set; }
public virtual Perfomance Perfomance { get; set; }
}
}
| 23.52 | 68 | 0.644558 | [
"MIT"
] | behluluysal/asp-net-core-5-training | rokWebsite/Models/KvkPlayers.cs | 590 | C# |
namespace Sportify.Services
{
using System.Collections.Generic;
using System.Linq;
using Data;
using Data.Models;
using Data.ViewModels.Countries;
using global::AutoMapper;
using Interfaces;
using Microsoft.AspNetCore.Identity;
public class CountriesService : BaseService, ICountriesService
{
public CountriesService(SportifyDbContext context, IMapper mapper, UserManager<User> userManager, SignInManager<User> signInManager)
: base(context, mapper, userManager, signInManager)
{
}
public Country GetCountryById(int id)
{
var country = this.Context
.Countries
.FirstOrDefault(x => x.Id == id);
return country;
}
public Country GetCountryByName(string name)
{
var country = this.Context
.Countries
.FirstOrDefault(x => x.Name == name);
return country;
}
public IEnumerable<CountrySelectViewModel> GetAllCountryNames()
{
var countries = this.Context
.Countries
.OrderBy(x => x.Name);
var countriesModel = this.Mapper.Map<IOrderedQueryable<Country>, IEnumerable<CountrySelectViewModel>>(countries);
return countriesModel;
}
}
} | 27.877551 | 140 | 0.599561 | [
"MIT"
] | dobroslav-atanasov/Sportify | src/Services/Sportify.Services/CountriesService.cs | 1,368 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace backend.Migrations
{
public partial class Title : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Title",
table: "Notes",
type: "text",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Title",
table: "Notes");
}
}
}
| 25 | 71 | 0.546667 | [
"MIT"
] | caprapaul/habit-app | backend/backend/Migrations/20211205124443_Title.cs | 602 | C# |
using System;
using System.Collections.Generic;
using Siege.Eventing.Messages;
namespace Siege.Eventing
{
public class ThreadedMessageTracker : IMessageTracker
{
[ThreadStatic] private static List<IMessage> receivedMessages;
public void Track(IMessage message)
{
receivedMessages = receivedMessages ?? new List<IMessage>();
if (receivedMessages.Contains(message)) return;
receivedMessages.Add(message);
}
public bool IsTracked(IMessage message)
{
return receivedMessages.Contains(message);
}
public void Clear()
{
receivedMessages.Clear();
}
}
} | 24.6 | 73 | 0.593496 | [
"Apache-2.0"
] | lokalan/Siege | Siege.Futures/Siege.Eventing/ThreadedMessageTracker.cs | 740 | C# |
using System.Collections.Generic;
using System.Configuration;
namespace NConfig
{
/// <summary>
/// Sections merger which performs configuration property-by-property merge.
/// </summary>
/// <typeparam name="TSection">Configuration section type.</typeparam>
public class PropertyMerger<TSection> : NSectionMerger<TSection>
where TSection : ConfigurationSection, new()
{
/// <summary>
/// Merges the specified typed configuration sections.
/// </summary>
/// <param name="sections">The sections to merge in order from the most important to lower.</param>
/// <returns>The merge resulting section.</returns>
public override TSection Merge(IEnumerable<TSection> sections)
{
var result = new TSection();
foreach (PropertyInformation resultPropery in result.ElementInformation.Properties)
{
foreach (TSection section in sections) // The order of sections should be from the most important to lower
{
var sectionProperty = section.ElementInformation.Properties[resultPropery.Name];
if (sectionProperty == null)
break;
resultPropery.Value = sectionProperty.Value;
if (IsConfigurationPropertyDefined(sectionProperty))
// leave the value of first defined in config file property.
break;
}
}
return result;
}
private bool IsConfigurationPropertyDefined(PropertyInformation property)
{
return property.ValueOrigin == PropertyValueOrigin.SetHere;
}
}
}
| 35.653061 | 122 | 0.606182 | [
"MIT"
] | Yegoroff/NConfig | NConfig/Implementation/Mergers/PropertyLevelMerger.cs | 1,749 | C# |
public class SavedInt
{
private readonly string id;
private int value;
public int Value
{
get => value;
set
{
this.value = value;
Save();
}
}
public SavedInt(string id)
{
this.id = id;
string stringValue = LocalStorage.GetLocalStorageItem(id);
if (stringValue == "") return;
if (stringValue == null) return;
Value = stringValue.ToInt();
}
public static implicit operator int(SavedInt savedInt) => savedInt.value;
private void Save()
{
LocalStorage.SetLocalStorageItem(id, Value.ToStringExtension());
}
} | 20.060606 | 77 | 0.563444 | [
"MIT"
] | MartinKral/Spherestroyer | Assets/Scripts/Main/Utils/GameSaver/SavedInt.cs | 664 | C# |
using System;
using System.Runtime.Serialization;
using System.Web.Security;
using Orchard.ContentManagement.Records;
namespace CloudBust.Application.Models
{
public class ApplicationApplicationCategoriesRecord
{
public virtual int Id { get; set; }
public virtual ApplicationRecord Application { get; set; }
public virtual ApplicationCategoryRecord ApplicationCategory { get; set; }
}
} | 30.214286 | 82 | 0.751773 | [
"BSD-3-Clause"
] | doticca/Orchard.CloudBust | src/Orchard.Web/Modules/CloudBust.Application/Models/ApplicationApplicationCategoriesRecord.cs | 423 | C# |
using Nssol.Platypus.ApiModels.Components;
using Nssol.Platypus.Controllers.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Nssol.Platypus.ApiModels.PreprocessingApiModels
{
/// <summary>
/// 前処理作成の入力モデル
/// </summary>
/// <remarks>
/// 前処理はKAMONOHASHIで実行不能なものも設定できる(履歴管理用)ので、ジョブでは必須入力であったエントリポイントなども必須としない。
/// </remarks>
public class CreateInputModel
{
/// <summary>
/// 識別名
/// </summary>
[Required]
[ValidInputAsTag]
public string Name { get; set; }
/// <summary>
/// エントリポイント
/// </summary>
public string EntryPoint { get; set; }
/// <summary>
/// コンテナ情報
/// </summary>
public ContainerImageInputModel ContainerImage { get; set; }
/// <summary>
/// 前処理ソースコードGit情報
/// </summary>
public GitCommitNullableInputModel GitModel { get; set; }
/// <summary>
/// メモ
/// </summary>
public string Memo { get; set; }
/// <summary>
/// CPUコア数のデフォルト値
/// </summary>
public int Cpu { get; set; }
/// <summary>
/// メモリ容量(GiB)のデフォルト値
/// </summary>
public int Memory { get; set; }
/// <summary>
/// GPU数のデフォルト値
/// </summary>
public int Gpu { get; set; }
}
}
| 24.949153 | 78 | 0.548913 | [
"Apache-2.0"
] | 428s/kamonohashi | web-api/platypus/platypus/ApiModels/PreprocessingApiModels/CreateInputModel.cs | 1,738 | C# |
using System;
using System.Collections.Generic;
using SFA.DAS.Commitments.Domain.Entities;
namespace SFA.DAS.Commitments.Application.Interfaces.ApprenticeshipEvents
{
public interface IApprenticeshipEventsList
{
void Add(Commitment commitment, Apprenticeship apprenticeship, string @event, DateTime? effectiveFrom = null, DateTime? effectiveTo = null);
void Clear();
IReadOnlyList<IApprenticeshipEvent> Events { get; }
}
}
| 32.928571 | 148 | 0.754881 | [
"MIT"
] | Ryan-Fitchett/Test | src/SFA.DAS.Commitments.Application/Interfaces/ApprenticeshipEvents/IApprenticeshipEventsList.cs | 463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Brume.Common.Office
{
public interface IFileHelper
{
string GetDocumentPath(string id);
void ClearTempDocument(string dir);
}
}
| 17.8125 | 43 | 0.722807 | [
"MIT"
] | alienblog/OfficePreviewOnline | Brume.Common.Office/Brume.Common.Office/IFileHelper.cs | 287 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WpfAppDeviceSimulator
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.611111 | 42 | 0.713433 | [
"MIT"
] | ms-iotkithol-jp/StreamAnalyticsUnzipDeserialize | simulator/WpfAppDeviceSimulator/App.xaml.cs | 337 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using LogicBuilder.Attributes;
namespace Contoso.Domain.Entities
{
public class DepartmentModel : BaseModelClass
{
[VariableEditorControl(VariableControlType.SingleLineTextBox)]
[AlsoKnownAs("Department_DepartmentID")]
public int DepartmentID { get; set; }
[StringLength(50, MinimumLength = 3)]
[VariableEditorControl(VariableControlType.SingleLineTextBox)]
[AlsoKnownAs("Department_Name")]
public string Name { get; set; }
[DataType(DataType.Currency)]
[VariableEditorControl(VariableControlType.SingleLineTextBox)]
[AlsoKnownAs("Department_Budget")]
public decimal Budget { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Start Date")]
[VariableEditorControl(VariableControlType.SingleLineTextBox)]
[AlsoKnownAs("Department_StartDate")]
public System.DateTime StartDate { get; set; }
[VariableEditorControl(VariableControlType.SingleLineTextBox)]
[AlsoKnownAs("Department_InstructorID")]
public int? InstructorID { get; set; }
[ListEditorControl(ListControlType.HashSetForm)]
[AlsoKnownAs("Department_RowVersion")]
public byte[] RowVersion { get; set; }
[AlsoKnownAs("Department_Administrator")]
public InstructorModel Administrator { get; set; }
[ListEditorControl(ListControlType.HashSetForm)]
[AlsoKnownAs("Department_Courses")]
public ICollection<CourseModel> Courses { get; set; }
}
} | 33.456522 | 85 | 0.769331 | [
"MIT"
] | BlaiseD/Contoso | .NetCore/ContosoUniversity/DomainFiles/DepartmentModel.cs | 1,541 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190201
{
/// <summary>
/// Peering in an ExpressRoute Cross Connection resource.
/// </summary>
public partial class ExpressRouteCrossConnectionPeering : Pulumi.CustomResource
{
/// <summary>
/// The Azure ASN.
/// </summary>
[Output("azureASN")]
public Output<int> AzureASN { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// The GatewayManager Etag.
/// </summary>
[Output("gatewayManagerEtag")]
public Output<string?> GatewayManagerEtag { get; private set; } = null!;
/// <summary>
/// The IPv6 peering configuration.
/// </summary>
[Output("ipv6PeeringConfig")]
public Output<Outputs.Ipv6ExpressRouteCircuitPeeringConfigResponse?> Ipv6PeeringConfig { get; private set; } = null!;
/// <summary>
/// Gets whether the provider or the customer last modified the peering.
/// </summary>
[Output("lastModifiedBy")]
public Output<string?> LastModifiedBy { get; private set; } = null!;
/// <summary>
/// The Microsoft peering configuration.
/// </summary>
[Output("microsoftPeeringConfig")]
public Output<Outputs.ExpressRouteCircuitPeeringConfigResponse?> MicrosoftPeeringConfig { get; private set; } = null!;
/// <summary>
/// Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Output("name")]
public Output<string?> Name { get; private set; } = null!;
/// <summary>
/// The peer ASN.
/// </summary>
[Output("peerASN")]
public Output<int?> PeerASN { get; private set; } = null!;
/// <summary>
/// The peering type.
/// </summary>
[Output("peeringType")]
public Output<string?> PeeringType { get; private set; } = null!;
/// <summary>
/// The primary port.
/// </summary>
[Output("primaryAzurePort")]
public Output<string> PrimaryAzurePort { get; private set; } = null!;
/// <summary>
/// The primary address prefix.
/// </summary>
[Output("primaryPeerAddressPrefix")]
public Output<string?> PrimaryPeerAddressPrefix { get; private set; } = null!;
/// <summary>
/// Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The secondary port.
/// </summary>
[Output("secondaryAzurePort")]
public Output<string> SecondaryAzurePort { get; private set; } = null!;
/// <summary>
/// The secondary address prefix.
/// </summary>
[Output("secondaryPeerAddressPrefix")]
public Output<string?> SecondaryPeerAddressPrefix { get; private set; } = null!;
/// <summary>
/// The shared key.
/// </summary>
[Output("sharedKey")]
public Output<string?> SharedKey { get; private set; } = null!;
/// <summary>
/// The peering state.
/// </summary>
[Output("state")]
public Output<string?> State { get; private set; } = null!;
/// <summary>
/// The VLAN ID.
/// </summary>
[Output("vlanId")]
public Output<int?> VlanId { get; private set; } = null!;
/// <summary>
/// Create a ExpressRouteCrossConnectionPeering resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ExpressRouteCrossConnectionPeering(string name, ExpressRouteCrossConnectionPeeringArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190201:ExpressRouteCrossConnectionPeering", name, args ?? new ExpressRouteCrossConnectionPeeringArgs(), MakeResourceOptions(options, ""))
{
}
private ExpressRouteCrossConnectionPeering(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190201:ExpressRouteCrossConnectionPeering", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/latest:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteCrossConnectionPeering"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteCrossConnectionPeering"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ExpressRouteCrossConnectionPeering resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ExpressRouteCrossConnectionPeering Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ExpressRouteCrossConnectionPeering(name, id, options);
}
}
public sealed class ExpressRouteCrossConnectionPeeringArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the ExpressRouteCrossConnection.
/// </summary>
[Input("crossConnectionName", required: true)]
public Input<string> CrossConnectionName { get; set; } = null!;
/// <summary>
/// The GatewayManager Etag.
/// </summary>
[Input("gatewayManagerEtag")]
public Input<string>? GatewayManagerEtag { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The IPv6 peering configuration.
/// </summary>
[Input("ipv6PeeringConfig")]
public Input<Inputs.Ipv6ExpressRouteCircuitPeeringConfigArgs>? Ipv6PeeringConfig { get; set; }
/// <summary>
/// Gets whether the provider or the customer last modified the peering.
/// </summary>
[Input("lastModifiedBy")]
public Input<string>? LastModifiedBy { get; set; }
/// <summary>
/// The Microsoft peering configuration.
/// </summary>
[Input("microsoftPeeringConfig")]
public Input<Inputs.ExpressRouteCircuitPeeringConfigArgs>? MicrosoftPeeringConfig { get; set; }
/// <summary>
/// Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The peer ASN.
/// </summary>
[Input("peerASN")]
public Input<int>? PeerASN { get; set; }
/// <summary>
/// The name of the peering.
/// </summary>
[Input("peeringName", required: true)]
public Input<string> PeeringName { get; set; } = null!;
/// <summary>
/// The peering type.
/// </summary>
[Input("peeringType")]
public Input<string>? PeeringType { get; set; }
/// <summary>
/// The primary address prefix.
/// </summary>
[Input("primaryPeerAddressPrefix")]
public Input<string>? PrimaryPeerAddressPrefix { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The secondary address prefix.
/// </summary>
[Input("secondaryPeerAddressPrefix")]
public Input<string>? SecondaryPeerAddressPrefix { get; set; }
/// <summary>
/// The shared key.
/// </summary>
[Input("sharedKey")]
public Input<string>? SharedKey { get; set; }
/// <summary>
/// The peering state.
/// </summary>
[Input("state")]
public Input<string>? State { get; set; }
/// <summary>
/// The VLAN ID.
/// </summary>
[Input("vlanId")]
public Input<int>? VlanId { get; set; }
public ExpressRouteCrossConnectionPeeringArgs()
{
}
}
}
| 42.211073 | 182 | 0.603082 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20190201/ExpressRouteCrossConnectionPeering.cs | 12,199 | 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("InchesToCentimeters")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InchesToCentimeters")]
[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("168e6227-0113-43f0-b836-4a6b1bf831fe")]
// 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 | 84 | 0.750356 | [
"MIT"
] | vanya3254/SoftUni-CSharp-PBasics | SimpleCalculation/InchesToCentimeters/Properties/AssemblyInfo.cs | 1,409 | C# |
// Deployment Framework for BizTalk
// Copyright (C) 2008-14 Thomas F. Abraham, 2004-08 Scott Colestock
// This source file is subject to the Microsoft Public License (Ms-PL).
// See http://www.opensource.org/licenses/ms-pl.html.
// All other rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace DeploymentFramework.BuildTasks
{
/// <summary>
/// This MSBuild task uses the BizTalk 2006 R2 WCF publishing libraries to export schemas
/// and definition files for a WCF Web service exposed from BizTalk.
///
/// Published services contain copies of all of the schemas related to the service in a
/// set of XSD files on disk. This means that every time one of those schemas changes,
/// the service must be re-published. That's where this task comes in. It removes the
/// need to store copies of the published schema files because it can re-publish them
/// on demand.
///
/// This task requires that the service be manually exported once with the WCF Service
/// Publishing Wizard. Among other files, the export process creates a definition file called
/// WcfServiceDescription.xml, which captures the settings used in the wizard. The file
/// is saved to wwwroot\[service]\App_Data\Temp. The task requires this definition
/// file to reproduce the original export.
///
/// There are only four files that should be preserved in source control from the published
/// service: [service].svc and web.config in wwwroot\[service] and the service description
/// and binding XML files in wwwroot\[service]\App_Data\Temp. Everything in App_Data can
/// be recreated with this task.
///
/// This task does not directly reference the BizTalk assemblies. The WcfPublishingAssemblyName
/// property can override the .NET assembly name, which defaults to that of BizTalk 2006 R2.
/// </summary>
public class PublishWcfServiceArtifacts : Task
{
private const string BizTalkWcfPublishingAssembly =
"Microsoft.BizTalk.Adapter.Wcf.Publishing, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
private string _outputPath;
private string _serviceDescriptionPath;
private string _wcfPublishingAssembly = BizTalkWcfPublishingAssembly;
/// <summary>
/// Path to the service home directory. App_Data will be created below this folder.
/// </summary>
[Required]
public string OutputPath
{
get { return _outputPath; }
set { _outputPath = value; }
}
/// <summary>
/// Path to the WcfServiceDescription.xml file saved from a manual publication of the service.
/// </summary>
[Required]
public string ServiceDescriptionPath
{
get { return _serviceDescriptionPath; }
set { _serviceDescriptionPath = value; }
}
/// <summary>
/// The complete assembly name (name, version, culture, public key) of the BizTalk
/// WCF Publishing assembly. Default value is correct for BizTalk 2006 R2.
/// </summary>
public string WcfPublishingAssemblyName
{
get { return _wcfPublishingAssembly; }
set { _wcfPublishingAssembly = value; }
}
public override bool Execute()
{
try
{
//
// This code is based on Microsoft.BizTalk.Adapter.Wcf.Publishing.Publisher.Export().
// Since most of the classes and methods are private, this code has to use reflection
// to do most of the work. It was developed and tested against the original release
// of BizTalk Server 2006 R2.
//
// First, read in the service description file saved from a manual run of the
// WCF Service Publishing Wizard.
Type wsdType = Type.GetType(
"Microsoft.BizTalk.Adapter.Wcf.Publishing.Description.WcfServiceDescription, " + _wcfPublishingAssembly, true);
object svcDescription =
wsdType.InvokeMember("LoadXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] { _serviceDescriptionPath });
Type wmtType = Type.GetType(
"Microsoft.BizTalk.Adapter.Wcf.Publishing.Description.WcfMessageType, " + _wcfPublishingAssembly, true);
IDictionary uniqueMessageTypes = null;
// Build a list of the message types defined in the service description file.
Type publisherType = Type.GetType(
"Microsoft.BizTalk.Adapter.Wcf.Publishing.Publisher, " + _wcfPublishingAssembly, true);
uniqueMessageTypes =
publisherType.InvokeMember("GetUniqueMessageTypes", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, new object[] { svcDescription }) as IDictionary;
// Create a new instance of the WebServiceImplementation class, which will carry
// out the save to disk later on.
Type wsiType = Type.GetType(
"Microsoft.BizTalk.Adapter.Wcf.Publishing.Implementation.WebServiceImplementation, " + _wcfPublishingAssembly, true);
object wsi = wsiType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
// Create a BtsServiceDescription object based on the service description.
Type bsdeType = Type.GetType(
"Microsoft.BizTalk.Adapter.Wcf.Publishing.Exporters.BtsServiceDescriptionExporter, " + _wcfPublishingAssembly, true);
object bsd =
bsdeType.InvokeMember("Export", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] { svcDescription });
// Set the BtsServiceDescription object into the WebServiceImplementation object's
// BtsServiceDescription property.
wsiType.InvokeMember(
"BtsServiceDescription", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Public, null, wsi, new object[] { bsd });
// Add the WCF-default DataContractSerializer schema to the WebServiceImplementation object.
MethodInfo asstiMethod =
publisherType.GetMethod("AddSerializationSchemaToImplementation", BindingFlags.Static | BindingFlags.NonPublic);
asstiMethod.Invoke(null, new object[] { wsi });
MethodInfo pwmtMethod =
publisherType.GetMethod("ProcessWcfMessageType", BindingFlags.Static | BindingFlags.NonPublic);
Log.LogMessage(MessageImportance.Normal, "Exporting WCF service artifacts from {0}...", _serviceDescriptionPath);
// For each unique message type defined in the service description, extract the schemas
// into the WebServiceImplementation object.
foreach (object type in uniqueMessageTypes.Values)
{
pwmtMethod.Invoke(null, new object[] { wsi, type });
}
// Now that we have everything we need in the WebServiceImplementation object,
// it can save everything out to disk.
MethodInfo stfMethod =
wsiType.GetMethod("SaveToFolder", BindingFlags.Instance | BindingFlags.Public);
stfMethod.Invoke(wsi, new object[] { _outputPath });
}
catch (Exception ex)
{
Log.LogErrorFromException(ex);
return false;
}
return true;
}
}
}
| 49.94375 | 206 | 0.642973 | [
"MIT"
] | BTDF/BTDF | src/btdf/Tools/BuildTasks/BizTalkDeploymentFramework.Tasks/PublishWcfServiceArtifacts.cs | 7,993 | C# |
using Microsoft.EntityFrameworkCore;
using Stize.CQRS.Command;
using Stize.CQRS.EntityFrameworkCore.Internal;
using Stize.Domain.Entity;
using Stize.DotNet.Result;
namespace Stize.CQRS.EntityFrameworkCore.Command
{
public class EntityCommand<TEntity, TKey, TContext> : ICommand<Result<TKey>>, IEntityCqrsRequest<TEntity, TKey, TContext>
where TEntity : class, IEntity<TKey>
where TContext : DbContext
{
}
public class EntityCommand<TModel, TEntity, TKey, TContext> : ICommand<Result<TKey>>, IEntityCqrsRequest<TModel, TEntity, TKey, TContext>
where TModel : class
where TEntity : class, IEntity<TKey>
where TContext : DbContext
{
}
}
| 29.5 | 141 | 0.716102 | [
"Apache-2.0"
] | stize/dotnet | src/CQRS/EntityFrameworkCore/EntityCommand.cs | 710 | C# |
using Entitas;
/// <summary>
/// A marker to identify the Entity within each context that holds Unique Components
/// </summary>
public class UniqueComponentsHolder : IComponent
{
}
| 18.5 | 84 | 0.740541 | [
"MIT"
] | jeffvella/EntitasGenerics | Assets/Libs/Entitas-Generics/Components/UniqueComponents.cs | 187 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.CodeAnalysis.CSharp;
using Moq;
using Xunit;
namespace Microsoft.CodeAnalysis.Razor
{
public class CompilationTagHelperFeatureTest
{
[Fact]
public void IsValidCompilation_ReturnsTrueIfTagHelperInterfaceCannotBeFound()
{
// Arrange
var references = new[]
{
MetadataReference.CreateFromFile(typeof(string).Assembly.Location),
};
var compilation = CSharpCompilation.Create("Test", references: references);
// Act
var result = CompilationTagHelperFeature.IsValidCompilation(compilation);
// Assert
Assert.True(result);
}
[Fact]
public void IsValidCompilation_ReturnsFalseIfSystemStringCannotBeFound()
{
// Arrange
var references = new[]
{
MetadataReference.CreateFromFile(typeof(ITagHelper).Assembly.Location),
};
var compilation = CSharpCompilation.Create("Test", references: references);
// Act
var result = CompilationTagHelperFeature.IsValidCompilation(compilation);
// Assert
Assert.False(result);
}
[Fact]
public void IsValidCompilation_ReturnsTrueIfWellKnownTypesAreFound()
{
// Arrange
var references = new[]
{
MetadataReference.CreateFromFile(typeof(string).Assembly.Location),
MetadataReference.CreateFromFile(typeof(ITagHelper).Assembly.Location),
};
var compilation = CSharpCompilation.Create("Test", references: references);
// Act
var result = CompilationTagHelperFeature.IsValidCompilation(compilation);
// Assert
Assert.True(result);
}
[Fact]
public void GetDescriptors_DoesNotSetCompilation_IfCompilationIsInvalid()
{
// Arrange
Compilation compilation = null;
var provider = new Mock<ITagHelperDescriptorProvider>();
provider
.Setup(c => c.Execute(It.IsAny<TagHelperDescriptorProviderContext>()))
.Callback<TagHelperDescriptorProviderContext>(c => compilation = c.GetCompilation())
.Verifiable();
var engine = RazorProjectEngine.Create(
configure =>
{
configure.Features.Add(new DefaultMetadataReferenceFeature());
configure.Features.Add(provider.Object);
configure.Features.Add(new CompilationTagHelperFeature());
}
);
var feature = engine.EngineFeatures.OfType<CompilationTagHelperFeature>().First();
// Act
var result = feature.GetDescriptors();
// Assert
Assert.Empty(result);
provider.Verify();
Assert.Null(compilation);
}
[Fact]
public void GetDescriptors_SetsCompilation_IfCompilationIsValid()
{
// Arrange
Compilation compilation = null;
var provider = new Mock<ITagHelperDescriptorProvider>();
provider
.Setup(c => c.Execute(It.IsAny<TagHelperDescriptorProviderContext>()))
.Callback<TagHelperDescriptorProviderContext>(c => compilation = c.GetCompilation())
.Verifiable();
var references = new[]
{
MetadataReference.CreateFromFile(typeof(string).Assembly.Location),
MetadataReference.CreateFromFile(typeof(ITagHelper).Assembly.Location),
};
var engine = RazorProjectEngine.Create(
configure =>
{
configure.Features.Add(
new DefaultMetadataReferenceFeature { References = references }
);
configure.Features.Add(provider.Object);
configure.Features.Add(new CompilationTagHelperFeature());
}
);
var feature = engine.EngineFeatures.OfType<CompilationTagHelperFeature>().First();
// Act
var result = feature.GetDescriptors();
// Assert
Assert.Empty(result);
provider.Verify();
Assert.NotNull(compilation);
}
}
}
| 34.34058 | 111 | 0.58008 | [
"Apache-2.0"
] | belav/aspnetcore | src/Razor/Microsoft.CodeAnalysis.Razor/test/CompilationTagHelperFeatureTest.cs | 4,741 | 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("Delegate_Lamda_function")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Delegate_Lamda_function")]
[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("22c0dbc5-2b96-46ff-9ac0-c4387be25883")]
// 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.351351 | 84 | 0.749119 | [
"MIT"
] | donstany/Sand_Box | Delegate_Lamda_function/Properties/AssemblyInfo.cs | 1,422 | 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/strmif.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="IVMRImageCompositor" /> struct.</summary>
public static unsafe partial class IVMRImageCompositorTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IVMRImageCompositor" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IVMRImageCompositor).GUID, Is.EqualTo(IID_IVMRImageCompositor));
}
/// <summary>Validates that the <see cref="IVMRImageCompositor" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IVMRImageCompositor>(), Is.EqualTo(sizeof(IVMRImageCompositor)));
}
/// <summary>Validates that the <see cref="IVMRImageCompositor" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IVMRImageCompositor).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IVMRImageCompositor" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IVMRImageCompositor), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IVMRImageCompositor), Is.EqualTo(4));
}
}
}
| 35.921569 | 145 | 0.694323 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/strmif/IVMRImageCompositorTests.cs | 1,834 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Kujikatsu066.Algorithms;
using Kujikatsu066.Collections;
using Kujikatsu066.Extensions;
using Kujikatsu066.Numerics;
using Kujikatsu066.Questions;
namespace Kujikatsu066.Questions
{
/// <summary>
/// https://atcoder.jp/contests/abc170/tasks/abc170_f
/// </summary>
public class QuestionF : AtCoderQuestionBase
{
public override IEnumerable<object> Solve(TextReader inputStream)
{
const int Inf = 1 << 28;
var (height, width, length) = inputStream.ReadValue<int, int, int>();
var (startRow, startColumn, goalRow, goalColumn) = inputStream.ReadValue<int, int, int, int>();
var canEnter = new bool[height + 2][];
canEnter[0] = Enumerable.Repeat(false, width + 2).ToArray();
canEnter[^1] = Enumerable.Repeat(false, width + 2).ToArray();
for (int row = 0; row < height; row++)
{
canEnter[row + 1] = new[] { false }.Concat(inputStream.ReadLine().Select(c => c == '.')).Concat(new[] { false }).ToArray();
}
int Bfs()
{
var distances = new int[height + 2, width + 2].SetAll((i, j) => Inf);
var seen = new bool[height + 2, width + 2, 4];
distances[startRow, startColumn] = 0;
for (int dir = 0; dir < 4; dir++)
{
seen[startRow, startColumn, dir] = true;
}
const int Left = 0;
const int Right = 1;
const int Up = 2;
const int Down = 3;
var todo = new Queue<(int row, int column)>();
todo.Enqueue((startRow, startColumn));
var directions = new (int dr, int dc, int dir)[] { (-1, 0, Left), (1, 0, Right), (0, -1, Up), (0, 1, Down) };
var stack = new Stack<(int row, int column)>();
while (todo.Count > 0)
{
var (row, column) = todo.Dequeue();
var nextDistance = distances[row, column] + 1;
foreach (var (dr, dc, dir) in directions)
{
var nextRow = row;
var nextColumn = column;
for (int d = 1; d <= length; d++)
{
nextRow += dr;
nextColumn += dc;
if (canEnter[nextRow][nextColumn] && !seen[nextRow, nextColumn, dir])
{
seen[nextRow, nextColumn, dir] = true;
if (distances[nextRow, nextColumn] > nextDistance)
{
distances[nextRow, nextColumn] = nextDistance;
stack.Push((nextRow, nextColumn));
}
}
else
{
break;
}
}
while (stack.Count > 0)
{
todo.Enqueue(stack.Pop());
}
}
}
return distances[goalRow, goalColumn];
}
var result = Bfs();
if (result < Inf)
{
yield return result;
}
else
{
yield return -1;
}
}
}
}
| 35.551402 | 139 | 0.430862 | [
"MIT"
] | terry-u16/AtCoder | Kujikatsu066/Kujikatsu066/Kujikatsu066/Questions/QuestionF.cs | 3,806 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using OpenConfigurator.Core.XmlDAL;
namespace OpenConfigurator.Core.XmlDAL.ModelFile.DataEntities
{
[DataContract]
internal class Feature : iDataEntity
{
// Fields
List<Attribute> attributes = new List<Attribute>();
// Properties
[DataMember(Order = 0)]
public string Identifier
{
get;
set;
}
[DataMember(Order = 1)]
public string Name
{
get;
set;
}
[DataMember(Order = 2)]
public List<Attribute> Attributes
{
get
{
return attributes ?? (attributes = new List<Attribute>());
}
}
[DataMember(Order = 3)]
public Nullable<double> XPos
{
get;
set;
}
[DataMember(Order = 4)]
public Nullable<double> YPos
{
get;
set;
}
}
}
| 21.538462 | 74 | 0.513393 | [
"MIT"
] | rmitache/OpenConfigurator | XmlDAL/ModelFile/DataEntities/Feature.cs | 1,122 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Silky.Core;
using Silky.Core.Rpc;
using Silky.Core.Serialization;
using Silky.Rpc.Messages;
using Silky.Rpc.Transport;
using SkyApm.Tracing;
namespace Silky.Rpc.SkyApm.Diagnostics.Collections
{
public class SilkyCarrierHeaderCollection : ICarrierHeaderDictionary
{
private readonly RpcContext _rpcContext;
public SilkyCarrierHeaderCollection(RpcContext rpcContext)
{
_rpcContext = rpcContext;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _rpcContext.GetContextAttachments()
.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())).GetEnumerator();
}
public void Add(string key, string value)
{
if (_rpcContext.GetContextAttachments().ContainsKey(key))
{
_rpcContext.GetContextAttachments().Remove(key);
}
_rpcContext.GetContextAttachments().Add(key, value);
}
public string Get(string key)
{
if (_rpcContext.GetContextAttachments().TryGetValue(key, out var value))
return value.ToString();
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | 28.24 | 106 | 0.631728 | [
"MIT"
] | scjjcs/silky | framework/src/Silky.SkyApm.Diagnostics/Collections/SilkyCarrierHeaderCollection.cs | 1,412 | C# |
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using AutoFixture.Idioms;
using EMG.Extensions.DependencyInjection.Discovery;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Tests
{
public class ServiceCollectionDiscoveryExtensionsTests
{
[Test, CustomAutoData]
public void AddServiceDiscovery_registers_IDiscoveryService(ServiceCollection services)
{
services.AddServiceDiscoveryAdapter();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetRequiredService<IDiscoveryService>();
Assert.That(service, Is.Not.Null);
}
[Test, CustomAutoData]
public void AddServiceDiscovery_registers_IBindingFactory(ServiceCollection services)
{
services.AddServiceDiscoveryAdapter();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetRequiredService<IBindingFactory>();
Assert.That(service, Is.Not.Null);
}
[Test, CustomAutoData]
public void AddServiceDiscovery_does_not_accept_nulls(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(ServiceCollectionDiscoveryExtensions).GetMethod(nameof(ServiceCollectionDiscoveryExtensions.AddServiceDiscoveryAdapter)));
}
[Test, CustomAutoData]
public void ConfigureServiceDiscovery_configures_options_with_delegate(ServiceCollection services, Action<NetTcpDiscoveryOptions> configureOptions)
{
services.ConfigureServiceDiscovery(configureOptions);
var serviceProvider = services.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<NetTcpDiscoveryOptions>>();
Mock.Get(configureOptions).Verify(p => p(options.Value));
}
[Test, CustomAutoData]
public void ConfigureServiceDiscovery_configures_options_with_configuration(ServiceCollection services, ConfigurationBuilder configurationBuilder, string sectionName, Uri probeEndpoint)
{
configurationBuilder.AddInMemoryCollection(new Dictionary<string, string>
{
[$"{sectionName}:ProbeEndpoint"] = probeEndpoint.ToString()
});
var configuration = configurationBuilder.Build();
services.ConfigureServiceDiscovery(configuration.GetSection(sectionName));
var serviceProvider = services.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<NetTcpDiscoveryOptions>>();
Assert.That(options.Value.ProbeEndpoint, Is.EqualTo(probeEndpoint));
}
[Test, CustomAutoData]
public void ConfigureServiceDiscovery_does_not_accept_nulls(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(ServiceCollectionDiscoveryExtensions).GetRuntimeMethods().Where(m => m.Name == nameof(ServiceCollectionDiscoveryExtensions.ConfigureServiceDiscovery)));
}
[Test, CustomAutoData]
public void DiscoverServiceUsingAdapter_registers_service_using_discovery(ServiceCollection services, ServiceLifetime lifetime, ITestService testService, IDiscoveryService discoveryService, IBindingFactory bindingFactory)
{
services.DiscoverServiceUsingAdapter<ITestService>(lifetime);
services.AddSingleton<IBindingFactory>(bindingFactory);
services.AddSingleton<IDiscoveryService>(discoveryService);
Mock.Get(discoveryService).Setup(p => p.Discover<ITestService>(It.IsAny<NetTcpBinding>())).Returns(testService);
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetRequiredService<ITestService>();
Assert.That(service, Is.SameAs(testService));
}
[Test, CustomAutoData]
public void AddServiceBindingCustomization_does_not_accept_nulls(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(ServiceCollectionDiscoveryExtensions).GetRuntimeMethods().Where(m => m.Name == nameof(ServiceCollectionDiscoveryExtensions.AddServiceBindingCustomization)));
}
[Test, CustomAutoData]
public void AddServiceBindingCustomization_registers_binding_customization_for_service(ServiceCollection services, Action<NetTcpBinding> bindingCustomization)
{
services.AddServiceBindingCustomization<ITestService>(bindingCustomization);
var serviceProvider = services.BuildServiceProvider();
var customization = serviceProvider.GetRequiredService<IBindingFactoryCustomization>();
_ = customization.Create();
Mock.Get(bindingCustomization).Verify(p => p(It.IsAny<NetTcpBinding>()), Times.Once());
}
[Test, CustomAutoData]
public void AddBindingCustomization_does_not_accept_nulls(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(ServiceCollectionDiscoveryExtensions).GetRuntimeMethods().Where(m => m.Name == nameof(ServiceCollectionDiscoveryExtensions.AddBindingCustomization)));
}
[Test, CustomAutoData]
public void AddBindingCustomization_registers_customization_by_type(ServiceCollection services)
{
services.AddBindingCustomization<TestCustomization>();
var serviceProvider = services.BuildServiceProvider();
var customization = serviceProvider.GetRequiredService<IBindingFactoryCustomization>();
Assert.That(customization, Is.InstanceOf<TestCustomization>());
}
[Test, CustomAutoData]
public void AddBindingCustomization_registers_binding_customization(ServiceCollection services, Action<NetTcpBinding> bindingCustomization)
{
services.AddBindingCustomization(bindingCustomization);
var serviceProvider = services.BuildServiceProvider();
var customization = serviceProvider.GetRequiredService<IBindingFactoryCustomization>();
_ = customization.Create();
Mock.Get(bindingCustomization).Verify(p => p(It.IsAny<NetTcpBinding>()), Times.Once());
}
}
} | 41.432258 | 229 | 0.722205 | [
"MIT"
] | Josephson199/dotnet-extensions | tests/DependencyInjection/Tests.ServiceModel.DiscoveryAdapter/ServiceCollectionDiscoveryExtensionsTests.cs | 6,422 | C# |
// -----------------------------------------------------------------------
// Copyright 2018 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FeatureCAM;
namespace FeatureCAMToNCSIMUL
{
class UCS
{
public FeatureCAM.FMUcs ucs;
public string name;
public double x, y, z,
i, j, k;
public UCS() { }
public UCS(FeatureCAM.FMUcs fc_ucs)
{
this.ucs = fc_ucs;
this.name = fc_ucs.Name;
this.ucs.GetLocation(out x, out y, out z);
this.x = Math.Round(x, 4);
this.y = Math.Round(y, 4);
this.z = Math.Round(z, 4);
ComputeEulerAngles();
}
private void ComputeEulerAngles()
{
double
x1, y1, z1,
x2, y2, z2,
x3, y3, z3,
i1, j1, k1,
j1_rad;
this.ucs.GetVectors(out x1, out x2, out x3, out y1, out y2, out y3, out z1, out z2, out z3);
if (z1 != 1 && z1 != -1)
{
j1_rad = -Math.Asin(x3);
j1 = Lib.Radians2Degrees(j1_rad);
i1 = Lib.Radians2Degrees(Math.Atan2(y3 / Math.Cos(j1_rad), z3 / Math.Cos(j1_rad)));
k1 = Lib.Radians2Degrees(Math.Atan2(x2 / Math.Cos(j1_rad), x1 / Math.Cos(j1_rad)));
this.i = i1;
this.j = j1;
this.k = k1;
}
else
{
this.k = 0;
if (z1 == -1)
{
this.j = 90;
this.i = k + Lib.Radians2Degrees(Math.Atan2(x2, x3));
}
else
{
this.j = -90;
this.i = -k + Lib.Radians2Degrees(Math.Atan2(-x2, -x3));
}
}
this.i = Math.Round(this.i, 4);
this.j = Math.Round(this.j, 4);
this.k = Math.Round(this.k, 4);
}
}
class SetupInfo
{
public List<UCS> ucss;
public string
tool_fpath,
nc_fpath,
name,
first_ucs_name;
public int num_features;
public bool enabled;
public SetupInfo() { }
public SetupInfo(FeatureCAM.FMSetup setup)
{
this.name = setup.Name;
this.enabled = setup.Enabled;
this.num_features = setup.Features.Count;
this.tool_fpath = "";
this.nc_fpath = "";
if (this.ucss == null) this.ucss = new List<UCS>();
this.ucss.Add(new UCS(setup.ucs));
this.first_ucs_name = setup.ucs.Name;
}
}
public class Turret
{
public bool available = false;
public bool is_milling_head = false;
public Turret() { }
}
public class SolidInfo
{
public FeatureCAM.FMSolid solid;
public bool is_export;
public SolidInfo(FMSolid solid_obj, bool export_solid)
{
solid = solid_obj;
is_export = export_solid;
}
}
static class Variables
{
public static FeatureCAM.FMDocument doc = null;
public static FeatureCAM.FMStock stock = null;
public static bool is_export_project = true;
public static string file_dirpath = "",
output_dirpath = "";
public static string prev_doc_name = "";
public static List<SolidInfo> clamps;
public static List<string> clamp_fpaths;
public static string ncsimul_path = "",
ncsimul_md_files_dir = "";
public static double offset_x, offset_y, offset_z;
public static FeatureCAM.FMPoint offset_pt = null;
public static string
stock_fpath = "";
public static string
output_msg = "",
unsupported_tool_names = "";
public static List<string> setup_names = null;
public static bool
is_single_program,
are_all_setups_milling = true;
public static int selected_setup_id;
public static bool orig_single_stock = false;
public static string warning_msg;
public static List<SetupInfo> setups_info;
public static int num_enabled_setups;
public static Turret
lsss = new Turret(),
usss = new Turret(),
lmss = new Turret(),
umss = new Turret();
public static void Cleanup()
{
doc = null;
warning_msg = "";
if (setups_info != null)
{
for (int i = 0; i < setups_info.Count; i++)
setups_info[i] = null;
setups_info.Clear();
setups_info = null;
}
if (clamps != null)
{
for (int i = 0; i < clamps.Count; i++)
clamps[i] = null;
clamps.Clear();
clamps = null;
}
if (clamp_fpaths != null)
{
clamp_fpaths.Clear();
clamp_fpaths = null;
}
output_msg = "";
num_enabled_setups = 0;
}
}
}
| 29.05102 | 104 | 0.479628 | [
"BSD-3-Clause"
] | Autodesk/featurecam-api-examples | addin-featurecam-to-ncsimul/SourceCode/Variables.cs | 5,696 | C# |
using System.Collections.Generic;
using System.Linq;
namespace com.snake.framework
{
namespace runtime
{
/// <summary>
/// 下载管理器
/// </summary>
public class DownloadManager : BaseManager
{
/// <summary>
/// 下载任务列表
/// </summary>
private List<DownloadTask> _downloadingList;
/// <summary>
/// 下载速度刷新时间(秒)
/// </summary>
private float mUpdateDownloadSpeedInterval = 1;
/// <summary>
/// 并行下载数量,(默认5个)
/// </summary>
public int mMaxDownloadTaskCount = 5;
/// <summary>
/// 下载速度开关
/// </summary>
public bool mActiveDownloadSpeedMonitor { get; private set; } = false;
/// <summary>
/// 下载速度
/// </summary>
public long mDownloadSpeed { get; private set; } = 0;
/// <summary>
/// 下载的总大小
/// </summary>
public long mTotalDownloadSize { get; private set; } = 0;
/// <summary>
/// 是否下载中
/// </summary>
public bool mDownloading { get; private set; } = false;
/// <summary>
/// 完成所有下载任务的回调
/// </summary>
public System.Action mOnCompleted { get; private set; }
//上一次记录下载速度时间
private float _prevTickDownloadSpeedTime = 0;
//上一次记录下载大小
private long _prevTickDownloadedSize = 0;
protected override void onInitialization()
{
this._downloadingList = new List<DownloadTask>();
}
/// <summary>
/// 计算已经完成下载的大小
/// </summary>
public long GetCurrDownLoadSize()
{
long downloadingSize = 0;
for (var i = 0; i < _downloadingList.Count; i++)
{
DownloadTask task = _downloadingList[i];
switch (task.mState)
{
case DownloadTask.STATE.success:
downloadingSize += task.mTotalSize;
break;
case DownloadTask.STATE.downloading:
downloadingSize += (long)(task.mTotalSize * task.mProgress);
break;
default:
break;
}
}
return downloadingSize;
}
/// <summary>
/// 下载速度监控开关
/// </summary>
public void SetDownloadSpeedMonitor(bool active)
{
if (mActiveDownloadSpeedMonitor == active)
return;
mActiveDownloadSpeedMonitor = active;
}
/// <summary>
/// 开始下载
/// </summary>
/// <param name="downloadFilePathQueue"></param>
/// <param name="downloadingCallback"></param>
/// <param name="finishCallback"></param>
async public void StartDownload(string url, string savePath, int priority = 0, bool backGround = false)
{
if (mDownloading == false)
{
mDownloading = true;
mFramework.mLifeCycle.mUpdateHandle.AddEventHandler(onDownloadProcess);
}
DownloadTask downloadTask = ReferencePool.Take<DownloadTask>();
downloadTask.SetBackGround(backGround);
_downloadingList.Add(downloadTask);
await downloadTask.SetDownloadInfo(url, savePath);
this.mTotalDownloadSize += downloadTask.mTotalSize;
if (priority > 0)
{
downloadTask.mPriority = priority;
sortPriority();
}
}
/// <summary>
/// 获取下载出错的信息
/// </summary>
/// <returns></returns>
public string[] GetDownloadErrorInfos()
{
if (this._downloadingList.Count == 0)
return new string[0];
string[] errors = new string[this._downloadingList.Count];
for (int i = 0; i < this._downloadingList.Count; i++)
errors[i] = this._downloadingList[i].mURL;
return errors;
}
/// <summary>
/// 获取已经获取web头,但未开始下载的数量
/// </summary>
/// <returns></returns>
public int GetReadyTaskCount()
{
if (this._downloadingList == null)
return 0;
int count = 0;
for (int i = 0; i < this._downloadingList.Count; i++)
count += this._downloadingList[i].mState == DownloadTask.STATE.ready ? 1 : 0;
return count;
}
/// <summary>
/// 下载过程监控
/// </summary>
/// <param name="frameCount"></param>
/// <param name="time"></param>
/// <param name="deltaTime"></param>
/// <param name="unscaledTime"></param>
/// <param name="realElapseSeconds"></param>
private void onDownloadProcess(int frameCount, float time, float deltaTime, float unscaledTime, float realElapseSeconds)
{
int downloadCount = this._downloadingList.Sum(a => a.mState == DownloadTask.STATE.downloading ? 1 : 0);
if (this.mMaxDownloadTaskCount > downloadCount)
{
int index = _downloadingList.FindIndex(a => a.mState == DownloadTask.STATE.ready);
if (index >= 0)
_downloadingList[index].StartDownLoad();
}
//监控下载速度
if (mActiveDownloadSpeedMonitor == true)
internalUpdateDownloadSpeed(realElapseSeconds);
//如果全部完成,移除tick生命周期
foreach (var a in _downloadingList)
{
if (a.mIsDone == false)
return;
}
mFramework.mLifeCycle.mUpdateHandle.RemoveEventHandler(onDownloadProcess);
this.mOnCompleted?.Invoke();
//重置环境
reset();
}
/// <summary>
/// 优先级排序
/// </summary>
private void sortPriority()
{
_downloadingList.Sort((left, right) =>
{
return left.mPriority.CompareTo(right.mPriority);
});
}
/// <summary>
/// 更新下载速度
/// </summary>
/// <param name="realElapseSeconds"></param>
private void internalUpdateDownloadSpeed(float realElapseSeconds)
{
if (realElapseSeconds - _prevTickDownloadSpeedTime < 1.0f)
return;
long downloadedSize = GetCurrDownLoadSize();
long detailSize = downloadedSize - _prevTickDownloadedSize;
this.mDownloadSpeed = (long)(detailSize / mUpdateDownloadSpeedInterval);
_prevTickDownloadSpeedTime = realElapseSeconds;
_prevTickDownloadedSize = downloadedSize;
}
/// <summary>
/// 重置环境
/// </summary>
private void reset()
{
this._prevTickDownloadSpeedTime = 0;
this._prevTickDownloadedSize = 0;
_downloadingList?.Clear();
mOnCompleted = null;
mDownloading = false;
mActiveDownloadSpeedMonitor = false;
mDownloadSpeed = 0;
mTotalDownloadSize = 0;
}
}
}
} | 35.377682 | 133 | 0.451899 | [
"MIT"
] | ClaineLe/SnakeFramework-Develop | Assets/UnityPackages/com.snake.framework.core/Runtime/Core/Implement/Managers/DownloadManager/DownloadManager.cs | 8,603 | C# |
using System.Collections.Generic;
using Pulsee1.Utils.Mathp;
using Pulsee1.Utils.Display;
using System.Linq;
using OpenTK;
using System;
namespace Pulsee1.Game.LevelGenerators.Generators
{
class FloorGenerator
{
private Vector2 _floorSize = new Vector2(20, 20);
private Dictionary<Vector2, char> _rooms = new Dictionary<Vector2, char>();
private List<Vector2> _takenPos = new List<Vector2>();
private int _roomNumber = 100;
private float _seed;
public FloorGenerator()
{
xConsole.WarningInstanceUnstable(this);
return;
}
public FloorGenerator(Vector2 size_, float seed_ = 0.6f, int roomNumber_ = 100)
{
xConsole.WriteLine("Generating Floor");
xConsole.WriteLine("Initializing", ConsoleColor.Yellow);
this._floorSize = new Vector2(20, 20);
this._seed = seed_;
this._roomNumber = roomNumber_;
return;
}
public Floor GenerateFloor()
{
BFSFilling();
Console.WriteLine("Number of rooms : " + _takenPos.Count);
return new Floor(_rooms);
}
private void BFSFilling()
{
Queue<Vector2> stroller = new Queue<Vector2>();
Vector2 startPos = new Vector2(((int)Math.Floor(_floorSize.X / 2.0)), ((int)Math.Floor(_floorSize.Y / 2.0)));
_takenPos.Add(startPos);
_rooms.Add(startPos, (char)RoomCharacter.start);
while (_takenPos.Count <= _roomNumber)
{
stroller.Clear();
stroller.Enqueue(startPos);
for (int index = 0; index < (_floorSize.X * _floorSize.Y); index++)
{
List<Vector2> gypsy = GitGudDirections(stroller.ElementAt<Vector2>(index));
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < gypsy.Count; j++)
{
if (!(stroller.Contains(gypsy[j])))
{
stroller.Enqueue(gypsy[j]);
RoomInstaller(index, gypsy[j]);
}
if (_takenPos.Count >= _roomNumber)
return;
}//end checking direction
}//end browsing directions
}//end browsing map
}//end while
}
private List<Vector2> GitGudDirections(Vector2 currentPos_)
{
List<Vector2> gud = new List<Vector2>();
if (currentPos_.X - 1 >= 0)
gud.Add(new Vector2(currentPos_.X - 1, currentPos_.Y));
if (currentPos_.Y - 1 >= 0)
gud.Add(new Vector2(currentPos_.X, currentPos_.Y - 1));
if (currentPos_.X + 1 <= _floorSize.X - 1)
gud.Add(new Vector2(currentPos_.X + 1, currentPos_.Y));
if (currentPos_.Y + 1 <= _floorSize.Y - 1)
gud.Add(new Vector2(currentPos_.X, currentPos_.Y + 1));
return gud;
}
private bool HasNeighbor(List<Vector2> takenPos, Vector2 pos)
{
List<Vector2> udlr = GitGudDirections(pos);
foreach (Vector2 coordinate in udlr)
if (takenPos.Contains(coordinate))
return true;
return false;
}
private void RoomInstaller(int index, Vector2 currElem)
{
if (index <= 4 || HasNeighbor(_takenPos, currElem) && (xRandom.GetRandomNumber() / 100 <= _seed))
{
_takenPos.Add(currElem);
_rooms.Add(currElem, (_takenPos.Count == _roomNumber - 1) ? (char)RoomCharacter.finish : (char)RoomCharacter.regular);
}
}
}
public enum RoomCharacter
{
start = 'S',
finish = 'F',
regular = 'X'
};
}
| 35.415929 | 134 | 0.513243 | [
"MIT"
] | Pandav0x/RogueTest | RogueTest/Temp/Generators/LevelGenerators/FloorGenerator.cs | 4,004 | C# |
namespace SolidPrinciples.InterfaceSegregationPrinciple.WithoutPrinciple.Client;
public class CannonMg2470 : IPrintTasks
{
public bool PrintContent(string content)
{
Console.WriteLine("Printing...");
return true;
}
public bool ScanContent(string content)
{
Console.WriteLine("Printing...");
return true;
}
public bool FaxContent(string content)
{
// The Cannon MG 2470 does not have fax capabilities
throw new NotImplementedException();
}
public bool PhotocopyContent(string content)
{
Console.WriteLine("Printing...");
return true;
}
public bool PrintDuplexContent(string content)
{
throw new NotImplementedException();
}
} | 23.090909 | 81 | 0.650919 | [
"MIT"
] | pncsoares/dotnet-solid-principles | InterfaceSegregationPrinciple/WithoutPrinciple/Client/CannonMg2470.cs | 764 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using static Interop;
using static Interop.Ole32;
namespace System.Windows.Forms
{
/// <summary>
/// This class implements the necessary interfaces required for an ActiveX site.
///
/// This class is public, but has an internal constructor so that external
/// users can only reference the Type (cannot instantiate it directly).
/// Other classes have to inherit this class and expose it to the outside world.
///
/// This class does not have any public property/method/event by itself.
/// All implementations of the site interface methods are private, which
/// means that inheritors who want to override even a single method of one
/// of these interfaces will have to implement the whole interface.
/// </summary>
public class WebBrowserSiteBase :
IOleControlSite,
IOleInPlaceSite,
IOleClientSite,
ISimpleFrameSite,
IPropertyNotifySink,
IDisposable
{
private readonly WebBrowserBase host;
private AxHost.ConnectionPointCookie connectionPoint;
//
// The constructor takes an WebBrowserBase as a parameter, so unfortunately,
// this cannot be used as a standalone site. It has to be used in conjunction
// with WebBrowserBase. Perhaps we can change it in future.
//
internal WebBrowserSiteBase(WebBrowserBase h)
{
host = h ?? throw new ArgumentNullException(nameof(h));
}
/// <summary>
/// Dispose(release the cookie)
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Release the cookie if we're disposing
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
StopEvents();
}
}
/// <summary>
/// Retrieves the WebBrowserBase object set in the constructor.
/// </summary>
internal WebBrowserBase Host
{
get
{
return host;
}
}
// IOleControlSite methods:
HRESULT IOleControlSite.OnControlInfoChanged()
{
return HRESULT.S_OK;
}
HRESULT IOleControlSite.LockInPlaceActive(BOOL fLock)
{
return HRESULT.E_NOTIMPL;
}
unsafe HRESULT IOleControlSite.GetExtendedControl(IntPtr* ppDisp)
{
if (ppDisp is null)
{
return HRESULT.E_POINTER;
}
*ppDisp = IntPtr.Zero;
return HRESULT.E_NOTIMPL;
}
unsafe HRESULT IOleControlSite.TransformCoords(Point* pPtlHimetric, PointF* pPtfContainer, XFORMCOORDS dwFlags)
{
if (pPtlHimetric is null || pPtfContainer is null)
{
return HRESULT.E_POINTER;
}
if ((dwFlags & XFORMCOORDS.HIMETRICTOCONTAINER) != 0)
{
if ((dwFlags & XFORMCOORDS.SIZE) != 0)
{
pPtfContainer->X = (float)WebBrowserHelper.HM2Pix(pPtlHimetric->X, WebBrowserHelper.LogPixelsX);
pPtfContainer->Y = (float)WebBrowserHelper.HM2Pix(pPtlHimetric->Y, WebBrowserHelper.LogPixelsY);
}
else if ((dwFlags & XFORMCOORDS.POSITION) != 0)
{
pPtfContainer->X = (float)WebBrowserHelper.HM2Pix(pPtlHimetric->X, WebBrowserHelper.LogPixelsX);
pPtfContainer->Y = (float)WebBrowserHelper.HM2Pix(pPtlHimetric->Y, WebBrowserHelper.LogPixelsY);
}
else
{
return HRESULT.E_INVALIDARG;
}
}
else if ((dwFlags & XFORMCOORDS.CONTAINERTOHIMETRIC) != 0)
{
if ((dwFlags & XFORMCOORDS.SIZE) != 0)
{
pPtlHimetric->X = WebBrowserHelper.Pix2HM((int)pPtfContainer->X, WebBrowserHelper.LogPixelsX);
pPtlHimetric->Y = WebBrowserHelper.Pix2HM((int)pPtfContainer->Y, WebBrowserHelper.LogPixelsY);
}
else if ((dwFlags & XFORMCOORDS.POSITION) != 0)
{
pPtlHimetric->X = WebBrowserHelper.Pix2HM((int)pPtfContainer->X, WebBrowserHelper.LogPixelsX);
pPtlHimetric->Y = WebBrowserHelper.Pix2HM((int)pPtfContainer->Y, WebBrowserHelper.LogPixelsY);
}
else
{
return HRESULT.E_INVALIDARG;
}
}
else
{
return HRESULT.E_INVALIDARG;
}
return HRESULT.S_OK;
}
unsafe HRESULT IOleControlSite.TranslateAccelerator(User32.MSG* pMsg, KEYMODIFIERS grfModifiers)
{
if (pMsg is null)
{
return HRESULT.E_POINTER;
}
Debug.Assert(!Host.GetAXHostState(WebBrowserHelper.siteProcessedInputKey), "Re-entering IOleControlSite.TranslateAccelerator!!!");
Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, true);
Message msg = *pMsg;
try
{
bool f = ((Control)Host).PreProcessControlMessage(ref msg) == PreProcessControlState.MessageProcessed;
return f ? HRESULT.S_OK : HRESULT.S_FALSE;
}
finally
{
Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false);
}
}
HRESULT IOleControlSite.OnFocus(BOOL fGotFocus) => HRESULT.S_OK;
HRESULT IOleControlSite.ShowPropertyFrame() => HRESULT.E_NOTIMPL;
// IOleClientSite methods:
HRESULT IOleClientSite.SaveObject() => HRESULT.E_NOTIMPL;
unsafe HRESULT IOleClientSite.GetMoniker(OLEGETMONIKER dwAssign, OLEWHICHMK dwWhichMoniker, IntPtr* ppmk)
{
if (ppmk is null)
{
return HRESULT.E_POINTER;
}
*ppmk = IntPtr.Zero;
return HRESULT.E_NOTIMPL;
}
IOleContainer IOleClientSite.GetContainer()
{
return Host.GetParentContainer();
}
unsafe HRESULT IOleClientSite.ShowObject()
{
if (Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive)
{
IntPtr hwnd = IntPtr.Zero;
if (Host.AXInPlaceObject.GetWindow(&hwnd).Succeeded())
{
if (Host.GetHandleNoCreate() != hwnd)
{
if (hwnd != IntPtr.Zero)
{
Host.AttachWindow(hwnd);
RECT posRect = Host.Bounds;
OnActiveXRectChange(&posRect);
}
}
}
else if (Host.AXInPlaceObject is IOleInPlaceObjectWindowless)
{
throw new InvalidOperationException(SR.AXWindowlessControl);
}
}
return HRESULT.S_OK;
}
HRESULT IOleClientSite.OnShowWindow(BOOL fShow) => HRESULT.S_OK;
HRESULT IOleClientSite.RequestNewObjectLayout() => HRESULT.E_NOTIMPL;
// IOleInPlaceSite methods:
unsafe HRESULT IOleInPlaceSite.GetWindow(IntPtr* phwnd)
{
if (phwnd is null)
{
return HRESULT.E_POINTER;
}
*phwnd = User32.GetParent(Host);
return HRESULT.S_OK;
}
HRESULT IOleInPlaceSite.ContextSensitiveHelp(BOOL fEnterMode) => HRESULT.E_NOTIMPL;
HRESULT IOleInPlaceSite.CanInPlaceActivate() => HRESULT.S_OK;
unsafe HRESULT IOleInPlaceSite.OnInPlaceActivate()
{
Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive;
RECT posRect = Host.Bounds;
OnActiveXRectChange(&posRect);
return HRESULT.S_OK;
}
HRESULT IOleInPlaceSite.OnUIActivate()
{
Host.ActiveXState = WebBrowserHelper.AXState.UIActive;
Host.GetParentContainer().OnUIActivate(Host);
return HRESULT.S_OK;
}
unsafe HRESULT IOleInPlaceSite.GetWindowContext(
out IOleInPlaceFrame ppFrame,
out IOleInPlaceUIWindow ppDoc,
RECT* lprcPosRect,
RECT* lprcClipRect,
OLEINPLACEFRAMEINFO* lpFrameInfo)
{
ppDoc = null;
ppFrame = Host.GetParentContainer();
if (lprcPosRect is null || lprcClipRect is null)
{
return HRESULT.E_POINTER;
}
*lprcPosRect = Host.Bounds;
*lprcClipRect = WebBrowserHelper.GetClipRect();
if (lpFrameInfo is not null)
{
lpFrameInfo->cb = (uint)Marshal.SizeOf<OLEINPLACEFRAMEINFO>();
lpFrameInfo->fMDIApp = BOOL.FALSE;
lpFrameInfo->hAccel = IntPtr.Zero;
lpFrameInfo->cAccelEntries = 0;
lpFrameInfo->hwndFrame = (Host.ParentInternal is null) ? IntPtr.Zero : Host.ParentInternal.Handle;
}
return HRESULT.S_OK;
}
HRESULT IOleInPlaceSite.Scroll(Size scrollExtant) => HRESULT.S_FALSE;
HRESULT IOleInPlaceSite.OnUIDeactivate(BOOL fUndoable)
{
Host.GetParentContainer().OnUIDeactivate(Host);
if (Host.ActiveXState > WebBrowserHelper.AXState.InPlaceActive)
{
Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive;
}
return HRESULT.S_OK;
}
HRESULT IOleInPlaceSite.OnInPlaceDeactivate()
{
if (Host.ActiveXState == WebBrowserHelper.AXState.UIActive)
{
((IOleInPlaceSite)this).OnUIDeactivate(0);
}
Host.GetParentContainer().OnInPlaceDeactivate(Host);
Host.ActiveXState = WebBrowserHelper.AXState.Running;
return HRESULT.S_OK;
}
HRESULT IOleInPlaceSite.DiscardUndoState() => HRESULT.S_OK;
HRESULT IOleInPlaceSite.DeactivateAndUndo() => Host.AXInPlaceObject.UIDeactivate();
unsafe HRESULT IOleInPlaceSite.OnPosRectChange(RECT* lprcPosRect) => OnActiveXRectChange(lprcPosRect);
// ISimpleFrameSite methods:
unsafe HRESULT ISimpleFrameSite.PreMessageFilter(IntPtr hWnd, uint msg, IntPtr wp, IntPtr lp, IntPtr* plResult, uint* pdwCookie)
{
return HRESULT.S_OK;
}
unsafe HRESULT ISimpleFrameSite.PostMessageFilter(IntPtr hWnd, uint msg, IntPtr wp, IntPtr lp, IntPtr* plResult, uint dwCookie)
{
return HRESULT.S_FALSE;
}
// IPropertyNotifySink methods:
HRESULT IPropertyNotifySink.OnChanged(DispatchID dispid)
{
// Some controls fire OnChanged() notifications when getting values of some properties.
// To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call.
if (Host.NoComponentChangeEvents != 0)
{
return HRESULT.S_OK;
}
Host.NoComponentChangeEvents++;
try
{
OnPropertyChanged(dispid);
}
catch (Exception t)
{
Debug.Fail(t.ToString());
throw;
}
finally
{
Host.NoComponentChangeEvents--;
}
return HRESULT.S_OK;
}
HRESULT IPropertyNotifySink.OnRequestEdit(DispatchID dispid)
{
return HRESULT.S_OK;
}
internal virtual void OnPropertyChanged(DispatchID dispid)
{
try
{
ISite site = Host.Site;
if (site is not null)
{
IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (changeService is not null)
{
try
{
changeService.OnComponentChanging(Host, null);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw;
}
// Now notify the change service that the change was successful.
//
changeService.OnComponentChanged(Host, null, null, null);
}
}
}
catch (Exception t)
{
Debug.Fail(t.ToString());
throw;
}
}
internal void StartEvents()
{
if (connectionPoint is not null)
{
return;
}
object nativeObject = Host.activeXInstance;
if (nativeObject is not null)
{
try
{
connectionPoint = new AxHost.ConnectionPointCookie(nativeObject, this, typeof(IPropertyNotifySink));
}
catch (Exception ex)
{
if (ClientUtils.IsCriticalException(ex))
{
throw;
}
}
}
}
internal void StopEvents()
{
if (connectionPoint is not null)
{
connectionPoint.Disconnect();
connectionPoint = null;
}
}
private unsafe HRESULT OnActiveXRectChange(RECT* lprcPosRect)
{
if (lprcPosRect is null)
{
return HRESULT.E_INVALIDARG;
}
var posRect = new RECT(0, 0, lprcPosRect->right - lprcPosRect->left, lprcPosRect->bottom - lprcPosRect->top);
var clipRect = WebBrowserHelper.GetClipRect();
Host.AXInPlaceObject.SetObjectRects(&posRect, &clipRect);
Host.MakeDirty();
return HRESULT.S_OK;
}
}
}
| 33.384787 | 142 | 0.538632 | [
"MIT"
] | abdullah1133/winforms | src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs | 14,925 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Online.Store.Models.ManageViewModels
{
public class TwoFactorAuthenticationViewModel
{
public bool HasAuthenticator { get; set; }
public int RecoveryCodesLeft { get; set; }
public bool Is2faEnabled { get; set; }
}
}
| 22.666667 | 50 | 0.727941 | [
"MIT"
] | chsakell/planet-scale-azure | Online.Store/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs | 410 | C# |
using CustomGamemode;
using GamemodeManager.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GamemodeManager
{
internal class GamemodeLoader
{
internal List<object> LoadedGamemodes { get; set; }
internal List<string> NextRoundGamemodes { get; set; }
private string _gamemodeDirectory;
public GamemodeLoader(string gamemodeDirectory)
{
_gamemodeDirectory = gamemodeDirectory;
LoadedGamemodes = new List<object>();
NextRoundGamemodes = new List<string>();
}
//[Credits] Assembly-Loading inspired by Synapse.
public void LoadGamemodes()
{
if (!Directory.Exists(_gamemodeDirectory))
Directory.CreateDirectory(_gamemodeDirectory);
var gamemodePaths = Directory.GetFiles(_gamemodeDirectory, "*.dll").ToList();
var gamemodeDict = new Dictionary<Type, List<Type>>();
foreach (var gamemodePath in gamemodePaths)
{
try
{
var gamemodeAssembly = Assembly.Load(File.ReadAllBytes(gamemodePath));
foreach (var type in gamemodeAssembly.GetTypes())
{
if (!typeof(IGamemode).IsAssignableFrom(type))
continue;
var allTypes = gamemodeAssembly.GetTypes().ToList();
allTypes.Remove(type);
gamemodeDict.Add(type, allTypes);
break;
}
}
catch (Exception e)
{
SynapseController.Server.Logger.Info($"{Path.GetFileName(gamemodePath)} failed to load.\n{e.StackTrace}");
}
}
foreach (var infoTypePair in gamemodeDict)
{
try
{
SynapseController.Server.Logger.Info($"{infoTypePair.Key.Name} will now be activated!");
object gamemode = Activator.CreateInstance(infoTypePair.Key);
LoadedGamemodes.Add(gamemode);
}
catch (Exception e)
{
SynapseController.Server.Logger.Error($"Instantiating {infoTypePair.Key.Assembly.GetName().Name} failed!\n{e}");
}
}
foreach (var gamemode in LoadedGamemodes)
SynapseController.Server.Logger.Info(((IGamemode)gamemode).ToInfoString());
}
}
}
| 33.35443 | 132 | 0.544592 | [
"Apache-2.0"
] | AlmightyLks/GamemodeManager | GamemodeManager/GamemodeLoader.cs | 2,637 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ce-2017-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.CostExplorer.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CostExplorer.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetReservationUtilization operation
/// </summary>
public class GetReservationUtilizationResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetReservationUtilizationResponse response = new GetReservationUtilizationResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("NextPageToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextPageToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Total", targetDepth))
{
var unmarshaller = ReservationAggregatesUnmarshaller.Instance;
response.Total = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UtilizationsByTime", targetDepth))
{
var unmarshaller = new ListUnmarshaller<UtilizationByTime, UtilizationByTimeUnmarshaller>(UtilizationByTimeUnmarshaller.Instance);
response.UtilizationsByTime = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("DataUnavailableException"))
{
return DataUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidNextTokenException"))
{
return InvalidNextTokenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonCostExplorerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetReservationUtilizationResponseUnmarshaller _instance = new GetReservationUtilizationResponseUnmarshaller();
internal static GetReservationUtilizationResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetReservationUtilizationResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.676923 | 196 | 0.62643 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CostExplorer/Generated/Model/Internal/MarshallTransformations/GetReservationUtilizationResponseUnmarshaller.cs | 5,418 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#define WLT_ARCORE_EXTRA_DEBUGGING
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if WLT_ARCORE_SDK_INCLUDED
using GoogleARCore;
#endif // WLT_ARCORE_SDK_INCLUDED
namespace Microsoft.MixedReality.WorldLocking.Core
{
public class SpongyAnchorARCore : SpongyAnchor
{
public static float TrackingStartDelayTime = 0.3f;
private float lastNotLocatedTime = float.NegativeInfinity;
#if WLT_ARCORE_SDK_INCLUDED
private GoogleARCore.Anchor internalAnchor = null;
#endif // WLT_ARCORE_SDK_INCLUDED
/// <summary>
/// Returns true if the anchor is reliably located. False might mean loss of tracking or not fully initialized.
/// </summary>
public override bool IsLocated =>
IsReliablyLocated && Time.unscaledTime > lastNotLocatedTime + TrackingStartDelayTime;
private bool IsReliablyLocated
{
get
{
#if WLT_ARCORE_SDK_INCLUDED
return internalAnchor != null && internalAnchor.TrackingState == GoogleARCore.TrackingState.Tracking;
#else // WLT_ARCORE_SDK_INCLUDED
return false;
#endif // WLT_ARCORE_SDK_INCLUDED
}
}
public override Pose SpongyPose
{
get
{
return transform.GetGlobalPose();
}
}
// Update is called once per frame
private void Update()
{
if (!IsReliablyLocated)
{
lastNotLocatedTime = Time.unscaledTime;
}
#if WLT_ARCORE_SDK_INCLUDED
else
{
Vector3 move = internalAnchor.transform.position - transform.position;
#if WLT_ARCORE_EXTRA_DEBUGGING
if (move.magnitude > 0.001f)
{
Debug.Log($"{name} Moving by {move.ToString("F3")}");
}
#endif // WLT_ARCORE_EXTRA_DEBUGGING
transform.SetGlobalPose(internalAnchor.transform.GetGlobalPose());
}
#endif // WLT_ARCORE_SDK_INCLUDED
}
// Start is called before the first frame update
private void Start()
{
#if WLT_ARCORE_SDK_INCLUDED
internalAnchor = Session.CreateAnchor(transform.GetGlobalPose());
#endif // WLT_ARCORE_SDK_INCLUDED
}
}
} | 30.012048 | 119 | 0.633079 | [
"MIT"
] | QPC-database/MixedReality-WorldLockingTools-Samples | Advanced/ASA/Assets/WorldLocking.Core/Scripts/ARCore/SpongyAnchorARCore.cs | 2,493 | 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 WordCompletedNotes.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.612903 | 151 | 0.584343 | [
"MIT"
] | DominikaBogusz/WordCompletedNotes | WordCompletedNotes/Properties/Settings.Designer.cs | 1,075 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NoFluentValidatorViewModel.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Test.Extensions.FluentValidation.ViewModels
{
using Catel.MVVM;
/// <summary>
/// The person view model with out validator.
/// </summary>
public class NoFluentValidatorViewModel : ViewModelBase
{
}
} | 39.058824 | 120 | 0.448795 | [
"MIT"
] | gautamsi/Catel | src/Catel.Test/Catel.Test.NET40/Extensions/FluentValidation/ViewModels/NoFluentValidatorViewModel.cs | 666 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SwiftyProject
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| 21.904762 | 65 | 0.593478 | [
"MIT"
] | askeet/SwiffyToNet | NetProject/SwiftyProject/SwiftyProject/Program.cs | 492 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace eShop.Configuration.Setup.Entities.Ordering
{
public class Orders : Aggregates.Entity<Orders, State, Setup>
{
private Orders() { }
public void Seeded()
{
Apply<Events.Seeded>(x => { });
}
}
}
| 19.294118 | 65 | 0.606707 | [
"MIT"
] | charlessolar/eShopOnContainersDDD | src/Contexts/Configuration/Domain/Entities/Setup/Entities/Ordering/Orders.cs | 330 | C# |
#nullable enable
using Newtonsoft.Json;
namespace BizHawk.Client.Common
{
public struct FeedbackBind
{
public string? Channel;
/// <remarks>"X# "/"J# " (with the trailing space)</remarks>
public string? GamepadPrefix;
[JsonIgnore]
public bool IsZeroed => GamepadPrefix == null;
public float Prescale;
public FeedbackBind(string prefix, string channel, float prescale)
{
GamepadPrefix = prefix;
Channel = channel;
Prescale = prescale;
}
}
}
| 17.666667 | 68 | 0.70021 | [
"MIT"
] | CartoonFan/BizHawk | src/BizHawk.Client.Common/config/FeedbackBind.cs | 479 | C# |
#region History
#if HISTORY_COMMENT
// <[History]>
Update 2014-12-07
=================
- DataAccess : ExcelConfig
- Re-Implement Database Config classes for Excel File.
======================================================================================================================
Update 2010-02-03
=================
- OleDb Config inherited classes ported
- ExcelConfig class ported and re-implements.
- Excel sql model and related class ported.
======================================================================================================================
Update 2008-10-21
=================
- Sql Model (OleDb) updated.
[Excel]
- Add new class ExcelSqlModel.ExcelDDLFormatter for handle DDL generate script.
- Implement method CreateDDLFormatter.
- Implement method GenerateViewScript (incompleted) in it's DDLFormatter.
- Implement method GenerateTableScript in it's DDLFormatter.
- Implement method GenerateTableColumnScript in it's DDLFormatter.
- Implement method GenerateTableConstraintScript in it's DDLFormatter.
======================================================================================================================
Update 2008-07-07
=================
- DataAccess library new Features add
- Implement Task for Excel maintance routine.
======================================================================================================================
// </[History]>
#endif
#endregion
#region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using NLib;
using NLib.Design;
using NLib.Data;
using NLib.Data.Design;
using NLib.Reflection;
using NLib.Xml;
using NLib.Utils;
#endregion
namespace NLib.Data.Design
{
#region Excel Design time Editor
#region Open Excel
/// <summary>
/// *.xls Open File Editor
/// </summary>
public class OpenExcelFileNameEditor : System.Windows.Forms.Design.FileNameEditor
{
#region Override For Dialog
/// <summary>
/// Initialize Dialog before process Opening
/// </summary>
/// <param name="openFileDialog">Open Dialog Instance</param>
protected override void InitializeDialog(
System.Windows.Forms.OpenFileDialog openFileDialog)
{
base.InitializeDialog(openFileDialog);
openFileDialog.Filter = "Ms Excel Files (*.xls, *.xlsx, *.xlsb, *.xlsm)|*.xls;*.xlsx;*.xlsb;*.xlsm|All Files (*.*)|*.*";
}
#endregion
}
#endregion
#region Save Excel
/// <summary>
/// *.xls Save File Editor
/// </summary>
public class SaveExcelFileNameEditor : SaveFileEditor
{
#region Override For Dialog
/// <summary>
/// Initialize Dialog before process Saving
/// </summary>
/// <param name="saveFileDialog">Save Dialog Instance</param>
protected override void InitializeDialog(
System.Windows.Forms.SaveFileDialog saveFileDialog)
{
base.InitializeDialog(saveFileDialog);
saveFileDialog.Filter = "Ms Excel Files (*.xls, *.xlsx, *.xlsb, *.xlsm)|*.xls;*.xlsx;*.xlsb;*.xlsm|All Files (*.*)|*.*";
}
#endregion
}
#endregion
#endregion
}
namespace NLib.Data
{
#region Common classes and Enums
#region Enums for Excel
#region ExcelDriver
/// <summary>
/// Excel Driver.
/// </summary>
public enum ExcelDriver
{
/// <summary>
/// Used Jet
/// </summary>
Jet,
/// <summary>
/// Used ACE
/// </summary>
ACE
}
#endregion
#region Excel Version Enum
/// <summary>
/// Excel Driver Version
/// </summary>
public enum ExcelVersion
{
/// <summary>
/// Excel 95 version compatible
/// </summary>
Excel95,
/// <summary>
/// Excel 97 version compatible
/// </summary>
Excel97,
/// <summary>
/// Excel 2K version compatible
/// </summary>
Excel2K,
/// <summary>
/// Excel XP (2002) version compatible
/// </summary>
ExcelXP,
/// <summary>
/// Excel 2003 version compatible
/// </summary>
Excel2003,
/// <summary>
/// Excel 2007 version compatible
/// </summary>
Excel2007,
/// <summary>
/// Excel 2010 version compatible
/// </summary>
Excel2010,
/// <summary>
/// Excel 2012 version compatible
/// </summary>
Excel2012
}
#endregion
#region Inter Mixed
/// <summary>
/// Enum for Inter Mixed Parameter for Excel Driver
/// </summary>
public enum IMex
{
/// <summary>
/// not include in connection string
/// </summary>
Default = -1,
/// <summary>
/// set ExportMode
/// </summary>
ExportMode = 0,
/// <summary>
/// set ImportMixedType=Text in registry (force mixed data to Text)
/// </summary>
ImportMode = 1,
/// <summary>
/// full update capabilities
/// </summary>
LinkedMode = 2
}
#endregion
#endregion
#region Common classes for Serialization connection config
/// <summary>
/// The ExcelOptions class.
/// </summary>
[Serializable]
[TypeConverter(typeof(PropertySorterSupportExpandableTypeConverter))]
public class ExcelOptions
{
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public ExcelOptions()
: base()
{
this.FileName = string.Empty;
this.HeaderInFirstRow = true;
this.Version = ExcelVersion.Excel2007;
this.IMexMode = IMex.Default;
this.Driver = ExcelDriver.Jet;
}
#endregion
#region Overrides
/// <summary>
/// Gets Hash Code.
/// </summary>
/// <returns>Returns hashcode of current object.</returns>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Conpare if object is equals.
/// </summary>
/// <param name="obj">The target objct to compare.</param>
/// <returns>Returns true if object is the same.</returns>
public override bool Equals(object obj)
{
if (null == obj || obj.GetType() != this.GetType())
return false;
return this.GetHashCode().Equals(obj.GetHashCode());
}
/// <summary>
/// ToString.
/// </summary>
/// <returns>Returns string that represents an object.</returns>
public override string ToString()
{
return string.Format(@"{0}, Mode = {1}, Driver = {2}",
this.FileName, this.IMexMode, this.Driver);
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the Excel File Name.
/// </summary>
[Category("Database")]
[Description("Gets or sets the Excel File Name.")]
[RefreshProperties(RefreshProperties.Repaint)]
[Editor(typeof(OpenExcelFileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[PropertyOrder(1)]
[XmlAttribute]
public string FileName { get; set; }
/// <summary>
/// Gets or sets the IMEX Mode (need to see MAXROWSCAN Extended Properties documents).
/// </summary>
[Category("Database")]
[Description("Gets or sets IMEX Mode (need to see MAXROWSCAN Extended Properties documents).")]
[RefreshProperties(RefreshProperties.Repaint)]
[PropertyOrder(2)]
[XmlAttribute]
public IMex IMexMode { get; set; }
/// <summary>
/// Gets or sets Excel Header Options.
/// </summary>
[Category("Database")]
[Description("Gets or sets Excel Header Options.")]
[RefreshProperties(RefreshProperties.Repaint)]
[PropertyOrder(3)]
[XmlAttribute]
public bool HeaderInFirstRow { get; set; }
/// <summary>
/// Gets or sets the excel version.
/// </summary>
[Category("Database")]
[Description("Gets or sets excel version.")]
[RefreshProperties(RefreshProperties.Repaint)]
[PropertyOrder(4)]
[XmlAttribute]
public ExcelVersion Version { get; set; }
/// <summary>
/// Gets or sets the excel driver.
/// </summary>
[Category("Database")]
[Description("Gets or sets excel driver.")]
[RefreshProperties(RefreshProperties.Repaint)]
[PropertyOrder(5)]
[XmlAttribute]
public ExcelDriver Driver { get; set; }
#endregion
}
#endregion
#endregion
#region ExcelConfig
/// <summary>
/// Microsoft Excel Connection Config class.
/// </summary>
[Serializable]
[TypeConverter(typeof(PropertySorterSupportExpandableTypeConverter))]
public class ExcelConfig : OleDbConfig
{
#region Internal Variables
private ExcelOptions _datasource = null;
#endregion
#region Constructor and Destructor
/// <summary>
/// Constructor.
/// </summary>
public ExcelConfig()
: base()
{
// set default user name, password and authentication mode.
this.Security.UserName = string.Empty;
this.Security.Password = string.Empty;
this.Security.Authentication = AuthenticationMode.Server;
// set default server and database name.
this.DataSource.Driver = ExcelDriver.Jet;
// set default server date format.
this.Optional.ServerDateFormat = string.Empty;
this.Optional.EnableMARS = false;
}
/// <summary>
/// Destructor.
/// </summary>
~ExcelConfig()
{
}
#endregion
#region Abstract Implements
#region GetUniqueName/GetConnectionString/GetFactory
/// <summary>
/// Define Each Connection Unique Name.
/// </summary>
/// <returns>Unique Name for Connection</returns>
protected override string GetUniqueName()
{
return this.DataSource.ToString();
}
/// <summary>
/// Get Connection String.
/// </summary>
/// <returns>Connection string based on property settings</returns>
protected override string GetConnectionString()
{
#region Sample of Connection string
// OleDbConnection
// ===============
// #Standard:
// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
// "HDR=Yes;" indicates that the first row contains columnnames, not data
// "IMEX=1;" tells the driver to always read "intermixed" data columns as text
//
// TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
//
// OdbcConnection
// ==============
// #Standard:
// "Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;"
//
// TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
#endregion
string result = string.Empty;
string sProvider = string.Empty;
string ExtProp = string.Empty;
if (this.DataSource.Driver == ExcelDriver.ACE)
{
#region Ace
sProvider = "Microsoft.ACE.OLEDB.12.0";
if (!string.IsNullOrWhiteSpace(this.DataSource.FileName))
{
string ext = string.Empty;
try { ext = System.IO.Path.GetExtension(this.DataSource.FileName); }
catch { ext = string.Empty; }
if (!string.IsNullOrWhiteSpace(ext))
{
if (ext.ToLower().Contains("xlsx"))
{
// Version 2007 or later xlsx file (2007 Marco disable).
// This one is for connecting to Excel 2007 files with the Xlsx file extension.
// That is the Office Open XML format with macros disabled.
ExtProp = "Excel 12.0 xml";
}
else if (ext.ToLower().Contains("xlsb"))
{
// Version 2007 or later xlsb file (2007 Binary)
// This one is for connecting to Excel 2007 files with the Xlsb file extension.
// That is the Office Open XML format saved in a binary format.
// I.e. the structure is similar but it's not saved in a text readable
// format as the Xlsx files and can improve performance if the file
// contains a lot of data.
ExtProp = "Excel 12.0";
}
else if (ext.ToLower().Contains("xlsm"))
{
// Version 2007 or later xlsm file (2007 Marco enable).
// This one is for connecting to Excel 2007 files with the Xlsm file extension.
// That is the Office Open XML format with macros enabled.
ExtProp = "Excel 12.0 Macro";
}
else ExtProp = "Excel 8.0"; // assume used older file
}
else ExtProp = "Excel 8.0"; // cannot extract extension
}
else ExtProp = "Excel 8.0"; // no file assigned
#endregion
}
else // Jet
{
#region Jet
// Excel 5.0 = Excel 5, Excel 7
// Excel 8.0 = Excel 97-2000 or later
sProvider = "Microsoft.Jet.OLEDB.4.0";
if (this.DataSource.Version == ExcelVersion.Excel95)
ExtProp = "Excel 5.0";
else ExtProp = "Excel 8.0";
#endregion
}
if (!this.DataSource.HeaderInFirstRow) ExtProp += ";HDR=NO";
else ExtProp += ";HDR=YES";
if (this.DataSource.IMexMode != IMex.Default)
{
ExtProp += ";IMEX=" + ((int)this.DataSource.IMexMode).ToString().Trim();
}
// Clear and Setup parameters
this.ConnectionStrings.Clear();
this.ConnectionStrings["Provider"] = sProvider;
this.ConnectionStrings["Data Source"] = this.DataSource.FileName;
this.ConnectionStrings["Extended Properties"] = "\"" + ExtProp + "\"";
this.ConnectionStrings["Persist Security Info"] = "False";
// Build result connection string.
result = this.ConnectionStrings.GetConnectionString();
if (!string.IsNullOrWhiteSpace(this.Optional.ExtendConnectionString))
{
// Append extend connection string.
result += this.Optional.ExtendConnectionString;
}
return result;
}
/// <summary>
/// Create database factory provider.
/// </summary>
/// <returns>Returns instance of database factory provider.</returns>
protected override NDbFactory CreateFactory()
{
ExcelConnectionFactory result = new ExcelConnectionFactory();
result.SetConfig(this);
return result;
}
#endregion
#endregion
#region Public Properties
#region Data Source
/// <summary>
/// Gets or sets Excel Connection Options.
/// </summary>
[Category("Connection")]
[Description("Gets or sets Excel Connection Options.")]
[RefreshProperties(RefreshProperties.Repaint)]
[XmlElement]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PropertyOrder(ConfigOrders.DataSource)]
public ExcelOptions DataSource
{
get
{
_datasource = this.CheckVar(_datasource);
return _datasource;
}
set
{
_datasource = value;
_datasource = this.CheckVar(_datasource);
RaiseConfigChanged();
}
}
#endregion
#endregion
#region Static Methods
#region Get Provider Name
/// <summary>
/// Get Connection Provider Name.
/// </summary>
public static new string DbProviderName
{
get { return "MS Excel (OLEDB)"; }
}
#endregion
#region Create
/// <summary>
/// Create new NDbConfig Instance.
/// </summary>
/// <returns>Returns NDbConfig Instance.</returns>
public static new NDbConfig Create() { return new ExcelConfig(); }
#endregion
#endregion
}
#endregion
}
| 30.668966 | 132 | 0.52676 | [
"MIT"
] | chumpon-asaneerat/DMT.TA.TODv3 | 00.NLib/NLib/Data/Configs/OleDb/ExcelConfig.cs | 17,790 | C# |
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Catan.Scripts.Common;
namespace Catan.Scripts.Player
{
public class OrderDetermining : MonoBehaviour
{
public int[] orderNum = new int[4];
private PlayerId[] playerNames = new PlayerId[] { PlayerId.Player1, PlayerId.Player2, PlayerId.Player3, PlayerId.Player4 };
private PlayerId[] playerIds = new PlayerId[4];
Dictionary<PlayerId, int> dic = new Dictionary<PlayerId, int>();
// 取得した値をソート
public void OrderDecide()
{
orderNum = Dice.RollTwiceDice();
for (int i = 0; i < 4; i++)
{
dic.Add(playerNames[i], orderNum[i]);
}
// ソート済み
var sortOrder = dic.OrderBy((x) => x.Value);
int j = 0;
foreach (var v in sortOrder)
{
playerIds[j] = v.Key;
// Debug.Log(v.Key + ":" + v.Value);
j++;
}
}
public PlayerId[] GetOrder()
{
return playerIds;
}
}
} | 23.893617 | 131 | 0.515583 | [
"MIT"
] | THEToilet/OnlineCatan | OnlineCatan/Assets/Catan/Scripts/Player/OrderDetermining.cs | 1,153 | C# |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace SlideOverKit.MoreSample
{
public partial class PopOverWithTriangleView : SlidePopupView
{
public const int iOSTopMargin = 0;
public const int AndroidTopMargin = 0;
public const int WinPHoneTopMargin = 10;
public PopOverWithTriangleView ()
{
InitializeComponent ();
// In this case, you must set both LeftMargin and TopMarin
this.LeftMargin = 20;
this.BackgroundViewColor = Color.FromRgba(0,0,0,125);
// In some small screen Android devices, the menu cannot be layout with full size.
// In this case, we just set LeftMargin and TopMargin,
// you do not need to set the HeightRequest or WidthRequest, as they are no effect in Pop up View.
// If the view is too small for Android devices, we can reduce the TopMargin.
this.TopMargin = Device.OnPlatform<int> (iOSTopMargin, AndroidTopMargin, WinPHoneTopMargin);
// The menu will hide without animation,
// If you want to have the animation, you can call the MenuContainerPage.HideMenu(),
// But you cannot call it from this View, cause of cycle references, you can sent a message to ContainerPage
DoneButton.Clicked += (object sender, EventArgs e) => {
this.HideMySelf ();
};
}
}
}
| 37.769231 | 120 | 0.634759 | [
"Apache-2.0"
] | daniel-luberda/SlideOverKit | SlideOverKitMoreSamples/SlideOverKit.Sample/Pages/PopOverWithTriangleView.xaml.cs | 1,475 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.
*
*/
#region Import
using System;
using System.Collections.Generic;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Tenants;
using ASC.CRM.Core.Entities;
#endregion
namespace ASC.CRM.Core.Dao
{
public class CachedTaskTemplateContainerDao : TaskTemplateContainerDao
{
#region Constructor
public CachedTaskTemplateContainerDao(int tenantID)
: base(tenantID)
{
}
#endregion
}
public class CachedTaskTemplateDao : TaskTemplateDao
{
#region Constructor
public CachedTaskTemplateDao(int tenantID)
: base(tenantID)
{
}
#endregion
}
public class TaskTemplateContainerDao : AbstractDao
{
#region Constructor
public TaskTemplateContainerDao(int tenantID)
: base(tenantID)
{
}
#endregion
#region Methods
public virtual int SaveOrUpdate(TaskTemplateContainer item)
{
if (item.ID == 0 && Db.ExecuteScalar<int>(Query("crm_task_template_container").SelectCount().Where(Exp.Eq("id", item.ID))) == 0)
{
item.ID = Db.ExecuteScalar<int>(
Insert("crm_task_template_container")
.InColumnValue("id", 0)
.InColumnValue("title", item.Title)
.InColumnValue("entity_type", (int)item.EntityType)
.InColumnValue("create_on", DateTime.UtcNow)
.InColumnValue("create_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.InColumnValue("last_modifed_on", DateTime.UtcNow)
.InColumnValue("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.Identity(1, 0, true));
}
else
{
Db.ExecuteScalar<int>(
Update("crm_task_template_container")
.Set("title", item.Title)
.Set("entity_type", (int)item.EntityType)
.Set("last_modifed_on", DateTime.UtcNow)
.Set("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.Where(Exp.Eq("id", item.ID)));
}
return item.ID;
}
public virtual void Delete(int id)
{
if (id <= 0)
throw new ArgumentException();
Db.ExecuteNonQuery(Delete("crm_task_template_container").Where("id", id));
}
public virtual TaskTemplateContainer GetByID(int id)
{
if (id <= 0)
throw new ArgumentException();
var result = Db.ExecuteList(GetQuery(null).Where(Exp.Eq("id", id))).ConvertAll(row => ToObject(row));
if (result.Count == 0) return null;
return result[0];
}
public virtual List<TaskTemplateContainer> GetItems(EntityType entityType)
{
if (!_supportedEntityType.Contains(entityType))
throw new ArgumentException("", entityType.ToString());
return Db.ExecuteList(GetQuery(Exp.Eq("entity_type", (int)entityType)))
.ConvertAll(row => ToObject(row));
}
#endregion
protected SqlQuery GetQuery(Exp where)
{
var sqlQuery = Query("crm_task_template_container")
.Select("id",
"title",
"entity_type");
if (where != null)
sqlQuery.Where(where);
return sqlQuery;
}
protected TaskTemplateContainer ToObject(object[] row)
{
return new TaskTemplateContainer
{
ID = Convert.ToInt32(row[0]),
Title = Convert.ToString(row[1]),
EntityType = (EntityType)Convert.ToInt32(row[2])
};
}
}
public class TaskTemplateDao : AbstractDao
{
#region Constructor
public TaskTemplateDao(int tenantID)
: base(tenantID)
{
}
#endregion
#region Methods
public int SaveOrUpdate(TaskTemplate item)
{
if (item.ID == 0 && Db.ExecuteScalar<int>(Query("crm_task_template").SelectCount().Where(Exp.Eq("id", item.ID))) == 0)
{
item.ID = Db.ExecuteScalar<int>(
Insert("crm_task_template")
.InColumnValue("id", 0)
.InColumnValue("title", item.Title)
.InColumnValue("category_id", item.CategoryID)
.InColumnValue("description", item.Description)
.InColumnValue("responsible_id", item.ResponsibleID)
.InColumnValue("is_notify", item.isNotify)
.InColumnValue("offset", item.Offset.Ticks)
.InColumnValue("deadLine_is_fixed", item.DeadLineIsFixed)
.InColumnValue("container_id", item.ContainerID)
.InColumnValue("create_on", DateTime.UtcNow)
.InColumnValue("create_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.InColumnValue("last_modifed_on", DateTime.UtcNow)
.InColumnValue("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.Identity(1, 0, true));
}
else
{
Db.ExecuteNonQuery(
Update("crm_task_template")
.Set("title", item.Title)
.Set("category_id", item.CategoryID)
.Set("description", item.Description)
.Set("responsible_id", item.ResponsibleID)
.Set("is_notify", item.isNotify)
.Set("offset", item.Offset.Ticks)
.Set("deadLine_is_fixed", item.DeadLineIsFixed)
.Set("container_id", item.ContainerID)
.Set("last_modifed_on", DateTime.UtcNow)
.Set("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
.Where("id", item.ID));
}
return item.ID;
}
public TaskTemplate GetNext(int taskID)
{
using (var tx = Db.BeginTransaction())
{
var sqlResult = Db.ExecuteList(
Query("crm_task_template_task tblTTT")
.Select("tblTT.container_id")
.Select("tblTT.sort_order")
.LeftOuterJoin("crm_task_template tblTT", Exp.EqColumns("tblTT.tenant_id", "tblTTT.tenant_id") & Exp.EqColumns("tblTT.id", "tblTTT.task_template_id"))
.Where(Exp.Eq("tblTTT.task_id", taskID) & Exp.Eq("tblTT.tenant_id", TenantID)));
if (sqlResult.Count == 0) return null;
var result = Db.ExecuteList(GetQuery(Exp.Eq("container_id", sqlResult[0][0]) &
Exp.Gt("sort_order", sqlResult[0][1]) &
Exp.Eq("deadLine_is_fixed", false)).SetMaxResults(1)).ConvertAll(
row => ToObject(row));
Db.ExecuteNonQuery(Delete("crm_task_template_task").Where(Exp.Eq("task_id", taskID)));
tx.Commit();
if (result.Count == 0) return null;
return result[0];
}
}
public List<TaskTemplate> GetAll()
{
return Db.ExecuteList(GetQuery(null))
.ConvertAll(row => ToObject(row));
}
public List<TaskTemplate> GetList(int containerID)
{
if (containerID <= 0)
throw new NotImplementedException();
return Db.ExecuteList(GetQuery(Exp.Eq("container_id", containerID)))
.ConvertAll(row => ToObject(row));
}
public virtual TaskTemplate GetByID(int id)
{
if (id <= 0)
throw new NotImplementedException();
var items = Db.ExecuteList(GetQuery(Exp.Eq("id", id))).ConvertAll(row => ToObject(row));
if (items.Count == 0)
return null;
return items[0];
}
public virtual void Delete(int id)
{
if (id <= 0)
throw new NotImplementedException();
Db.ExecuteNonQuery(Delete("crm_task_template").Where("id", id));
}
protected TaskTemplate ToObject(object[] row)
{
return new TaskTemplate
{
ID = Convert.ToInt32(row[0]),
Title = Convert.ToString(row[1]),
CategoryID = Convert.ToInt32(row[2]),
Description = Convert.ToString(row[3]),
ResponsibleID = ToGuid(row[4]),
isNotify = Convert.ToBoolean(row[5]),
Offset = TimeSpan.FromTicks((long)row[6]),
DeadLineIsFixed = Convert.ToBoolean(row[7]),
ContainerID = Convert.ToInt32(row[8]),
CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[9])),
CreateBy = ToGuid(row[10])
};
}
protected SqlQuery GetQuery(Exp where)
{
var sqlQuery = Query("crm_task_template")
.Select("id",
"title",
"category_id",
"description",
"responsible_id",
"is_notify",
"offset",
"deadLine_is_fixed",
"container_id",
"create_on",
"create_by"
);
if (where != null)
sqlQuery.Where(where);
sqlQuery.OrderBy("sort_order", true);
return sqlQuery;
}
#endregion
}
} | 33.302941 | 171 | 0.495363 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | ONLYOFFICE/CommunityServer | web/studio/ASC.Web.Studio/Products/CRM/Core/Dao/TaskTemplateContainerDao.cs | 11,323 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p1beta1/text_annotation.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.Vision.V1P1Beta1 {
/// <summary>Holder for reflection information generated from google/cloud/vision/v1p1beta1/text_annotation.proto</summary>
public static partial class TextAnnotationReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/vision/v1p1beta1/text_annotation.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TextAnnotationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNnb29nbGUvY2xvdWQvdmlzaW9uL3YxcDFiZXRhMS90ZXh0X2Fubm90YXRp",
"b24ucHJvdG8SHWdvb2dsZS5jbG91ZC52aXNpb24udjFwMWJldGExGhxnb29n",
"bGUvYXBpL2Fubm90YXRpb25zLnByb3RvGixnb29nbGUvY2xvdWQvdmlzaW9u",
"L3YxcDFiZXRhMS9nZW9tZXRyeS5wcm90byKyBAoOVGV4dEFubm90YXRpb24S",
"MgoFcGFnZXMYASADKAsyIy5nb29nbGUuY2xvdWQudmlzaW9uLnYxcDFiZXRh",
"MS5QYWdlEgwKBHRleHQYAiABKAkaPQoQRGV0ZWN0ZWRMYW5ndWFnZRIVCg1s",
"YW5ndWFnZV9jb2RlGAEgASgJEhIKCmNvbmZpZGVuY2UYAiABKAIa3AEKDURl",
"dGVjdGVkQnJlYWsSUwoEdHlwZRgBIAEoDjJFLmdvb2dsZS5jbG91ZC52aXNp",
"b24udjFwMWJldGExLlRleHRBbm5vdGF0aW9uLkRldGVjdGVkQnJlYWsuQnJl",
"YWtUeXBlEhEKCWlzX3ByZWZpeBgCIAEoCCJjCglCcmVha1R5cGUSCwoHVU5L",
"Tk9XThAAEgkKBVNQQUNFEAESDgoKU1VSRV9TUEFDRRACEhIKDkVPTF9TVVJF",
"X1NQQUNFEAMSCgoGSFlQSEVOEAQSDgoKTElORV9CUkVBSxAFGr8BCgxUZXh0",
"UHJvcGVydHkSWgoSZGV0ZWN0ZWRfbGFuZ3VhZ2VzGAEgAygLMj4uZ29vZ2xl",
"LmNsb3VkLnZpc2lvbi52MXAxYmV0YTEuVGV4dEFubm90YXRpb24uRGV0ZWN0",
"ZWRMYW5ndWFnZRJTCg5kZXRlY3RlZF9icmVhaxgCIAEoCzI7Lmdvb2dsZS5j",
"bG91ZC52aXNpb24udjFwMWJldGExLlRleHRBbm5vdGF0aW9uLkRldGVjdGVk",
"QnJlYWsivQEKBFBhZ2USTAoIcHJvcGVydHkYASABKAsyOi5nb29nbGUuY2xv",
"dWQudmlzaW9uLnYxcDFiZXRhMS5UZXh0QW5ub3RhdGlvbi5UZXh0UHJvcGVy",
"dHkSDQoFd2lkdGgYAiABKAUSDgoGaGVpZ2h0GAMgASgFEjQKBmJsb2NrcxgE",
"IAMoCzIkLmdvb2dsZS5jbG91ZC52aXNpb24udjFwMWJldGExLkJsb2NrEhIK",
"CmNvbmZpZGVuY2UYBSABKAIiggMKBUJsb2NrEkwKCHByb3BlcnR5GAEgASgL",
"MjouZ29vZ2xlLmNsb3VkLnZpc2lvbi52MXAxYmV0YTEuVGV4dEFubm90YXRp",
"b24uVGV4dFByb3BlcnR5EkEKDGJvdW5kaW5nX2JveBgCIAEoCzIrLmdvb2ds",
"ZS5jbG91ZC52aXNpb24udjFwMWJldGExLkJvdW5kaW5nUG9seRI8CgpwYXJh",
"Z3JhcGhzGAMgAygLMiguZ29vZ2xlLmNsb3VkLnZpc2lvbi52MXAxYmV0YTEu",
"UGFyYWdyYXBoEkIKCmJsb2NrX3R5cGUYBCABKA4yLi5nb29nbGUuY2xvdWQu",
"dmlzaW9uLnYxcDFiZXRhMS5CbG9jay5CbG9ja1R5cGUSEgoKY29uZmlkZW5j",
"ZRgFIAEoAiJSCglCbG9ja1R5cGUSCwoHVU5LTk9XThAAEggKBFRFWFQQARIJ",
"CgVUQUJMRRACEgsKB1BJQ1RVUkUQAxIJCgVSVUxFUhAEEgsKB0JBUkNPREUQ",
"BSLkAQoJUGFyYWdyYXBoEkwKCHByb3BlcnR5GAEgASgLMjouZ29vZ2xlLmNs",
"b3VkLnZpc2lvbi52MXAxYmV0YTEuVGV4dEFubm90YXRpb24uVGV4dFByb3Bl",
"cnR5EkEKDGJvdW5kaW5nX2JveBgCIAEoCzIrLmdvb2dsZS5jbG91ZC52aXNp",
"b24udjFwMWJldGExLkJvdW5kaW5nUG9seRIyCgV3b3JkcxgDIAMoCzIjLmdv",
"b2dsZS5jbG91ZC52aXNpb24udjFwMWJldGExLldvcmQSEgoKY29uZmlkZW5j",
"ZRgEIAEoAiLjAQoEV29yZBJMCghwcm9wZXJ0eRgBIAEoCzI6Lmdvb2dsZS5j",
"bG91ZC52aXNpb24udjFwMWJldGExLlRleHRBbm5vdGF0aW9uLlRleHRQcm9w",
"ZXJ0eRJBCgxib3VuZGluZ19ib3gYAiABKAsyKy5nb29nbGUuY2xvdWQudmlz",
"aW9uLnYxcDFiZXRhMS5Cb3VuZGluZ1BvbHkSNgoHc3ltYm9scxgDIAMoCzIl",
"Lmdvb2dsZS5jbG91ZC52aXNpb24udjFwMWJldGExLlN5bWJvbBISCgpjb25m",
"aWRlbmNlGAQgASgCIrsBCgZTeW1ib2wSTAoIcHJvcGVydHkYASABKAsyOi5n",
"b29nbGUuY2xvdWQudmlzaW9uLnYxcDFiZXRhMS5UZXh0QW5ub3RhdGlvbi5U",
"ZXh0UHJvcGVydHkSQQoMYm91bmRpbmdfYm94GAIgASgLMisuZ29vZ2xlLmNs",
"b3VkLnZpc2lvbi52MXAxYmV0YTEuQm91bmRpbmdQb2x5EgwKBHRleHQYAyAB",
"KAkSEgoKY29uZmlkZW5jZRgEIAEoAkKCAQohY29tLmdvb2dsZS5jbG91ZC52",
"aXNpb24udjFwMWJldGExQhNUZXh0QW5ub3RhdGlvblByb3RvUAFaQ2dvb2ds",
"ZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQvdmlzaW9u",
"L3YxcDFiZXRhMTt2aXNpb274AQFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.Vision.V1P1Beta1.GeometryReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation), global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Parser, new[]{ "Pages", "Text" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage), global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage.Parser, new[]{ "LanguageCode", "Confidence" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak), global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak.Parser, new[]{ "Type", "IsPrefix" }, null, new[]{ typeof(global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak.Types.BreakType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty), global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty.Parser, new[]{ "DetectedLanguages", "DetectedBreak" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.Page), global::Google.Cloud.Vision.V1P1Beta1.Page.Parser, new[]{ "Property", "Width", "Height", "Blocks", "Confidence" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.Block), global::Google.Cloud.Vision.V1P1Beta1.Block.Parser, new[]{ "Property", "BoundingBox", "Paragraphs", "BlockType", "Confidence" }, null, new[]{ typeof(global::Google.Cloud.Vision.V1P1Beta1.Block.Types.BlockType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.Paragraph), global::Google.Cloud.Vision.V1P1Beta1.Paragraph.Parser, new[]{ "Property", "BoundingBox", "Words", "Confidence" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.Word), global::Google.Cloud.Vision.V1P1Beta1.Word.Parser, new[]{ "Property", "BoundingBox", "Symbols", "Confidence" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Vision.V1P1Beta1.Symbol), global::Google.Cloud.Vision.V1P1Beta1.Symbol.Parser, new[]{ "Property", "BoundingBox", "Text", "Confidence" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// TextAnnotation contains a structured representation of OCR extracted text.
/// The hierarchy of an OCR extracted text structure is like this:
/// TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol
/// Each structural component, starting from Page, may further have their own
/// properties. Properties describe detected languages, breaks etc.. Please refer
/// to the
/// [TextAnnotation.TextProperty][google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty]
/// message definition below for more detail.
/// </summary>
public sealed partial class TextAnnotation : pb::IMessage<TextAnnotation> {
private static readonly pb::MessageParser<TextAnnotation> _parser = new pb::MessageParser<TextAnnotation>(() => new TextAnnotation());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TextAnnotation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextAnnotation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextAnnotation(TextAnnotation other) : this() {
pages_ = other.pages_.Clone();
text_ = other.text_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextAnnotation Clone() {
return new TextAnnotation(this);
}
/// <summary>Field number for the "pages" field.</summary>
public const int PagesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.Page> _repeated_pages_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Vision.V1P1Beta1.Page.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Page> pages_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Page>();
/// <summary>
/// List of pages detected by OCR.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Page> Pages {
get { return pages_; }
}
/// <summary>Field number for the "text" field.</summary>
public const int TextFieldNumber = 2;
private string text_ = "";
/// <summary>
/// UTF-8 text detected on the pages.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Text {
get { return text_; }
set {
text_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TextAnnotation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TextAnnotation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!pages_.Equals(other.pages_)) return false;
if (Text != other.Text) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= pages_.GetHashCode();
if (Text.Length != 0) hash ^= Text.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
pages_.WriteTo(output, _repeated_pages_codec);
if (Text.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Text);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += pages_.CalculateSize(_repeated_pages_codec);
if (Text.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Text);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TextAnnotation other) {
if (other == null) {
return;
}
pages_.Add(other.pages_);
if (other.Text.Length != 0) {
Text = other.Text;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
pages_.AddEntriesFrom(input, _repeated_pages_codec);
break;
}
case 18: {
Text = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the TextAnnotation message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Detected language for a structural component.
/// </summary>
public sealed partial class DetectedLanguage : pb::IMessage<DetectedLanguage> {
private static readonly pb::MessageParser<DetectedLanguage> _parser = new pb::MessageParser<DetectedLanguage>(() => new DetectedLanguage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DetectedLanguage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedLanguage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedLanguage(DetectedLanguage other) : this() {
languageCode_ = other.languageCode_;
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedLanguage Clone() {
return new DetectedLanguage(this);
}
/// <summary>Field number for the "language_code" field.</summary>
public const int LanguageCodeFieldNumber = 1;
private string languageCode_ = "";
/// <summary>
/// The BCP-47 language code, such as "en-US" or "sr-Latn". For more
/// information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string LanguageCode {
get { return languageCode_; }
set {
languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 2;
private float confidence_;
/// <summary>
/// Confidence of detected language. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DetectedLanguage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DetectedLanguage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (LanguageCode != other.LanguageCode) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (LanguageCode.Length != 0) {
output.WriteRawTag(10);
output.WriteString(LanguageCode);
}
if (Confidence != 0F) {
output.WriteRawTag(21);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (LanguageCode.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode);
}
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DetectedLanguage other) {
if (other == null) {
return;
}
if (other.LanguageCode.Length != 0) {
LanguageCode = other.LanguageCode;
}
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
LanguageCode = input.ReadString();
break;
}
case 21: {
Confidence = input.ReadFloat();
break;
}
}
}
}
}
/// <summary>
/// Detected start or end of a structural component.
/// </summary>
public sealed partial class DetectedBreak : pb::IMessage<DetectedBreak> {
private static readonly pb::MessageParser<DetectedBreak> _parser = new pb::MessageParser<DetectedBreak>(() => new DetectedBreak());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DetectedBreak> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedBreak() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedBreak(DetectedBreak other) : this() {
type_ = other.type_;
isPrefix_ = other.isPrefix_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DetectedBreak Clone() {
return new DetectedBreak(this);
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak.Types.BreakType type_ = 0;
/// <summary>
/// Detected break type.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak.Types.BreakType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "is_prefix" field.</summary>
public const int IsPrefixFieldNumber = 2;
private bool isPrefix_;
/// <summary>
/// True if break prepends the element.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsPrefix {
get { return isPrefix_; }
set {
isPrefix_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DetectedBreak);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DetectedBreak other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Type != other.Type) return false;
if (IsPrefix != other.IsPrefix) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Type != 0) hash ^= Type.GetHashCode();
if (IsPrefix != false) hash ^= IsPrefix.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Type != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Type);
}
if (IsPrefix != false) {
output.WriteRawTag(16);
output.WriteBool(IsPrefix);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (IsPrefix != false) {
size += 1 + 1;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DetectedBreak other) {
if (other == null) {
return;
}
if (other.Type != 0) {
Type = other.Type;
}
if (other.IsPrefix != false) {
IsPrefix = other.IsPrefix;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
type_ = (global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak.Types.BreakType) input.ReadEnum();
break;
}
case 16: {
IsPrefix = input.ReadBool();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the DetectedBreak message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Enum to denote the type of break found. New line, space etc.
/// </summary>
public enum BreakType {
/// <summary>
/// Unknown break label type.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 0,
/// <summary>
/// Regular space.
/// </summary>
[pbr::OriginalName("SPACE")] Space = 1,
/// <summary>
/// Sure space (very wide).
/// </summary>
[pbr::OriginalName("SURE_SPACE")] SureSpace = 2,
/// <summary>
/// Line-wrapping break.
/// </summary>
[pbr::OriginalName("EOL_SURE_SPACE")] EolSureSpace = 3,
/// <summary>
/// End-line hyphen that is not present in text; does not co-occur with
/// `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
/// </summary>
[pbr::OriginalName("HYPHEN")] Hyphen = 4,
/// <summary>
/// Line break that ends a paragraph.
/// </summary>
[pbr::OriginalName("LINE_BREAK")] LineBreak = 5,
}
}
#endregion
}
/// <summary>
/// Additional information detected on the structural component.
/// </summary>
public sealed partial class TextProperty : pb::IMessage<TextProperty> {
private static readonly pb::MessageParser<TextProperty> _parser = new pb::MessageParser<TextProperty>(() => new TextProperty());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TextProperty> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Descriptor.NestedTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextProperty() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextProperty(TextProperty other) : this() {
detectedLanguages_ = other.detectedLanguages_.Clone();
DetectedBreak = other.detectedBreak_ != null ? other.DetectedBreak.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TextProperty Clone() {
return new TextProperty(this);
}
/// <summary>Field number for the "detected_languages" field.</summary>
public const int DetectedLanguagesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage> _repeated_detectedLanguages_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage> detectedLanguages_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage>();
/// <summary>
/// A list of detected languages together with confidence.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedLanguage> DetectedLanguages {
get { return detectedLanguages_; }
}
/// <summary>Field number for the "detected_break" field.</summary>
public const int DetectedBreakFieldNumber = 2;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak detectedBreak_;
/// <summary>
/// Detected start or end of a text segment.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak DetectedBreak {
get { return detectedBreak_; }
set {
detectedBreak_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TextProperty);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TextProperty other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!detectedLanguages_.Equals(other.detectedLanguages_)) return false;
if (!object.Equals(DetectedBreak, other.DetectedBreak)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= detectedLanguages_.GetHashCode();
if (detectedBreak_ != null) hash ^= DetectedBreak.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
detectedLanguages_.WriteTo(output, _repeated_detectedLanguages_codec);
if (detectedBreak_ != null) {
output.WriteRawTag(18);
output.WriteMessage(DetectedBreak);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += detectedLanguages_.CalculateSize(_repeated_detectedLanguages_codec);
if (detectedBreak_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DetectedBreak);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TextProperty other) {
if (other == null) {
return;
}
detectedLanguages_.Add(other.detectedLanguages_);
if (other.detectedBreak_ != null) {
if (detectedBreak_ == null) {
detectedBreak_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak();
}
DetectedBreak.MergeFrom(other.DetectedBreak);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
detectedLanguages_.AddEntriesFrom(input, _repeated_detectedLanguages_codec);
break;
}
case 18: {
if (detectedBreak_ == null) {
detectedBreak_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.DetectedBreak();
}
input.ReadMessage(detectedBreak_);
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// Detected page from OCR.
/// </summary>
public sealed partial class Page : pb::IMessage<Page> {
private static readonly pb::MessageParser<Page> _parser = new pb::MessageParser<Page>(() => new Page());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Page> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Page() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Page(Page other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
width_ = other.width_;
height_ = other.height_;
blocks_ = other.blocks_.Clone();
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Page Clone() {
return new Page(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty property_;
/// <summary>
/// Additional information detected on the page.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "width" field.</summary>
public const int WidthFieldNumber = 2;
private int width_;
/// <summary>
/// Page width in pixels.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Width {
get { return width_; }
set {
width_ = value;
}
}
/// <summary>Field number for the "height" field.</summary>
public const int HeightFieldNumber = 3;
private int height_;
/// <summary>
/// Page height in pixels.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Height {
get { return height_; }
set {
height_ = value;
}
}
/// <summary>Field number for the "blocks" field.</summary>
public const int BlocksFieldNumber = 4;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.Block> _repeated_blocks_codec
= pb::FieldCodec.ForMessage(34, global::Google.Cloud.Vision.V1P1Beta1.Block.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Block> blocks_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Block>();
/// <summary>
/// List of blocks of text, images etc on this page.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Block> Blocks {
get { return blocks_; }
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 5;
private float confidence_;
/// <summary>
/// Confidence of the OCR results on the page. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Page);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Page other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (Width != other.Width) return false;
if (Height != other.Height) return false;
if(!blocks_.Equals(other.blocks_)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (Width != 0) hash ^= Width.GetHashCode();
if (Height != 0) hash ^= Height.GetHashCode();
hash ^= blocks_.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (Width != 0) {
output.WriteRawTag(16);
output.WriteInt32(Width);
}
if (Height != 0) {
output.WriteRawTag(24);
output.WriteInt32(Height);
}
blocks_.WriteTo(output, _repeated_blocks_codec);
if (Confidence != 0F) {
output.WriteRawTag(45);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (Width != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width);
}
if (Height != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height);
}
size += blocks_.CalculateSize(_repeated_blocks_codec);
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Page other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
Property.MergeFrom(other.Property);
}
if (other.Width != 0) {
Width = other.Width;
}
if (other.Height != 0) {
Height = other.Height;
}
blocks_.Add(other.blocks_);
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
input.ReadMessage(property_);
break;
}
case 16: {
Width = input.ReadInt32();
break;
}
case 24: {
Height = input.ReadInt32();
break;
}
case 34: {
blocks_.AddEntriesFrom(input, _repeated_blocks_codec);
break;
}
case 45: {
Confidence = input.ReadFloat();
break;
}
}
}
}
}
/// <summary>
/// Logical element on the page.
/// </summary>
public sealed partial class Block : pb::IMessage<Block> {
private static readonly pb::MessageParser<Block> _parser = new pb::MessageParser<Block>(() => new Block());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Block> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Block() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Block(Block other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
BoundingBox = other.boundingBox_ != null ? other.BoundingBox.Clone() : null;
paragraphs_ = other.paragraphs_.Clone();
blockType_ = other.blockType_;
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Block Clone() {
return new Block(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty property_;
/// <summary>
/// Additional information detected for the block.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "bounding_box" field.</summary>
public const int BoundingBoxFieldNumber = 2;
private global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly boundingBox_;
/// <summary>
/// The bounding box for the block.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertice order will still be (0, 1, 2, 3).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly BoundingBox {
get { return boundingBox_; }
set {
boundingBox_ = value;
}
}
/// <summary>Field number for the "paragraphs" field.</summary>
public const int ParagraphsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.Paragraph> _repeated_paragraphs_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Vision.V1P1Beta1.Paragraph.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Paragraph> paragraphs_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Paragraph>();
/// <summary>
/// List of paragraphs in this block (if this blocks is of type text).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Paragraph> Paragraphs {
get { return paragraphs_; }
}
/// <summary>Field number for the "block_type" field.</summary>
public const int BlockTypeFieldNumber = 4;
private global::Google.Cloud.Vision.V1P1Beta1.Block.Types.BlockType blockType_ = 0;
/// <summary>
/// Detected block type (text, image etc) for this block.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.Block.Types.BlockType BlockType {
get { return blockType_; }
set {
blockType_ = value;
}
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 5;
private float confidence_;
/// <summary>
/// Confidence of the OCR results on the block. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Block);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Block other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (!object.Equals(BoundingBox, other.BoundingBox)) return false;
if(!paragraphs_.Equals(other.paragraphs_)) return false;
if (BlockType != other.BlockType) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (boundingBox_ != null) hash ^= BoundingBox.GetHashCode();
hash ^= paragraphs_.GetHashCode();
if (BlockType != 0) hash ^= BlockType.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (boundingBox_ != null) {
output.WriteRawTag(18);
output.WriteMessage(BoundingBox);
}
paragraphs_.WriteTo(output, _repeated_paragraphs_codec);
if (BlockType != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) BlockType);
}
if (Confidence != 0F) {
output.WriteRawTag(45);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (boundingBox_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BoundingBox);
}
size += paragraphs_.CalculateSize(_repeated_paragraphs_codec);
if (BlockType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) BlockType);
}
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Block other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
Property.MergeFrom(other.Property);
}
if (other.boundingBox_ != null) {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
BoundingBox.MergeFrom(other.BoundingBox);
}
paragraphs_.Add(other.paragraphs_);
if (other.BlockType != 0) {
BlockType = other.BlockType;
}
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
input.ReadMessage(property_);
break;
}
case 18: {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
input.ReadMessage(boundingBox_);
break;
}
case 26: {
paragraphs_.AddEntriesFrom(input, _repeated_paragraphs_codec);
break;
}
case 32: {
blockType_ = (global::Google.Cloud.Vision.V1P1Beta1.Block.Types.BlockType) input.ReadEnum();
break;
}
case 45: {
Confidence = input.ReadFloat();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Block message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Type of a block (text, image etc) as identified by OCR.
/// </summary>
public enum BlockType {
/// <summary>
/// Unknown block type.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 0,
/// <summary>
/// Regular text block.
/// </summary>
[pbr::OriginalName("TEXT")] Text = 1,
/// <summary>
/// Table block.
/// </summary>
[pbr::OriginalName("TABLE")] Table = 2,
/// <summary>
/// Image block.
/// </summary>
[pbr::OriginalName("PICTURE")] Picture = 3,
/// <summary>
/// Horizontal/vertical line box.
/// </summary>
[pbr::OriginalName("RULER")] Ruler = 4,
/// <summary>
/// Barcode block.
/// </summary>
[pbr::OriginalName("BARCODE")] Barcode = 5,
}
}
#endregion
}
/// <summary>
/// Structural unit of text representing a number of words in certain order.
/// </summary>
public sealed partial class Paragraph : pb::IMessage<Paragraph> {
private static readonly pb::MessageParser<Paragraph> _parser = new pb::MessageParser<Paragraph>(() => new Paragraph());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Paragraph> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Paragraph() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Paragraph(Paragraph other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
BoundingBox = other.boundingBox_ != null ? other.BoundingBox.Clone() : null;
words_ = other.words_.Clone();
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Paragraph Clone() {
return new Paragraph(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty property_;
/// <summary>
/// Additional information detected for the paragraph.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "bounding_box" field.</summary>
public const int BoundingBoxFieldNumber = 2;
private global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly boundingBox_;
/// <summary>
/// The bounding box for the paragraph.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertice order will still be (0, 1, 2, 3).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly BoundingBox {
get { return boundingBox_; }
set {
boundingBox_ = value;
}
}
/// <summary>Field number for the "words" field.</summary>
public const int WordsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.Word> _repeated_words_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Vision.V1P1Beta1.Word.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Word> words_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Word>();
/// <summary>
/// List of words in this paragraph.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Word> Words {
get { return words_; }
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 4;
private float confidence_;
/// <summary>
/// Confidence of the OCR results for the paragraph. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Paragraph);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Paragraph other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (!object.Equals(BoundingBox, other.BoundingBox)) return false;
if(!words_.Equals(other.words_)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (boundingBox_ != null) hash ^= BoundingBox.GetHashCode();
hash ^= words_.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (boundingBox_ != null) {
output.WriteRawTag(18);
output.WriteMessage(BoundingBox);
}
words_.WriteTo(output, _repeated_words_codec);
if (Confidence != 0F) {
output.WriteRawTag(37);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (boundingBox_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BoundingBox);
}
size += words_.CalculateSize(_repeated_words_codec);
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Paragraph other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
Property.MergeFrom(other.Property);
}
if (other.boundingBox_ != null) {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
BoundingBox.MergeFrom(other.BoundingBox);
}
words_.Add(other.words_);
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
input.ReadMessage(property_);
break;
}
case 18: {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
input.ReadMessage(boundingBox_);
break;
}
case 26: {
words_.AddEntriesFrom(input, _repeated_words_codec);
break;
}
case 37: {
Confidence = input.ReadFloat();
break;
}
}
}
}
}
/// <summary>
/// A word representation.
/// </summary>
public sealed partial class Word : pb::IMessage<Word> {
private static readonly pb::MessageParser<Word> _parser = new pb::MessageParser<Word>(() => new Word());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Word> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Word() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Word(Word other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
BoundingBox = other.boundingBox_ != null ? other.BoundingBox.Clone() : null;
symbols_ = other.symbols_.Clone();
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Word Clone() {
return new Word(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty property_;
/// <summary>
/// Additional information detected for the word.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "bounding_box" field.</summary>
public const int BoundingBoxFieldNumber = 2;
private global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly boundingBox_;
/// <summary>
/// The bounding box for the word.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertice order will still be (0, 1, 2, 3).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly BoundingBox {
get { return boundingBox_; }
set {
boundingBox_ = value;
}
}
/// <summary>Field number for the "symbols" field.</summary>
public const int SymbolsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Vision.V1P1Beta1.Symbol> _repeated_symbols_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Vision.V1P1Beta1.Symbol.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Symbol> symbols_ = new pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Symbol>();
/// <summary>
/// List of symbols in the word.
/// The order of the symbols follows the natural reading order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Vision.V1P1Beta1.Symbol> Symbols {
get { return symbols_; }
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 4;
private float confidence_;
/// <summary>
/// Confidence of the OCR results for the word. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Word);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Word other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (!object.Equals(BoundingBox, other.BoundingBox)) return false;
if(!symbols_.Equals(other.symbols_)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (boundingBox_ != null) hash ^= BoundingBox.GetHashCode();
hash ^= symbols_.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (boundingBox_ != null) {
output.WriteRawTag(18);
output.WriteMessage(BoundingBox);
}
symbols_.WriteTo(output, _repeated_symbols_codec);
if (Confidence != 0F) {
output.WriteRawTag(37);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (boundingBox_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BoundingBox);
}
size += symbols_.CalculateSize(_repeated_symbols_codec);
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Word other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
Property.MergeFrom(other.Property);
}
if (other.boundingBox_ != null) {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
BoundingBox.MergeFrom(other.BoundingBox);
}
symbols_.Add(other.symbols_);
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
input.ReadMessage(property_);
break;
}
case 18: {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
input.ReadMessage(boundingBox_);
break;
}
case 26: {
symbols_.AddEntriesFrom(input, _repeated_symbols_codec);
break;
}
case 37: {
Confidence = input.ReadFloat();
break;
}
}
}
}
}
/// <summary>
/// A single symbol representation.
/// </summary>
public sealed partial class Symbol : pb::IMessage<Symbol> {
private static readonly pb::MessageParser<Symbol> _parser = new pb::MessageParser<Symbol>(() => new Symbol());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Symbol> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Vision.V1P1Beta1.TextAnnotationReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Symbol() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Symbol(Symbol other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
BoundingBox = other.boundingBox_ != null ? other.BoundingBox.Clone() : null;
text_ = other.text_;
confidence_ = other.confidence_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Symbol Clone() {
return new Symbol(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty property_;
/// <summary>
/// Additional information detected for the symbol.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "bounding_box" field.</summary>
public const int BoundingBoxFieldNumber = 2;
private global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly boundingBox_;
/// <summary>
/// The bounding box for the symbol.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertice order will still be (0, 1, 2, 3).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly BoundingBox {
get { return boundingBox_; }
set {
boundingBox_ = value;
}
}
/// <summary>Field number for the "text" field.</summary>
public const int TextFieldNumber = 3;
private string text_ = "";
/// <summary>
/// The actual UTF-8 representation of the symbol.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Text {
get { return text_; }
set {
text_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "confidence" field.</summary>
public const int ConfidenceFieldNumber = 4;
private float confidence_;
/// <summary>
/// Confidence of the OCR results for the symbol. Range [0, 1].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Confidence {
get { return confidence_; }
set {
confidence_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Symbol);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Symbol other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (!object.Equals(BoundingBox, other.BoundingBox)) return false;
if (Text != other.Text) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (boundingBox_ != null) hash ^= BoundingBox.GetHashCode();
if (Text.Length != 0) hash ^= Text.GetHashCode();
if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (boundingBox_ != null) {
output.WriteRawTag(18);
output.WriteMessage(BoundingBox);
}
if (Text.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Text);
}
if (Confidence != 0F) {
output.WriteRawTag(37);
output.WriteFloat(Confidence);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (boundingBox_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BoundingBox);
}
if (Text.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Text);
}
if (Confidence != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Symbol other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
Property.MergeFrom(other.Property);
}
if (other.boundingBox_ != null) {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
BoundingBox.MergeFrom(other.BoundingBox);
}
if (other.Text.Length != 0) {
Text = other.Text;
}
if (other.Confidence != 0F) {
Confidence = other.Confidence;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (property_ == null) {
property_ = new global::Google.Cloud.Vision.V1P1Beta1.TextAnnotation.Types.TextProperty();
}
input.ReadMessage(property_);
break;
}
case 18: {
if (boundingBox_ == null) {
boundingBox_ = new global::Google.Cloud.Vision.V1P1Beta1.BoundingPoly();
}
input.ReadMessage(boundingBox_);
break;
}
case 26: {
Text = input.ReadString();
break;
}
case 37: {
Confidence = input.ReadFloat();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 37.968897 | 493 | 0.639295 | [
"Apache-2.0"
] | kontab/google-cloud-dotnet | apis/Google.Cloud.Vision.V1P1Beta1/Google.Cloud.Vision.V1P1Beta1/TextAnnotation.cs | 80,570 | C# |
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 17.11.2020.
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.Common.Query.Sql.Expressions.Translators.Code{
////////////////////////////////////////////////////////////////////////////////
//using
using Structure_MemberIdCache
=Structure.Structure_MemberIdCache;
////////////////////////////////////////////////////////////////////////////////
//class FB_Common__Sql_ETranslator__NullableInt16__std__HasValue
static class FB_Common__Sql_ETranslator__NullableInt16__std__HasValue
{
public static readonly FB_Common__Sql_ETranslator_Member.tagDescr
Instance
=new FB_Common__Sql_ETranslator_Member.tagDescr
(Structure_MemberIdCache.MemberIdOf__NullableInt16__std__HasValue,
Internal.FB_Common__Sql_ETranslator__Nullable__std__HasValue.Instance);
};//class FB_Common__Sql_ETranslator__NullableInt16__std__HasValue
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.Common.Query.Sql.Expressions.Translators.Code
| 48.807692 | 132 | 0.619385 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source/Basement/EF/Dbms/Firebird/Common/Query/Sql/Expressions/Translators/Code/Funcs/NullableInt16/FB_Common__Sql_ETranslator__NullableInt16__std__HasValue.cs | 1,271 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalytics-2015-08-14.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.KinesisAnalytics.Model
{
/// <summary>
/// Container for the parameters to the DiscoverInputSchema operation.
/// <note>
/// <para>
/// This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which
/// only supports SQL applications. Version 2 of the API supports SQL and Java applications.
/// For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon
/// Kinesis Data Analytics API V2 Documentation</a>.
/// </para>
/// </note>
/// <para>
/// Infers a schema by evaluating sample records on the specified streaming source (Amazon
/// Kinesis stream or Amazon Kinesis Firehose delivery stream) or S3 object. In the response,
/// the operation returns the inferred schema and also the sample records that the operation
/// used to infer the schema.
/// </para>
///
/// <para>
/// You can use the inferred schema when configuring a streaming source for your application.
/// For conceptual information, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html">Configuring
/// Application Input</a>. Note that when you create an application using the Amazon Kinesis
/// Analytics console, the console uses this operation to infer a schema and show it in
/// the console user interface.
/// </para>
///
/// <para>
/// This operation requires permissions to perform the <code>kinesisanalytics:DiscoverInputSchema</code>
/// action.
/// </para>
/// </summary>
public partial class DiscoverInputSchemaRequest : AmazonKinesisAnalyticsRequest
{
private InputProcessingConfiguration _inputProcessingConfiguration;
private InputStartingPositionConfiguration _inputStartingPositionConfiguration;
private string _resourceARN;
private string _roleARN;
private S3Configuration _s3Configuration;
/// <summary>
/// Gets and sets the property InputProcessingConfiguration.
/// <para>
/// The <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_InputProcessingConfiguration.html">InputProcessingConfiguration</a>
/// to use to preprocess the records before discovering the schema of the records.
/// </para>
/// </summary>
public InputProcessingConfiguration InputProcessingConfiguration
{
get { return this._inputProcessingConfiguration; }
set { this._inputProcessingConfiguration = value; }
}
// Check to see if InputProcessingConfiguration property is set
internal bool IsSetInputProcessingConfiguration()
{
return this._inputProcessingConfiguration != null;
}
/// <summary>
/// Gets and sets the property InputStartingPositionConfiguration.
/// <para>
/// Point at which you want Amazon Kinesis Analytics to start reading records from the
/// specified streaming source discovery purposes.
/// </para>
/// </summary>
public InputStartingPositionConfiguration InputStartingPositionConfiguration
{
get { return this._inputStartingPositionConfiguration; }
set { this._inputStartingPositionConfiguration = value; }
}
// Check to see if InputStartingPositionConfiguration property is set
internal bool IsSetInputStartingPositionConfiguration()
{
return this._inputStartingPositionConfiguration != null;
}
/// <summary>
/// Gets and sets the property ResourceARN.
/// <para>
/// Amazon Resource Name (ARN) of the streaming source.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string ResourceARN
{
get { return this._resourceARN; }
set { this._resourceARN = value; }
}
// Check to see if ResourceARN property is set
internal bool IsSetResourceARN()
{
return this._resourceARN != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// ARN of the IAM role that Amazon Kinesis Analytics can assume to access the stream
/// on your behalf.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
/// <summary>
/// Gets and sets the property S3Configuration.
/// <para>
/// Specify this parameter to discover a schema from data in an Amazon S3 object.
/// </para>
/// </summary>
public S3Configuration S3Configuration
{
get { return this._s3Configuration; }
set { this._s3Configuration = value; }
}
// Check to see if S3Configuration property is set
internal bool IsSetS3Configuration()
{
return this._s3Configuration != null;
}
}
} | 38.630303 | 153 | 0.627393 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/KinesisAnalytics/Generated/Model/DiscoverInputSchemaRequest.cs | 6,374 | C# |
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4
#define UNITY_OLD_LINE_RENDERER
#endif
using UnityEngine;
using System.Collections.Generic;
namespace Lean.Touch
{
// This script shows you how you can check tos ee which part of the screen a finger is on, and work accordingly
public class LeanFingerShoot : MonoBehaviour
{
// This class will store an association between a Finger and a LineRenderer instance
[System.Serializable]
public class Link
{
public LeanFinger Finger;
public LineRenderer Line;
}
[Tooltip("Ignore fingers with StartedOverGui?")]
public bool IgnoreStartedOverGui = true;
[Tooltip("Ignore fingers with IsOverGui?")]
public bool IgnoreIsOverGui;
[Tooltip("The line prefab")]
public LineRenderer LinePrefab;
[Tooltip("The distance from the camera the line points will be spawned in world space")]
public float Distance = 1.0f;
[Tooltip("The prefab you want to throw")]
public GameObject ShootPrefab;
[Tooltip("The strength of the throw")]
public float Force = 1.0f;
public float Thickness = 1.0f;
public float Length = 1.0f;
[Tooltip("The maximum amount of fingers used")]
public int MaxLines;
[Tooltip("The camera the translation will be calculated using (default = MainCamera)")]
public Camera Camera;
private List<Link> links = new List<Link>();
protected virtual void OnEnable()
{
// Hook events
LeanTouch.OnFingerDown += FingerDown;
LeanTouch.OnFingerSet += FingerSet;
LeanTouch.OnFingerUp += FingerUp;
}
protected virtual void OnDisable()
{
// Unhook events
LeanTouch.OnFingerDown -= FingerDown;
LeanTouch.OnFingerSet -= FingerSet;
LeanTouch.OnFingerUp -= FingerUp;
}
// Override the WritePositions method from LeanDragLine
protected virtual void WritePositions(LineRenderer line, LeanFinger finger)
{
// Get start and current world position of finger
var start = finger.GetStartWorldPosition(Distance);
var end = finger.GetWorldPosition(Distance);
// Limit the length?
if (start != end)
{
end = start + Vector3.Normalize(end - start) * Length;
}
// Write positions
#if UNITY_OLD_LINE_RENDERER
line.SetVertexCount(2);
line.SetWidth(Thickness, Thickness);
#else
line.positionCount = 2;
line.startWidth = Thickness;
line.endWidth = Thickness;
#endif
line.SetPosition(0, start);
line.SetPosition(1, end);
}
private void FingerDown(LeanFinger finger)
{
// Ignore?
if (MaxLines > 0 && links.Count >= MaxLines)
{
return;
}
if (IgnoreStartedOverGui == true && finger.StartedOverGui == true)
{
return;
}
if (IgnoreIsOverGui == true && finger.IsOverGui == true)
{
return;
}
// Make new link
var link = new Link();
// Assign this finger to this link
link.Finger = finger;
// Create LineRenderer instance for this link
link.Line = Instantiate(LinePrefab);
// Add new link to list
links.Add(link);
}
private void FingerSet(LeanFinger finger)
{
// Try and find the link for this finger
var link = FindLink(finger);
// Link exists?
if (link != null && link.Line != null)
{
WritePositions(link.Line, link.Finger);
}
}
private void FingerUp(LeanFinger finger)
{
// Try and find the link for this finger
var link = FindLink(finger);
// Link exists?
if (link != null)
{
// Remove link from list
links.Remove(link);
// Destroy line GameObject
if (link.Line != null)
{
Destroy(link.Line.gameObject);
}
Shoot(finger);
}
}
private Link FindLink(LeanFinger finger)
{
for (var i = 0; i < links.Count; i++)
{
var link = links[i];
if (link.Finger == finger)
{
return link;
}
}
return null;
}
private void Shoot(LeanFinger finger)
{
// Start and end points of the drag
var start = finger.GetStartWorldPosition(Distance);
var end = finger.GetWorldPosition(Distance);
if (start != end)
{
// Vector between points
var direction = Vector3.Normalize(end - start);
// Angle between points
var angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
// Instance the prefab, position it at the start point, and rotate it to the vector
var instance = Instantiate(ShootPrefab);
instance.transform.position = start;
instance.transform.rotation = Quaternion.Euler(0.0f, 0.0f, -angle);
// Apply 3D force?
var rigidbody3D = instance.GetComponent<Rigidbody>();
if (rigidbody3D != null)
{
rigidbody3D.velocity = direction * Force;
}
// Apply 2D force?
var rigidbody2D = instance.GetComponent<Rigidbody2D>();
if (rigidbody2D != null)
{
rigidbody2D.velocity = direction * Force;
}
}
}
}
} | 22.772512 | 112 | 0.668887 | [
"Apache-2.0"
] | soniamaryc/ARUI_RandomObjectManipulation | Assets/LeanTouch/Examples+/Scripts/LeanFingerShoot.cs | 4,805 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Security;
namespace System.Runtime
{
internal class ExceptionTrace
{
private const ushort FailFastEventLogCategory = 6;
private string _eventSourceName;
private readonly EtwDiagnosticTrace _diagnosticTrace;
public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace)
{
Fx.Assert(diagnosticTrace != null, "'diagnosticTrace' MUST NOT be NULL.");
_eventSourceName = eventSourceName;
_diagnosticTrace = diagnosticTrace;
}
public void AsInformation(Exception exception)
{
//Traces an informational trace message
}
public void AsWarning(Exception exception)
{
//Traces a warning trace message
}
public Exception AsError(Exception exception)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException);
}
return TraceException(exception);
}
public Exception AsError(Exception exception, string eventSource)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException, eventSource);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException, eventSource);
}
return TraceException(exception, eventSource);
}
public Exception AsError(TargetInvocationException targetInvocationException, string eventSource)
{
Fx.Assert(targetInvocationException != null, "targetInvocationException cannot be null.");
// If targetInvocationException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(targetInvocationException))
{
return targetInvocationException;
}
// A non-null inner exception could require further unwrapping in AsError.
Exception innerException = targetInvocationException.InnerException;
if (innerException != null)
{
return AsError(innerException, eventSource);
}
// A null inner exception is unlikely but possible.
// In this case, trace and return the targetInvocationException itself.
return TraceException<Exception>(targetInvocationException, eventSource);
}
public Exception AsError<TPreferredException>(AggregateException aggregateException)
{
return AsError<TPreferredException>(aggregateException, _eventSourceName);
}
/// <summary>
/// Extracts the first inner exception of type <typeparamref name="TPreferredException"/>
/// from the <see cref="AggregateException"/> if one is present.
/// </summary>
/// <remarks>
/// If no <typeparamref name="TPreferredException"/> inner exception is present, this
/// method returns the first inner exception. All inner exceptions will be traced,
/// including the one returned. The containing <paramref name="aggregateException"/>
/// will not be traced unless there are no inner exceptions.
/// </remarks>
/// <typeparam name="TPreferredException">The preferred type of inner exception to extract.
/// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam>
/// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param>
/// <param name="eventSource">The event source to trace.</param>
/// <returns>The extracted exception. It will not be <c>null</c>
/// but it may not be of type <typeparamref name="TPreferredException"/>.</returns>
public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource)
{
Fx.Assert(aggregateException != null, "aggregateException cannot be null.");
// If aggregateException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(aggregateException))
{
return aggregateException;
}
// Collapse possibly nested graph into a flat list.
// Empty inner exception list is unlikely but possible via public api.
ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;
if (innerExceptions.Count == 0)
{
return TraceException(aggregateException, eventSource);
}
// Find the first inner exception, giving precedence to TPreferredException
Exception favoredException = null;
foreach (Exception nextInnerException in innerExceptions)
{
// AggregateException may wrap TargetInvocationException, so unwrap those as well
TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException;
Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null)
? targetInvocationException.InnerException
: nextInnerException;
if (innerException is TPreferredException && favoredException == null)
{
favoredException = innerException;
}
// All inner exceptions are traced
TraceException(innerException, eventSource);
}
if (favoredException == null)
{
Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here.");
favoredException = innerExceptions[0];
}
return favoredException;
}
public ArgumentException Argument(string paramName, string message)
{
return TraceException(new ArgumentException(message, paramName));
}
public ArgumentNullException ArgumentNull(string paramName)
{
return TraceException(new ArgumentNullException(paramName));
}
public ArgumentNullException ArgumentNull(string paramName, string message)
{
return TraceException(new ArgumentNullException(paramName, message));
}
public ArgumentException ArgumentNullOrEmpty(string paramName)
{
return Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName));
}
public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
{
return TraceException(new ArgumentOutOfRangeException(paramName, actualValue, message));
}
// When throwing ObjectDisposedException, it is highly recommended that you use this ctor
// [C#]
// public ObjectDisposedException(string objectName, string message);
// And provide null for objectName but meaningful and relevant message for message.
// It is recommended because end user really does not care or can do anything on the disposed object, commonly an internal or private object.
public ObjectDisposedException ObjectDisposed(string message)
{
// pass in null, not disposedObject.GetType().FullName as per the above guideline
return TraceException(new ObjectDisposedException(null, message));
}
public void TraceHandledException(Exception exception, TraceEventType traceEventType)
{
switch (traceEventType)
{
case TraceEventType.Error:
if (!TraceCore.HandledExceptionErrorIsEnabled(_diagnosticTrace))
break;
TraceCore.HandledExceptionError(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
break;
case TraceEventType.Warning:
if (!TraceCore.HandledExceptionWarningIsEnabled(_diagnosticTrace))
break;
TraceCore.HandledExceptionWarning(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
break;
case TraceEventType.Verbose:
if (!TraceCore.HandledExceptionVerboseIsEnabled(_diagnosticTrace))
break;
TraceCore.HandledExceptionVerbose(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
break;
default:
if (!TraceCore.HandledExceptionIsEnabled(_diagnosticTrace))
break;
TraceCore.HandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
break;
}
}
public void TraceUnhandledException(Exception exception)
{
TraceCore.UnhandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
}
public void TraceEtwException(Exception exception, EventLevel eventLevel)
{
switch (eventLevel)
{
case EventLevel.Error:
case EventLevel.Warning:
if (WcfEventSource.Instance.ThrowingEtwExceptionIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.ThrowingEtwException(_eventSourceName, exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
case EventLevel.Critical:
if (WcfEventSource.Instance.UnhandledExceptionIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.EtwUnhandledException(exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
default:
if (WcfEventSource.Instance.ThrowingExceptionVerboseIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.ThrowingEtwExceptionVerbose(_eventSourceName, exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
}
}
private TException TraceException<TException>(TException exception)
where TException : Exception
{
return TraceException(exception, _eventSourceName);
}
[Fx.Tag.SecurityNote(Critical = "Calls 'System.Runtime.Interop.UnsafeNativeMethods.IsDebuggerPresent()' which is a P/Invoke method",
Safe = "Does not leak any resource, needed for debugging")]
[SecuritySafeCritical]
private TException TraceException<TException>(TException exception, string eventSource)
where TException : Exception
{
if (TraceCore.ThrowingExceptionIsEnabled(_diagnosticTrace))
{
TraceCore.ThrowingException(_diagnosticTrace, eventSource, exception != null ? exception.ToString() : string.Empty, exception);
}
BreakOnException(exception);
return exception;
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical method UnsafeNativeMethods.IsDebuggerPresent and UnsafeNativeMethods.DebugBreak",
Safe = "Safe because it's a no-op in retail builds.")]
[SecuritySafeCritical]
private void BreakOnException(Exception exception)
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void TraceFailFast(string message)
{
}
}
}
| 45.266447 | 172 | 0.632294 | [
"MIT"
] | GrabYourPitchforks/wcf | src/System.Private.ServiceModel/src/Internals/System/Runtime/ExceptionTrace.cs | 13,761 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsRequiredOptional.Models
{
using System.Linq;
public partial class IntWrapper
{
/// <summary>
/// Initializes a new instance of the IntWrapper class.
/// </summary>
public IntWrapper() { }
/// <summary>
/// Initializes a new instance of the IntWrapper class.
/// </summary>
public IntWrapper(int value)
{
Value = value;
}
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "value")]
public int Value { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
//Nothing to validate
}
}
}
| 27.377778 | 74 | 0.587662 | [
"MIT"
] | fhoering/autorest | src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/Models/IntWrapper.cs | 1,232 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601
{
using static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Extensions;
/// <summary>A list of server configurations.</summary>
public partial class ConfigurationListResultAutoGenerated :
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationListResultAutoGenerated,
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationListResultAutoGeneratedInternal
{
/// <summary>Backing field for <see cref="NextLink" /> property.</summary>
private string _nextLink;
/// <summary>The link used to get the next page of operations.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Origin(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.PropertyOrigin.Owned)]
public string NextLink { get => this._nextLink; set => this._nextLink = value; }
/// <summary>Backing field for <see cref="Value" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationAutoGenerated[] _value;
/// <summary>The list of server configurations.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Origin(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationAutoGenerated[] Value { get => this._value; set => this._value = value; }
/// <summary>Creates an new <see cref="ConfigurationListResultAutoGenerated" /> instance.</summary>
public ConfigurationListResultAutoGenerated()
{
}
}
/// A list of server configurations.
public partial interface IConfigurationListResultAutoGenerated :
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IJsonSerializable
{
/// <summary>The link used to get the next page of operations.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The link used to get the next page of operations.",
SerializedName = @"nextLink",
PossibleTypes = new [] { typeof(string) })]
string NextLink { get; set; }
/// <summary>The list of server configurations.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The list of server configurations.",
SerializedName = @"value",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationAutoGenerated) })]
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationAutoGenerated[] Value { get; set; }
}
/// A list of server configurations.
internal partial interface IConfigurationListResultAutoGeneratedInternal
{
/// <summary>The link used to get the next page of operations.</summary>
string NextLink { get; set; }
/// <summary>The list of server configurations.</summary>
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IConfigurationAutoGenerated[] Value { get; set; }
}
} | 53.852941 | 168 | 0.70781 | [
"MIT"
] | Agazoth/azure-powershell | src/PostgreSql/generated/api/Models/Api20210601/ConfigurationListResultAutoGenerated.cs | 3,595 | C# |
namespace Greenergy.Settings
{
public class MongoSettings
{
public string ConnectionString;
public string Database;
}
} | 19.375 | 47 | 0.632258 | [
"MIT"
] | sorbra/greenergy | emissions-api/emissions-api.server/Settings/MongoSettings.cs | 155 | C# |
using AutoMapper;
using Bloemert.Data.Entity.Auth.Entity;
using Bloemert.Data.Entity.Auth.Repository;
using Bloemert.Data.Entity.Skills.Entity;
using Bloemert.Lib.Auto.Mapping.AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
namespace Bloemert.WebAPI.Skills.Models.Mappers
{
public class SkillCategoryMapperProfile : TwoWayMappingProfile<SkillCategory, SkillCategoryModel>
{
protected override void ConfigureMapping(IMappingExpression<SkillCategoryModel, SkillCategory> map)
{
}
protected override void ConfigureMapping(IMappingExpression<SkillCategory, SkillCategoryModel> map)
{
}
}
}
| 27.608696 | 101 | 0.818898 | [
"MIT"
] | Bloemert/Einstein | src/Bloemert.WebAPI.Skills/Models/Mappers/SkillCategoryMapperProfile.cs | 637 | C# |
//
// Copyright (c) 2010-2018 Antmicro
// Copyright (c) 2011-2015 Realtime Embedded
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using Antmicro.Renode.Core.Structure;
using System.Collections.Generic;
using System.Linq;
using System;
using Antmicro.Migrant;
using Antmicro.Renode.Peripherals;
using Antmicro.Renode.Exceptions;
using Antmicro.Renode.UserInterface;
namespace Antmicro.Renode.Core
{
[Icon("comp")]
[ControllerMask(typeof(IExternal))]
public class HostMachine : IExternal, IHasChildren<IHostMachineElement>, IDisposable
{
public HostMachine()
{
hostEmulationElements = new Dictionary<string, IHostMachineElement>();
}
public void AddHostMachineElement(IHostMachineElement element, string name)
{
if(hostEmulationElements.ContainsKey(name))
{
throw new RecoverableException("Element with the same name already exists");
}
hostEmulationElements.Add(name, element);
var elementAsIHasOwnLife = element as IHasOwnLife;
if(elementAsIHasOwnLife != null)
{
EmulationManager.Instance.CurrentEmulation.ExternalsManager.RegisterIHasOwnLife(elementAsIHasOwnLife);
}
var cc = ContentChanged;
if(cc != null)
{
cc();
}
}
public void RemoveHostMachineElement(string name)
{
RemoveHostMachineElement(hostEmulationElements[name]);
}
public void RemoveHostMachineElement(IHostMachineElement element)
{
var elementAsIHasOwnLife = element as IHasOwnLife;
if(elementAsIHasOwnLife != null)
{
EmulationManager.Instance.CurrentEmulation.ExternalsManager.UnregisterIHasOwnLife(elementAsIHasOwnLife);
}
var key = hostEmulationElements.SingleOrDefault(x => x.Value == element).Key;
hostEmulationElements.Remove(key);
var cc = ContentChanged;
if(cc != null)
{
cc();
}
}
public IEnumerable<string> GetNames()
{
return hostEmulationElements.Keys;
}
public IHostMachineElement TryGetByName(string name, out bool success)
{
IHostMachineElement value;
success = hostEmulationElements.TryGetValue(name, out value);
return value;
}
public bool TryGetName(IHostMachineElement element, out string name)
{
var pair = hostEmulationElements.SingleOrDefault(x => x.Value == element);
if(pair.Value == element)
{
name = pair.Key;
return true;
}
name = null;
return false;
}
#region IDisposable implementation
public void Dispose()
{
foreach(var element in hostEmulationElements)
{
var disposable = element.Value as IDisposable;
if(disposable != null)
{
disposable.Dispose();
}
}
}
#endregion
[field: Transient]
public event Action ContentChanged;
private readonly Dictionary<string, IHostMachineElement> hostEmulationElements;
public const string HostMachineName = "host";
}
}
| 28.5 | 120 | 0.589983 | [
"MIT"
] | UPBIoT/renode-iot | src/Infrastructure/src/Emulator/Main/Core/HostMachine.cs | 3,534 | C# |
namespace Assets.Scripts.Levels
{
class Advanced17 : GameLevel
{
public Advanced17()
: base("Advanced17")
{
Initialize(3, 5);
MapButtons = new int[,]
{
{YLW, GRN, YLW},
{OFF, LIT, OFF},
{GRN, LIT, GRN},
};
}
public override GameLevel NextLevel
{
get
{
return new Advanced21();
}
}
}
}
| 20.24 | 43 | 0.37747 | [
"MIT"
] | magius96/ShortCircuit_Android | Assets/Scripts/Levels/Advanced/1/Advanced17.cs | 508 | C# |
#region License
/*
* WebSocket.cs
*
* This code is derived from WebSocket.java
* (http://github.com/adamac/Java-WebSocket-client).
*
* The MIT License
*
* Copyright (c) 2009 Adam MacBeth
* Copyright (c) 2010-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Frank Razenberg <frank@zzattack.org>
* - David Wood <dpwood@gmail.com>
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp
{
/// <summary>
/// Implements the WebSocket interface.
/// </summary>
/// <remarks>
/// <para>
/// This class provides a set of methods and properties for two-way
/// communication using the WebSocket protocol.
/// </para>
/// <para>
/// The WebSocket protocol is defined in
/// <see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>.
/// </para>
/// </remarks>
public class WebSocket : IDisposable
{
#region Private Fields
private AuthenticationChallenge _authChallenge;
private string _base64Key;
private bool _client;
private Action _closeContext;
private CompressionMethod _compression;
private WebSocketContext _context;
private CookieCollection _cookies;
private NetworkCredential _credentials;
private bool _emitOnPing;
private bool _enableRedirection;
private string _extensions;
private bool _extensionsRequested;
private object _forMessageEventQueue;
private object _forPing;
private object _forSend;
private object _forState;
private MemoryStream _fragmentsBuffer;
private bool _fragmentsCompressed;
private Opcode _fragmentsOpcode;
private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private Func<WebSocketContext, string> _handshakeRequestChecker;
private bool _ignoreExtensions;
private bool _inContinuation;
private volatile bool _inMessage;
private volatile Logger _logger;
private static readonly int _maxRetryCountForConnect;
private Action<MessageEventArgs> _message;
private Queue<MessageEventArgs> _messageEventQueue;
private uint _nonceCount;
private string _origin;
private ManualResetEvent _pongReceived;
private bool _preAuth;
private string _protocol;
private string[] _protocols;
private bool _protocolsRequested;
private NetworkCredential _proxyCredentials;
private Uri _proxyUri;
private volatile WebSocketState _readyState;
private ManualResetEvent _receivingExited;
private int _retryCountForConnect;
private bool _secure;
private ClientSslConfiguration _sslConfig;
private Stream _stream;
private TcpClient _tcpClient;
private Uri _uri;
private const string _version = "13";
private TimeSpan _waitTime;
#endregion
#region Internal Fields
/// <summary>
/// Represents the empty array of <see cref="byte"/> used internally.
/// </summary>
internal static readonly byte[] EmptyBytes;
/// <summary>
/// Represents the length used to determine whether the data should be fragmented in sending.
/// </summary>
/// <remarks>
/// <para>
/// The data will be fragmented if that length is greater than the value of this field.
/// </para>
/// <para>
/// If you would like to change the value, you must set it to a value between <c>125</c> and
/// <c>Int32.MaxValue - 14</c> inclusive.
/// </para>
/// </remarks>
internal static readonly int FragmentLength;
/// <summary>
/// Represents the random number generator used internally.
/// </summary>
internal static readonly RandomNumberGenerator RandomNumber;
#endregion
#region Static Constructor
static WebSocket ()
{
_maxRetryCountForConnect = 10;
EmptyBytes = new byte[0];
FragmentLength = 1016;
RandomNumber = new RNGCryptoServiceProvider ();
}
#endregion
#region Internal Constructors
// As server
internal WebSocket (HttpListenerWebSocketContext context, string protocol)
{
_context = context;
_protocol = protocol;
_closeContext = context.Close;
_logger = context.Log;
_message = messages;
_secure = context.IsSecureConnection;
_stream = context.Stream;
_waitTime = TimeSpan.FromSeconds (1);
init ();
}
// As server
internal WebSocket (TcpListenerWebSocketContext context, string protocol)
{
_context = context;
_protocol = protocol;
_closeContext = context.Close;
_logger = context.Log;
_message = messages;
_secure = context.IsSecureConnection;
_stream = context.Stream;
_waitTime = TimeSpan.FromSeconds (1);
init ();
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocket"/> class with
/// <paramref name="url"/> and optionally <paramref name="protocols"/>.
/// </summary>
/// <param name="url">
/// <para>
/// A <see cref="string"/> that specifies the URL to which to connect.
/// </para>
/// <para>
/// The scheme of the URL must be ws or wss.
/// </para>
/// <para>
/// The new instance uses a secure connection if the scheme is wss.
/// </para>
/// </param>
/// <param name="protocols">
/// <para>
/// An array of <see cref="string"/> that specifies the names of
/// the subprotocols if necessary.
/// </para>
/// <para>
/// Each value of the array must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
/// RFC 2616</see>.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is an invalid WebSocket URL string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocols"/> contains a value that is not a token.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocols"/> contains a value twice.
/// </para>
/// </exception>
public WebSocket (string url, params string[] protocols)
{
if (url == null)
throw new ArgumentNullException ("url");
if (url.Length == 0)
throw new ArgumentException ("An empty string.", "url");
string msg;
if (!url.TryCreateWebSocketUri (out _uri, out msg))
throw new ArgumentException (msg, "url");
if (protocols != null && protocols.Length > 0) {
if (!checkProtocols (protocols, out msg))
throw new ArgumentException (msg, "protocols");
_protocols = protocols;
}
_base64Key = CreateBase64Key ();
_client = true;
_logger = new Logger ();
_message = messagec;
_secure = _uri.Scheme == "wss";
_waitTime = TimeSpan.FromSeconds (5);
init ();
}
#endregion
#region Internal Properties
internal CookieCollection CookieCollection {
get {
return _cookies;
}
}
// As server
internal Func<WebSocketContext, string> CustomHandshakeRequestChecker {
get {
return _handshakeRequestChecker;
}
set {
_handshakeRequestChecker = value;
}
}
internal bool HasMessage {
get {
lock (_forMessageEventQueue)
return _messageEventQueue.Count > 0;
}
}
// As server
internal bool IgnoreExtensions {
get {
return _ignoreExtensions;
}
set {
_ignoreExtensions = value;
}
}
internal bool IsConnected {
get {
return _readyState == WebSocketState.Open || _readyState == WebSocketState.Closing;
}
}
#endregion
#region Public Properties
private static string _header_UserAgent = "websocket-sharp/1.0";
public static String Header_UserAgent {
get
{
return _header_UserAgent;
}
set
{
if (String.IsNullOrWhiteSpace(value))
_header_UserAgent = String.Empty;
else
_header_UserAgent = value;
}
}
/// <summary>
/// Gets or sets the compression method used to compress a message.
/// </summary>
/// <remarks>
/// The set operation does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <value>
/// <para>
/// One of the <see cref="CompressionMethod"/> enum values.
/// </para>
/// <para>
/// It specifies the compression method used to compress a message.
/// </para>
/// <para>
/// The default value is <see cref="CompressionMethod.None"/>.
/// </para>
/// </value>
/// <exception cref="InvalidOperationException">
/// The set operation is not available if this instance is not a client.
/// </exception>
public CompressionMethod Compression {
get {
return _compression;
}
set {
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
_compression = value;
}
}
}
/// <summary>
/// Gets the HTTP cookies included in the handshake request/response.
/// </summary>
/// <value>
/// <para>
/// An <see cref="T:System.Collections.Generic.IEnumerable{WebSocketSharp.Net.Cookie}"/>
/// instance.
/// </para>
/// <para>
/// It provides an enumerator which supports the iteration over
/// the collection of the cookies.
/// </para>
/// </value>
public IEnumerable<Cookie> Cookies {
get {
lock (_cookies.SyncRoot) {
foreach (Cookie cookie in _cookies)
yield return cookie;
}
}
}
/// <summary>
/// Gets the credentials for the HTTP authentication (Basic/Digest).
/// </summary>
/// <value>
/// <para>
/// A <see cref="NetworkCredential"/> that represents the credentials
/// used to authenticate the client.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public NetworkCredential Credentials {
get {
return _credentials;
}
}
/// <summary>
/// Gets or sets a value indicating whether a <see cref="OnMessage"/> event
/// is emitted when a ping is received.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if this instance emits a <see cref="OnMessage"/> event
/// when receives a ping; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool EmitOnPing {
get {
return _emitOnPing;
}
set {
_emitOnPing = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the URL redirection for
/// the handshake request is allowed.
/// </summary>
/// <remarks>
/// The set operation does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if this instance allows the URL redirection for
/// the handshake request; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
/// <exception cref="InvalidOperationException">
/// The set operation is not available if this instance is not a client.
/// </exception>
public bool EnableRedirection {
get {
return _enableRedirection;
}
set {
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
_enableRedirection = value;
}
}
}
/// <summary>
/// Gets the extensions selected by server.
/// </summary>
/// <value>
/// A <see cref="string"/> that will be a list of the extensions
/// negotiated between client and server, or an empty string if
/// not specified or selected.
/// </value>
public string Extensions {
get {
return _extensions ?? String.Empty;
}
}
/// <summary>
/// Gets a value indicating whether the connection is alive.
/// </summary>
/// <remarks>
/// The get operation returns the value by using a ping/pong
/// if the current state of the connection is Open.
/// </remarks>
/// <value>
/// <c>true</c> if the connection is alive; otherwise, <c>false</c>.
/// </value>
public bool IsAlive {
get {
return ping (EmptyBytes);
}
}
/// <summary>
/// Gets a value indicating whether a secure connection is used.
/// </summary>
/// <value>
/// <c>true</c> if this instance uses a secure connection; otherwise,
/// <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets the logging function.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging function.
/// </value>
public Logger Log {
get {
return _logger;
}
internal set {
_logger = value;
}
}
/// <summary>
/// Gets or sets the value of the HTTP Origin header to send with
/// the handshake request.
/// </summary>
/// <remarks>
/// <para>
/// The HTTP Origin header is defined in
/// <see href="http://tools.ietf.org/html/rfc6454#section-7">
/// Section 7 of RFC 6454</see>.
/// </para>
/// <para>
/// This instance sends the Origin header if this property has any.
/// </para>
/// <para>
/// The set operation does nothing if the connection has already been
/// established or it is closing.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Origin
/// header to send.
/// </para>
/// <para>
/// The syntax is <scheme>://<host>[:<port>].
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
/// <exception cref="InvalidOperationException">
/// The set operation is not available if this instance is not a client.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The value specified for a set operation is not an absolute URI string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The value specified for a set operation includes the path segments.
/// </para>
/// </exception>
public string Origin {
get {
return _origin;
}
set {
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (!value.IsNullOrEmpty ()) {
Uri uri;
if (!Uri.TryCreate (value, UriKind.Absolute, out uri)) {
msg = "Not an absolute URI string.";
throw new ArgumentException (msg, "value");
}
if (uri.Segments.Length > 1) {
msg = "It includes the path segments.";
throw new ArgumentException (msg, "value");
}
}
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
_origin = !value.IsNullOrEmpty () ? value.TrimEnd ('/') : value;
}
}
}
/// <summary>
/// Gets the name of subprotocol selected by the server.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that will be one of the names of
/// subprotocols specified by client.
/// </para>
/// <para>
/// An empty string if not specified or selected.
/// </para>
/// </value>
public string Protocol {
get {
return _protocol ?? String.Empty;
}
internal set {
_protocol = value;
}
}
/// <summary>
/// Gets the current state of the connection.
/// </summary>
/// <value>
/// <para>
/// One of the <see cref="WebSocketState"/> enum values.
/// </para>
/// <para>
/// It indicates the current state of the connection.
/// </para>
/// <para>
/// The default value is <see cref="WebSocketState.Connecting"/>.
/// </para>
/// </value>
public WebSocketState ReadyState {
get {
return _readyState;
}
}
/// <summary>
/// Gets the configuration for secure connection.
/// </summary>
/// <remarks>
/// This configuration will be referenced when attempts to connect,
/// so it must be configured before any connect method is called.
/// </remarks>
/// <value>
/// A <see cref="ClientSslConfiguration"/> that represents
/// the configuration used to establish a secure connection.
/// </value>
/// <exception cref="InvalidOperationException">
/// <para>
/// This instance is not a client.
/// </para>
/// <para>
/// This instance does not use a secure connection.
/// </para>
/// </exception>
public ClientSslConfiguration SslConfiguration {
get {
if (!_client) {
var msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (!_secure) {
var msg = "This instance does not use a secure connection.";
throw new InvalidOperationException (msg);
}
return getSslConfiguration ();
}
}
/// <summary>
/// Gets the URL to which to connect.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the URL to which to connect.
/// </value>
public Uri Url {
get {
return _client ? _uri : _context.RequestUri;
}
}
/// <summary>
/// Gets or sets the time to wait for the response to the ping or close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="TimeSpan"/> to wait for the response.
/// </para>
/// <para>
/// The default value is the same as 5 seconds if this instance is
/// a client.
/// </para>
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _waitTime;
}
set {
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("value", "Zero or less.");
string msg;
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
_waitTime = value;
}
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the WebSocket connection has been closed.
/// </summary>
public event EventHandler<CloseEventArgs> OnClose;
/// <summary>
/// Occurs when the <see cref="WebSocket"/> gets an error.
/// </summary>
public event EventHandler<ErrorEventArgs> OnError;
/// <summary>
/// Occurs when the <see cref="WebSocket"/> receives a message.
/// </summary>
public event EventHandler<MessageEventArgs> OnMessage;
/// <summary>
/// Occurs when the WebSocket connection has been established.
/// </summary>
public event EventHandler OnOpen;
#endregion
#region Private Methods
// As server
private bool accept ()
{
if (_readyState == WebSocketState.Open) {
var msg = "The handshake request has already been accepted.";
_logger.Warn (msg);
return false;
}
lock (_forState) {
if (_readyState == WebSocketState.Open) {
var msg = "The handshake request has already been accepted.";
_logger.Warn (msg);
return false;
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process has set in.";
_logger.Error (msg);
msg = "An interruption has occurred while attempting to accept.";
error (msg, null);
return false;
}
if (_readyState == WebSocketState.Closed) {
var msg = "The connection has been closed.";
_logger.Error (msg);
msg = "An interruption has occurred while attempting to accept.";
error (msg, null);
return false;
}
try {
if (!acceptHandshake ())
return false;
}
catch (Exception ex) {
_logger.Fatal (ex.Message);
_logger.Debug (ex.ToString ());
var msg = "An exception has occurred while attempting to accept.";
fatal (msg, ex);
return false;
}
_readyState = WebSocketState.Open;
return true;
}
}
// As server
private bool acceptHandshake ()
{
_logger.Debug (
String.Format (
"A handshake request from {0}:\n{1}", _context.UserEndPoint, _context
)
);
string msg;
if (!checkHandshakeRequest (_context, out msg)) {
_logger.Error (msg);
refuseHandshake (
CloseStatusCode.ProtocolError,
"A handshake error has occurred while attempting to accept."
);
return false;
}
if (!customCheckHandshakeRequest (_context, out msg)) {
_logger.Error (msg);
refuseHandshake (
CloseStatusCode.PolicyViolation,
"A handshake error has occurred while attempting to accept."
);
return false;
}
_base64Key = _context.Headers["Sec-WebSocket-Key"];
if (_protocol != null) {
var vals = _context.SecWebSocketProtocols;
processSecWebSocketProtocolClientHeader (vals);
}
if (!_ignoreExtensions) {
var val = _context.Headers["Sec-WebSocket-Extensions"];
processSecWebSocketExtensionsClientHeader (val);
}
return sendHttpResponse (createHandshakeResponse ());
}
private bool canSet (out string message)
{
message = null;
if (_readyState == WebSocketState.Open) {
message = "The connection has already been established.";
return false;
}
if (_readyState == WebSocketState.Closing) {
message = "The connection is closing.";
return false;
}
return true;
}
// As server
private bool checkHandshakeRequest (
WebSocketContext context, out string message
)
{
message = null;
if (!context.IsWebSocketRequest) {
message = "Not a handshake request.";
return false;
}
if (context.RequestUri == null) {
message = "It specifies an invalid Request-URI.";
return false;
}
var headers = context.Headers;
var key = headers["Sec-WebSocket-Key"];
if (key == null) {
message = "It includes no Sec-WebSocket-Key header.";
return false;
}
if (key.Length == 0) {
message = "It includes an invalid Sec-WebSocket-Key header.";
return false;
}
var version = headers["Sec-WebSocket-Version"];
if (version == null) {
message = "It includes no Sec-WebSocket-Version header.";
return false;
}
if (version != _version) {
message = "It includes an invalid Sec-WebSocket-Version header.";
return false;
}
var protocol = headers["Sec-WebSocket-Protocol"];
if (protocol != null && protocol.Length == 0) {
message = "It includes an invalid Sec-WebSocket-Protocol header.";
return false;
}
if (!_ignoreExtensions) {
var extensions = headers["Sec-WebSocket-Extensions"];
if (extensions != null && extensions.Length == 0) {
message = "It includes an invalid Sec-WebSocket-Extensions header.";
return false;
}
}
return true;
}
// As client
private bool checkHandshakeResponse (HttpResponse response, out string message)
{
message = null;
if (response.IsRedirect) {
message = "Indicates the redirection.";
return false;
}
if (response.IsUnauthorized) {
message = "Requires the authentication.";
return false;
}
if (!response.IsWebSocketResponse) {
message = "Not a WebSocket handshake response.";
return false;
}
var headers = response.Headers;
if (!validateSecWebSocketAcceptHeader (headers["Sec-WebSocket-Accept"])) {
message = "Includes no Sec-WebSocket-Accept header, or it has an invalid value.";
return false;
}
if (!validateSecWebSocketProtocolServerHeader (headers["Sec-WebSocket-Protocol"])) {
message = "Includes no Sec-WebSocket-Protocol header, or it has an invalid value.";
return false;
}
if (!validateSecWebSocketExtensionsServerHeader (headers["Sec-WebSocket-Extensions"])) {
message = "Includes an invalid Sec-WebSocket-Extensions header.";
return false;
}
if (!validateSecWebSocketVersionServerHeader (headers["Sec-WebSocket-Version"])) {
message = "Includes an invalid Sec-WebSocket-Version header.";
return false;
}
return true;
}
private static bool checkProtocols (string[] protocols, out string message)
{
message = null;
Func<string, bool> cond = protocol => protocol.IsNullOrEmpty ()
|| !protocol.IsToken ();
if (protocols.Contains (cond)) {
message = "It contains a value that is not a token.";
return false;
}
if (protocols.ContainsTwice ()) {
message = "It contains a value twice.";
return false;
}
return true;
}
private bool checkReceivedFrame (WebSocketFrame frame, out string message)
{
message = null;
var masked = frame.IsMasked;
if (_client && masked) {
message = "A frame from the server is masked.";
return false;
}
if (!_client && !masked) {
message = "A frame from a client is not masked.";
return false;
}
if (_inContinuation && frame.IsData) {
message = "A data frame has been received while receiving continuation frames.";
return false;
}
if (frame.IsCompressed && _compression == CompressionMethod.None) {
message = "A compressed frame has been received without any agreement for it.";
return false;
}
if (frame.Rsv2 == Rsv.On) {
message = "The RSV2 of a frame is non-zero without any negotiation for it.";
return false;
}
if (frame.Rsv3 == Rsv.On) {
message = "The RSV3 of a frame is non-zero without any negotiation for it.";
return false;
}
return true;
}
private void close (ushort code, string reason)
{
if (_readyState == WebSocketState.Closing) {
_logger.Info ("The closing is already in progress.");
return;
}
if (_readyState == WebSocketState.Closed) {
_logger.Info ("The connection has already been closed.");
return;
}
if (code == 1005) { // == no status
close (PayloadData.Empty, true, true, false);
return;
}
var send = !code.IsReserved ();
close (new PayloadData (code, reason), send, send, false);
}
private void close (
PayloadData payloadData, bool send, bool receive, bool received
)
{
lock (_forState) {
if (_readyState == WebSocketState.Closing) {
_logger.Info ("The closing is already in progress.");
return;
}
if (_readyState == WebSocketState.Closed) {
_logger.Info ("The connection has already been closed.");
return;
}
send = send && _readyState == WebSocketState.Open;
receive = send && receive;
_readyState = WebSocketState.Closing;
}
_logger.Trace ("Begin closing the connection.");
var res = closeHandshake (payloadData, send, receive, received);
releaseResources ();
_logger.Trace ("End closing the connection.");
_readyState = WebSocketState.Closed;
var e = new CloseEventArgs (payloadData, res);
try {
OnClose.Emit (this, e);
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
}
}
private void closeAsync (ushort code, string reason)
{
if (_readyState == WebSocketState.Closing) {
_logger.Info ("The closing is already in progress.");
return;
}
if (_readyState == WebSocketState.Closed) {
_logger.Info ("The connection has already been closed.");
return;
}
if (code == 1005) { // == no status
closeAsync (PayloadData.Empty, true, true, false);
return;
}
var send = !code.IsReserved ();
closeAsync (new PayloadData (code, reason), send, send, false);
}
private void closeAsync (
PayloadData payloadData, bool send, bool receive, bool received
)
{
Action<PayloadData, bool, bool, bool> closer = close;
closer.BeginInvoke (
payloadData, send, receive, received, ar => closer.EndInvoke (ar), null
);
}
private bool closeHandshake (byte[] frameAsBytes, bool receive, bool received)
{
var sent = frameAsBytes != null && sendBytes (frameAsBytes);
var wait = !received && sent && receive && _receivingExited != null;
if (wait)
received = _receivingExited.WaitOne (_waitTime);
var ret = sent && received;
_logger.Debug (
String.Format (
"Was clean?: {0}\n sent: {1}\n received: {2}", ret, sent, received
)
);
return ret;
}
private bool closeHandshake (
PayloadData payloadData, bool send, bool receive, bool received
)
{
var sent = false;
if (send) {
var frame = WebSocketFrame.CreateCloseFrame (payloadData, _client);
sent = sendBytes (frame.ToArray ());
if (_client)
frame.Unmask ();
}
var wait = !received && sent && receive && _receivingExited != null;
if (wait)
received = _receivingExited.WaitOne (_waitTime);
var ret = sent && received;
_logger.Debug (
String.Format (
"Was clean?: {0}\n sent: {1}\n received: {2}", ret, sent, received
)
);
return ret;
}
// As client
private bool connect ()
{
if (_readyState == WebSocketState.Open) {
var msg = "The connection has already been established.";
_logger.Warn (msg);
return false;
}
lock (_forState) {
if (_readyState == WebSocketState.Open) {
var msg = "The connection has already been established.";
_logger.Warn (msg);
return false;
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process has set in.";
_logger.Error (msg);
msg = "An interruption has occurred while attempting to connect.";
error (msg, null);
return false;
}
if (_retryCountForConnect > _maxRetryCountForConnect) {
var msg = "An opportunity for reconnecting has been lost.";
_logger.Error (msg);
msg = "An interruption has occurred while attempting to connect.";
error (msg, null);
return false;
}
_readyState = WebSocketState.Connecting;
try {
doHandshake ();
}
catch (Exception ex) {
_retryCountForConnect++;
_logger.Fatal (ex.Message);
_logger.Debug (ex.ToString ());
var msg = "An exception has occurred while attempting to connect.";
fatal (msg, ex);
return false;
}
_retryCountForConnect = 1;
_readyState = WebSocketState.Open;
return true;
}
}
// As client
private string createExtensions ()
{
var buff = new StringBuilder (80);
if (_compression != CompressionMethod.None) {
var str = _compression.ToExtensionString (
"server_no_context_takeover", "client_no_context_takeover");
buff.AppendFormat ("{0}, ", str);
}
var len = buff.Length;
if (len > 2) {
buff.Length = len - 2;
return buff.ToString ();
}
return null;
}
// As server
private HttpResponse createHandshakeFailureResponse (HttpStatusCode code)
{
var ret = HttpResponse.CreateCloseResponse (code);
ret.Headers["Sec-WebSocket-Version"] = _version;
return ret;
}
// As client
private HttpRequest createHandshakeRequest ()
{
var ret = HttpRequest.CreateWebSocketRequest (_uri);
var headers = ret.Headers;
if (!_origin.IsNullOrEmpty ())
headers["Origin"] = _origin;
headers["Sec-WebSocket-Key"] = _base64Key;
_protocolsRequested = _protocols != null;
if (_protocolsRequested)
headers["Sec-WebSocket-Protocol"] = _protocols.ToString (", ");
_extensionsRequested = _compression != CompressionMethod.None;
if (_extensionsRequested)
headers["Sec-WebSocket-Extensions"] = createExtensions ();
headers["Sec-WebSocket-Version"] = _version;
AuthenticationResponse authRes = null;
if (_authChallenge != null && _credentials != null) {
authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
_nonceCount = authRes.NonceCount;
}
else if (_preAuth) {
authRes = new AuthenticationResponse (_credentials);
}
if (authRes != null)
headers["Authorization"] = authRes.ToString ();
if (_cookies.Count > 0)
ret.SetCookies (_cookies);
return ret;
}
// As server
private HttpResponse createHandshakeResponse ()
{
var ret = HttpResponse.CreateWebSocketResponse ();
var headers = ret.Headers;
headers["Sec-WebSocket-Accept"] = CreateResponseKey (_base64Key);
if (_protocol != null)
headers["Sec-WebSocket-Protocol"] = _protocol;
if (_extensions != null)
headers["Sec-WebSocket-Extensions"] = _extensions;
if (_cookies.Count > 0)
ret.SetCookies (_cookies);
return ret;
}
// As server
private bool customCheckHandshakeRequest (
WebSocketContext context, out string message
)
{
message = null;
if (_handshakeRequestChecker == null)
return true;
message = _handshakeRequestChecker (context);
return message == null;
}
private MessageEventArgs dequeueFromMessageEventQueue ()
{
lock (_forMessageEventQueue)
return _messageEventQueue.Count > 0 ? _messageEventQueue.Dequeue () : null;
}
// As client
private void doHandshake ()
{
setClientStream ();
var res = sendHandshakeRequest ();
string msg;
if (!checkHandshakeResponse (res, out msg))
throw new WebSocketException (CloseStatusCode.ProtocolError, msg);
if (_protocolsRequested)
_protocol = res.Headers["Sec-WebSocket-Protocol"];
if (_extensionsRequested)
processSecWebSocketExtensionsServerHeader (res.Headers["Sec-WebSocket-Extensions"]);
processCookies (res.Cookies);
}
private void enqueueToMessageEventQueue (MessageEventArgs e)
{
lock (_forMessageEventQueue)
_messageEventQueue.Enqueue (e);
}
private void error (string message, Exception exception)
{
try {
OnError.Emit (this, new ErrorEventArgs (message, exception));
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
}
}
private void fatal (string message, Exception exception)
{
var code = exception is WebSocketException
? ((WebSocketException) exception).Code
: CloseStatusCode.Abnormal;
fatal (message, (ushort) code);
}
private void fatal (string message, ushort code)
{
var payload = new PayloadData (code, message);
close (payload, !code.IsReserved (), false, false);
}
private void fatal (string message, CloseStatusCode code)
{
fatal (message, (ushort) code);
}
private ClientSslConfiguration getSslConfiguration ()
{
if (_sslConfig == null)
_sslConfig = new ClientSslConfiguration (_uri.DnsSafeHost);
return _sslConfig;
}
private void init ()
{
_compression = CompressionMethod.None;
_cookies = new CookieCollection ();
_forPing = new object ();
_forSend = new object ();
_forState = new object ();
_messageEventQueue = new Queue<MessageEventArgs> ();
_forMessageEventQueue = ((ICollection) _messageEventQueue).SyncRoot;
_readyState = WebSocketState.Connecting;
}
private void message ()
{
MessageEventArgs e = null;
lock (_forMessageEventQueue) {
if (_inMessage || _messageEventQueue.Count == 0 || _readyState != WebSocketState.Open)
return;
_inMessage = true;
e = _messageEventQueue.Dequeue ();
}
_message (e);
}
private void messagec (MessageEventArgs e)
{
do {
try {
OnMessage.Emit (this, e);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error ("An error has occurred during an OnMessage event.", ex);
}
lock (_forMessageEventQueue) {
if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) {
_inMessage = false;
break;
}
e = _messageEventQueue.Dequeue ();
}
}
while (true);
}
private void messages (MessageEventArgs e)
{
try {
OnMessage.Emit (this, e);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error ("An error has occurred during an OnMessage event.", ex);
}
lock (_forMessageEventQueue) {
if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) {
_inMessage = false;
return;
}
e = _messageEventQueue.Dequeue ();
}
ThreadPool.QueueUserWorkItem (state => messages (e));
}
private void open ()
{
_inMessage = true;
startReceiving ();
try {
OnOpen.Emit (this, EventArgs.Empty);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error ("An error has occurred during the OnOpen event.", ex);
}
MessageEventArgs e = null;
lock (_forMessageEventQueue) {
if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) {
_inMessage = false;
return;
}
e = _messageEventQueue.Dequeue ();
}
_message.BeginInvoke (e, ar => _message.EndInvoke (ar), null);
}
private bool ping (byte[] data)
{
if (_readyState != WebSocketState.Open)
return false;
var pongReceived = _pongReceived;
if (pongReceived == null)
return false;
lock (_forPing) {
try {
pongReceived.Reset ();
if (!send (Fin.Final, Opcode.Ping, data, false))
return false;
return pongReceived.WaitOne (_waitTime);
}
catch (ObjectDisposedException) {
return false;
}
}
}
private bool processCloseFrame (WebSocketFrame frame)
{
var payload = frame.PayloadData;
close (payload, !payload.HasReservedCode, false, true);
return false;
}
// As client
private void processCookies (CookieCollection cookies)
{
if (cookies.Count == 0)
return;
_cookies.SetOrRemove (cookies);
}
private bool processDataFrame (WebSocketFrame frame)
{
enqueueToMessageEventQueue (
frame.IsCompressed
? new MessageEventArgs (
frame.Opcode, frame.PayloadData.ApplicationData.Decompress (_compression))
: new MessageEventArgs (frame));
return true;
}
private bool processFragmentFrame (WebSocketFrame frame)
{
if (!_inContinuation) {
// Must process first fragment.
if (frame.IsContinuation)
return true;
_fragmentsOpcode = frame.Opcode;
_fragmentsCompressed = frame.IsCompressed;
_fragmentsBuffer = new MemoryStream ();
_inContinuation = true;
}
_fragmentsBuffer.WriteBytes (frame.PayloadData.ApplicationData, 1024);
if (frame.IsFinal) {
using (_fragmentsBuffer) {
var data = _fragmentsCompressed
? _fragmentsBuffer.DecompressToArray (_compression)
: _fragmentsBuffer.ToArray ();
enqueueToMessageEventQueue (new MessageEventArgs (_fragmentsOpcode, data));
}
_fragmentsBuffer = null;
_inContinuation = false;
}
return true;
}
private bool processPingFrame (WebSocketFrame frame)
{
_logger.Trace ("A ping was received.");
var pong = WebSocketFrame.CreatePongFrame (frame.PayloadData, _client);
lock (_forState) {
if (_readyState != WebSocketState.Open) {
_logger.Error ("The connection is closing.");
return true;
}
if (!sendBytes (pong.ToArray ()))
return false;
}
_logger.Trace ("A pong to this ping has been sent.");
if (_emitOnPing) {
if (_client)
pong.Unmask ();
enqueueToMessageEventQueue (new MessageEventArgs (frame));
}
return true;
}
private bool processPongFrame (WebSocketFrame frame)
{
_logger.Trace ("A pong was received.");
try {
_pongReceived.Set ();
}
catch (NullReferenceException ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
return false;
}
catch (ObjectDisposedException ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
return false;
}
_logger.Trace ("It has been signaled.");
return true;
}
private bool processReceivedFrame (WebSocketFrame frame)
{
string msg;
if (!checkReceivedFrame (frame, out msg))
throw new WebSocketException (CloseStatusCode.ProtocolError, msg);
frame.Unmask ();
return frame.IsFragment
? processFragmentFrame (frame)
: frame.IsData
? processDataFrame (frame)
: frame.IsPing
? processPingFrame (frame)
: frame.IsPong
? processPongFrame (frame)
: frame.IsClose
? processCloseFrame (frame)
: processUnsupportedFrame (frame);
}
// As server
private void processSecWebSocketExtensionsClientHeader (string value)
{
if (value == null)
return;
var buff = new StringBuilder (80);
var comp = false;
foreach (var elm in value.SplitHeaderValue (',')) {
var extension = elm.Trim ();
if (extension.Length == 0)
continue;
if (!comp) {
if (extension.IsCompressionExtension (CompressionMethod.Deflate)) {
_compression = CompressionMethod.Deflate;
buff.AppendFormat (
"{0}, ",
_compression.ToExtensionString (
"client_no_context_takeover", "server_no_context_takeover"
)
);
comp = true;
}
}
}
var len = buff.Length;
if (len <= 2)
return;
buff.Length = len - 2;
_extensions = buff.ToString ();
}
// As client
private void processSecWebSocketExtensionsServerHeader (string value)
{
if (value == null) {
_compression = CompressionMethod.None;
return;
}
_extensions = value;
}
// As server
private void processSecWebSocketProtocolClientHeader (
IEnumerable<string> values
)
{
if (values.Contains (val => val == _protocol))
return;
_protocol = null;
}
private bool processUnsupportedFrame (WebSocketFrame frame)
{
_logger.Fatal ("An unsupported frame:" + frame.PrintToString (false));
fatal ("There is no way to handle it.", CloseStatusCode.PolicyViolation);
return false;
}
// As server
private void refuseHandshake (CloseStatusCode code, string reason)
{
_readyState = WebSocketState.Closing;
var res = createHandshakeFailureResponse (HttpStatusCode.BadRequest);
sendHttpResponse (res);
releaseServerResources ();
_readyState = WebSocketState.Closed;
var e = new CloseEventArgs ((ushort) code, reason, false);
try {
OnClose.Emit (this, e);
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
}
}
// As client
private void releaseClientResources ()
{
if (_stream != null) {
_stream.Dispose ();
_stream = null;
}
if (_tcpClient != null) {
_tcpClient.Close ();
_tcpClient = null;
}
}
private void releaseCommonResources ()
{
if (_fragmentsBuffer != null) {
_fragmentsBuffer.Dispose ();
_fragmentsBuffer = null;
_inContinuation = false;
}
if (_pongReceived != null) {
_pongReceived.Close ();
_pongReceived = null;
}
if (_receivingExited != null) {
_receivingExited.Close ();
_receivingExited = null;
}
}
private void releaseResources ()
{
if (_client)
releaseClientResources ();
else
releaseServerResources ();
releaseCommonResources ();
}
// As server
private void releaseServerResources ()
{
if (_closeContext == null)
return;
_closeContext ();
_closeContext = null;
_stream = null;
_context = null;
}
private bool send (Opcode opcode, Stream stream)
{
lock (_forSend) {
var src = stream;
var compressed = false;
var sent = false;
try {
if (_compression != CompressionMethod.None) {
stream = stream.Compress (_compression);
compressed = true;
}
sent = send (opcode, stream, compressed);
if (!sent)
error ("A send has been interrupted.", null);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error ("An error has occurred during a send.", ex);
}
finally {
if (compressed)
stream.Dispose ();
src.Dispose ();
}
return sent;
}
}
private bool send (Opcode opcode, Stream stream, bool compressed)
{
var len = stream.Length;
if (len == 0)
return send (Fin.Final, opcode, EmptyBytes, false);
var quo = len / FragmentLength;
var rem = (int) (len % FragmentLength);
byte[] buff = null;
if (quo == 0) {
buff = new byte[rem];
return stream.Read (buff, 0, rem) == rem
&& send (Fin.Final, opcode, buff, compressed);
}
if (quo == 1 && rem == 0) {
buff = new byte[FragmentLength];
return stream.Read (buff, 0, FragmentLength) == FragmentLength
&& send (Fin.Final, opcode, buff, compressed);
}
/* Send fragments */
// Begin
buff = new byte[FragmentLength];
var sent = stream.Read (buff, 0, FragmentLength) == FragmentLength
&& send (Fin.More, opcode, buff, compressed);
if (!sent)
return false;
var n = rem == 0 ? quo - 2 : quo - 1;
for (long i = 0; i < n; i++) {
sent = stream.Read (buff, 0, FragmentLength) == FragmentLength
&& send (Fin.More, Opcode.Cont, buff, false);
if (!sent)
return false;
}
// End
if (rem == 0)
rem = FragmentLength;
else
buff = new byte[rem];
return stream.Read (buff, 0, rem) == rem
&& send (Fin.Final, Opcode.Cont, buff, false);
}
private bool send (Fin fin, Opcode opcode, byte[] data, bool compressed)
{
lock (_forState) {
if (_readyState != WebSocketState.Open) {
_logger.Error ("The connection is closing.");
return false;
}
var frame = new WebSocketFrame (fin, opcode, data, compressed, _client);
return sendBytes (frame.ToArray ());
}
}
private void sendAsync (Opcode opcode, Stream stream, Action<bool> completed)
{
Func<Opcode, Stream, bool> sender = send;
sender.BeginInvoke (
opcode,
stream,
ar => {
try {
var sent = sender.EndInvoke (ar);
if (completed != null)
completed (sent);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error (
"An error has occurred during the callback for an async send.",
ex
);
}
},
null
);
}
private bool sendBytes (byte[] bytes)
{
try {
_stream.Write (bytes, 0, bytes.Length);
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
return false;
}
return true;
}
// As client
private HttpResponse sendHandshakeRequest ()
{
var req = createHandshakeRequest ();
var res = sendHttpRequest (req, 90000);
if (res.IsUnauthorized) {
var chal = res.Headers["WWW-Authenticate"];
_logger.Warn (String.Format ("Received an authentication requirement for '{0}'.", chal));
if (chal.IsNullOrEmpty ()) {
_logger.Error ("No authentication challenge is specified.");
return res;
}
_authChallenge = AuthenticationChallenge.Parse (chal);
if (_authChallenge == null) {
_logger.Error ("An invalid authentication challenge is specified.");
return res;
}
if (_credentials != null &&
(!_preAuth || _authChallenge.Scheme == AuthenticationSchemes.Digest)) {
if (res.HasConnectionClose) {
releaseClientResources ();
setClientStream ();
}
var authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
_nonceCount = authRes.NonceCount;
req.Headers["Authorization"] = authRes.ToString ();
res = sendHttpRequest (req, 15000);
}
}
if (res.IsRedirect) {
var url = res.Headers["Location"];
_logger.Warn (String.Format ("Received a redirection to '{0}'.", url));
if (_enableRedirection) {
if (url.IsNullOrEmpty ()) {
_logger.Error ("No url to redirect is located.");
return res;
}
Uri uri;
string msg;
if (!url.TryCreateWebSocketUri (out uri, out msg)) {
_logger.Error ("An invalid url to redirect is located: " + msg);
return res;
}
releaseClientResources ();
_uri = uri;
_secure = uri.Scheme == "wss";
setClientStream ();
return sendHandshakeRequest ();
}
}
return res;
}
// As client
private HttpResponse sendHttpRequest (HttpRequest request, int millisecondsTimeout)
{
_logger.Debug ("A request to the server:\n" + request.ToString ());
var res = request.GetResponse (_stream, millisecondsTimeout);
_logger.Debug ("A response to this request:\n" + res.ToString ());
return res;
}
// As server
private bool sendHttpResponse (HttpResponse response)
{
_logger.Debug (
String.Format (
"A response to {0}:\n{1}", _context.UserEndPoint, response
)
);
return sendBytes (response.ToByteArray ());
}
// As client
private void sendProxyConnectRequest ()
{
var req = HttpRequest.CreateConnectRequest (_uri);
var res = sendHttpRequest (req, 90000);
if (res.IsProxyAuthenticationRequired) {
var chal = res.Headers["Proxy-Authenticate"];
_logger.Warn (
String.Format ("Received a proxy authentication requirement for '{0}'.", chal));
if (chal.IsNullOrEmpty ())
throw new WebSocketException ("No proxy authentication challenge is specified.");
var authChal = AuthenticationChallenge.Parse (chal);
if (authChal == null)
throw new WebSocketException ("An invalid proxy authentication challenge is specified.");
if (_proxyCredentials != null) {
if (res.HasConnectionClose) {
releaseClientResources ();
_tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
_stream = _tcpClient.GetStream ();
}
var authRes = new AuthenticationResponse (authChal, _proxyCredentials, 0);
req.Headers["Proxy-Authorization"] = authRes.ToString ();
res = sendHttpRequest (req, 15000);
}
if (res.IsProxyAuthenticationRequired)
throw new WebSocketException ("A proxy authentication is required.");
}
if (res.StatusCode[0] != '2')
throw new WebSocketException (
"The proxy has failed a connection to the requested host and port.");
}
// As client
private void setClientStream ()
{
if (_proxyUri != null) {
_tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
_stream = _tcpClient.GetStream ();
sendProxyConnectRequest ();
}
else {
_tcpClient = new TcpClient (_uri.DnsSafeHost, _uri.Port);
_stream = _tcpClient.GetStream ();
}
if (_secure) {
var conf = getSslConfiguration ();
var host = conf.TargetHost;
if (host != _uri.DnsSafeHost)
throw new WebSocketException (
CloseStatusCode.TlsHandshakeFailure, "An invalid host name is specified.");
try {
var sslStream = new SslStream (
_stream,
false,
conf.ServerCertificateValidationCallback,
conf.ClientCertificateSelectionCallback);
sslStream.AuthenticateAsClient (
host,
conf.ClientCertificates,
conf.EnabledSslProtocols,
conf.CheckCertificateRevocation);
_stream = sslStream;
}
catch (Exception ex) {
throw new WebSocketException (CloseStatusCode.TlsHandshakeFailure, ex);
}
}
}
private void startReceiving ()
{
if (_messageEventQueue.Count > 0)
_messageEventQueue.Clear ();
_pongReceived = new ManualResetEvent (false);
_receivingExited = new ManualResetEvent (false);
Action receive = null;
receive =
() =>
WebSocketFrame.ReadFrameAsync (
_stream,
false,
frame => {
if (!processReceivedFrame (frame) || _readyState == WebSocketState.Closed) {
var exited = _receivingExited;
if (exited != null)
exited.Set ();
return;
}
// Receive next asap because the Ping or Close needs a response to it.
receive ();
if (_inMessage || !HasMessage || _readyState != WebSocketState.Open)
return;
message ();
},
ex => {
_logger.Fatal (ex.ToString ());
fatal ("An exception has occurred while receiving.", ex);
}
);
receive ();
}
// As client
private bool validateSecWebSocketAcceptHeader (string value)
{
return value != null && value == CreateResponseKey (_base64Key);
}
// As client
private bool validateSecWebSocketExtensionsServerHeader (string value)
{
if (value == null)
return true;
if (value.Length == 0)
return false;
if (!_extensionsRequested)
return false;
var comp = _compression != CompressionMethod.None;
foreach (var e in value.SplitHeaderValue (',')) {
var ext = e.Trim ();
if (comp && ext.IsCompressionExtension (_compression)) {
if (!ext.Contains ("server_no_context_takeover")) {
_logger.Error ("The server hasn't sent back 'server_no_context_takeover'.");
return false;
}
if (!ext.Contains ("client_no_context_takeover"))
_logger.Warn ("The server hasn't sent back 'client_no_context_takeover'.");
var method = _compression.ToExtensionString ();
var invalid =
ext.SplitHeaderValue (';').Contains (
t => {
t = t.Trim ();
return t != method
&& t != "server_no_context_takeover"
&& t != "client_no_context_takeover";
}
);
if (invalid)
return false;
}
else {
return false;
}
}
return true;
}
// As client
private bool validateSecWebSocketProtocolServerHeader (string value)
{
if (value == null)
return !_protocolsRequested;
if (value.Length == 0)
return false;
return _protocolsRequested && _protocols.Contains (p => p == value);
}
// As client
private bool validateSecWebSocketVersionServerHeader (string value)
{
return value == null || value == _version;
}
#endregion
#region Internal Methods
// As server
internal void Close (HttpResponse response)
{
_readyState = WebSocketState.Closing;
sendHttpResponse (response);
releaseServerResources ();
_readyState = WebSocketState.Closed;
}
// As server
internal void Close (HttpStatusCode code)
{
Close (createHandshakeFailureResponse (code));
}
// As server
internal void Close (PayloadData payloadData, byte[] frameAsBytes)
{
lock (_forState) {
if (_readyState == WebSocketState.Closing) {
_logger.Info ("The closing is already in progress.");
return;
}
if (_readyState == WebSocketState.Closed) {
_logger.Info ("The connection has already been closed.");
return;
}
_readyState = WebSocketState.Closing;
}
_logger.Trace ("Begin closing the connection.");
var sent = frameAsBytes != null && sendBytes (frameAsBytes);
var received = sent && _receivingExited != null
? _receivingExited.WaitOne (_waitTime)
: false;
var res = sent && received;
_logger.Debug (
String.Format (
"Was clean?: {0}\n sent: {1}\n received: {2}", res, sent, received
)
);
releaseServerResources ();
releaseCommonResources ();
_logger.Trace ("End closing the connection.");
_readyState = WebSocketState.Closed;
var e = new CloseEventArgs (payloadData, res);
try {
OnClose.Emit (this, e);
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.Debug (ex.ToString ());
}
}
// As client
internal static string CreateBase64Key ()
{
var src = new byte[16];
RandomNumber.GetBytes (src);
return Convert.ToBase64String (src);
}
internal static string CreateResponseKey (string base64Key)
{
var buff = new StringBuilder (base64Key, 64);
buff.Append (_guid);
SHA1 sha1 = new SHA1CryptoServiceProvider ();
var src = sha1.ComputeHash (buff.ToString ().GetUTF8EncodedBytes ());
return Convert.ToBase64String (src);
}
// As server
internal void InternalAccept ()
{
try {
if (!acceptHandshake ())
return;
}
catch (Exception ex) {
_logger.Fatal (ex.Message);
_logger.Debug (ex.ToString ());
var msg = "An exception has occurred while attempting to accept.";
fatal (msg, ex);
return;
}
_readyState = WebSocketState.Open;
open ();
}
// As server
internal bool Ping (byte[] frameAsBytes, TimeSpan timeout)
{
if (_readyState != WebSocketState.Open)
return false;
var pongReceived = _pongReceived;
if (pongReceived == null)
return false;
lock (_forPing) {
try {
pongReceived.Reset ();
lock (_forState) {
if (_readyState != WebSocketState.Open)
return false;
if (!sendBytes (frameAsBytes))
return false;
}
return pongReceived.WaitOne (timeout);
}
catch (ObjectDisposedException) {
return false;
}
}
}
// As server
internal void Send (
Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache
)
{
lock (_forSend) {
lock (_forState) {
if (_readyState != WebSocketState.Open) {
_logger.Error ("The connection is closing.");
return;
}
byte[] found;
if (!cache.TryGetValue (_compression, out found)) {
found = new WebSocketFrame (
Fin.Final,
opcode,
data.Compress (_compression),
_compression != CompressionMethod.None,
false
)
.ToArray ();
cache.Add (_compression, found);
}
sendBytes (found);
}
}
}
// As server
internal void Send (
Opcode opcode, Stream stream, Dictionary<CompressionMethod, Stream> cache
)
{
lock (_forSend) {
Stream found;
if (!cache.TryGetValue (_compression, out found)) {
found = stream.Compress (_compression);
cache.Add (_compression, found);
}
else {
found.Position = 0;
}
send (opcode, found, _compression != CompressionMethod.None);
}
}
#endregion
#region Public Methods
/// <summary>
/// Accepts the handshake request.
/// </summary>
/// <remarks>
/// This method does nothing if the handshake request has already been
/// accepted.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <para>
/// This instance is a client.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The close process is in progress.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The connection has already been closed.
/// </para>
/// </exception>
public void Accept ()
{
if (_client) {
var msg = "This instance is a client.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process is in progress.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closed) {
var msg = "The connection has already been closed.";
throw new InvalidOperationException (msg);
}
if (accept ())
open ();
}
/// <summary>
/// Accepts the handshake request asynchronously.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the accept process to be complete.
/// </para>
/// <para>
/// This method does nothing if the handshake request has already been
/// accepted.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <para>
/// This instance is a client.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The close process is in progress.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The connection has already been closed.
/// </para>
/// </exception>
public void AcceptAsync ()
{
if (_client) {
var msg = "This instance is a client.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process is in progress.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closed) {
var msg = "The connection has already been closed.";
throw new InvalidOperationException (msg);
}
Func<bool> acceptor = accept;
acceptor.BeginInvoke (
ar => {
if (acceptor.EndInvoke (ar))
open ();
},
null
);
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <remarks>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </remarks>
public void Close ()
{
close (1005, String.Empty);
}
/// <summary>
/// Closes the connection with the specified code.
/// </summary>
/// <remarks>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </remarks>
/// <param name="code">
/// <para>
/// A <see cref="ushort"/> that represents the status code indicating
/// the reason for the close.
/// </para>
/// <para>
/// The status codes are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="code"/> is less than 1000 or greater than 4999.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is 1011 (server error).
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1010 (mandatory extension).
/// It cannot be used by servers.
/// </para>
/// </exception>
public void Close (ushort code)
{
if (!code.IsCloseStatusCode ()) {
var msg = "Less than 1000 or greater than 4999.";
throw new ArgumentOutOfRangeException ("code", msg);
}
if (_client && code == 1011) {
var msg = "1011 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == 1010) {
var msg = "1010 cannot be used.";
throw new ArgumentException (msg, "code");
}
close (code, String.Empty);
}
/// <summary>
/// Closes the connection with the specified code.
/// </summary>
/// <remarks>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </remarks>
/// <param name="code">
/// <para>
/// One of the <see cref="CloseStatusCode"/> enum values.
/// </para>
/// <para>
/// It represents the status code indicating the reason for the close.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.ServerError"/>.
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.MandatoryExtension"/>.
/// It cannot be used by servers.
/// </para>
/// </exception>
public void Close (CloseStatusCode code)
{
if (_client && code == CloseStatusCode.ServerError) {
var msg = "ServerError cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == CloseStatusCode.MandatoryExtension) {
var msg = "MandatoryExtension cannot be used.";
throw new ArgumentException (msg, "code");
}
close ((ushort) code, String.Empty);
}
/// <summary>
/// Closes the connection with the specified code and reason.
/// </summary>
/// <remarks>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </remarks>
/// <param name="code">
/// <para>
/// A <see cref="ushort"/> that represents the status code indicating
/// the reason for the close.
/// </para>
/// <para>
/// The status codes are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// </param>
/// <param name="reason">
/// <para>
/// A <see cref="string"/> that represents the reason for the close.
/// </para>
/// <para>
/// The size must be 123 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="code"/> is less than 1000 or greater than 4999.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The size of <paramref name="reason"/> is greater than 123 bytes.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is 1011 (server error).
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1010 (mandatory extension).
/// It cannot be used by servers.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1005 (no status) and there is reason.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="reason"/> could not be UTF-8-encoded.
/// </para>
/// </exception>
public void Close (ushort code, string reason)
{
if (!code.IsCloseStatusCode ()) {
var msg = "Less than 1000 or greater than 4999.";
throw new ArgumentOutOfRangeException ("code", msg);
}
if (_client && code == 1011) {
var msg = "1011 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == 1010) {
var msg = "1010 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (reason.IsNullOrEmpty ()) {
close (code, String.Empty);
return;
}
if (code == 1005) {
var msg = "1005 cannot be used.";
throw new ArgumentException (msg, "code");
}
byte[] bytes;
if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "reason");
}
if (bytes.Length > 123) {
var msg = "Its size is greater than 123 bytes.";
throw new ArgumentOutOfRangeException ("reason", msg);
}
close (code, reason);
}
/// <summary>
/// Closes the connection with the specified code and reason.
/// </summary>
/// <remarks>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </remarks>
/// <param name="code">
/// <para>
/// One of the <see cref="CloseStatusCode"/> enum values.
/// </para>
/// <para>
/// It represents the status code indicating the reason for the close.
/// </para>
/// </param>
/// <param name="reason">
/// <para>
/// A <see cref="string"/> that represents the reason for the close.
/// </para>
/// <para>
/// The size must be 123 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.ServerError"/>.
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.MandatoryExtension"/>.
/// It cannot be used by servers.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.NoStatus"/> and there is reason.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="reason"/> could not be UTF-8-encoded.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The size of <paramref name="reason"/> is greater than 123 bytes.
/// </exception>
public void Close (CloseStatusCode code, string reason)
{
if (_client && code == CloseStatusCode.ServerError) {
var msg = "ServerError cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == CloseStatusCode.MandatoryExtension) {
var msg = "MandatoryExtension cannot be used.";
throw new ArgumentException (msg, "code");
}
if (reason.IsNullOrEmpty ()) {
close ((ushort) code, String.Empty);
return;
}
if (code == CloseStatusCode.NoStatus) {
var msg = "NoStatus cannot be used.";
throw new ArgumentException (msg, "code");
}
byte[] bytes;
if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "reason");
}
if (bytes.Length > 123) {
var msg = "Its size is greater than 123 bytes.";
throw new ArgumentOutOfRangeException ("reason", msg);
}
close ((ushort) code, reason);
}
/// <summary>
/// Closes the connection asynchronously.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the close to be complete.
/// </para>
/// <para>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
public void CloseAsync ()
{
closeAsync (1005, String.Empty);
}
/// <summary>
/// Closes the connection asynchronously with the specified code.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the close to be complete.
/// </para>
/// <para>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
/// <param name="code">
/// <para>
/// A <see cref="ushort"/> that represents the status code indicating
/// the reason for the close.
/// </para>
/// <para>
/// The status codes are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="code"/> is less than 1000 or greater than 4999.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is 1011 (server error).
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1010 (mandatory extension).
/// It cannot be used by servers.
/// </para>
/// </exception>
public void CloseAsync (ushort code)
{
if (!code.IsCloseStatusCode ()) {
var msg = "Less than 1000 or greater than 4999.";
throw new ArgumentOutOfRangeException ("code", msg);
}
if (_client && code == 1011) {
var msg = "1011 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == 1010) {
var msg = "1010 cannot be used.";
throw new ArgumentException (msg, "code");
}
closeAsync (code, String.Empty);
}
/// <summary>
/// Closes the connection asynchronously with the specified code.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the close to be complete.
/// </para>
/// <para>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
/// <param name="code">
/// <para>
/// One of the <see cref="CloseStatusCode"/> enum values.
/// </para>
/// <para>
/// It represents the status code indicating the reason for the close.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.ServerError"/>.
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.MandatoryExtension"/>.
/// It cannot be used by servers.
/// </para>
/// </exception>
public void CloseAsync (CloseStatusCode code)
{
if (_client && code == CloseStatusCode.ServerError) {
var msg = "ServerError cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == CloseStatusCode.MandatoryExtension) {
var msg = "MandatoryExtension cannot be used.";
throw new ArgumentException (msg, "code");
}
closeAsync ((ushort) code, String.Empty);
}
/// <summary>
/// Closes the connection asynchronously with the specified code and reason.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the close to be complete.
/// </para>
/// <para>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
/// <param name="code">
/// <para>
/// A <see cref="ushort"/> that represents the status code indicating
/// the reason for the close.
/// </para>
/// <para>
/// The status codes are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// </param>
/// <param name="reason">
/// <para>
/// A <see cref="string"/> that represents the reason for the close.
/// </para>
/// <para>
/// The size must be 123 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="code"/> is less than 1000 or greater than 4999.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The size of <paramref name="reason"/> is greater than 123 bytes.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is 1011 (server error).
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1010 (mandatory extension).
/// It cannot be used by servers.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is 1005 (no status) and there is reason.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="reason"/> could not be UTF-8-encoded.
/// </para>
/// </exception>
public void CloseAsync (ushort code, string reason)
{
if (!code.IsCloseStatusCode ()) {
var msg = "Less than 1000 or greater than 4999.";
throw new ArgumentOutOfRangeException ("code", msg);
}
if (_client && code == 1011) {
var msg = "1011 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == 1010) {
var msg = "1010 cannot be used.";
throw new ArgumentException (msg, "code");
}
if (reason.IsNullOrEmpty ()) {
closeAsync (code, String.Empty);
return;
}
if (code == 1005) {
var msg = "1005 cannot be used.";
throw new ArgumentException (msg, "code");
}
byte[] bytes;
if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "reason");
}
if (bytes.Length > 123) {
var msg = "Its size is greater than 123 bytes.";
throw new ArgumentOutOfRangeException ("reason", msg);
}
closeAsync (code, reason);
}
/// <summary>
/// Closes the connection asynchronously with the specified code and reason.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the close to be complete.
/// </para>
/// <para>
/// This method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
/// <param name="code">
/// <para>
/// One of the <see cref="CloseStatusCode"/> enum values.
/// </para>
/// <para>
/// It represents the status code indicating the reason for the close.
/// </para>
/// </param>
/// <param name="reason">
/// <para>
/// A <see cref="string"/> that represents the reason for the close.
/// </para>
/// <para>
/// The size must be 123 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.ServerError"/>.
/// It cannot be used by clients.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.MandatoryExtension"/>.
/// It cannot be used by servers.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="code"/> is
/// <see cref="CloseStatusCode.NoStatus"/> and there is reason.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="reason"/> could not be UTF-8-encoded.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The size of <paramref name="reason"/> is greater than 123 bytes.
/// </exception>
public void CloseAsync (CloseStatusCode code, string reason)
{
if (_client && code == CloseStatusCode.ServerError) {
var msg = "ServerError cannot be used.";
throw new ArgumentException (msg, "code");
}
if (!_client && code == CloseStatusCode.MandatoryExtension) {
var msg = "MandatoryExtension cannot be used.";
throw new ArgumentException (msg, "code");
}
if (reason.IsNullOrEmpty ()) {
closeAsync ((ushort) code, String.Empty);
return;
}
if (code == CloseStatusCode.NoStatus) {
var msg = "NoStatus cannot be used.";
throw new ArgumentException (msg, "code");
}
byte[] bytes;
if (!reason.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "reason");
}
if (bytes.Length > 123) {
var msg = "Its size is greater than 123 bytes.";
throw new ArgumentOutOfRangeException ("reason", msg);
}
closeAsync ((ushort) code, reason);
}
/// <summary>
/// Establishes a connection.
/// </summary>
/// <remarks>
/// This method does nothing if the connection has already been established.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <para>
/// This instance is not a client.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The close process is in progress.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// A series of reconnecting has failed.
/// </para>
/// </exception>
public void Connect ()
{
if (!_client) {
var msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process is in progress.";
throw new InvalidOperationException (msg);
}
if (_retryCountForConnect > _maxRetryCountForConnect) {
var msg = "A series of reconnecting has failed.";
throw new InvalidOperationException (msg);
}
if (connect ())
open ();
}
/// <summary>
/// Establishes a connection asynchronously.
/// </summary>
/// <remarks>
/// <para>
/// This method does not wait for the connect process to be complete.
/// </para>
/// <para>
/// This method does nothing if the connection has already been
/// established.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <para>
/// This instance is not a client.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The close process is in progress.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// A series of reconnecting has failed.
/// </para>
/// </exception>
public void ConnectAsync ()
{
if (!_client) {
var msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (_readyState == WebSocketState.Closing) {
var msg = "The close process is in progress.";
throw new InvalidOperationException (msg);
}
if (_retryCountForConnect > _maxRetryCountForConnect) {
var msg = "A series of reconnecting has failed.";
throw new InvalidOperationException (msg);
}
Func<bool> connector = connect;
connector.BeginInvoke (
ar => {
if (connector.EndInvoke (ar))
open ();
},
null
);
}
/// <summary>
/// Sends a ping using the WebSocket connection.
/// </summary>
/// <returns>
/// <c>true</c> if the send has done with no error and a pong has been
/// received within a time; otherwise, <c>false</c>.
/// </returns>
public bool Ping ()
{
return ping (EmptyBytes);
}
/// <summary>
/// Sends a ping with <paramref name="message"/> using the WebSocket
/// connection.
/// </summary>
/// <returns>
/// <c>true</c> if the send has done with no error and a pong has been
/// received within a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="message">
/// <para>
/// A <see cref="string"/> that represents the message to send.
/// </para>
/// <para>
/// The size must be 125 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="message"/> could not be UTF-8-encoded.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The size of <paramref name="message"/> is greater than 125 bytes.
/// </exception>
public bool Ping (string message)
{
if (message.IsNullOrEmpty ())
return ping (EmptyBytes);
byte[] bytes;
if (!message.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "message");
}
if (bytes.Length > 125) {
var msg = "Its size is greater than 125 bytes.";
throw new ArgumentOutOfRangeException ("message", msg);
}
return ping (bytes);
}
/// <summary>
/// Sends the specified data using the WebSocket connection.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
public void Send (byte[] data)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
send (Opcode.Binary, new MemoryStream (data));
}
/// <summary>
/// Sends the specified file using the WebSocket connection.
/// </summary>
/// <param name="fileInfo">
/// <para>
/// A <see cref="FileInfo"/> that specifies the file to send.
/// </para>
/// <para>
/// The file is sent as the binary data.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The file does not exist.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The file could not be opened.
/// </para>
/// </exception>
public void Send (FileInfo fileInfo)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (fileInfo == null)
throw new ArgumentNullException ("fileInfo");
if (!fileInfo.Exists) {
var msg = "The file does not exist.";
throw new ArgumentException (msg, "fileInfo");
}
FileStream stream;
if (!fileInfo.TryOpenRead (out stream)) {
var msg = "The file could not be opened.";
throw new ArgumentException (msg, "fileInfo");
}
send (Opcode.Binary, stream);
}
/// <summary>
/// Sends the specified data using the WebSocket connection.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="data"/> could not be UTF-8-encoded.
/// </exception>
public void Send (string data)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
byte[] bytes;
if (!data.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "data");
}
send (Opcode.Text, new MemoryStream (bytes));
}
/// <summary>
/// Sends the data from the specified stream using the WebSocket connection.
/// </summary>
/// <param name="stream">
/// <para>
/// A <see cref="Stream"/> instance from which to read the data to send.
/// </para>
/// <para>
/// The data is sent as the binary data.
/// </para>
/// </param>
/// <param name="length">
/// An <see cref="int"/> that specifies the number of bytes to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="stream"/> cannot be read.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="length"/> is less than 1.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// No data could be read from <paramref name="stream"/>.
/// </para>
/// </exception>
public void Send (Stream stream, int length)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead) {
var msg = "It cannot be read.";
throw new ArgumentException (msg, "stream");
}
if (length < 1) {
var msg = "Less than 1.";
throw new ArgumentException (msg, "length");
}
var bytes = stream.ReadBytes (length);
var len = bytes.Length;
if (len == 0) {
var msg = "No data could be read from it.";
throw new ArgumentException (msg, "stream");
}
if (len < length) {
_logger.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the stream.",
len
)
);
}
send (Opcode.Binary, new MemoryStream (bytes));
}
/// <summary>
/// Sends the specified data asynchronously using the WebSocket connection.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <c>Action<bool></c> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// <para>
/// <c>true</c> is passed to the method if the send has done with
/// no error; otherwise, <c>false</c>.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
public void SendAsync (byte[] data, Action<bool> completed)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
sendAsync (Opcode.Binary, new MemoryStream (data), completed);
}
/// <summary>
/// Sends the specified file asynchronously using the WebSocket connection.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="fileInfo">
/// <para>
/// A <see cref="FileInfo"/> that specifies the file to send.
/// </para>
/// <para>
/// The file is sent as the binary data.
/// </para>
/// </param>
/// <param name="completed">
/// <para>
/// An <c>Action<bool></c> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// <para>
/// <c>true</c> is passed to the method if the send has done with
/// no error; otherwise, <c>false</c>.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The file does not exist.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The file could not be opened.
/// </para>
/// </exception>
public void SendAsync (FileInfo fileInfo, Action<bool> completed)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (fileInfo == null)
throw new ArgumentNullException ("fileInfo");
if (!fileInfo.Exists) {
var msg = "The file does not exist.";
throw new ArgumentException (msg, "fileInfo");
}
FileStream stream;
if (!fileInfo.TryOpenRead (out stream)) {
var msg = "The file could not be opened.";
throw new ArgumentException (msg, "fileInfo");
}
sendAsync (Opcode.Binary, stream, completed);
}
/// <summary>
/// Sends the specified data asynchronously using the WebSocket connection.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <c>Action<bool></c> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// <para>
/// <c>true</c> is passed to the method if the send has done with
/// no error; otherwise, <c>false</c>.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="data"/> could not be UTF-8-encoded.
/// </exception>
public void SendAsync (string data, Action<bool> completed)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
byte[] bytes;
if (!data.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "data");
}
sendAsync (Opcode.Text, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sends the data from the specified stream asynchronously using
/// the WebSocket connection.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// <para>
/// A <see cref="Stream"/> instance from which to read the data to send.
/// </para>
/// <para>
/// The data is sent as the binary data.
/// </para>
/// </param>
/// <param name="length">
/// An <see cref="int"/> that specifies the number of bytes to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <c>Action<bool></c> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// <para>
/// <c>true</c> is passed to the method if the send has done with
/// no error; otherwise, <c>false</c>.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the connection is not Open.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="stream"/> cannot be read.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="length"/> is less than 1.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// No data could be read from <paramref name="stream"/>.
/// </para>
/// </exception>
public void SendAsync (Stream stream, int length, Action<bool> completed)
{
if (_readyState != WebSocketState.Open) {
var msg = "The current state of the connection is not Open.";
throw new InvalidOperationException (msg);
}
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead) {
var msg = "It cannot be read.";
throw new ArgumentException (msg, "stream");
}
if (length < 1) {
var msg = "Less than 1.";
throw new ArgumentException (msg, "length");
}
var bytes = stream.ReadBytes (length);
var len = bytes.Length;
if (len == 0) {
var msg = "No data could be read from it.";
throw new ArgumentException (msg, "stream");
}
if (len < length) {
_logger.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the stream.",
len
)
);
}
sendAsync (Opcode.Binary, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sets an HTTP cookie to send with the handshake request.
/// </summary>
/// <remarks>
/// This method does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <param name="cookie">
/// A <see cref="Cookie"/> that represents the cookie to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// This instance is not a client.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void SetCookie (Cookie cookie)
{
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (cookie == null)
throw new ArgumentNullException ("cookie");
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_cookies.SyncRoot)
_cookies.SetOrRemove (cookie);
}
}
/// <summary>
/// Sets the credentials for the HTTP authentication (Basic/Digest).
/// </summary>
/// <remarks>
/// This method does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <param name="username">
/// <para>
/// A <see cref="string"/> that represents the username associated with
/// the credentials.
/// </para>
/// <para>
/// <see langword="null"/> or an empty string if initializes
/// the credentials.
/// </para>
/// </param>
/// <param name="password">
/// <para>
/// A <see cref="string"/> that represents the password for the username
/// associated with the credentials.
/// </para>
/// <para>
/// <see langword="null"/> or an empty string if not necessary.
/// </para>
/// </param>
/// <param name="preAuth">
/// <c>true</c> if sends the credentials for the Basic authentication in
/// advance with the first handshake request; otherwise, <c>false</c>.
/// </param>
/// <exception cref="InvalidOperationException">
/// This instance is not a client.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="username"/> contains an invalid character.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="password"/> contains an invalid character.
/// </para>
/// </exception>
public void SetCredentials (string username, string password, bool preAuth)
{
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
if (!username.IsNullOrEmpty ()) {
if (username.Contains (':') || !username.IsText ()) {
msg = "It contains an invalid character.";
throw new ArgumentException (msg, "username");
}
}
if (!password.IsNullOrEmpty ()) {
if (!password.IsText ()) {
msg = "It contains an invalid character.";
throw new ArgumentException (msg, "password");
}
}
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
if (username.IsNullOrEmpty ()) {
_credentials = null;
_preAuth = false;
return;
}
_credentials = new NetworkCredential (
username, password, _uri.PathAndQuery
);
_preAuth = preAuth;
}
}
/// <summary>
/// Sets the URL of the HTTP proxy server through which to connect and
/// the credentials for the HTTP proxy authentication (Basic/Digest).
/// </summary>
/// <remarks>
/// This method does nothing if the connection has already been
/// established or it is closing.
/// </remarks>
/// <param name="url">
/// <para>
/// A <see cref="string"/> that represents the URL of the proxy server
/// through which to connect.
/// </para>
/// <para>
/// The syntax is http://<host>[:<port>].
/// </para>
/// <para>
/// <see langword="null"/> or an empty string if initializes the URL and
/// the credentials.
/// </para>
/// </param>
/// <param name="username">
/// <para>
/// A <see cref="string"/> that represents the username associated with
/// the credentials.
/// </para>
/// <para>
/// <see langword="null"/> or an empty string if the credentials are not
/// necessary.
/// </para>
/// </param>
/// <param name="password">
/// <para>
/// A <see cref="string"/> that represents the password for the username
/// associated with the credentials.
/// </para>
/// <para>
/// <see langword="null"/> or an empty string if not necessary.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// This instance is not a client.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is not an absolute URI string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The scheme of <paramref name="url"/> is not http.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> includes the path segments.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="username"/> contains an invalid character.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="password"/> contains an invalid character.
/// </para>
/// </exception>
public void SetProxy (string url, string username, string password)
{
string msg = null;
if (!_client) {
msg = "This instance is not a client.";
throw new InvalidOperationException (msg);
}
Uri uri = null;
if (!url.IsNullOrEmpty ()) {
if (!Uri.TryCreate (url, UriKind.Absolute, out uri)) {
msg = "Not an absolute URI string.";
throw new ArgumentException (msg, "url");
}
if (uri.Scheme != "http") {
msg = "The scheme part is not http.";
throw new ArgumentException (msg, "url");
}
if (uri.Segments.Length > 1) {
msg = "It includes the path segments.";
throw new ArgumentException (msg, "url");
}
}
if (!username.IsNullOrEmpty ()) {
if (username.Contains (':') || !username.IsText ()) {
msg = "It contains an invalid character.";
throw new ArgumentException (msg, "username");
}
}
if (!password.IsNullOrEmpty ()) {
if (!password.IsText ()) {
msg = "It contains an invalid character.";
throw new ArgumentException (msg, "password");
}
}
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
lock (_forState) {
if (!canSet (out msg)) {
_logger.Warn (msg);
return;
}
if (url.IsNullOrEmpty ()) {
_proxyUri = null;
_proxyCredentials = null;
return;
}
_proxyUri = uri;
_proxyCredentials = !username.IsNullOrEmpty ()
? new NetworkCredential (
username,
password,
String.Format (
"{0}:{1}", _uri.DnsSafeHost, _uri.Port
)
)
: null;
}
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Closes the connection and releases all associated resources.
/// </summary>
/// <remarks>
/// <para>
/// This method closes the connection with close status 1001 (going away).
/// </para>
/// <para>
/// And this method does nothing if the current state of the connection is
/// Closing or Closed.
/// </para>
/// </remarks>
void IDisposable.Dispose ()
{
close (1001, String.Empty);
}
#endregion
}
}
| 28.13705 | 99 | 0.551515 | [
"MIT"
] | UCan927/websocket-sharp | websocket-sharp/WebSocket.cs | 115,587 | C# |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Kodestruct.Steel.AISC.FloorVibrations.EffectiveProperties
{
/// <summary>
/// Interaction logic for Kodestruct.Steel.AISC10.JoistToGirderConnectionTypeSelectionView.xaml
/// </summary>
public partial class JoistToGirderConnectionTypeSelectionView: UserControl
{
public JoistToGirderConnectionTypeSelectionView()
{
InitializeComponent();
}
}
}
| 31 | 99 | 0.759467 | [
"Apache-2.0"
] | Kodestruct/Kodestruct.Dynamo | Kodestruct.Dynamo.UI/Views/Steel/AISC/Floor vibrations/JoistToGirderConnectionTypeSelectionView.xaml.cs | 1,426 | C# |
namespace xUnitTutorial
{
public class Calculator
{
private CalculatorState _state = CalculatorState.Cleared;
public decimal Value { get; private set; } = 0;
public decimal Add(decimal value)
{
_state = CalculatorState.Active;
return Value += value;
}
public decimal Subtract(decimal value)
{
_state = CalculatorState.Active;
return Value -= value;
}
public decimal Multiply(decimal value)
{
if (Value == 0 && _state == CalculatorState.Cleared)
{
_state = CalculatorState.Active;
return Value = value;
}
return Value *= value;
}
public decimal Divide(decimal value)
{
if (Value == 0 && _state == CalculatorState.Cleared)
{
_state = CalculatorState.Active;
return Value = value;
}
return Value /= value;
}
}
} | 24.928571 | 65 | 0.502388 | [
"MIT"
] | mirusser/Learning-dontNet | src/Testing/xUnitTutorial/Calculator.cs | 1,049 | C# |
//this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
internal class UnityEngine_YieldInstructionWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(UnityEngine.YieldInstruction), typeof(System.Object));
L.RegFunction("New", _CreateUnityEngine_YieldInstruction);
L.RegFunction("__tostring", ToLua.op_ToString);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateUnityEngine_YieldInstruction(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 0)
{
var obj = new UnityEngine.YieldInstruction();
ToLua.PushObject(L, obj);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.YieldInstruction.New");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
}
| 22.325 | 102 | 0.717805 | [
"MIT"
] | mybios/CSharpLuaForUnity | Assets/BaseScripts/Source/Generate/UnityEngine_YieldInstructionWrap.cs | 895 | C# |
using System;
using ReactiveDomain.Util;
namespace ReactiveDomain.Messaging.Bus
{
public class AdHocHandler<T> : IHandle<T> where T : class, IMessage
{
private readonly Action<T> _handle;
public AdHocHandler(Action<T> handle)
{
Ensure.NotNull(handle, "handle");
_handle = handle;
}
public void Handle(T message)
{
_handle(message);
}
}
} | 21.142857 | 71 | 0.576577 | [
"MIT"
] | PKI-InVivo/reactive-domain | src/ReactiveDomain.Messaging/Bus/AdHocHandler.cs | 444 | C# |
using System.Linq;
using System.Threading.Tasks;
using Sitecore.Commerce.Core;
using Sitecore.Commerce.Plugin.Carts;
using Sitecore.Commerce.Plugin.Catalog;
using Sitecore.Framework.Conditions;
using Sitecore.Framework.Pipelines;
namespace Plugin.LoyaltyPoints.Pipelines.Blocks
{
class AddCartLineLoyaltyBlock: PipelineBlock<Cart, Cart, CommercePipelineExecutionContext>
{
public override Task<Cart> Run(Cart cart, CommercePipelineExecutionContext context)
{
Condition.Requires(cart).IsNotNull($"{this.Name}: {nameof(cart)} cannot be null.");
var sellableItem = context.CommerceContext.GetObjects<SellableItem>().First();
var arg = context.CommerceContext.GetObjects<CartLineArgument>().First();
var cartLine = arg.Line;
var lp = sellableItem.GetComponent<Components.LoyaltyPointsComponent>();
if (lp != null)
{
cartLine.SetComponent(lp);
}
return Task.FromResult(cart);
}
}
}
| 35.862069 | 95 | 0.678846 | [
"MIT"
] | Velir/LoyaltyPoints | src/Plugin.LoyaltyPoints/Pipelines/Blocks/AddCartLineLoyaltyBlock.cs | 1,042 | C# |
// Copyright (c) 2021 Yoakke.
// Licensed under the Apache License, Version 2.0.
// Source repository: https://github.com/LanguageDev/Yoakke
namespace Yoakke.Symbols
{
/// <summary>
/// Represents a single symbol.
/// </summary>
public interface ISymbol
{
/// <summary>
/// The scope that contains this symbol.
/// </summary>
public IReadOnlyScope Scope { get; }
/// <summary>
/// The name of this symbol.
/// </summary>
public string Name { get; }
}
}
| 23.608696 | 59 | 0.570902 | [
"Apache-2.0"
] | kant2002/Yoakke | Sources/Core/Yoakke.Symbols/ISymbol.cs | 543 | C# |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace Minotaur.Pocs.HighPerf
{
public interface IObjectLifecycle<T>
{
T New();
void Reset(T value);
}
public interface IProcessAwareBehavior
{
int Buckets { get; }
}
public interface IEvictionStrategy<in T> where T : class
{
bool CanEvict(T item);
}
public sealed class ObjectPool<T> : ObjectPool<T, NoResetFactorySupport<T>, NonThreadAwareBehavior>
where T : class, new()
{
public ObjectPool(NoResetFactorySupport<T>.Factory factory, int size = 16)
: base(size, new NoResetFactorySupport<T>(factory)) { }
}
public sealed class ObjectPool<T, TObjectLifecycle> : ObjectPool<T, TObjectLifecycle, NonThreadAwareBehavior>
where T : class
where TObjectLifecycle : struct, IObjectLifecycle<T>
{
public ObjectPool(int size = 16, TObjectLifecycle factory = default)
: base(size, factory) { }
}
public class ObjectPool<T, TObjectLifecycle, TProcessAwareBehavior>
where T : class
where TObjectLifecycle : struct, IObjectLifecycle<T>
where TProcessAwareBehavior : struct, IProcessAwareBehavior
{
private static readonly TObjectLifecycle lifecycle = new TObjectLifecycle();
// Storage for the pool objects. The first item is stored in a dedicated field because we
// expect to be able to satisfy most requests from it.
private readonly CacheAwareElement[] _firstItems;
private readonly int _bucketsMask;
private T _firstElement;
private int _itemTopCounter;
private int _itemBottomCounter;
private readonly uint _itemsMask;
private readonly Element[] _items;
private readonly TObjectLifecycle _factory;
public ObjectPool(int size = 16, TObjectLifecycle factory = default, TProcessAwareBehavior behavior = default)
{
Debug.Assert(size >= 1);
_factory = factory;
if (typeof(TProcessAwareBehavior) == typeof(ThreadAwareBehavior))
{
var buckets = Bits.NextPowerOf2(behavior.Buckets);
_bucketsMask = buckets - 1;
_firstItems = new CacheAwareElement[buckets];
}
// PERF: We will always have power of two pools to make operations a lot faster.
size = Bits.NextPowerOf2(size);
size = Math.Max(16, size);
_items = new Element[size];
_itemsMask = (uint)size - 1;
}
/// <summary>
/// Produces an instance.
/// </summary>
/// <remarks>
/// Search strategy is a simple linear probing which is chosen for it cache-friendliness.
/// Note that Free will try to store recycled objects close to the start thus statistically
/// reducing how far we will typically search.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Get()
{
T inst;
if (typeof(TProcessAwareBehavior) == typeof(ThreadAwareBehavior))
{
var threadIndex = Environment.CurrentManagedThreadId & _bucketsMask;
ref var firstItem = ref _firstItems[threadIndex];
if (!CacheAwareElement.TryClaim(ref firstItem, out inst))
{
inst = AllocateSlow();
}
}
else
{
// PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements.
// Note that the initial read is optimistically not synchronized. That is intentional.
// We will interlock only when we have a candidate. in a worst case we may miss some
// recently returned objects. Not a big deal.
inst = _firstElement;
if (inst == null || inst != Interlocked.CompareExchange(ref _firstElement, null, inst))
{
inst = AllocateSlow();
}
}
return inst;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private T AllocateSlow()
{
var items = _items;
if (_itemBottomCounter < _itemTopCounter)
{
var claim = ((uint)Interlocked.Increment(ref _itemBottomCounter) - 1) & _itemsMask;
var inst = items[claim].Value;
if (inst != null)
{
// WARNING: In a absurdly fast loop this can still fail to get a proper, that is why
// we still use a compare exchange operation instead of using the reference.
if (inst == Interlocked.CompareExchange(ref items[claim].Value, null, inst))
return inst;
}
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
return _factory.New();
}
/// <summary>
/// Returns objects to the pool.
/// </summary>
/// <remarks>
/// Search strategy is a simple linear probing which is chosen for it cache-friendliness.
/// Note that Free will try to store recycled objects close to the start thus statistically
/// reducing how far we will typically search in Allocate.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Free(T obj)
{
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
lifecycle.Reset(obj);
if (typeof(TProcessAwareBehavior) == typeof(ThreadAwareBehavior))
{
int threadIndex = Environment.CurrentManagedThreadId & _bucketsMask;
ref var firstItem = ref _firstItems[threadIndex];
if (CacheAwareElement.TryRelease(ref firstItem, obj))
return;
}
else
{
if (_firstElement == null)
{
if (null == Interlocked.CompareExchange(ref _firstElement, obj, null))
return;
}
}
FreeSlow(obj);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void FreeSlow(T obj)
{
var items = _items;
var current = (uint)Interlocked.Increment(ref _itemTopCounter);
var claim = (current - 1) & _itemsMask;
ref var item = ref items[claim];
if (item.Value == null)
{
// Intentionally not using interlocked here.
// In a worst case scenario two objects may be stored into same slot.
// It is very unlikely to happen and will only mean that one of the objects will get collected.
item.Value = obj;
}
}
public void Clear(bool partial = true)
{
var doDispose = typeof(IDisposable).IsAssignableFrom(typeof(T));
if (typeof(TProcessAwareBehavior) == typeof(ThreadAwareBehavior) && !partial)
{
for (int i = 0; i < _firstItems.Length; i++)
{
ref var bucket = ref _firstItems[i];
while (CacheAwareElement.TryClaim(ref bucket, out var obj))
{
if (doDispose)
((IDisposable)obj).Dispose();
}
}
}
uint current;
do
{
current = (uint)Interlocked.Increment(ref _itemBottomCounter);
if (current < _itemTopCounter)
{
uint claim = (current - 1) & _itemsMask;
T inst = _items[claim].Value;
if (inst != null)
{
// WARNING: In a absurdly fast loop this can still fail to get a proper, that is why
// we still use a compare exchange operation instead of using the reference.
if (inst == Interlocked.CompareExchange(ref _items[claim].Value, null, inst) && doDispose)
{
((IDisposable)inst).Dispose();
}
}
}
}
while (current < _itemTopCounter);
}
public void Clear<TEvictionStrategy>(TEvictionStrategy evictionStrategy = default(TEvictionStrategy))
where TEvictionStrategy : struct, IEvictionStrategy<T>
{
var doDispose = typeof(IDisposable).IsAssignableFrom(typeof(T));
if (typeof(TProcessAwareBehavior) == typeof(ThreadAwareBehavior))
{
for (var i = 0; i < _firstItems.Length; i++)
{
ref var bucket = ref _firstItems[i];
if (doDispose)
CacheAwareElement.ClearAndDispose(ref bucket, ref evictionStrategy);
else
CacheAwareElement.Clear(ref bucket, ref evictionStrategy);
}
}
var current = (uint)_itemBottomCounter;
do
{
if (current < _itemTopCounter)
{
var claim = current & _itemsMask;
var inst = _items[claim].Value;
if (inst != null && evictionStrategy.CanEvict(inst))
{
// WARNING: In a absurdly fast loop this can still fail to get a proper, that is why
// we still use a compare exchange operation instead of using the reference.
if (inst == Interlocked.CompareExchange(ref _items[claim].Value, null, inst) && doDispose)
{
((IDisposable)inst).Dispose();
}
}
}
current++;
}
while (current < _itemTopCounter);
}
private struct Element
{
internal T Value;
}
[StructLayout(LayoutKind.Sequential, Size = 128)]
private struct CacheAwareElement
{
private readonly long _pad1;
private T Value1;
private T Value2;
private T Value3;
private T Value4;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryClaim(ref CacheAwareElement bucket, out T item)
{
// Note that the initial read is optimistically not synchronized. That is intentional.
// We will interlock only when we have a candidate. in a worst case we may miss some
// recently returned objects. Not a big deal.
var inst = bucket.Value1;
if (inst != null && inst == Interlocked.CompareExchange(ref bucket.Value1, null, inst))
goto Done;
inst = bucket.Value2;
if (inst != null && inst == Interlocked.CompareExchange(ref bucket.Value2, null, inst))
goto Done;
inst = bucket.Value3;
if (inst != null && inst == Interlocked.CompareExchange(ref bucket.Value3, null, inst))
goto Done;
inst = bucket.Value4;
if (inst != null && inst == Interlocked.CompareExchange(ref bucket.Value4, null, inst))
goto Done;
item = null;
return false;
Done:
item = inst;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryRelease(ref CacheAwareElement bucket, T value)
{
if (null == Interlocked.CompareExchange(ref bucket.Value1, value, null))
goto Done;
if (null == Interlocked.CompareExchange(ref bucket.Value2, value, null))
goto Done;
if (null == Interlocked.CompareExchange(ref bucket.Value3, value, null))
goto Done;
if (null == Interlocked.CompareExchange(ref bucket.Value4, value, null))
goto Done;
return false;
Done: return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Clear<TEvictionStrategy>(ref CacheAwareElement bucket, ref TEvictionStrategy policy)
where TEvictionStrategy : struct, IEvictionStrategy<T>
{
// Note that the initial read is optimistically not synchronized. That is intentional.
// We will interlock only when we have a candidate. in a worst case we may miss some
// recently returned objects. Not a big deal.
var inst = bucket.Value1;
if (inst != null && policy.CanEvict(inst))
{
Interlocked.CompareExchange(ref bucket.Value1, null, inst);
}
inst = bucket.Value2;
if (inst != null && policy.CanEvict(inst))
{
Interlocked.CompareExchange(ref bucket.Value2, null, inst);
}
inst = bucket.Value3;
if (inst != null && policy.CanEvict(inst))
{
Interlocked.CompareExchange(ref bucket.Value3, null, inst);
}
inst = bucket.Value4;
if (inst != null && policy.CanEvict(inst))
{
Interlocked.CompareExchange(ref bucket.Value4, null, inst);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ClearAndDispose<TEvictionStrategy>(ref CacheAwareElement bucket, ref TEvictionStrategy policy)
where TEvictionStrategy : struct, IEvictionStrategy<T>
{
// Note that the initial read is optimistically not synchronized. That is intentional.
// We will interlock only when we have a candidate. in a worst case we may miss some
// recently returned objects. Not a big deal.
T inst = bucket.Value1;
if (inst != null && policy.CanEvict(inst))
{
if (inst == Interlocked.CompareExchange(ref bucket.Value1, null, inst))
((IDisposable)inst).Dispose();
}
inst = bucket.Value2;
if (inst != null && policy.CanEvict(inst))
{
if (inst == Interlocked.CompareExchange(ref bucket.Value2, null, inst))
((IDisposable)inst).Dispose();
}
inst = bucket.Value3;
if (inst != null && policy.CanEvict(inst))
{
if (inst == Interlocked.CompareExchange(ref bucket.Value3, null, inst))
((IDisposable)inst).Dispose();
}
inst = bucket.Value4;
if (inst != null && policy.CanEvict(inst))
{
if (inst == Interlocked.CompareExchange(ref bucket.Value4, null, inst))
((IDisposable)inst).Dispose();
}
}
}
}
public struct NoResetFactorySupport<T> : IObjectLifecycle<T> where T : class, new()
{
public delegate T Factory();
// factory is stored for the lifetime of the pool. We will call this only when pool needs to
// expand. compared to "new T()", Func gives more flexibility to implementers and faster
// than "new T()".
private readonly Factory _factory;
public NoResetFactorySupport(Factory factory)
{
_factory = factory;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T New() => _factory();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset(T value) { }
}
public struct ThreadAwareBehavior : IProcessAwareBehavior
{
private readonly int _buckets;
public int Buckets
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _buckets == 0 ? 128 : _buckets;
}
public ThreadAwareBehavior(int buckets = 128)
{
_buckets = buckets;
}
}
public struct NonThreadAwareBehavior : IProcessAwareBehavior
{
public int Buckets
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => 0;
}
}
public struct AlwaysEvictStrategy<T> : IEvictionStrategy<T> where T : class
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanEvict(T item) => true;
}
public struct NeverEvictStrategy<T> : IEvictionStrategy<T> where T : class
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanEvict(T item) => false;
}
}
| 37.527897 | 125 | 0.539456 | [
"MIT"
] | fdieulle/Minotaur | Tests/Minotaur.Pocs/HighPerf/ObjectPool.cs | 17,490 | C# |
using System;
namespace Elsa.Services
{
public class IdGenerator : IIdGenerator
{
public string Generate() => Guid.NewGuid().ToString("N");
}
} | 18.222222 | 65 | 0.646341 | [
"BSD-3-Clause"
] | caiohomem/elsa-core | src/core/Elsa.Core/Services/IdGenerator.cs | 164 | C# |
// Jeebs Rapid Application Development
// Copyright (c) bfren - licensed under https://mit.bfren.dev/2013
using System.Collections.Generic;
using System.Threading.Tasks;
using Jeebs.Data;
using Jeebs.WordPress.Data.Entities;
using Jeebs.WordPress.Data.Querying;
namespace Jeebs.WordPress.Data;
/// <summary>
/// Query Terms - to enable testing of static functions
/// </summary>
public interface IQueryTerms
{
/// <summary>
/// Execute Terms query
/// </summary>
/// <typeparam name="T">Return Model type</typeparam>
/// <param name="db">IWpDb</param>
/// <param name="w">IUnitOfWork</param>
/// <param name="opt">Function to return query options</param>
Task<Option<IEnumerable<T>>> ExecuteAsync<T>(IWpDb db, IUnitOfWork w, GetTermsOptions opt)
where T : IWithId<WpTermId>;
}
| 29.296296 | 91 | 0.724399 | [
"MIT"
] | bfren/jeebs | src/Jeebs.WordPress.Abstractions/Data/IQueryTerms.cs | 793 | C# |
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace UnityEditor.Rendering
{
/// <summary>
/// Contains a set of method to be able to manage Menu Items for the editor
/// </summary>
static class MenuManager
{
#region Add Menu Item
static Action<string, string, bool, int, Action, Func<bool>> s_AddMenuItem = GetAddMenuItemMethod();
static Action<string, string, bool, int, Action, Func<bool>> GetAddMenuItemMethod()
{
MethodInfo addMenuItemMethodInfo = typeof(Menu).GetMethod("AddMenuItem", BindingFlags.Static | BindingFlags.NonPublic);
var nameParam = Expression.Parameter(typeof(string), "name");
var shortcutParam = Expression.Parameter(typeof(string), "shortcut");
var checkedParam = Expression.Parameter(typeof(bool), "checked");
var priorityParam = Expression.Parameter(typeof(int), "priority");
var executeParam = Expression.Parameter(typeof(Action), "execute");
var validateParam = Expression.Parameter(typeof(Func<bool>), "validate");
var addMenuItemExpressionCall = Expression.Call(null, addMenuItemMethodInfo,
nameParam,
shortcutParam,
checkedParam,
priorityParam,
executeParam,
validateParam);
return Expression.Lambda<Action<string, string, bool, int, Action, Func<bool>>>(
addMenuItemExpressionCall,
nameParam,
shortcutParam,
checkedParam,
priorityParam,
executeParam,
validateParam).Compile();
}
/// <summary>
/// Adds a menu Item to the editor
/// </summary>
/// <param name="path">The path to the menu item</param>
/// <param name="shortcut">The shortcut of the menu item</param>
/// <param name="checked">If the item can have an state, pressed or not</param>
/// <param name="priority">The priority of the menu item</param>
/// <param name="execute">The action that will be called once the menu item is pressed</param>
/// <param name="validate">The action that will be called to know if the menu itme is enabled</param>
public static void AddMenuItem(string path, string shortcut, bool @checked, int priority, System.Action execute, System.Func<bool> validate)
{
s_AddMenuItem(path, shortcut, @checked, priority, execute, validate);
}
#endregion
#region Remove Menu Item
static Action<string> s_RemoveMenuItem = GetRemoveMenuItemMethod();
static Action<string> GetRemoveMenuItemMethod()
{
MethodInfo removeMenuItemMethodInfo = typeof(Menu).GetMethod("RemoveMenuItem", BindingFlags.Static | BindingFlags.NonPublic);
var nameParam = Expression.Parameter(typeof(string), "name");
return Expression.Lambda<Action<string>>(
Expression.Call(null, removeMenuItemMethodInfo, nameParam),
nameParam).Compile();
}
#endregion
/// <summary>
/// Removes a Menu item from the editor, if the path is not found it does nothing
/// </summary>
/// <param name="path">The path of the menu item to be removed</param>
public static void RemoveMenuItem(string path)
{
s_RemoveMenuItem(path);
}
}
}
| 43.333333 | 148 | 0.618519 | [
"MIT"
] | turesnake/tpr_Unity_Render_Pipeline_LearningNotes | 12.1/Core_and_URP_12.1/rp.core.12.1/Editor/MenuManager.cs | 3,510 | C# |
//----------------------
// <auto-generated>
// This file was automatically generated. Any changes to it will be lost if and when the file is regenerated.
// </auto-generated>
//----------------------
#pragma warning disable
using System;
using SQEX.Luminous.Core.Object;
using System.Collections.Generic;
using CodeDom = System.CodeDom;
namespace Black.Entity.TPS.FilterNodeEntities
{
[Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")]
public partial class Distance2DTrapezoidFilterNodeEntity : Black.Entity.TPS.FilterDescriptorNodeEntity
{
new public static ObjectType ObjectType { get; private set; }
private static PropertyContainer fieldProperties;
public int subject_;
public bool useWeightFlag_;
public float weight_;
public bool allowAIGraphOverride_;
public float p0_;
public float p1_;
public float p2_;
public float p3_;
new public static void SetupObjectType()
{
if (ObjectType != null)
{
return;
}
var dummy = new Distance2DTrapezoidFilterNodeEntity();
var properties = dummy.GetFieldProperties();
ObjectType = new ObjectType("Black.Entity.TPS.FilterNodeEntities.Distance2DTrapezoidFilterNodeEntity", 0, Black.Entity.TPS.FilterNodeEntities.Distance2DTrapezoidFilterNodeEntity.ObjectType, Construct, properties, 0, 336);
}
public override ObjectType GetObjectType()
{
return ObjectType;
}
protected override PropertyContainer GetFieldProperties()
{
if (fieldProperties != null)
{
return fieldProperties;
}
fieldProperties = new PropertyContainer("Black.Entity.TPS.FilterNodeEntities.Distance2DTrapezoidFilterNodeEntity", base.GetFieldProperties(), -880825879, 1533398134);
fieldProperties.AddProperty(new Property("subject_", 3903058736, "Black.Entity.TPS.FallbackQueryDescriptorNodeEntity.SubjectType", 304, 4, 1, Property.PrimitiveType.Enum, 0, (char)0));
fieldProperties.AddProperty(new Property("useWeightFlag_", 4027223091, "bool", 308, 1, 1, Property.PrimitiveType.Bool, 0, (char)0));
fieldProperties.AddProperty(new Property("weight_", 3537511442, "float", 312, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
fieldProperties.AddProperty(new Property("allowAIGraphOverride_", 2548859529, "bool", 316, 1, 1, Property.PrimitiveType.Bool, 0, (char)0));
fieldProperties.AddProperty(new Property("p0_", 1092520214, "float", 320, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
fieldProperties.AddProperty(new Property("p1_", 2166037567, "float", 324, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
fieldProperties.AddProperty(new Property("p2_", 2165890472, "float", 328, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
fieldProperties.AddProperty(new Property("p3_", 1091975761, "float", 332, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
return fieldProperties;
}
private static BaseObject Construct()
{
return new Distance2DTrapezoidFilterNodeEntity();
}
}
} | 40.1375 | 233 | 0.680785 | [
"MIT"
] | Gurrimo/Luminaire | Assets/Editor/Generated/Black/Entity/TPS/FilterNodeEntities/Distance2DTrapezoidFilterNodeEntity.generated.cs | 3,211 | C# |
/**
* Copyright (c) 2019 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using SimpleJSON;
using UnityEngine;
namespace Simulator.Api.Commands
{
class AgentOnLaneChange : ICommand
{
public string Name => "agent/on_lane_change";
public void Execute(JSONNode args)
{
var api = ApiManager.Instance;
var uid = args["uid"].Value;
if (api.Agents.TryGetValue(uid, out GameObject obj))
{
api.LaneChange.Add(obj);
api.SendResult();
SIM.LogAPI(SIM.API.OnLaneChanged);
}
else
{
api.SendError($"Agent '{uid}' not found");
}
}
}
}
| 22.142857 | 64 | 0.530323 | [
"Apache-2.0",
"BSD-3-Clause"
] | 0x8BADFOOD/simulator | Assets/Scripts/Api/Commands/AgentOnLaneChange.cs | 775 | C# |
// https://github.com/LDj3SNuD/ARM_v8-A_AArch64_Instructions_Tester/blob/master/Tester/Types/Integer.cs
using System;
using System.Numerics;
namespace Ryujinx.Tests.Cpu.Tester.Types
{
internal static class Integer
{
public static Bits SubBigInteger(this BigInteger x, int highIndex, int lowIndex) // ASL: "<:>".
{
if (highIndex < lowIndex)
{
throw new IndexOutOfRangeException();
}
Bits src = new Bits(x);
bool[] dst = new bool[highIndex - lowIndex + 1];
for (int i = lowIndex, n = 0; i <= highIndex; i++, n++)
{
if (i <= src.Count - 1)
{
dst[n] = src[i];
}
else
{
dst[n] = (x.Sign != -1 ? false : true); // Zero / Sign Extension.
}
}
return new Bits(dst);
}
public static bool SubBigInteger(this BigInteger x, int index) // ASL: "<>".
{
Bits dst = x.SubBigInteger(index, index);
return (bool)dst;
}
}
}
| 26.860465 | 103 | 0.47619 | [
"Unlicense"
] | 0x0ade/Ryujinx | Ryujinx.Tests/Cpu/Tester/Types/Integer.cs | 1,155 | C# |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.Common;
namespace WebsitePanel.Portal
{
public partial class ServersAddService : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGroup();
BindProviders();
}
}
private void BindGroup()
{
ResourceGroupInfo group = ES.Services.Servers.GetResourceGroup(PanelRequest.GroupID);
litGroupName.Text = serviceName.Text = PanelFormatter.GetLocalizedResourceGroupName(group.GroupName);
}
private void BindProviders()
{
ddlProviders.DataSource = ES.Services.Servers.GetProvidersByGroupId(PanelRequest.GroupID);
ddlProviders.DataBind();
ddlProviders.Items.Insert(0, new ListItem(GetLocalizedString("SelectProvider.Text"), ""));
}
protected void btnAdd_Click(object sender, EventArgs e)
{
// validate input
if (!Page.IsValid)
return;
// register service type
int providerId = Utils.ParseInt(ddlProviders.SelectedValue, 0);
// add a new service ...
try
{
ServiceInfo service = new ServiceInfo();
service.ServerId = PanelRequest.ServerId;
service.ProviderId = providerId;
service.ServiceName = serviceName.Text;
BoolResult res = ES.Services.Servers.IsInstalled(PanelRequest.ServerId, providerId);
if (res.IsSuccess)
{
if (!res.Value)
{
ShowErrorMessage("SOFTWARE_IS_NOT_INSTALLED");
return;
}
}
else
{
ShowErrorMessage("SERVER_ADD_SERVICE");
}
int serviceId = ES.Services.Servers.AddService(service);
if (serviceId < 0)
{
ShowResultMessage(serviceId);
return;
}
// ...and go to service configuration page
Response.Redirect(EditUrl("ServerID", PanelRequest.ServerId.ToString(), "edit_service",
"ServiceID=" + serviceId.ToString()), true);
}
catch (Exception ex)
{
ShowErrorMessage("SERVER_ADD_SERVICE", ex);
return;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ServerID", PanelRequest.ServerId.ToString(), "edit_server"), true);
}
}
}
| 39.54918 | 107 | 0.604767 | [
"BSD-3-Clause"
] | 9192939495969798/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ServersAddService.ascx.cs | 4,825 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* Coin Exchange is a high performance exchange system specialized for
* Crypto currency trading. It has different general purpose uses such as
* independent deposit and withdrawal channels for Bitcoin and Litecoin,
* but can also act as a standalone exchange that can be used with
* different asset classes.
* Coin Exchange uses state of the art technologies such as ASP.NET REST API,
* AngularJS and NUnit. It also uses design patterns for complex event
* processing and handling of thousands of transactions per second, such as
* Domain Driven Designing, Disruptor Pattern and CQRS With Event Sourcing.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
using System.Management.Instrumentation;
using System.Security.Authentication;
using CoinExchange.IdentityAccess.Application.AccessControlServices.Commands;
using CoinExchange.IdentityAccess.Domain.Model.Repositories;
using CoinExchange.IdentityAccess.Domain.Model.SecurityKeysAggregate;
namespace CoinExchange.IdentityAccess.Application.AccessControlServices
{
/// <summary>
/// Service to serve the loging out process for a user
/// </summary>
public class LogoutApplicationService : ILogoutApplicationService
{
private ISecurityKeysRepository _securityKeysRepository;
/// <summary>
/// Parameterized Constructor
/// </summary>
/// <param name="securityKeysRepository"></param>
public LogoutApplicationService(ISecurityKeysRepository securityKeysRepository)
{
_securityKeysRepository = securityKeysRepository;
}
/// <summary>
/// Logs the user out
/// </summary>
/// <returns></returns>
public bool Logout(LogoutCommand logoutCommand)
{
if (logoutCommand.ApiKey != null &&
!string.IsNullOrEmpty(logoutCommand.ApiKey.Value))
{
SecurityKeysPair securityKeysPair =
_securityKeysRepository.GetByApiKey(logoutCommand.ApiKey.Value);
if (securityKeysPair != null)
{
return _securityKeysRepository.DeleteSecurityKeysPair(securityKeysPair);
}
else
{
throw new InstanceNotFoundException("No SecurityKeysPair found for the given API key.");
}
}
else
{
throw new InvalidCredentialException("Invalid or Incomplete Logout Credentials");
}
}
}
}
| 42.186047 | 109 | 0.644983 | [
"Apache-2.0"
] | 3plcoins/coin-exchange-backend | src/IdentityAccess/CoinExchange.IdentityAccess.Application/AccessControlServices/LogoutApplicationService.cs | 3,630 | C# |
using Newtonsoft.Json;
namespace PingboardApiClient.Models.CustomFields.Requests
{
public class UpdateCustomFieldRequest
{
[JsonProperty("custom_fields")]
public CustomField CustomField { get; } = new CustomField();
}
}
| 22.727273 | 68 | 0.708 | [
"MIT"
] | Johnmancini30/PingboardApiClient | src/PingboardApiClient/Models/CustomFields/Requests/UpdateCustomFieldRequest.cs | 252 | C# |
using Abp.Configuration.Startup;
using Abp.Localization.Dictionaries;
using Abp.Localization.Dictionaries.Xml;
using Abp.Reflection.Extensions;
namespace LogViewer.Localization
{
public static class LogViewerLocalizationConfigurer
{
public static void Configure(ILocalizationConfiguration localizationConfiguration)
{
localizationConfiguration.Sources.Add(
new DictionaryBasedLocalizationSource(LogViewerConsts.LocalizationSourceName,
new XmlEmbeddedFileLocalizationDictionaryProvider(
typeof(LogViewerLocalizationConfigurer).GetAssembly(),
"LogViewer.Localization.SourceFiles"
)
)
);
}
}
}
| 33.608696 | 93 | 0.663648 | [
"MIT"
] | hitenzo/LogViewer | aspnet-core/src/LogViewer.Core/Localization/LogViewerLocalizationConfigurer.cs | 775 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace ClangSharp.UnitTests
{
public sealed class CSharpLatestUnix_FunctionDeclarationBodyImportTest : FunctionDeclarationBodyImportTest
{
protected override Task ArraySubscriptTestImpl()
{
var inputContents = @"int MyFunction(int* pData, int index)
{
return pData[index];
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static int MyFunction(int* pData, int index)
{
return pData[index];
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task BasicTestImpl()
{
var inputContents = @"void MyFunction()
{
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static void MyFunction()
{
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task BinaryOperatorBasicTestImpl(string opcode)
{
var inputContents = $@"int MyFunction(int x, int y)
{{
return x {opcode} y;
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static int MyFunction(int x, int y)
{{
return x {opcode} y;
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task BinaryOperatorCompareTestImpl(string opcode)
{
var inputContents = $@"bool MyFunction(int x, int y)
{{
return x {opcode} y;
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static bool MyFunction(int x, int y)
{{
return x {opcode} y;
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task BinaryOperatorBooleanTestImpl(string opcode)
{
var inputContents = $@"bool MyFunction(bool x, bool y)
{{
return x {opcode} y;
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static bool MyFunction(bool x, bool y)
{{
return x {opcode} y;
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task BreakTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
while (true)
{
break;
}
return 0;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
while (true)
{
break;
}
return 0;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CallFunctionTestImpl()
{
var inputContents = @"void MyCalledFunction()
{
}
void MyFunction()
{
MyCalledFunction();
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static void MyCalledFunction()
{
}
public static void MyFunction()
{
MyCalledFunction();
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CallFunctionWithArgsTestImpl()
{
var inputContents = @"void MyCalledFunction(int x, int y)
{
}
void MyFunction()
{
MyCalledFunction(0, 1);
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static void MyCalledFunction(int x, int y)
{
}
public static void MyFunction()
{
MyCalledFunction(0, 1);
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CaseTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
switch (value)
{
case 0:
{
return 0;
}
case 1:
case 2:
{
return 3;
}
}
return -1;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
switch (value)
{
case 0:
{
return 0;
}
case 1:
case 2:
{
return 3;
}
}
return -1;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CaseNoCompoundTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
switch (value)
{
case 0:
return 0;
case 2:
case 3:
return 5;
}
return -1;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
switch (value)
{
case 0:
{
return 0;
}
case 2:
case 3:
{
return 5;
}
}
return -1;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CompareMultipleEnumTestImpl()
{
var inputContents = @"enum MyEnum : int
{
MyEnum_Value0,
MyEnum_Value1,
MyEnum_Value2,
};
static inline int MyFunction(MyEnum x)
{
return x == MyEnum_Value0 ||
x == MyEnum_Value1 ||
x == MyEnum_Value2;
}
";
var expectedOutputContents = @"using static ClangSharp.Test.MyEnum;
namespace ClangSharp.Test
{
public enum MyEnum
{
MyEnum_Value0,
MyEnum_Value1,
MyEnum_Value2,
}
public static partial class Methods
{
public static int MyFunction(MyEnum x)
{
return (x == MyEnum_Value0 || x == MyEnum_Value1 || x == MyEnum_Value2) ? 1 : 0;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ConditionalOperatorTestImpl()
{
var inputContents = @"int MyFunction(bool condition, int lhs, int rhs)
{
return condition ? lhs : rhs;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(bool condition, int lhs, int rhs)
{
return condition ? lhs : rhs;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ContinueTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
while (true)
{
continue;
}
return 0;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
while (true)
{
continue;
}
return 0;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CStyleFunctionalCastTestImpl()
{
var inputContents = @"int MyFunction(float input)
{
return (int)input;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(float input)
{
return (int)(input);
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CxxFunctionalCastTestImpl()
{
var inputContents = @"int MyFunction(float input)
{
return int(input);
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(float input)
{
return (int)(input);
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CxxConstCastTestImpl()
{
var inputContents = @"void* MyFunction(const void* input)
{
return const_cast<void*>(input);
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static void* MyFunction([NativeTypeName(""const void *"")] void* input)
{
return input;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CxxDynamicCastTestImpl()
{
var inputContents = @"struct MyStructA
{
virtual void MyMethod() = 0;
};
struct MyStructB : MyStructA { };
MyStructB* MyFunction(MyStructA* input)
{
return dynamic_cast<MyStructB*>(input);
}
";
var expectedOutputContents = $@"using System.Runtime.CompilerServices;
namespace ClangSharp.Test
{{
public unsafe partial struct MyStructA
{{
public void** lpVtbl;
public void MyMethod()
{{
((delegate* unmanaged[Thiscall]<MyStructA*, void>)(lpVtbl[0]))((MyStructA*)Unsafe.AsPointer(ref this));
}}
}}
[NativeTypeName(""struct MyStructB : MyStructA"")]
public unsafe partial struct MyStructB
{{
public void** lpVtbl;
public void MyMethod()
{{
((delegate* unmanaged[Thiscall]<MyStructB*, void>)(lpVtbl[0]))((MyStructB*)Unsafe.AsPointer(ref this));
}}
}}
public static unsafe partial class Methods
{{
public static MyStructB* MyFunction(MyStructA* input)
{{
return (MyStructB*)(input);
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CxxReinterpretCastTestImpl()
{
var inputContents = @"int* MyFunction(void* input)
{
return reinterpret_cast<int*>(input);
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static int* MyFunction(void* input)
{
return (int*)(input);
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task CxxStaticCastTestImpl()
{
var inputContents = @"int* MyFunction(void* input)
{
return static_cast<int*>(input);
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static int* MyFunction(void* input)
{
return (int*)(input);
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task DeclTestImpl()
{
var inputContents = @"\
int MyFunction()
{
int x = 0;
int y = 1, z = 2;
return x + y + z;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction()
{
int x = 0;
int y = 1, z = 2;
return x + y + z;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task DoTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
int i = 0;
do
{
i++;
}
while (i < count);
return i;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
int i = 0;
do
{
i++;
}
while (i < count);
return i;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task DoNonCompoundTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
int i = 0;
while (i < count)
i++;
return i;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
int i = 0;
while (i < count)
{
i++;
}
return i;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ForTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
for (int i = 0; i < count; i--)
{
i += 2;
}
int x;
for (x = 0; x < count; x--)
{
x += 2;
}
x = 0;
for (; x < count; x--)
{
x += 2;
}
for (int i = 0;;i--)
{
i += 2;
}
for (x = 0;;x--)
{
x += 2;
}
for (int i = 0; i < count;)
{
i++;
}
for (x = 0; x < count;)
{
x++;
}
// x = 0;
//
// for (;; x--)
// {
// x += 2;
// }
x = 0;
for (; x < count;)
{
x++;
}
for (int i = 0;;)
{
i++;
}
for (x = 0;;)
{
x++;
}
for (;;)
{
return -1;
}
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
for (int i = 0; i < count; i--)
{
i += 2;
}
int x;
for (x = 0; x < count; x--)
{
x += 2;
}
x = 0;
for (; x < count; x--)
{
x += 2;
}
for (int i = 0;; i--)
{
i += 2;
}
for (x = 0;; x--)
{
x += 2;
}
for (int i = 0; i < count;)
{
i++;
}
for (x = 0; x < count;)
{
x++;
}
x = 0;
for (; x < count;)
{
x++;
}
for (int i = 0;;)
{
i++;
}
for (x = 0;;)
{
x++;
}
for (;;)
{
return -1;
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ForNonCompoundTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
for (int i = 0; i < count; i--)
i += 2;
int x;
for (x = 0; x < count; x--)
x += 2;
x = 0;
for (; x < count; x--)
x += 2;
for (int i = 0;;i--)
i += 2;
for (x = 0;;x--)
x += 2;
for (int i = 0; i < count;)
i++;
for (x = 0; x < count;)
x++;
// x = 0;
//
// for (;; x--)
// x += 2;
x = 0;
for (; x < count;)
x++;
for (int i = 0;;)
i++;
for (x = 0;;)
x++;
for (;;)
return -1;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
for (int i = 0; i < count; i--)
{
i += 2;
}
int x;
for (x = 0; x < count; x--)
{
x += 2;
}
x = 0;
for (; x < count; x--)
{
x += 2;
}
for (int i = 0;; i--)
{
i += 2;
}
for (x = 0;; x--)
{
x += 2;
}
for (int i = 0; i < count;)
{
i++;
}
for (x = 0; x < count;)
{
x++;
}
x = 0;
for (; x < count;)
{
x++;
}
for (int i = 0;;)
{
i++;
}
for (x = 0;;)
{
x++;
}
for (;;)
{
return -1;
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task IfTestImpl()
{
var inputContents = @"int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
{
return lhs;
}
return rhs;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
{
return lhs;
}
return rhs;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task IfElseTestImpl()
{
var inputContents = @"int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
{
return lhs;
}
else
{
return rhs;
}
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
{
return lhs;
}
else
{
return rhs;
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task IfElseIfTestImpl()
{
var inputContents = @"int MyFunction(bool condition1, int a, int b, bool condition2, int c)
{
if (condition1)
{
return a;
}
else if (condition2)
{
return b;
}
return c;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(bool condition1, int a, int b, bool condition2, int c)
{
if (condition1)
{
return a;
}
else if (condition2)
{
return b;
}
return c;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task IfElseNonCompoundTestImpl()
{
var inputContents = @"int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
return lhs;
else
return rhs;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(bool condition, int lhs, int rhs)
{
if (condition)
{
return lhs;
}
else
{
return rhs;
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task InitListForArrayTestImpl()
{
var inputContents = @"
void MyFunction()
{
int x[4] = { 1, 2, 3, 4 };
int y[4] = { 1, 2, 3 };
int z[] = { 1, 2 };
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static void MyFunction()
{
int[] x = new int[4]
{
1,
2,
3,
4,
};
int[] y = new int[4]
{
1,
2,
3,
default,
};
int[] z = new int[2]
{
1,
2,
};
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task InitListForRecordDeclTestImpl()
{
var inputContents = @"struct MyStruct
{
float x;
float y;
float z;
float w;
};
MyStruct MyFunction1()
{
return { 1.0f, 2.0f, 3.0f, 4.0f };
}
MyStruct MyFunction2()
{
return { 1.0f, 2.0f, 3.0f };
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public partial struct MyStruct
{
public float x;
public float y;
public float z;
public float w;
}
public static partial class Methods
{
public static MyStruct MyFunction1()
{
return new MyStruct
{
x = 1.0f,
y = 2.0f,
z = 3.0f,
w = 4.0f,
};
}
public static MyStruct MyFunction2()
{
return new MyStruct
{
x = 1.0f,
y = 2.0f,
z = 3.0f,
};
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task MemberTestImpl()
{
var inputContents = @"struct MyStruct
{
int value;
};
int MyFunction1(MyStruct instance)
{
return instance.value;
}
int MyFunction2(MyStruct* instance)
{
return instance->value;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public partial struct MyStruct
{
public int value;
}
public static unsafe partial class Methods
{
public static int MyFunction1(MyStruct instance)
{
return instance.value;
}
public static int MyFunction2(MyStruct* instance)
{
return instance->value;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task RefToPtrTestImpl()
{
var inputContents = @"struct MyStruct {
int value;
};
bool MyFunction(const MyStruct& lhs, const MyStruct& rhs)
{
return lhs.value == rhs.value;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public partial struct MyStruct
{
public int value;
}
public static unsafe partial class Methods
{
public static bool MyFunction([NativeTypeName(""const MyStruct &"")] MyStruct* lhs, [NativeTypeName(""const MyStruct &"")] MyStruct* rhs)
{
return lhs->value == rhs->value;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnCXXNullPtrTestImpl()
{
var inputContents = @"void* MyFunction()
{
return nullptr;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static void* MyFunction()
{
return null;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnCXXBooleanLiteralTestImpl(string value)
{
var inputContents = $@"bool MyFunction()
{{
return {value};
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static bool MyFunction()
{{
return {value};
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnFloatingLiteralDoubleTestImpl(string value)
{
var inputContents = $@"double MyFunction()
{{
return {value};
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static double MyFunction()
{{
return {value};
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnFloatingLiteralSingleTestImpl(string value)
{
var inputContents = $@"float MyFunction()
{{
return {value};
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static float MyFunction()
{{
return {value};
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnEmptyTestImpl()
{
var inputContents = @"void MyFunction()
{
return;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static void MyFunction()
{
return;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnIntegerLiteralInt32TestImpl()
{
var inputContents = @"int MyFunction()
{
return -1;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction()
{
return -1;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task AccessUnionMemberTestImpl()
{
var inputContents = @"union MyUnion
{
struct { int a; };
};
void MyFunction()
{
MyUnion myUnion;
myUnion.a = 10;
}
";
var expectedOutputContents = @"using System.Runtime.InteropServices;
namespace ClangSharp.Test
{
[StructLayout(LayoutKind.Explicit)]
public partial struct MyUnion
{
[FieldOffset(0)]
[NativeTypeName(""MyUnion::(anonymous struct at ClangUnsavedFile.h:3:5)"")]
public _Anonymous_e__Struct Anonymous;
public ref int a
{
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.a, 1));
}
}
public partial struct _Anonymous_e__Struct
{
public int a;
}
}
public static partial class Methods
{
public static void MyFunction()
{
MyUnion myUnion = new MyUnion();
myUnion.Anonymous.a = 10;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task ReturnStructTestImpl()
{
var inputContents = @"struct MyStruct
{
double r;
double g;
double b;
};
MyStruct MyFunction()
{
MyStruct myStruct;
return myStruct;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public partial struct MyStruct
{
public double r;
public double g;
public double b;
}
public static partial class Methods
{
public static MyStruct MyFunction()
{
MyStruct myStruct = new MyStruct();
return myStruct;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task SwitchTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
switch (value)
{
default:
{
return 0;
}
}
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
switch (value)
{
default:
{
return 0;
}
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task SwitchNonCompoundTestImpl()
{
var inputContents = @"int MyFunction(int value)
{
switch (value)
default:
{
return 0;
}
switch (value)
default:
return 0;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int value)
{
switch (value)
{
default:
{
return 0;
}
}
switch (value)
{
default:
{
return 0;
}
}
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task UnaryOperatorAddrOfTestImpl()
{
var inputContents = @"int* MyFunction(int value)
{
return &value;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static int* MyFunction(int value)
{
return &value;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task UnaryOperatorDerefTestImpl()
{
var inputContents = @"int MyFunction(int* value)
{
return *value;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static unsafe partial class Methods
{
public static int MyFunction(int* value)
{
return *value;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task UnaryOperatorLogicalNotTestImpl()
{
var inputContents = @"bool MyFunction(bool value)
{
return !value;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static bool MyFunction(bool value)
{
return !value;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task UnaryOperatorPostfixTestImpl(string opcode)
{
var inputContents = $@"int MyFunction(int value)
{{
return value{opcode};
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static int MyFunction(int value)
{{
return value{opcode};
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task UnaryOperatorPrefixTestImpl(string opcode)
{
var inputContents = $@"int MyFunction(int value)
{{
return {opcode}value;
}}
";
var expectedOutputContents = $@"namespace ClangSharp.Test
{{
public static partial class Methods
{{
public static int MyFunction(int value)
{{
return {opcode}value;
}}
}}
}}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task WhileTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
int i = 0;
while (i < count)
{
i++;
}
return i;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
int i = 0;
while (i < count)
{
i++;
}
return i;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
protected override Task WhileNonCompoundTestImpl()
{
var inputContents = @"int MyFunction(int count)
{
int i = 0;
while (i < count)
i++;
return i;
}
";
var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
public static int MyFunction(int count)
{
int i = 0;
while (i < count)
{
i++;
}
return i;
}
}
}
";
return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents);
}
}
}
| 19.955081 | 169 | 0.523889 | [
"MIT"
] | Color-Of-Code/ClangSharp | tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationBodyImportTest.cs | 35,540 | C# |
using Newtonsoft.Json;
namespace GitExtensions.GitLab.Client.Repo
{
public class User
{
/// <summary>
/// The GitLab username
/// </summary>
public int Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string State { get; set; }
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; }
[JsonProperty("web_url")]
public string WebUrl { get; set; }
public User()
{
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
public override int GetHashCode()
{
return GetType().GetHashCode() + Id.GetHashCode();
}
public override string ToString()
{
return Name;
}
}
}
| 21.214286 | 62 | 0.516274 | [
"MIT"
] | ahmeturun/GitExtensions.GitLab | src/GitExtensions.GitLab.Client/Repo/User.cs | 893 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Runtime.CompilerServices.Tests
{
public class SwitchExpressionExceptionTests
{
[Fact]
public void Constructors()
{
string message = "exception message";
var e = new SwitchExpressionException();
Assert.NotEmpty(e.Message);
Assert.Null(e.InnerException);
e = new SwitchExpressionException(message);
Assert.Equal(message, e.Message);
Assert.Null(e.InnerException);
var inner = new Exception();
e = new SwitchExpressionException(message, inner);
Assert.Equal(message, e.Message);
Assert.Same(inner, e.InnerException);
}
[Fact]
public static void Constructor_StringVsObjectArg()
{
object message = "exception message";
var ex = new SwitchExpressionException(message as object);
Assert.NotEqual(message, ex.Message);
Assert.Same(message, ex.UnmatchedValue);
ex = new SwitchExpressionException(message as string);
Assert.Same(message, ex.Message);
Assert.Null(ex.UnmatchedValue);
}
[Fact]
public void UnmatchedValue_Null()
{
var ex = new SwitchExpressionException((object)null);
Assert.Null(ex.UnmatchedValue);
}
[Theory]
[InlineData(34)]
[InlineData(new byte[] { 1, 2, 3 })]
[InlineData(true)]
[InlineData("34")]
public void UnmatchedValue_NotNull(object unmatchedValue)
{
var ex = new SwitchExpressionException(unmatchedValue);
Assert.Equal(unmatchedValue, ex.UnmatchedValue);
Assert.Contains(ex.UnmatchedValue.ToString(), ex.Message);
}
}
}
| 31.8 | 71 | 0.610063 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Runtime.Extensions/tests/System/Runtime/CompilerServices/SwitchExpressionExceptionTests.cs | 2,067 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Luna.Utils
{
public abstract class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
internal void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 28.5625 | 88 | 0.704595 | [
"MIT"
] | mettelephant/Luna | Luna/Utils/NotifyPropertyChanged.cs | 459 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Kalakoi.Xbox.OpenXBL
{
public static class XboxConnection
{
public const string BASEURI = "https://xbl.io/api/v2";
public static string APIKEY = string.Empty;
public static void SetApiKey(string Key)
{
APIKEY = Key;
}
public static async Task<string> XuidFromGamertagAsync(string Gamertag)
{
string Endpoint = string.Format("/friends/search?gt={0}", Gamertag);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
XboxProfile p = new XboxProfile(Response);
return p.ID.ToString();
}
public static string XuidFromGamertag(string Gamertag)
{
string Endpoint = string.Format("/friends/search?gt={0}", Gamertag);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
XboxProfile p = new XboxProfile(Response);
return p.ID.ToString();
}
public static async Task<XboxProfile> GetProfileAsync()
{
string Endpoint = "/account";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
return new XboxProfile(Response);
}
public static XboxProfile GetProfile()
{
string Endpoint = "/account";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return new XboxProfile(Response);
}
public static async Task<XboxProfile> GetProfileAsync(string Gamertag)
{
string Endpoint = string.Format("/friends/search?gt={0}", Gamertag);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
return new XboxProfile(Response);
}
public static XboxProfile GetProfile(string Gamertag)
{
string Endpoint = string.Format("/friends/search?gt={0}", Gamertag);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return new XboxProfile(Response);
}
public static async Task<List<Friend>> GetFriendsAsync()
{
string Endpoint = "/friends";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
List<Friend> Return = new List<Friend>();
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
Return.Add(new Friend(Person.DeserializeJSON(t)));
return Return;
}
public static IEnumerable<Friend> GetFriends()
{
string Endpoint = "/friends";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
yield return new Friend(Person.DeserializeJSON(t));
}
public static async Task<List<Friend>> GetFriendsAsync(string xuid)
{
string Endpoint = "/friends?xuid=";
Uri RequestAddress = new Uri(string.Format("{0}{1}{2}", BASEURI, Endpoint, xuid));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
List<Friend> Return = new List<Friend>();
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
Return.Add(new Friend(Person.DeserializeJSON(t)));
return Return;
}
public static IEnumerable<Friend> GetFriends(string xuid)
{
string Endpoint = "/friends?xuid=";
Uri RequestAddress = new Uri(string.Format("{0}{1}{2}", BASEURI, Endpoint, xuid));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
yield return new Friend(Person.DeserializeJSON(t));
}
public static async Task AddFriendAsync(string xuid)
{
string Endpoint = string.Format("/friends/add/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
}
public static void AddFriend(string xuid)
{
string Endpoint = string.Format("/friends/add/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
}
public static async Task RemoveFriendAsync(string xuid)
{
string Endpoint = string.Format("/friends/remove/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
}
public static void RemoveFriend(string xuid)
{
string Endpoint = string.Format("/friends/remove/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
}
public static async Task FavoriteFriendAsync(string xuid)
{
string Endpoint = "/friends/favorite";
//string Data = string.Format("{\"xuids\":[{0}]}", xuid);
string Data = "{\"xuids\":[" + xuid + "]}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetPostResponseAsync(RequestAddress, Data, APIKEY).ConfigureAwait(false);
}
public static void FavoriteFriend(string xuid)
{
string Endpoint = "/friends/favorite";
//string Data = string.Format("{\"xuids\":[{0}]}", xuid);
string Data = "{\"xuids\":[" + xuid + "]}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetPostResponse(RequestAddress, Data, APIKEY);
}
public static async Task UnfavoriteFriendAsync(string xuid)
{
string Endpoint = "/friends/favorite/remove";
//string Data = string.Format("{\"xuids\":[{0}]}", xuid);
string Data = "{\"xuids\":[" + xuid + "]}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetPostResponseAsync(RequestAddress, Data, APIKEY).ConfigureAwait(false);
}
public static void UnfavoriteFriend(string xuid)
{
string Endpoint = "/friends/favorite/remove";
//string Data = string.Format("{\"xuids\":[{0}]}", xuid);
string Data = "{\"xuids\":[" + xuid +"]}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetPostResponse(RequestAddress, Data, APIKEY);
}
public static async Task<List<Friend>> GetRecentPlayersAsync()
{
string Endpoint = "/recent-players";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
List<Friend> Return = new List<Friend>();
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
Return.Add(new Friend(Person.DeserializeJSON(t)));
return Return;
}
public static IEnumerable<Friend> GetRecentPlayers()
{
string Endpoint = "/recent-players";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("people"));
foreach (JToken t in tokens.Children())
yield return new Friend(Person.DeserializeJSON(t));
}
public static async Task<List<ConversationSummary>> GetConversationsAsync()
{
string Endpoint = "/conversations";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("results"));
List<ConversationSummary> l = new List<ConversationSummary>();
foreach (JToken t in tokens.Children())
l.Add(ConversationSummary.DeserializeJSON(t));
return l;
}
public static IEnumerable<ConversationSummary> GetConversations()
{
string Endpoint = "/conversations";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("results"));
foreach (JToken t in tokens.Children())
yield return ConversationSummary.DeserializeJSON(t);
}
public static async Task<Conversation> GetConversationAsync(string xuid)
{
string Endpoint = string.Format("/conversations/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
return Conversation.DeserializeJSON(Response);
}
public static Conversation GetConversation(string xuid)
{
string Endpoint = string.Format("/conversations/{0}", xuid);
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Conversation.DeserializeJSON(Response);
}
public static async Task SendMessageAsync(string Gamertag, string Message)
{
string Endpoint = "/conversations";
//string Data = string.Format("{\"to\":\"{0}\",\"message\":\"{1}\"}", Gamertag, Message);
string Data = "{\"to\":\"" + Gamertag + "\",\"message\":\"" + Message + "\"}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetPostResponseAsync(RequestAddress, Data, APIKEY).ConfigureAwait(false);
}
public static void SendMessage(string Gamertag, string Message)
{
string Endpoint = "/conversations";
//string Data = string.Format("{\"to\":\"{0}\",\"message\":\"{1}\"}", Gamertag, Message);
string Data = "{\"to\":\"" + Gamertag + "\",\"message\":\"" + Message + "\"}";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetPostResponse(RequestAddress, Data, APIKEY);
}
public static async Task<List<Alert>> GetAlertsAsync()
{
string Endpoint = "/alerts";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("alerts"));
List<Alert> l = new List<Alert>();
foreach (JToken t in tokens.Children())
l.Add(Alert.DeserializeJSON(t));
return l;
}
public static IEnumerable<Alert> GetAlerts()
{
string Endpoint = "/alerts";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
List<JToken> tokens = new List<JToken>(JObject.Parse(Response).SelectTokens("alerts"));
List<Alert> l = new List<Alert>();
foreach (JToken t in tokens.Children())
yield return Alert.DeserializeJSON(t);
}
public static string GetFeed()
{
string Endpoint = "/activity/feed";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Response;
}
public static string GetHistory()
{
string Endpoint = "/activity/history";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Response;
}
public static async Task<Friend> GetSummaryAsync()
{
string Endpoint = "/player/summary";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = await RestServices.GetResponseAsync(RequestAddress, APIKEY).ConfigureAwait(false);
return new Friend(Response);
}
public static Friend GetSummary()
{
string Endpoint = "/player/summary";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return new Friend(Response);
}
public static string GetClips()
{
string Endpoint = "/dvr/gameclips";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Response;
}
public static string GetScreenshots()
{
string Endpoint = "/dvr/screenshots";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Response;
}
public static string GetAchievements()
{
string Endpoint = "/achievements";
Uri RequestAddress = new Uri(string.Format("{0}{1}", BASEURI, Endpoint));
string Response = RestServices.GetResponse(RequestAddress, APIKEY);
return Response;
}
//TODO:
//GET /account/{xuid}
//GET /friends?xuid={xuid}
//GET /presence
//GET /{xuid}/presence
//POST /generate/gamertag Payload: {"Algorithm":1,"Count":3,"Locale":"en-US","Seed":""}
//POST /clubs/recommendations
//GET /clubs/owned
//POST /clubs/create Payload: {"name":"Hello World", "type":"[public/private/hidden]"}
//GET /clubs/find?q={query}
//POST /clubs/reserve Payload: {"name":"Hello World"}
//GET /activity/feed
//POST /activity/feed
//GET /activity/history
//GET /dvr/gameclips
//GET /dvr/screenshots
//GET /achievements
//GET /achievements/{titleid}
}
}
| 47.558659 | 123 | 0.593504 | [
"MIT"
] | Kalakoi/OpenXBL.NET | src/XboxConnection.cs | 17,028 | C# |
// Copyright (c) 2010 Joe Moorhouse
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading;
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Hosting.Providers;
using Microsoft.Scripting.Hosting.Shell;
namespace PythonConsoleControl
{
public delegate void ConsoleCreatedEventHandler(object sender, EventArgs e);
/// <summary>
/// Hosts the python console.
/// </summary>
public class PythonConsoleHost : ConsoleHost, IDisposable
{
Thread thread;
PythonTextEditor textEditor;
PythonConsole pythonConsole;
public event ConsoleCreatedEventHandler ConsoleCreated;
public PythonConsoleHost(PythonTextEditor textEditor)
{
this.textEditor = textEditor;
}
public PythonConsole Console
{
get { return pythonConsole; }
}
public PythonTextEditor Editor
{
get { return textEditor; }
}
protected override Type Provider
{
get { return typeof(PythonContext); }
}
/// <summary>
/// Runs the console host in its own thread.
/// </summary>
public void Run()
{
thread = new Thread(RunConsole);
thread.IsBackground = true;
thread.Start();
}
public void Dispose()
{
if (pythonConsole != null)
{
pythonConsole.Dispose();
}
if (thread != null)
{
thread.Join();
}
}
protected override CommandLine CreateCommandLine()
{
return new PythonCommandLine();
}
protected override OptionsParser CreateOptionsParser()
{
return new PythonOptionsParser();
}
/// <remarks>
/// After the engine is created the standard output is replaced with our custom Stream class so we
/// can redirect the stdout to the text editor window.
/// This can be done in this method since the Runtime object will have been created before this method
/// is called.
/// </remarks>
protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
{
SetOutput(new PythonOutputStream(textEditor));
pythonConsole = new PythonConsole(textEditor, commandLine);
if (ConsoleCreated != null) ConsoleCreated(this, EventArgs.Empty);
return pythonConsole;
}
public void WhenConsoleCreated(Action<PythonConsoleHost> action)
{
if (pythonConsole != null)
{
pythonConsole.WhenConsoleInitialized(() => action(this));
}
else
{
ConsoleCreated += (sender, args) => WhenConsoleCreated(action);
}
}
protected virtual void SetOutput(PythonOutputStream stream)
{
Runtime.IO.SetOutput(stream, Encoding.UTF8);
}
/// <summary>
/// Runs the console.
/// </summary>
void RunConsole()
{
this.Run(new string[] { "-X:FullFrames" });
}
protected override ScriptRuntimeSetup CreateRuntimeSetup()
{
ScriptRuntimeSetup srs = ScriptRuntimeSetup.ReadConfiguration();
foreach (var langSetup in srs.LanguageSetups)
{
if (langSetup.FileExtensions.Contains(".py"))
{
langSetup.Options["SearchPaths"] = new string[0];
}
}
return srs;
}
protected override void ParseHostOptions(string/*!*/[]/*!*/ args)
{
// Python doesn't want any of the DLR base options.
foreach (string s in args)
{
Options.IgnoredArgs.Add(s);
}
}
protected override void ExecuteInternal()
{
var pc = HostingHelpers.GetLanguageContext(Engine) as PythonContext;
pc.SetModuleState(typeof(ScriptEngine), Engine);
base.ExecuteInternal();
}
}
}
| 29.383117 | 120 | 0.544972 | [
"MIT"
] | Emin-A/revitpythonshell | PythonConsoleControl/PythonConsoleHost.cs | 4,527 | C# |
using System;
using System.Diagnostics;
using MbUnit.Framework;
namespace MbUnit.Demo
{
[TestFixture]
public class TestFixtureSetUpAndTearDownDemo
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
Console.WriteLine("TestFixtureSetUp");
}
[SetUp]
public void SetUp()
{
Console.WriteLine("TestFixtureSetUp");
}
[Test]
public void Test1()
{
Console.WriteLine("Test1");
}
[Test]
public void Test2()
{
Console.WriteLine("Test2");
}
[TearDown]
public void TearDown()
{
Console.WriteLine("TearDown");
}
[TestFixtureTearDown]
public void TestFixtureDown()
{
Console.WriteLine("TestFixtureDown");
}
}
}
| 21.465116 | 51 | 0.494041 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v2 | src/mbunit/MbUnit.Demo/TestFixtureSetUpAndTearDownDemo.cs | 925 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.BLOCKCHAIN.Models
{
public class DeployBusinessAgreementResponse : TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
[NameInMap("req_msg_id")]
[Validation(Required=false)]
public string ReqMsgId { get; set; }
// 结果码,一般OK表示调用成功
[NameInMap("result_code")]
[Validation(Required=false)]
public string ResultCode { get; set; }
// 异常信息的文本描述
[NameInMap("result_msg")]
[Validation(Required=false)]
public string ResultMsg { get; set; }
// 返回值
[NameInMap("data")]
[Validation(Required=false)]
public string Data { get; set; }
// 0表示成功
[NameInMap("status")]
[Validation(Required=false)]
public long? Status { get; set; }
// 部署合约交易在链上的地址
[NameInMap("tx_hash")]
[Validation(Required=false)]
public string TxHash { get; set; }
}
}
| 23.666667 | 61 | 0.595305 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | blockchain/csharp/core/Models/DeployBusinessAgreementResponse.cs | 1,177 | C# |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
namespace UnrealBuildTool.Rules
{
public class HTNPlanner : ModuleRules
{
public HTNPlanner(ReadOnlyTargetRules Target) : base(Target)
{
PublicIncludePaths.AddRange(
new string[] {
"Runtime/HTNPlanner/Public",
}
);
PrivateIncludePaths.AddRange(
new string[] {
"Runtime/AIModule/Public",
"Runtime/AIModule/Private",
"Runtime/Engine/Private",
}
);
PublicDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"Engine",
"GameplayTags",
"GameplayTasks",
"AIModule"
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[] {
// ... add any modules that your module loads dynamically here ...
}
);
if (Target.bBuildEditor == true)
{
PrivateDependencyModuleNames.Add("UnrealEd");
}
if (Target.bBuildDeveloperTools || (Target.Configuration != UnrealTargetConfiguration.Shipping && Target.Configuration != UnrealTargetConfiguration.Test))
{
PrivateDependencyModuleNames.Add("GameplayDebugger");
Definitions.Add("WITH_GAMEPLAY_DEBUGGER=1");
}
else
{
Definitions.Add("WITH_GAMEPLAY_DEBUGGER=0");
}
}
}
}
| 31.491228 | 166 | 0.457382 | [
"MIT"
] | CaptainUnknown/UnrealEngine_NVIDIAGameWorks | Engine/Plugins/Runtime/HTNPlanner/Source/HTNPlanner/HTNPlanner.Build.cs | 1,795 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Vostok.Clusterclient.Strategies
{
internal class ForkingDelaysPlanner : IForkingDelaysPlanner
{
public static readonly ForkingDelaysPlanner Instance = new ForkingDelaysPlanner();
public Task Plan(TimeSpan delay, CancellationToken token)
{
return Task.Delay(delay, token);
}
}
}
| 24.411765 | 90 | 0.706024 | [
"MIT"
] | vostok-archives/clusterclient.prototype | Vostok.ClusterClient/Strategies/ForkingDelaysPlanner.cs | 417 | C# |
// <auto-generated />
using dev.Data;
using IdentityServer4AspNetIdentity.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
namespace IdentityServer4AspNetIdentity.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125");
modelBuilder.Entity("IdentityServer4AspNetIdentity.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("IdentityServer4AspNetIdentity.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("IdentityServer4AspNetIdentity.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("IdentityServer4AspNetIdentity.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("IdentityServer4AspNetIdentity.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 34.640351 | 96 | 0.471638 | [
"MIT"
] | mokokosoft/Demo.IdentityServer | Data/Users/Migrations/ApplicationDbContextModelSnapshot.cs | 7,900 | C# |
namespace DevTeam.Patterns.IoC.Configuration.Json
{
internal class ContainerElement: ConfigurationElement
{
public KeyElement Key { get; set; }
public override string ToString()
{
return $"{nameof(ContainerElement)} [Key: {Key?.ToString() ?? "null"}, {GetDesctiption()}]";
}
}
} | 28 | 104 | 0.613095 | [
"MIT"
] | DevTeam/patterns | DevTeam.Patterns.IoC.Configuration/Json/ContainerElement.cs | 338 | C# |
namespace TEConstruye.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | 22.090909 | 54 | 0.646091 | [
"MIT"
] | germago119/TEConstruye | Server/TEConstruye/TEConstruye/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | 243 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.