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
namespace HREngine.Bots { class Pen_EX1_560 : PenTemplate //nozdormu { // spieler haben nur jeweils 15 sekunden für ihren zug. public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal) { return 0; } } }
26.818182
107
0.633898
[ "MIT" ]
chi-rei-den/Silverfish
penalties/Pen_EX1_560.cs
296
C#
using Microsoft.TeamFoundation.Client; using Sep.Git.Tfs.Core.TfsInterop; namespace Sep.Git.Tfs.VsCommon { public partial class TfsHelper : ITfsHelper { private TeamFoundationServer server; public string TfsClientLibraryVersion { get { return typeof(TeamFoundationServer).Assembly.GetName().Version.ToString() + " (MS)"; } } private void UpdateServer() { if (string.IsNullOrEmpty(Url)) { server = null; } else { server = new TeamFoundationServer(Url, new UICredentialsProvider()); server.EnsureAuthenticated(); } } private TeamFoundationServer Server { get { return server; } } } }
23.916667
104
0.522648
[ "Apache-2.0" ]
olivierdagenais/git-tfs
GitTfs.Vs2008/TfsHelper.Vs2008.cs
861
C#
namespace Manga.UnitTests.EntitiesTests { using Manga.Domain.Accounts; using Manga.Domain.Customers; using Manga.Domain.ValueObjects; using Xunit; public class CustomerTests { [Fact] public void Customer_Should_Be_Registered_With_1_Account() { var entityFactory = new Manga.Infrastructure.InMemoryDataAccess.EntityFactory(); // // Arrange ICustomer sut = entityFactory.NewCustomer( new SSN("198608179922"), new Name("Ivan Paulovich") ); var account = entityFactory.NewAccount(sut); // Act sut.Register(account); // Assert Assert.Single(sut.Accounts.GetAccountIds()); } } }
26.266667
92
0.576142
[ "Apache-2.0" ]
2GDev/clean-architecture-manga
tests/Manga.UnitTests/EntitiesTests/CustomerTests.cs
788
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tile : MonoBehaviour { [SerializeField] private Tower tower; [SerializeField] private bool isPlaceable = true; private GridManager _gridManager; private PathFinder _pathFinder; Vector2Int _coordinates = new Vector2Int(); private CanvasManager _canvas; private void Awake() { _gridManager = FindObjectOfType<GridManager>(); _pathFinder = FindObjectOfType<PathFinder>(); _canvas = FindObjectOfType<CanvasManager>(); } private void Start() { if (_gridManager != null) { _coordinates = _gridManager.GetCoordsFromPos(transform.position); if (!isPlaceable) { _gridManager.BlockNode(_coordinates); } } } private void OnMouseDown() { // the tile has to be walkable and will not block the path, to build a tower if (isPlaceable && _gridManager.GetNode(_coordinates).isWalkable && !_pathFinder.WillBlockPath(_coordinates)) { var isSuccessful = tower.CreateTower(tower, transform.position); if (isSuccessful) { _gridManager.BlockNode(_coordinates); _pathFinder.NotifyReceivers(); _canvas.UpdateCost(tower.Cost()); } else { _canvas.NoticeNoMoney(Input.mousePosition); } } } }
27.052632
117
0.59987
[ "Unlicense" ]
StacyYG/RealmRushRepo
Realm Rush Project/Assets/Tiles/Tile.cs
1,542
C#
#define AdvancedMode #if AdvancedMode #define MultiThreadingEnabled #define InMemoryXmlHandling #if DEBUG #define SeperatedReferenceDetection #endif #endif using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using DataStructures; using Newtonsoft.Json; namespace Downloader { public class Download { private const string divName = "{http://www.w3.org/1999/xhtml}div"; public static readonly string xhtmlIncompliant = "<li id=\"grDarst6\"><a href=\"http://www.justiz.de/onlinedienste/bundesundlandesrecht/index.php\" title=\"Die Startseite dieses Angebotes wird in einem neuen Fenster ge�ffnet\" target=\"_blank\" class=\"nav\">Landesrecht</a>"; public static async Task Main(string[] args) { IEnumerable<string> hrefs = await DownloadLawListUrls(); #if MultiThreadingEnabled Task.WaitAll(hrefs.Select(x => Task.Run(() => AllLawsStartingWith(x))).ToArray()); #if SeperatedReferenceDetection #if true Processor.Program.ActualReferences(); #endif File.WriteAllText(Path.Combine(DataStructures.JsonRoot.LawPath, "MetaOnly.json"), JsonConvert.SerializeObject(Processor.Program.root)); File.WriteAllText(Path.Combine(DataStructures.JsonRoot.LawPath, "TextOnly.json"), JsonConvert.SerializeObject(Processor.Program.toProcess)); Console.WriteLine("Text and Meta written"); #else Processor.ReferenceProcessor.MCReferenceDetector(); #endif #if !InMemoryXmlHandling Processor.Program.Stats(); #endif #else foreach (string href in hrefs) { await allLawsStartingWith(href); } Console.WriteLine($"Loaded {new DirectoryInfo(JsonRoot.LawPath).GetFiles().Length} laws"); #endif } public static readonly Uri BaseUrl = new Uri("https://www.gesetze-im-internet.de/"); public static HttpClient Client = new HttpClient(); /// <summary> /// Download all Laws to <see cref="JsonRoot.LawPath"/> /// </summary> /// <returns>a Task because its async</returns> public static async Task<IEnumerable<string>> DownloadLawListUrls() { Directory.CreateDirectory(JsonRoot.LawPath); string akt = await Client.GetStringAsync(new Uri(BaseUrl, "aktuell.html")); akt = Xhtml.XhtmlReplace(akt).Replace(xhtmlIncompliant, ""); XDocument aktDocument = XDocument.Parse(akt); return aktDocument.Root?.Element("{http://www.w3.org/1999/xhtml}body")?.Elements(divName) ?.FirstOrDefault(x => x.Attribute("id")?.Value == "level2")?.Element(divName)?.Element(divName)?.Element(divName)?.Elements() ?.SelectMany(x => x.Elements(divName)).Select(x => x.Attribute("href")?.Value).Where(x => x != null) ?? throw new Exception($"The data sent by {BaseUrl} is not in the form this program expects"); } /// <summary> /// Downloads all laws from one of the subpages /// </summary> /// <param name="href">The link to the subpage to load data from, example: https://www.gesetze-im-internet.de/Teilliste_I.html</param> /// <returns>a task because this method is async</returns> public static async Task AllLawsStartingWith(string href) { Console.WriteLine( $"Running downloader for {href} on Thread {Thread.CurrentThread.Name} {Thread.CurrentThread.IsBackground} on Proc "); Thread.CurrentThread.Name = $"Worker for {href}"; string xhtml = await Client.GetStringAsync(new Uri(BaseUrl, href)); xhtml = Downloader.Xhtml.XhtmlReplace(xhtml).Replace(xhtmlIncompliant, ""); XDocument aktDocument = XDocument.Parse(xhtml); XElement container = aktDocument.Root?.Element("{http://www.w3.org/1999/xhtml}body") ?.Elements(divName) ?.FirstOrDefault(x => x.Attribute("id")?.Value == "level2") ?.Element(divName) ?.Element(divName)?? throw new Exception($"The data sent by {BaseUrl} is not in the form this program expects"); IEnumerable<string> Laws = container.Element(divName).Elements() .Select(x => (x.Element("{http://www.w3.org/1999/xhtml}a")?.Attribute("href")?.Value ?? throw new Exception($"The data sent by {BaseUrl} is not in the form this program expects")).Substring(2)) .Select(GetXmlUri); foreach (string law in Laws) { Console.WriteLine($"Loading {law}"); Stream unusedZipStream; try { unusedZipStream = await Client.GetStreamAsync(law); } catch (HttpRequestException e) { Console.WriteLine($"Error when loading {law}: {e}"); continue; } using (Stream zipStream = unusedZipStream) { var z = new ZipArchive(zipStream); foreach (ZipArchiveEntry zipArchiveEntry in z.Entries.Where(x => x.Name.EndsWith(".xml"))) { using (Stream zipContentStream = zipArchiveEntry.Open()) #if InMemoryXmlHandling { Processor.MetadataProcessor.LoadMetaData(XDocument.Load(zipContentStream)); } #else try { using FileStream fileStream = File.Create(Path.Combine(JsonRoot.LawPath, zipArchiveEntry.Name), 32000, FileOptions.None); await zipContentStream.CopyToAsync(fileStream); await fileStream.FlushAsync(); } catch (IOException e) { Console.WriteLine(e); continue; } #endif } } /* using Stream xmlStream=z.Entries.First().Open(); using var xmlReader=new StreamReader(xmlStream); allXmls.Add(await xmlReader.ReadToEndAsync());*/ // z.Entries.First() } } private static string GetXmlUri(string x) => $"{new Uri(BaseUrl, x.Substring(0, x.Length - 11) /*removes normal html ending*/)}/xml.zip"; } }
38.842857
229
0.725083
[ "MIT" ]
Jugendhackt/SafeDeleteForLaw
Backend/Downloader/Download.cs
5,442
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace WeatherAPI { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.083333
99
0.586505
[ "MIT" ]
HenkeHulk/WeatherApi
WeatherAPI/App_Start/RouteConfig.cs
580
C#
#region MIT. // // Gorgon. // Copyright (C) 2012 Michael Winsor // // 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 // 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. // // Created: Wednesday, April 04, 2012 12:35:23 PM // #endregion using System.Threading; using DX = SharpDX; using Gorgon.Graphics; using Gorgon.Graphics.Core; using Gorgon.Renderers.Properties; namespace Gorgon.Renderers { /// <summary> /// An effect that renders an inverted image. /// </summary> public class Gorgon2DInvertEffect : Gorgon2DEffect, IGorgon2DCompositorEffect { #region Variables. // Buffer for the inversion effect. private GorgonConstantBufferView _invertBuffer; // Flag to invert the alpha channel. private bool _invertAlpha; // The pixel shader for the effect. private GorgonPixelShader _invertShader; private Gorgon2DShaderState<GorgonPixelShader> _invertState; // The batch render state. private Gorgon2DBatchState _batchState; #endregion #region Properties. /// <summary> /// Property to set or return whether to invert the alpha channel. /// </summary> public bool InvertAlpha { get => _invertAlpha; set { if (_invertAlpha == value) { return; } _invertAlpha = value; _invertBuffer?.Buffer.SetData(ref _invertAlpha); } } #endregion #region Methods. /// <summary> /// Function called to build a new (or return an existing) 2D batch state. /// </summary> /// <param name="passIndex">The index of the current rendering pass.</param> /// <param name="builders">The builder types that will manage the state of the effect.</param> /// <param name="statesChanged"><b>true</b> if the blend, raster, or depth/stencil state was changed. <b>false</b> if not.</param> /// <returns>The 2D batch state.</returns> protected override Gorgon2DBatchState OnGetBatchState(int passIndex, IGorgon2DEffectBuilders builders, bool statesChanged) { if ((_batchState == null) || (statesChanged)) { if (_invertState == null) { _invertState = builders.PixelShaderBuilder .ConstantBuffer(_invertBuffer, 1) .Shader(_invertShader) .Build(); } _batchState = builders.BatchBuilder .PixelShaderState(_invertState) .Build(BatchStateAllocator); } return _batchState; } /// <summary> /// Function called when the effect is being initialized. /// </summary> /// <remarks> /// Use this method to set up the effect upon its creation. For example, this method could be used to create the required shaders for the effect. /// <para>When creating a custom effect, use this method to initialize the effect. Do not put initialization code in the effect constructor.</para> /// </remarks> protected override void OnInitialize() { _invertBuffer = GorgonConstantBufferView.CreateConstantBuffer(Graphics, ref _invertAlpha, "Gorgon2DInvertEffect Constant Buffer"); _invertShader = CompileShader<GorgonPixelShader>(Resources.BasicSprite, "GorgonPixelShaderInvert"); } /// <summary> /// Function called prior to rendering. /// </summary> /// <param name="output">The final render target that will receive the rendering from the effect.</param> /// <param name="sizeChanged"><b>true</b> if the output size changed since the last render, or <b>false</b> if it's the same.</param> /// <remarks> /// <para> /// Applications can use this to set up common states and other configuration settings prior to executing the render passes. This is an ideal method to initialize and resize your internal render /// targets (if applicable). /// </para> /// </remarks> protected override void OnBeforeRender(GorgonRenderTargetView output, bool sizeChanged) { if (Graphics.RenderTargets[0] != output) { Graphics.SetRenderTarget(output, Graphics.DepthStencilView); } } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><b>true</b> to release both managed and unmanaged resources; <b>false</b> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { GorgonConstantBufferView buffer = Interlocked.Exchange(ref _invertBuffer, null); GorgonPixelShader pixelShader = Interlocked.Exchange(ref _invertShader, null); buffer?.Dispose(); pixelShader?.Dispose(); } /// <summary> /// Function to begin rendering the effect. /// </summary> /// <param name="blendState">[Optional] A user defined blend state to apply when rendering.</param> /// <param name="depthStencilState">[Optional] A user defined depth/stencil state to apply when rendering.</param> /// <param name="rasterState">[Optional] A user defined rasterizer state to apply when rendering.</param> /// <param name="camera">[Optional] The camera to use when rendering.</param> public void Begin(GorgonBlendState blendState = null, GorgonDepthStencilState depthStencilState = null, GorgonRasterState rasterState = null, IGorgon2DCamera camera = null) { GorgonRenderTargetView target = Graphics.RenderTargets[0]; if (target == null) { return; } BeginRender(target, blendState, depthStencilState, rasterState); BeginPass(0, target, camera); } /// <summary> /// Function to end the effect rendering. /// </summary> public void End() { GorgonRenderTargetView target = Graphics.RenderTargets[0]; if (target == null) { return; } EndPass(0, target); EndRender(target); } /// <summary>Function to render an effect under the <see cref="T:Gorgon.Renderers.Gorgon2DCompositor"/>.</summary> /// <param name="texture">The texture to render into the next target.</param> /// <param name="output">The render target that will receive the final output.</param> public void Render(GorgonTexture2DView texture, GorgonRenderTargetView output) { if ((texture == null) || (output == null)) { return; } Graphics.SetRenderTarget(output); Begin(GorgonBlendState.Default, GorgonDepthStencilState.Default, GorgonRasterState.Default, null); Renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, output.Width, output.Height), GorgonColor.White, texture, new DX.RectangleF(0, 0, 1, 1)); End(); } #endregion #region Constructor/Destructor. /// <summary> /// Initializes a new instance of the <see cref="Gorgon2DInvertEffect" /> class. /// </summary> /// <param name="renderer">The renderer used to draw with this effect.</param> public Gorgon2DInvertEffect(Gorgon2D renderer) : base(renderer, Resources.GOR2D_EFFECT_INVERT, Resources.GOR2D_EFFECT_INVERT_DESC, 1) => Macros.Add(new GorgonShaderMacro("INVERSE_EFFECT")); #endregion } }
41.780374
202
0.60944
[ "MIT" ]
Tape-Worm/Gorgon
Gorgon/Gorgon.Renderers/Gorgon2D/Effects/Gorgon2DInvertEffect.cs
8,943
C#
namespace DotNetCore.Validation; public static class Regexes { public static readonly string Date = @"^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))) ?((20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2}))?$"; public static readonly string Decimal = @"^((-?[1-9]+)|[0-9]+)(\.?|\,?)([0-9]*)$"; public static readonly string Email = @"^([a-z0-9_\.\-]{3,})@([\da-z\.\-]{3,})\.([a-z\.]{2,6})$"; public static readonly string Hex = "^#?([a-f0-9]{6}|[a-f0-9]{3})$"; public static readonly string Integer = "^((-?[1-9]+)|[0-9]+)$"; public static readonly string Login = "^[a-z0-9_-]{10,50}$"; public static readonly string Password = @"^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=]).*$"; public static readonly string Tag = @"^<([a-z1-6]+)([^<]+)*(?:>(.*)<\/\1>| *\/>)$"; public static readonly string Time = @"^([01]?[0-9]|2[0-3]):[0-5][0-9]$"; public static readonly string Url = @"^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$"; }
63.12
709
0.445501
[ "MIT" ]
fabricepeltier/DotNetCore_CR_Examples
source/Validation/Regexes.cs
1,578
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookShopSystem.Utilities { /// <summary> /// Json帮助类 /// </summary> public class JsonHelper { /// <summary> ///将对象/对象集合转换成Json数据 /// </summary> /// <param name="obj">对象</param> /// <param name="dateFormat">是否日期格式化</param> /// <returns>Json数据</returns> public static string SerializeObject(object obj, bool dateFormat = true) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore;//空值处理 if (dateFormat) { //日期类型默认格式化处理 settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; settings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; } return JsonConvert.SerializeObject(obj, settings); } /// <summary> /// 将Json数据转换成对象/对象集合 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="json">Json数据</param> /// <param name="dateFormat">是否日期格式化</param>m> /// <returns>对象/对象集合</returns> public static T DeSerializeObject<T>(string json, bool dateFormat = true) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore;//空值处理 if (dateFormat) { //日期类型默认格式化处理 settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; settings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; } return JsonConvert.DeserializeObject<T>(json, settings); } } }
32.586207
101
0.592593
[ "Apache-2.0" ]
a156845044/BookShopSystem
BookShopSystem.Utilities/JsonHelper.cs
2,066
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using System.Diagnostics; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an immutable snapshot of assembly CLI metadata. /// </summary> public sealed class AssemblyMetadata : Metadata { private sealed class Data { public static readonly Data Disposed = new Data(); public readonly ImmutableArray<ModuleMetadata> Modules; public readonly PEAssembly Assembly; private Data() { } public Data(ImmutableArray<ModuleMetadata> modules, PEAssembly assembly) { Debug.Assert(!modules.IsDefaultOrEmpty && assembly != null); this.Modules = modules; this.Assembly = assembly; } public bool IsDisposed { get { return Assembly == null; } } } /// <summary> /// Factory that provides the <see cref="ModuleMetadata"/> for additional modules (other than <see cref="_initialModules"/>) of the assembly. /// Shall only throw <see cref="BadImageFormatException"/> or <see cref="IOException"/>. /// Null of all modules were specified at construction time. /// </summary> private readonly Func<string, ModuleMetadata> _moduleFactoryOpt; /// <summary> /// Modules the <see cref="AssemblyMetadata"/> was created with, in case they are eagerly allocated. /// </summary> private readonly ImmutableArray<ModuleMetadata> _initialModules; // Encapsulates the modules and the corresponding PEAssembly produced by the modules factory. private Data _lazyData; // The actual array of modules exposed via Modules property. // The same modules as the ones produced by the factory or their copies. private ImmutableArray<ModuleMetadata> _lazyPublishedModules; /// <summary> /// Cached assembly symbols. /// </summary> /// <remarks> /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>. /// </remarks> internal readonly WeakList<IAssemblySymbolInternal> CachedSymbols = new WeakList<IAssemblySymbolInternal>(); // creates a copy private AssemblyMetadata(AssemblyMetadata other, bool shareCachedSymbols) : base(isImageOwner: false, id: other.Id) { if (shareCachedSymbols) { this.CachedSymbols = other.CachedSymbols; } _lazyData = other._lazyData; _moduleFactoryOpt = other._moduleFactoryOpt; _initialModules = other._initialModules; // Leave lazyPublishedModules unset. Published modules will be set and copied as needed. } internal AssemblyMetadata(ImmutableArray<ModuleMetadata> modules) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { Debug.Assert(!modules.IsDefaultOrEmpty); _initialModules = modules; } internal AssemblyMetadata(ModuleMetadata manifestModule, Func<string, ModuleMetadata> moduleFactory) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { Debug.Assert(manifestModule != null); Debug.Assert(moduleFactory != null); _initialModules = ImmutableArray.Create(manifestModule); _moduleFactoryOpt = moduleFactory; } /// <summary> /// Creates a single-module assembly. /// </summary> /// <param name="peImage"> /// Manifest module image. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static AssemblyMetadata CreateFromImage(ImmutableArray<byte> peImage) { return Create(ModuleMetadata.CreateFromImage(peImage)); } /// <summary> /// Creates a single-module assembly. /// </summary> /// <param name="peImage"> /// Manifest module image. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> public static AssemblyMetadata CreateFromImage(IEnumerable<byte> peImage) { return Create(ModuleMetadata.CreateFromImage(peImage)); } /// <summary> /// Creates a single-module assembly. /// </summary> /// <param name="peStream">Manifest module PE image stream.</param> /// <param name="leaveOpen">False to close the stream upon disposal of the metadata.</param> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> public static AssemblyMetadata CreateFromStream(Stream peStream, bool leaveOpen = false) { return Create(ModuleMetadata.CreateFromStream(peStream, leaveOpen)); } /// <summary> /// Creates a single-module assembly. /// </summary> /// <param name="peStream">Manifest module PE image stream.</param> /// <param name="options">False to close the stream upon disposal of the metadata.</param> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> public static AssemblyMetadata CreateFromStream(Stream peStream, PEStreamOptions options) { return Create(ModuleMetadata.CreateFromStream(peStream, options)); } /// <summary> /// Finds all modules of an assembly on a specified path and builds an instance of <see cref="AssemblyMetadata"/> that represents them. /// </summary> /// <param name="path">The full path to the assembly on disk.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is invalid.</exception> /// <exception cref="IOException">Error reading file <paramref name="path"/>. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="NotSupportedException">Reading from a file path is not supported by the platform.</exception> public static AssemblyMetadata CreateFromFile(string path) { return CreateFromFile(ModuleMetadata.CreateFromFile(path), path); } internal static AssemblyMetadata CreateFromFile(ModuleMetadata manifestModule, string path) { return new AssemblyMetadata(manifestModule, moduleName => ModuleMetadata.CreateFromFile(Path.Combine(Path.GetDirectoryName(path), moduleName))); } /// <summary> /// Creates a single-module assembly. /// </summary> /// <param name="module"> /// Manifest module. /// </param> /// <remarks>This object disposes <paramref name="module"/> it when it is itself disposed.</remarks> public static AssemblyMetadata Create(ModuleMetadata module) { if (module == null) { throw new ArgumentNullException(nameof(module)); } return new AssemblyMetadata(ImmutableArray.Create(module)); } /// <summary> /// Creates a multi-module assembly. /// </summary> /// <param name="modules"> /// Modules comprising the assembly. The first module is the manifest module of the assembly.</param> /// <remarks>This object disposes the elements of <paramref name="modules"/> it when it is itself <see cref="Dispose"/>.</remarks> /// <exception cref="ArgumentException"><paramref name="modules"/> is default value.</exception> /// <exception cref="ArgumentNullException"><paramref name="modules"/> contains null elements.</exception> /// <exception cref="ArgumentException"><paramref name="modules"/> is empty or contains a module that doesn't own its image (was created via <see cref="Metadata.Copy"/>).</exception> public static AssemblyMetadata Create(ImmutableArray<ModuleMetadata> modules) { if (modules.IsDefaultOrEmpty) { throw new ArgumentException(CodeAnalysisResources.AssemblyMustHaveAtLeastOneModule, nameof(modules)); } for (int i = 0; i < modules.Length; i++) { if (modules[i] == null) { throw new ArgumentNullException(nameof(modules) + "[" + i + "]"); } if (!modules[i].IsImageOwner) { throw new ArgumentException(CodeAnalysisResources.ModuleCopyCannotBeUsedToCreateAssemblyMetadata, nameof(modules) + "[" + i + "]"); } } return new AssemblyMetadata(modules); } /// <summary> /// Creates a multi-module assembly. /// </summary> /// <param name="modules"> /// Modules comprising the assembly. The first module is the manifest module of the assembly.</param> /// <remarks>This object disposes the elements of <paramref name="modules"/> it when it is itself <see cref="Dispose"/>.</remarks> /// <exception cref="ArgumentException"><paramref name="modules"/> is default value.</exception> /// <exception cref="ArgumentNullException"><paramref name="modules"/> contains null elements.</exception> /// <exception cref="ArgumentException"><paramref name="modules"/> is empty or contains a module that doesn't own its image (was created via <see cref="Metadata.Copy"/>).</exception> public static AssemblyMetadata Create(IEnumerable<ModuleMetadata> modules) { return Create(modules.AsImmutableOrNull()); } /// <summary> /// Creates a multi-module assembly. /// </summary> /// <param name="modules">Modules comprising the assembly. The first module is the manifest module of the assembly.</param> /// <remarks>This object disposes the elements of <paramref name="modules"/> it when it is itself <see cref="Dispose"/>.</remarks> /// <exception cref="ArgumentException"><paramref name="modules"/> is default value.</exception> /// <exception cref="ArgumentNullException"><paramref name="modules"/> contains null elements.</exception> /// <exception cref="ArgumentException"><paramref name="modules"/> is empty or contains a module that doesn't own its image (was created via <see cref="Metadata.Copy"/>).</exception> public static AssemblyMetadata Create(params ModuleMetadata[] modules) { return Create(ImmutableArray.CreateRange(modules)); } /// <summary> /// Creates a shallow copy of contained modules and wraps them into a new instance of <see cref="AssemblyMetadata"/>. /// </summary> /// <remarks> /// The resulting copy shares the metadata images and metadata information read from them with the original. /// It doesn't own the underlying metadata images and is not responsible for its disposal. /// /// This is used, for example, when a metadata cache needs to return the cached metadata to its users /// while keeping the ownership of the cached metadata object. /// </remarks> internal new AssemblyMetadata Copy() { return new AssemblyMetadata(this, shareCachedSymbols: true); } internal AssemblyMetadata CopyWithoutSharingCachedSymbols() { return new AssemblyMetadata(this, shareCachedSymbols: false); } protected override Metadata CommonCopy() { return Copy(); } /// <summary> /// Modules comprising this assembly. The first module is the manifest module. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="ObjectDisposedException">The object has been disposed.</exception> public ImmutableArray<ModuleMetadata> GetModules() { if (_lazyPublishedModules.IsDefault) { var data = GetOrCreateData(); var newModules = data.Modules; if (!IsImageOwner) { newModules = newModules.SelectAsArray(module => module.Copy()); } ImmutableInterlocked.InterlockedInitialize(ref _lazyPublishedModules, newModules); } if (_lazyData == Data.Disposed) { throw new ObjectDisposedException(nameof(AssemblyMetadata)); } return _lazyPublishedModules; } /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error while reading the metadata. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="ObjectDisposedException">The object has been disposed.</exception> internal PEAssembly GetAssembly() { return GetOrCreateData().Assembly; } /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error while reading the metadata. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="ObjectDisposedException">The object has been disposed.</exception> private Data GetOrCreateData() { if (_lazyData == null) { ImmutableArray<ModuleMetadata> modules = _initialModules; ImmutableArray<ModuleMetadata>.Builder moduleBuilder = null; bool createdModulesUsed = false; try { if (_moduleFactoryOpt != null) { Debug.Assert(_initialModules.Length == 1); var additionalModuleNames = _initialModules[0].GetModuleNames(); if (additionalModuleNames.Length > 0) { moduleBuilder = ImmutableArray.CreateBuilder<ModuleMetadata>(1 + additionalModuleNames.Length); moduleBuilder.Add(_initialModules[0]); foreach (string moduleName in additionalModuleNames) { moduleBuilder.Add(_moduleFactoryOpt(moduleName)); } modules = moduleBuilder.ToImmutable(); } } var assembly = new PEAssembly(this, modules.SelectAsArray(m => m.Module)); var newData = new Data(modules, assembly); createdModulesUsed = Interlocked.CompareExchange(ref _lazyData, newData, null) == null; } finally { if (moduleBuilder != null && !createdModulesUsed) { // dispose unused modules created above: for (int i = _initialModules.Length; i < moduleBuilder.Count; i++) { moduleBuilder[i].Dispose(); } } } } if (_lazyData.IsDisposed) { throw new ObjectDisposedException(nameof(AssemblyMetadata)); } return _lazyData; } /// <summary> /// Disposes all modules contained in the assembly. /// </summary> public override void Dispose() { var previousData = Interlocked.Exchange(ref _lazyData, Data.Disposed); if (previousData == Data.Disposed || !this.IsImageOwner) { // already disposed, or not an owner return; } // AssemblyMetadata assumes their ownership of all modules passed to the constructor. foreach (var module in _initialModules) { module.Dispose(); } if (previousData == null) { // no additional modules were created yet => nothing to dispose return; } Debug.Assert(_initialModules.Length == 1 || _initialModules.Length == previousData.Modules.Length); // dispose additional modules created lazily: for (int i = _initialModules.Length; i < previousData.Modules.Length; i++) { previousData.Modules[i].Dispose(); } } /// <summary> /// Checks if the first module has a single row in Assembly table and that all other modules have none. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="ObjectDisposedException">The object has been disposed.</exception> internal bool IsValidAssembly() { var modules = GetModules(); if (!modules[0].Module.IsManifestModule) { return false; } for (int i = 1; i < modules.Length; i++) { // Ignore winmd modules since runtime winmd modules may be loaded as non-primary modules. var module = modules[i].Module; if (!module.IsLinkedModule && module.MetadataReader.MetadataKind != MetadataKind.WindowsMetadata) { return false; } } return true; } /// <summary> /// Returns the metadata kind. <seealso cref="MetadataImageKind"/> /// </summary> public override MetadataImageKind Kind { get { return MetadataImageKind.Assembly; } } /// <summary> /// Creates a reference to the assembly metadata. /// </summary> /// <param name="documentation">Provider of XML documentation comments for the metadata symbols contained in the module.</param> /// <param name="aliases">Aliases that can be used to refer to the assembly from source code (see "extern alias" directive in C#).</param> /// <param name="embedInteropTypes">True to embed interop types from the referenced assembly to the referencing compilation. Must be false for a module.</param> /// <param name="filePath">Path describing the location of the metadata, or null if the metadata have no location.</param> /// <param name="display">Display string used in error messages to identity the reference.</param> /// <returns>A reference to the assembly metadata.</returns> public PortableExecutableReference GetReference( DocumentationProvider documentation = null, ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false, string filePath = null, string display = null) { return new MetadataImageReference(this, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes), documentation, filePath, display); } } }
44.537281
190
0.604116
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs
20,311
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.Aks.Models.Api20200901 { using static Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Extensions; public partial class ManagedClusterAddonProfileConfig : Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IAssociativeArray<string> { protected global::System.Collections.Generic.Dictionary<global::System.String,string> __additionalProperties = new global::System.Collections.Generic.Dictionary<global::System.String,string>(); global::System.Collections.Generic.IDictionary<global::System.String,string> Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IAssociativeArray<string>.AdditionalProperties { get => __additionalProperties; } int Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IAssociativeArray<string>.Count { get => __additionalProperties.Count; } global::System.Collections.Generic.IEnumerable<global::System.String> Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IAssociativeArray<string>.Keys { get => __additionalProperties.Keys; } global::System.Collections.Generic.IEnumerable<string> Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IAssociativeArray<string>.Values { get => __additionalProperties.Values; } public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } /// <param name="key"></param> /// <param name="value"></param> public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); public void Clear() => __additionalProperties.Clear(); /// <param name="key"></param> public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); /// <param name="source"></param> public void CopyFrom(global::System.Collections.IDictionary source) { if (null != source) { foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet<global::System.String>() { } ) ) { if ((null != property.Key && null != property.Value)) { this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo<string>( property.Value)); } } } } /// <param name="source"></param> public void CopyFrom(global::System.Management.Automation.PSObject source) { if (null != source) { foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet<global::System.String>() { } ) ) { if ((null != property.Key && null != property.Value)) { this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo<string>( property.Value)); } } } } /// <param name="key"></param> public bool Remove(global::System.String key) => __additionalProperties.Remove( key); /// <param name="key"></param> /// <param name="value"></param> public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); /// <param name="source"></param> public static implicit operator global::System.Collections.Generic.Dictionary<global::System.String,string>(Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ManagedClusterAddonProfileConfig source) => source.__additionalProperties; } }
57.68
249
0.666436
[ "MIT" ]
Agazoth/azure-powershell
src/Aks/Aks.Autorest/generated/api/Models/Api20200901/ManagedClusterAddonProfileConfig.dictionary.cs
4,252
C#
namespace Rostelecom.DigitalProfile.Api.Authentication; public static class TvsAuthenticationDefaults { public const string Scheme = "TvsAuthentication"; }
26.666667
55
0.825
[ "MIT" ]
televizor-meta/teleapi
TeleTwins.Api/Authentication/TvsAuthenticationDefaults.cs
160
C#
namespace Microsoft.Maui.Handlers { public partial class LabelHandler { public static PropertyMapper<ILabel, LabelHandler> LabelMapper = new PropertyMapper<ILabel, LabelHandler>(ViewHandler.ViewMapper) { [nameof(ILabel.CharacterSpacing)] = MapCharacterSpacing, [nameof(ILabel.Font)] = MapFont, [nameof(ILabel.HorizontalTextAlignment)] = MapHorizontalTextAlignment, [nameof(ILabel.LineBreakMode)] = MapLineBreakMode, [nameof(ILabel.LineHeight)] = MapLineHeight, [nameof(ILabel.MaxLines)] = MapMaxLines, [nameof(ILabel.Padding)] = MapPadding, [nameof(ILabel.Text)] = MapText, [nameof(ILabel.TextColor)] = MapTextColor, [nameof(ILabel.TextDecorations)] = MapTextDecorations, }; public LabelHandler() : base(LabelMapper) { } public LabelHandler(PropertyMapper? mapper = null) : base(mapper ?? LabelMapper) { } } }
29.793103
131
0.734954
[ "MIT" ]
gilnicki/maui-linux
src/Core/src/Handlers/Label/LabelHandler.cs
864
C#
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using GYISMS.Authorization.Roles; namespace GYISMS.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository) : base( unitOfWorkManager, userRepository, roleRepository, asyncQueryableExecuter, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository) { } } }
33.757576
86
0.621185
[ "MIT" ]
DonaldTdz/GYISMS
aspnet-core/src/GYISMS.Core/Authorization/Users/UserStore.cs
1,114
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("DemoSite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DemoSite")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("337aae30-aafa-41dd-812c-028657a8ab65")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.333333
84
0.75
[ "Apache-2.0" ]
darcythomas/zxcvbn.net
DemoSite/Properties/AssemblyInfo.cs
1,347
C#
#region License // Copyright (c) 2015 1010Tires.com // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace MXTires.Microdata.LocalBusinesses.SportsActivityLocations { /// <summary> /// A tennis complex. /// </summary> public class TennisComplex : SportsActivityLocation { } }
35.52381
68
0.754021
[ "MIT" ]
idenys/MXTires.Microdata
LocalBusinesses/SportsActivityLocations/TennisComplex.cs
1,494
C#
using System.Linq; using System.Threading.Tasks; using AutoFixture; using AutoFixture.AutoMoq; using AutoFixture.Idioms; using AutoFixture.Xunit2; using FluentAssertions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Moq; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Ordering.Models; using NHSD.GPIT.BuyingCatalogue.Framework.Extensions; using NHSD.GPIT.BuyingCatalogue.ServiceContracts.Orders; using NHSD.GPIT.BuyingCatalogue.Test.Framework.AutoFixtureCustomisations; using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Order.Controllers; using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Order.Models.FundingSource; using Xunit; namespace NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests.Areas.Order.Controllers { public static class FundingSourceControllerTests { [Fact] public static void ClassIsCorrectlyDecorated() { typeof(FundingSourceController).Should().BeDecoratedWith<AuthorizeAttribute>(); typeof(FundingSourceController).Should().BeDecoratedWith<AreaAttribute>(a => a.RouteValue == "Order"); } [Fact] public static void Constructors_VerifyGuardClauses() { var fixture = new Fixture().Customize(new AutoMoqCustomization()); var assertion = new GuardClauseAssertion(fixture); var constructors = typeof(FundingSourceController).GetConstructors(); assertion.Verify(constructors); } [Theory] [CommonAutoData] public static async Task Get_FundingSource_ReturnsExpectedResult( string odsCode, EntityFramework.Ordering.Models.Order order, [Frozen] Mock<IOrderService> orderServiceMock, FundingSourceController controller) { var expectedViewData = new FundingSourceModel(odsCode, order.CallOffId, order.FundingSourceOnlyGms); orderServiceMock.Setup(s => s.GetOrderThin(order.CallOffId)).ReturnsAsync(order); var actualResult = await controller.FundingSource(odsCode, order.CallOffId); actualResult.Should().BeOfType<ViewResult>(); actualResult.As<ViewResult>().ViewData.Model.Should().BeEquivalentTo(expectedViewData, opt => opt.Excluding(m => m.BackLink)); } [Theory] [CommonAutoData] public static async Task Post_FundingSource_Deletes_CorrectlyRedirects( string odsCode, CallOffId callOffId, FundingSourceModel model, [Frozen] Mock<IFundingSourceService> fundingSourceServiceMock, FundingSourceController controller) { var actualResult = await controller.FundingSource(odsCode, callOffId, model); actualResult.Should().BeOfType<RedirectToActionResult>(); actualResult.As<RedirectToActionResult>().ActionName.Should().Be(nameof(OrderController.Order)); actualResult.As<RedirectToActionResult>().ControllerName.Should().Be(typeof(OrderController).ControllerName()); actualResult.As<RedirectToActionResult>().RouteValues.Should().BeEquivalentTo(new RouteValueDictionary { { "odsCode", odsCode }, { "callOffId", callOffId } }); fundingSourceServiceMock.Verify(o => o.SetFundingSource(callOffId, model.FundingSourceOnlyGms.EqualsIgnoreCase("Yes")), Times.Once); } [Theory] [CommonAutoData] public static async Task Post_FundingSource_InvalidModelState_ReturnsView( string errorKey, string errorMessage, string odsCode, CallOffId callOffId, FundingSourceModel model, FundingSourceController controller) { controller.ModelState.AddModelError(errorKey, errorMessage); var actualResult = (await controller.FundingSource(odsCode, callOffId, model)).As<ViewResult>(); actualResult.Should().NotBeNull(); actualResult.ViewName.Should().BeNull(); actualResult.ViewData.ModelState.IsValid.Should().BeFalse(); actualResult.ViewData.ModelState.ErrorCount.Should().Be(1); actualResult.ViewData.ModelState.Keys.Single().Should().Be(errorKey); actualResult.ViewData.ModelState.Values.Single().Errors.Single().ErrorMessage.Should().Be(errorMessage); } } }
43.87
171
0.699339
[ "MIT" ]
nhs-digital-gp-it-futures/GPITBuyingCatalogue
tests/NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests/Areas/Order/Controllers/FundingSourceControllerTests.cs
4,389
C#
using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; namespace Client { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddHttpClient("FoodService", client => { client.BaseAddress = new Uri("https://localhost:44334/foodservice/"); }); builder.Services.AddHttpClient("DrinkService", client => { client.BaseAddress = new Uri("https://localhost:44334/drinkservice/"); }); await builder.Build().RunAsync(); } } }
24.714286
74
0.723988
[ "MIT" ]
Layla-P/ApiGatewayWithYarpAndEureka
Code/Client/Program.cs
692
C#
//------------------------------------------------------------------------------ // <copyright file="XmlSchemaDerivationMethod.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { using System.Collections; using System.ComponentModel; using System.Xml.Serialization; /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Flags] public enum XmlSchemaDerivationMethod { /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.Empty"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("")] Empty = 0, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.Substitution"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("substitution")] Substitution = 0x0001, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.Extension"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("extension")] Extension = 0x0002, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.Restriction"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("restriction")] Restriction = 0x0004, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.List"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("list")] List = 0x0008, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.Union"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("union")] Union = 0x0010, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.All"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlEnum("#all")] All = 0x00FF, /// <include file='doc\XmlSchemaDerivationMethod.uex' path='docs/doc[@for="XmlSchemaDerivationMethod.None"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] None = 0x0100 } }
41.577465
129
0.525068
[ "Apache-2.0" ]
Distrotech/mono
external/referencesource/System.Xml/System/Xml/Schema/XmlSchemaDerivationMethod.cs
2,952
C#
using Avalonia.Controls; namespace BeatSaberModManager.Views.Pages { /// <summary> /// View for informational purposes. /// </summary> public partial class IntroPage : UserControl { /// <summary> /// Initializes a new instance of the <see cref="IntroPage"/> class. /// </summary> public IntroPage() { InitializeComponent(); } } }
21.894737
76
0.567308
[ "MIT" ]
Meivyn/BeatSaberModManager
BeatSaberModManager/Views/Pages/IntroPage.axaml.cs
418
C#
// CS0019: Operator `!=' cannot be applied to operands of type `ulong?' and `int' // Line: 8 class C { static void Test (ulong? x, int y) { if (x != y) { } } }
13.153846
82
0.555556
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs0019-49.cs
171
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 models.lex.v2-2020-08-07.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.LexModelsV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.LexModelsV2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for SlotDefaultValue Object /// </summary> public class SlotDefaultValueUnmarshaller : IUnmarshaller<SlotDefaultValue, XmlUnmarshallerContext>, IUnmarshaller<SlotDefaultValue, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> SlotDefaultValue IUnmarshaller<SlotDefaultValue, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public SlotDefaultValue Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; SlotDefaultValue unmarshalledObject = new SlotDefaultValue(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("defaultValue", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DefaultValue = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static SlotDefaultValueUnmarshaller _instance = new SlotDefaultValueUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static SlotDefaultValueUnmarshaller Instance { get { return _instance; } } } }
34.847826
162
0.625702
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/LexModelsV2/Generated/Model/Internal/MarshallTransformations/SlotDefaultValueUnmarshaller.cs
3,206
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFormation.Model { /// <summary> /// The <code>Export</code> structure describes the exported output values for a stack. /// </summary> public partial class Export { private string _exportingStackId; private string _name; private string _value; /// <summary> /// Gets and sets the property ExportingStackId. /// <para> /// The stack that contains the exported output name and value. /// </para> /// </summary> public string ExportingStackId { get { return this._exportingStackId; } set { this._exportingStackId = value; } } // Check to see if ExportingStackId property is set internal bool IsSetExportingStackId() { return this._exportingStackId != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of exported output value. Use this name and the <code>Fn::ImportValue</code> /// function to import the associated value into other stacks. The name is defined in /// the <code>Export</code> field in the associated stack's <code>Outputs</code> section. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// The value of the exported output, such as a resource physical ID. This value is defined /// in the <code>Export</code> field in the associated stack's <code>Outputs</code> section. /// </para> /// </summary> public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
31.193878
112
0.604514
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudFormation/Generated/Model/Export.cs
3,057
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Web.UI.ExpressionBinding.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI { sealed public partial class ExpressionBinding { #region Methods and constructors public override bool Equals(Object obj) { return default(bool); } public ExpressionBinding(string propertyName, Type propertyType, string expressionPrefix, string expression) { } public override int GetHashCode() { return default(int); } #endregion #region Properties and indexers public string Expression { get { return default(string); } set { } } public string ExpressionPrefix { get { return default(string); } set { } } public bool Generated { get { return default(bool); } } public Object ParsedExpressionData { get { return default(Object); } } public string PropertyName { get { return default(string); } } public Type PropertyType { get { return default(Type); } } #endregion } }
26.87069
463
0.688803
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.ExpressionBinding.cs
3,117
C#
namespace MassTransit.RedisIntegration.Contexts { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using MassTransit.Registration; using Specifications; using Transport; using Transports; public class ClientContextSupervisor : TransportPipeContextSupervisor<ClientContext>, IClientContextSupervisor { readonly ConcurrentDictionary<Uri, IRedisProducerFactory> _factories; readonly IReadOnlyDictionary<string, IRedisProducerSpecification> _producers; public ClientContextSupervisor(ClientConfig clientConfig, IEnumerable<IRedisProducerSpecification> producers) : base(new ClientContextFactory(clientConfig)) { _producers = producers.ToDictionary(x => x.StreamName); _factories = new ConcurrentDictionary<Uri, IRedisProducerFactory>(); } public IStreamProducer<TKey, TValue> CreateProducer<TKey, TValue>(IBusInstance busInstance, Uri address) where TValue : class { if (busInstance == null) throw new ArgumentNullException(nameof(busInstance)); if (address == null) throw new ArgumentNullException(nameof(address)); var StreamAddress = NormalizeAddress(busInstance.HostConfiguration.HostAddress, address); IRedisProducerFactory<TKey, TValue> factory = GetFactory<TKey, TValue>(StreamAddress, busInstance); return factory.CreateProducer(); } static RedisStreamAddress NormalizeAddress(Uri hostAddress, Uri address) { return new RedisStreamAddress(hostAddress, address); } IRedisProducerFactory<TKey, TValue> GetFactory<TKey, TValue>(RedisStreamAddress address, IBusInstance busInstance) where TValue : class { if (!_producers.TryGetValue(address.Stream, out var specification)) throw new ConfigurationException($"Producer for Stream: {address} is not configured."); var factory = _factories.GetOrAdd(address, _ => specification.CreateProducerFactory(busInstance)); if (factory is IRedisProducerFactory<TKey, TValue> f) return f; throw new ConfigurationException($"Producer for Stream: {address} is not configured for ${typeof(Message<TKey, TValue>).Name} message"); } } }
39.532258
148
0.682579
[ "ECL-2.0", "Apache-2.0" ]
architecture-astronaut/MassTransit
src/Transports/MassTransit.RedisIntegration/Contexts/ClientContextSupervisor.cs
2,451
C#
using System.Collections.Generic; using GameCore; using Hanabi.GameCore; using Hanabi.Types; namespace Hanabi.Payloads { #region Game public sealed class ResponseEnterGame { public ResponseEnterGame( ExitGameResult result ) { this.Result = result; } public ExitGameResult Result { get; set; } } public sealed class ResponseExitGame { public ResponseExitGame( ExitGameResult result ) { this.Result = result; } public ExitGameResult Result { get; set; } } #endregion #region Room public sealed class PlayerInfo { public string Nickname { get; set; } public int Status { get; set; } } public sealed class RoomInfo { public int RoomIndex { get; set; } public int Status { get; set; } public List<Status> Players { get; set; } } public sealed class ResponseRoomList { public List<RoomInfo> Rooms { get; set; } } public sealed class ResponseJoinRoom { public JoinRoomResult Result { get; set; } public RoomInfo Room { get; set; } } public sealed class ResponseQuitRoom { public QuitRoomResult Result { get; set; } public RoomInfo Room { get; set; } } #endregion #region Play public sealed class CardPrompt { public int Color { get; set; } public int Value { get; set; } public List<int> ImpossibleSet { get; set; } } public sealed class CardInfo { public CardInfo() { } public int Index { get; set; } public int Color { get; set; } public int Value { get; set; } public CardPrompt Prompt { get; set; } } public sealed class TokenInfo { public TokenInfo() { this.Note = 0; this.Storm = 0; } public int Note { get; set; } public int Storm { get; set; } } public sealed class ResponseGameData { public ResponseGameData() { this.Token = new TokenInfo(); this.DrawPileCount = 0; this.Cards = new Dictionary<string, List<CardInfo>>(); } public TokenInfo Token { get; set; } public int DrawPileCount { get; set; } public Dictionary<string, List<CardInfo>> Cards { get; set; } } public sealed class ResponsePromptCard { public ResponsePromptCard() { this.Result = 0; this.Nickname = string.Empty; this.PromptInformation = 0; this.Cards = new List<CardInfo>(); this.Token = new TokenInfo(); } public PromptCardResult Result { get; set; } public string Nickname { get; set; } public int PromptInformation { get; set; } public List<CardInfo> Cards { get; set; } public TokenInfo Token { get; set; } } public sealed class ResponsePlayCard { public ResponsePlayCard() { this.Nickname = string.Empty; this.OldCard = null; this.NewCard = null; this.Token = new TokenInfo(); this.DrawPileCount = 0; } public PlayCardResult Result { get; set; } public string Nickname { get; set; } public CardInfo OldCard { get; set; } public CardInfo NewCard { get; set; } public TokenInfo Token { get; set; } public int DrawPileCount { get; set; } } public sealed class ResponseDiscardCard { public ResponseDiscardCard() { this.Nickname = string.Empty; this.OldCard = null; this.NewCard = null; this.Token = new TokenInfo(); this.DrawPileCount = 0; } public DiscardCardResult Result { get; set; } public string Nickname { get; set; } public CardInfo OldCard { get; set; } public CardInfo NewCard { get; set; } public TokenInfo Token { get; set; } public int DrawPileCount { get; set; } } #endregion }
17.373596
67
0.374778
[ "MIT" ]
LiTsungYi/Hanabi
GameServer/Hanabi/Payloads/Response.cs
6,187
C#
using System; using Core.Extensions; namespace Hardware { public class Rotary : IRotary { public int Value { get; private set; } public void PopulateFromSerialReader(string value) { int result; if (Int32.TryParse(value.Trim(), out result)) { Value = result; } else { throw new InvalidOperationException("Could not parse a value of the rotary switch: {0}.".FormatWith(value)); } } public const string ROTARY_SWITCH = "SWITCH_"; } public interface IRotary { int Value { get; } } }
21.555556
117
0.609966
[ "MIT" ]
tnwinc/PressTo
ComputerSide/Hardware/Rotary.cs
584
C#
using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace Service { public class Program { public static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .AddCommandLine(args) .Build(); await BuildWebHost(args, configuration) .RunAsync(); } public static IWebHost BuildWebHost(string[] args, IConfiguration configuration) => WebHost.CreateDefaultBuilder(args) .UseConfiguration(configuration) .UseStartup<Startup>() .Build(); } }
28.346154
91
0.598372
[ "MIT" ]
streetcrednyc/agent-framework
src/Example/Service/Program.cs
739
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Entity.ModelConfiguration; using System.Linq; using PhotoMSK.Data.Enums; using PhotoMSK.Data.Models.ShoppingCart; using System.ComponentModel.DataAnnotations.Schema; using PhotoMSK.Data.Models.Clients; using PhotoMSK.Data.Models.Routes; namespace PhotoMSK.Data.Models { public class UserInformation { public UserInformation() { Events = new Collection<Event>(); Penalties = new List<Penalty>(); CreationTime = DateTime.Now; } public Guid ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string UserPhoto { get; set; } public string ClientType { get; set; } public string Email { get; set; } public string City { get; set; } public string Country { get; set; } public DateTime? DateOfBirth { get; set; } public DateTime CreationTime { get; set; } public virtual User User { get; set; } public virtual ICollection<UserPhone> Phones { get; set; } public virtual ICollection<Penalty> Penalties { get; set; } public virtual ICollection<Event> Events { get; set; } public virtual ICollection<Role> Roles { get; set; } public virtual ICollection<SaleCard> Cards { get; set; } public virtual ICollection<ShippingAddress> Adresses { get; set; } public ICollection<Order> Orders { get; set; } public virtual List<RouteReview> RouteReview { get; set; } public bool IsCup { get; set; } public bool Agreement { get; set; } public string VkLink { get; set; } public string FacebookLink { get; set; } public string Instagram { get; set; } public string Googleplus { get; set; } public string Site { get; set; } public virtual ICollection<RouteClientCategory> Categories { get; set; } public virtual bool IsInRole(Guid route, AccessStatus level) { return Roles.Any(x => x.Route.ID == route && x.AccessStatus <= level); } public class UserInformationConfiguration : EntityTypeConfiguration<UserInformation> { public UserInformationConfiguration() { HasKey(x => x.ID); HasOptional(x => x.User).WithOptionalDependent(x => x.UserInformation); HasMany(x => x.Penalties).WithRequired(x => x.User).HasForeignKey(x => x.UserInformationID); HasMany(x => x.Events).WithRequired(x => x.User).HasForeignKey(x => x.UserInformationID); } } } }
37.356164
108
0.625963
[ "MIT" ]
MarkusMokler/photomsmsk-by
PhotoMSK/Core/PhotoMSK.Data/Models/UserInformation.cs
2,729
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Autofac; using MediatR; using Registration.Web.Countries.GetCountries; using Registration.Web.PipelineBehaviours; namespace Registration.Web.Modules { public class MediatorModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces(); builder.Register<ServiceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => c.Resolve(t); }); builder.RegisterAssemblyTypes(typeof(GetCountriesQuery).GetTypeInfo().Assembly) .AsClosedTypesOf(typeof(IRequestHandler<,>)) .AsImplementedInterfaces(); builder.RegisterGeneric(typeof(ValidationBehavior<,>)).As(typeof(IPipelineBehavior<,>)); } } }
30.939394
110
0.670911
[ "MIT" ]
ramil89/Registration
src/Registration.Web/Modules/MediatorModule.cs
1,023
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace sage.challenge.api { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25
70
0.579048
[ "Apache-2.0" ]
aliabbasvohrashub/NetCoreForZ
src/sage.challenge.api/Program.cs
525
C#
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; using MsVsShell = Microsoft.VisualStudio.Shell; using ErrorHandler = Microsoft.VisualStudio.ErrorHandler; namespace Microsoft.Samples.VisualStudio.IDE.ToolWindow { /// <summary> /// The Package class is responsible for the following: /// - Attributes to enable registration of the components /// - Enable the creation of our tool windows /// - Respond to our commands /// /// The following attributes are covered in other samples: /// PackageRegistration: Reference.Package /// ProvideMenuResource: Reference.MenuAndCommands /// /// Our initialize method defines the command handlers for the commands that /// we provide under View|Other Windows to show our tool windows /// /// The first new attribute we are using is ProvideToolWindow. That attribute /// is used to advertise that our package provides a tool window. In addition /// it can specify optional parameters to describe the default start location /// of the tool window. For example, the PersistedWindowPane will start tabbed /// with Solution Explorer. The default position is only used the very first /// time a tool window with a specific Guid is shown for a user. After that, /// the position is persisted based on the last known position of the window. /// When trying different default start positions, you may find it useful to /// delete *.prf from: /// "%USERPROFILE%\Application Data\Microsoft\VisualStudio\10.0Exp\" /// as this is where the positions of the tool windows are persisted. /// /// To get the Guid corresponding to the Solution Explorer window, we ran this /// sample, made sure the Solution Explorer was visible, selected it in the /// Persisted Tool Window and looked at the properties in the Properties /// window. You can do the same for any window. /// /// The DynamicWindowPane makes use of a different set of optional properties. /// First it specifies a default position and size (again note that this only /// affects the very first time the window is displayed). Then it specifies the /// Transient flag which means it will not be persisted when Visual Studio is /// closed and reopened. /// /// The second new attribute is ProvideToolWindowVisibility. This attribute /// is used to specify that a tool window visibility should be controled /// by a UI Context. For a list of predefined UI Context, look in vsshell.idl /// and search for "UICONTEXT_". Since we are using the UICONTEXT_SolutionExists, /// this means that it is possible to cause the window to be displayed simply by /// creating a solution/project. /// </summary> [MsVsShell.ProvideToolWindow(typeof(PersistedWindowPane), Style = MsVsShell.VsDockStyle.Tabbed, Window = "3ae79031-e1bc-11d0-8f78-00a0c9110057")] [MsVsShell.ProvideToolWindow(typeof(DynamicWindowPane), PositionX=250, PositionY=250, Width=160, Height=180, Transient=true)] [MsVsShell.ProvideToolWindowVisibility(typeof(DynamicWindowPane), /*UICONTEXT_SolutionExists*/"f1536ef8-92ec-443c-9ed7-fdadf150da82")] [MsVsShell.ProvideMenuResource(1000, 1)] [MsVsShell.PackageRegistration(UseManagedResourcesOnly = true)] [Guid("01069CDD-95CE-4620-AC21-DDFF6C57F012")] public class PackageToolWindow : MsVsShell.Package { // Cache the Menu Command Service since we will use it multiple times private MsVsShell.OleMenuCommandService menuService; /// <summary> /// Package contructor. /// While we could have used the default constructor, adding the Trace makes it /// possible to verify that the package was created without having to set a break /// point in the debugger. /// </summary> public PackageToolWindow() { Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Entering constructor for class {0}.", this.GetType().Name)); } /// <summary> /// Initialization of the package; this is the place where you can put all the initilaization /// code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Entering Initialize for class {0}.", this.GetType().Name)); base.Initialize(); // Create one object derived from MenuCommand for each command defined in // the VSCT file and add it to the command service. // Each command is uniquely identified by a Guid/integer pair. CommandID id = new CommandID(GuidsList.guidClientCmdSet, PkgCmdId.cmdidPersistedWindow); // Add the handler for the persisted window with selection tracking DefineCommandHandler(new EventHandler(this.ShowPersistedWindow), id); // Add the handler for the tool window with dynamic visibility and events id = new CommandID(GuidsList.guidClientCmdSet, PkgCmdId.cmdidUiEventsWindow); DefineCommandHandler(new EventHandler(this.ShowDynamicWindow), id); } /// <summary> /// Define a command handler. /// When the user press the button corresponding to the CommandID /// the EventHandler will be called. /// </summary> /// <param name="id">The CommandID (Guid/ID pair) as defined in the .vsct file</param> /// <param name="handler">Method that should be called to implement the command</param> /// <returns>The menu command. This can be used to set parameter such as the default visibility once the package is loaded</returns> internal MsVsShell.OleMenuCommand DefineCommandHandler(EventHandler handler, CommandID id) { // if the package is zombied, we don't want to add commands if (this.Zombied) return null; // Make sure we have the service if (menuService == null) { // Get the OleCommandService object provided by the MPF; this object is the one // responsible for handling the collection of commands implemented by the package. menuService = GetService(typeof(IMenuCommandService)) as MsVsShell.OleMenuCommandService; } MsVsShell.OleMenuCommand command = null; if (null != menuService) { // Add the command handler command = new MsVsShell.OleMenuCommand(handler, id); menuService.AddCommand(command); } return command; } /// <summary> /// This method loads a localized string based on the specified resource. /// </summary> /// <param name="resourceName">Resource to load</param> /// <returns>String loaded for the specified resource</returns> internal string GetResourceString(string resourceName) { string resourceValue; IVsResourceManager resourceManager = (IVsResourceManager)GetService(typeof(SVsResourceManager)); if (resourceManager == null) { throw new InvalidOperationException("Could not get SVsResourceManager service. Make sure the package is Sited before calling this method"); } Guid packageGuid = this.GetType().GUID; int hr = resourceManager.LoadResourceString(ref packageGuid, -1, resourceName, out resourceValue); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); return resourceValue; } /// <summary> /// Event handler for our menu item. /// This results in the tool window being shown. /// </summary> /// <param name="sender"></param> /// <param name="arguments"></param> private void ShowPersistedWindow(object sender, EventArgs arguments) { // Get the 1 (index 0) and only instance of our tool window (if it does not already exist it will get created) MsVsShell.ToolWindowPane pane = this.FindToolWindow(typeof(PersistedWindowPane), 0, true); if (pane == null) { throw new COMException(this.GetResourceString("@101")); } IVsWindowFrame frame = pane.Frame as IVsWindowFrame; if (frame == null) { throw new COMException(this.GetResourceString("@102")); } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); } /// <summary> /// Event handler for our menu item. /// This result in the tool window being shown. /// </summary> /// <param name="sender"></param> /// <param name="arguments"></param> private void ShowDynamicWindow(object sender, EventArgs arguments) { // Get the one (index 0) and only instance of our tool window (if it does not already exist it will get created) MsVsShell.ToolWindowPane pane = this.FindToolWindow(typeof(DynamicWindowPane), 0, true); if (pane == null) { throw new COMException(this.GetResourceString("@101")); } IVsWindowFrame frame = pane.Frame as IVsWindowFrame; if (frame == null) { throw new COMException(this.GetResourceString("@102")); } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); } } }
43.871429
146
0.726908
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Visual Studio Product Team/Visual Studio 2010 SDK Samples/60968-Visual Studio 2010 SDK Samples/VSSDK IDE Sample Tool WPF Tool Windows/C#/PackageToolWindow.cs
9,213
C#
using System; using System.Net; namespace HipChat { /// <summary> /// Custom exception containing information returned from HipChat (extracted from WebException). /// </summary> /// <remarks> /// The HipChat API will return an HTTP 4XX in the case of an exception, and will put the error into the body of the response. /// This exception extracts the relevant information and presents in a more logical format. /// More details here - https://www.hipchat.com/docs/api/response_codes /// </remarks> public class HipChatApiWebException: ApplicationException { /// <summary> /// The HTTP status code returned by HipChat - usually a 4xx /// </summary> public HttpStatusCode Status { get; private set; } /// <summary> /// /// </summary> /// <param name="ex"></param> /// <param name="closeResponse">If True, the WebException.Response object is closed.</param> public HipChatApiWebException(WebException ex, bool closeResponse): base(HttpUtils.ReadResponseBody(ex.Response)) { this.Status = ((HttpWebResponse)ex.Response).StatusCode; if (closeResponse) { ex.Response.Close(); } } } }
35.75
131
0.61927
[ "MIT", "Unlicense" ]
akorczynski/HipChat.net
HipChatClient/HipChatApiWebException.cs
1,289
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Infrastructure; namespace Microsoft.AspNet.SignalR.Hubs { public class ConnectionIdProxy : SignalProxy { public ConnectionIdProxy(IConnection connection, IHubPipelineInvoker invoker, string signal, string hubName, params string[] exclude) : base(connection, invoker, signal, hubName, PrefixHelper.HubConnectionIdPrefix, exclude) { } } }
33.157895
143
0.749206
[ "Apache-2.0" ]
AndreasBieber/SignalR
src/Microsoft.AspNet.SignalR.Core/Hubs/ConnectionIdProxy.cs
632
C#
/* * WebAPI - Area Management * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: management * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Management.Client.SwaggerDateConverter; namespace IO.Swagger.Management.Model { /// <summary> /// Class of sql condition for type String /// </summary> [DataContract] public partial class SqlConditionStringDTO : SqlConditionBaseDTO, IEquatable<SqlConditionStringDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SqlConditionStringDTO" /> class. /// </summary> [JsonConstructorAttribute] protected SqlConditionStringDTO() { } /// <summary> /// Initializes a new instance of the <see cref="SqlConditionStringDTO" /> class. /// </summary> /// <param name="_operator">Possible values: 0: Non_Impostato 1: Uguale 2: Diverso 3: Inizia 4: Contiene 5: Termina 6: Nullo 7: Non_Nullo 8: Vuoto 9: Non_Vuoto 10: Nullo_o_Vuoto 11: Non_Nullo_e_Non_Vuoto 12: Like .</param> /// <param name="value1">First value.</param> /// <param name="value2">Second value.</param> public SqlConditionStringDTO(int? _operator = default(int?), string value1 = default(string), string value2 = default(string), string className = "SqlConditionStringDTO", string id = default(string), string name = default(string), string table = default(string), string field = default(string), bool? insensitiveSearch = default(bool?), string external1 = default(string), string external1Description = default(string), string external2 = default(string), string external2Description = default(string)) : base(className, id, name, table, field, insensitiveSearch, external1, external1Description, external2, external2Description) { this.Operator = _operator; this.Value1 = value1; this.Value2 = value2; } /// <summary> /// Possible values: 0: Non_Impostato 1: Uguale 2: Diverso 3: Inizia 4: Contiene 5: Termina 6: Nullo 7: Non_Nullo 8: Vuoto 9: Non_Vuoto 10: Nullo_o_Vuoto 11: Non_Nullo_e_Non_Vuoto 12: Like /// </summary> /// <value>Possible values: 0: Non_Impostato 1: Uguale 2: Diverso 3: Inizia 4: Contiene 5: Termina 6: Nullo 7: Non_Nullo 8: Vuoto 9: Non_Vuoto 10: Nullo_o_Vuoto 11: Non_Nullo_e_Non_Vuoto 12: Like </value> [DataMember(Name="operator", EmitDefaultValue=false)] public int? Operator { get; set; } /// <summary> /// First value /// </summary> /// <value>First value</value> [DataMember(Name="value1", EmitDefaultValue=false)] public string Value1 { get; set; } /// <summary> /// Second value /// </summary> /// <value>Second value</value> [DataMember(Name="value2", EmitDefaultValue=false)] public string Value2 { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SqlConditionStringDTO {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Operator: ").Append(Operator).Append("\n"); sb.Append(" Value1: ").Append(Value1).Append("\n"); sb.Append(" Value2: ").Append(Value2).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public override string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SqlConditionStringDTO); } /// <summary> /// Returns true if SqlConditionStringDTO instances are equal /// </summary> /// <param name="input">Instance of SqlConditionStringDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(SqlConditionStringDTO input) { if (input == null) return false; return base.Equals(input) && ( this.Operator == input.Operator || (this.Operator != null && this.Operator.Equals(input.Operator)) ) && base.Equals(input) && ( this.Value1 == input.Value1 || (this.Value1 != null && this.Value1.Equals(input.Value1)) ) && base.Equals(input) && ( this.Value2 == input.Value2 || (this.Value2 != null && this.Value2.Equals(input.Value2)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); if (this.Operator != null) hashCode = hashCode * 59 + this.Operator.GetHashCode(); if (this.Value1 != null) hashCode = hashCode * 59 + this.Value1.GetHashCode(); if (this.Value2 != null) hashCode = hashCode * 59 + this.Value2.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { foreach(var x in BaseValidate(validationContext)) yield return x; yield break; } } }
41.916168
637
0.589143
[ "Apache-2.0" ]
zanardini/ARXivarNext-WebApi
ARXivarNext-ConsumingWebApi/IO.Swagger.Management/Model/SqlConditionStringDTO.cs
7,000
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-a2i-runtime-2019-11-07.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.AugmentedAIRuntime { /// <summary> /// Configuration for accessing Amazon AugmentedAIRuntime service /// </summary> public partial class AmazonAugmentedAIRuntimeConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.100.30"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonAugmentedAIRuntimeConfig() { this.AuthenticationServiceName = "sagemaker"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "a2i-runtime.sagemaker"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2019-11-07"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.9625
119
0.598053
[ "Apache-2.0" ]
lukeenterprise/aws-sdk-net
sdk/src/Services/AugmentedAIRuntime/Generated/AmazonAugmentedAIRuntimeConfig.cs
2,157
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR #if ! UNITY_WEBPLAYER using System.IO; #endif #endif public class BuildDestroyAnimationManager : MonoBehaviour { public int mode = 0; // 0 - build // 1 - destroy // 2 = build and destroy public bool debugMode = false; Mesh originalMesh; Mesh originalMeshRuntime; void Start() { MeshFilter mf = GetComponent<MeshFilter>(); originalMesh = mf.mesh; originalMeshRuntime = CopyMesh(originalMesh); mf.mesh = originalMeshRuntime; Initialize(); if ((mode == 0) || (mode == 2)) { StartCoroutine(BuildSequence()); } if (mode == 1) { DestroyMesh(); } } KDTree kd; void Initialize() { Mesh msh = originalMeshRuntime; o_vertices = msh.vertices; o_normals = msh.normals; o_uv = msh.uv; o_triangles = msh.triangles; for (int i = 0; i < o_vertices.Length; i++) { o_vertices[i] = o_vertices[i] + 0.00001f * Random.insideUnitSphere; } kd = KDTree.MakeFromPoints(o_vertices); o_neighbours = new List<List<int>>(); for (int i = 0; i < o_vertices.Length; i++) { o_neighbours.Add(new List<int>()); int[] neighs = kd.FindNearestsK(o_vertices[i] + 0.00001f * Random.insideUnitSphere, 5); for (int j = 0; j < neighs.Length; j++) { int id = neighs[j]; if (id >= 0) { if (id < o_vertices.Length) { float r = (o_vertices[i] - o_vertices[id]).magnitude; if (r < 0.0001f) { o_neighbours[i].Add(id); } } } } } if (debugMode) { Debug.Log(o_vertices.Length); } o_indices = new List<int[]>(); o_topology = new List<MeshTopology>(); for (int i = 0; i < msh.subMeshCount; i++) { o_indices.Add(msh.GetIndices(i)); o_topology.Add(msh.GetTopology(i)); } if (msh != null) { FindLinkedVertex(msh); } } Vector3[] o_vertices; Vector3[] o_normals; Vector2[] o_uv; int[] o_triangles; List<int[]> o_indices; List<MeshTopology> o_topology; List<List<int>> o_neighbours; int[] o_clusterId; int o_nTri = 0; int[,] o_triangles3; IEnumerator BuildSequence() { Mesh msh = originalMeshRuntime; int iBuildPrinting = 0; for (int i = 0; i < nClustersTot; i++) { iClustCut++; if (debugMode) { Debug.Log(iClustCut); } SetPassMaskBelow(iClustCut); SetMesh(msh); if ((fileWriteMode == 0) || (fileWriteMode == 2)) { int totId = i; int nFrac = nClustersTot / (numBuildFrames - 1); if (totId % nFrac == 0) { iBuildPrinting++; WriteCurrentBuildIntoFile(iBuildPrinting); } } yield return new WaitForSeconds(0.1f); } if (mode == 2) { DestroyMesh(); } yield return new WaitForSeconds(0.1f); } int iClustCut = 10; int nClustersTot = 0; void FindLinkedVertex(Mesh msh) { Vector3[] vertices = o_vertices; int[] trianglesOrig = o_triangles; int[,] triangles = new int[trianglesOrig.Length / 3, 3]; int[] clusterId = new int[vertices.Length]; // Finding linked vertex groups - clusters for (int i = 0; i < clusterId.Length; i++) { clusterId[i] = 0; } int j1 = 0; int nTri = 0; for (int i = 0; i < trianglesOrig.Length; i++) { triangles[nTri, j1] = trianglesOrig[i]; j1++; if (j1 > 2) { nTri++; j1 = 0; } } int nClusters = 0; for (int i = 0; i < nTri; i++) { int clustId = 0; for (int j = 0; j < 3; j++) { int v = triangles[i, j]; if (clustId == 0) { if (clusterId[v] != 0) { clustId = clusterId[v]; } } } if (clustId != 0) { for (int j = 0; j < 3; j++) { int v = triangles[i, j]; clusterId[v] = clustId; } } else { nClusters++; for (int j = 0; j < 3; j++) { int v = triangles[i, j]; clusterId[v] = nClusters; } } } if (debugMode) { int nUnclusteredVerts = 0; for (int i = 0; i < vertices.Length; i++) { if (clusterId[i] == 0) { nUnclusteredVerts++; } } Debug.Log("nUnclusteredVerts " + nUnclusteredVerts); } int nClustersPrev = nClusters * 2; int imerge = 0; // Merging clusters List<List<int>> clusterVerticesList; while ((nClustersPrev > nClusters) && (imerge < 25)) { imerge++; nClustersPrev = nClusters; if (nClusters > 0) { // merging by neighbours for (int i = 0; i < vertices.Length; i++) { for (int j = 0; j < o_neighbours[i].Count; j++) { int id = o_neighbours[i][j]; if (clusterId[i] != 0) { if (clusterId[id] != 0) { if (clusterId[i] != clusterId[id]) { if (clusterId[i] < clusterId[id]) { clusterId[id] = clusterId[i]; } else if (clusterId[i] > clusterId[id]) { clusterId[i] = clusterId[id]; } } } } } } // merging by triangles int[] clusterRepeat = new int[nClusters]; for (int i = 0; i < nTri; i++) { for (int j = 0; j < 3; j++) { int v = triangles[i, j]; int clustId = clusterId[v]; if (clustId > 0) { clusterRepeat[clustId - 1] = 0; } } int nmax = 0; int cmax = 0; for (int j = 0; j < 3; j++) { int v = triangles[i, j]; int clustId = clusterId[v]; if (clustId > 0) { clusterRepeat[clustId - 1] = clusterRepeat[clustId - 1] + 1; if (clusterRepeat[clustId - 1] > nmax) { nmax = clusterRepeat[clustId - 1]; cmax = clustId; } } } if (nmax < 3) { for (int j = 0; j < 3; j++) { int v = triangles[i, j]; clusterId[v] = cmax; } } } clusterRepeat = new int[nClusters]; for (int i = 0; i < clusterRepeat.Length; i++) { clusterRepeat[i] = 0; } for (int i = 0; i < clusterId.Length; i++) { int j = clusterId[i]; if (j > 0) { clusterRepeat[j - 1] = clusterRepeat[j - 1] + 1; } } int[] clusterRemap = new int[nClusters]; for (int i = 0; i < clusterRemap.Length; i++) { clusterRemap[i] = 0; } int nClusters2 = 0; for (int i = 0; i < clusterRepeat.Length; i++) { if (clusterRepeat[i] > 0) { nClusters2++; clusterRemap[i] = nClusters2; } } for (int i = 0; i < clusterId.Length; i++) { int j = clusterId[i]; if (j > 0) { clusterId[i] = clusterRemap[j - 1]; } } nClusters = nClusters2; } } if (debugMode) { Debug.Log("nClusters " + nClusters); } clusterVerticesList = new List<List<int>>(); for (int i = 0; i < nClusters; i++) { clusterVerticesList.Add(new List<int>()); } for (int i = 0; i < clusterId.Length; i++) { int j = clusterId[i]; if (j > 0) { clusterVerticesList[j - 1].Add(i); } } // Sorting clusters by Y float[] ys = new float[nClusters]; int axis = 2; float ymax = float.MaxValue; for (int i = 0; i < vertices.Length; i++) { if (vertices[i][axis] < ymax) { ymax = vertices[i][axis]; } } nClustersTot = nClusters; for (int i = 0; i < nClusters; i++) { float ys1 = ymax; int n22 = 0; for (int j = 0; j < clusterVerticesList[i].Count; j++) { int k = clusterVerticesList[i][j]; n22++; ys1 = ys1 + vertices[k][axis]; } ys1 = ys1 / n22; ys[i] = ys1; } int[] sortIds = HeapSort(ys); for (int i = 0; i < clusterId.Length; i++) { clusterId[i] = 0; } for (int i = 0; i < nClusters; i++) { int isort = sortIds[i]; for (int j = 0; j < clusterVerticesList[isort].Count; j++) { int k = clusterVerticesList[isort][j]; clusterId[k] = i + 1; } } o_clusterId = clusterId; o_nTri = nTri; o_triangles3 = triangles; } int[] passMask; void SetPassMaskBelow(int clustVal) { passMask = new int[o_vertices.Length]; int i3 = 0; for (int i = 0; i < o_vertices.Length; i++) { passMask[i] = -1; if (o_clusterId[i] < clustVal) { passMask[i] = i3; i3++; } } } void SetPassMaskExclude(int clustVal) { int i3 = 0; for (int i = 0; i < o_vertices.Length; i++) { if (passMask[i] != -1) { if (o_clusterId[i] == clustVal) { passMask[i] = -1; } else { passMask[i] = i3; i3++; } } } } void SetPassMaskAbove(int clustVal) { passMask = new int[o_vertices.Length]; int i3 = 0; for (int i = 0; i < o_vertices.Length; i++) { passMask[i] = -1; if (o_clusterId[i] > clustVal) { passMask[i] = i3; i3++; } } } void SetPassMaskBetween(int min, int max) { passMask = new int[o_vertices.Length]; int i3 = 0; for (int i = 0; i < o_vertices.Length; i++) { passMask[i] = -1; if (o_clusterId[i] > min) { if (o_clusterId[i] < max) { passMask[i] = i3; i3++; } } } } void SetMesh(Mesh newMesh) { // setting up new mesh List<Vector3> newVertices = new List<Vector3>(); List<Vector3> newNormals = new List<Vector3>(); List<Vector2> newUv = new List<Vector2>(); for (int i = 0; i < o_vertices.Length; i++) { if (passMask[i] > -1) { newVertices.Add(o_vertices[i]); newNormals.Add(o_normals[i]); newUv.Add(o_uv[i]); } } List<int> newTriangles = new List<int>(); for (int i = 0; i < o_nTri; i++) { bool pass = true; for (int j = 0; j < 3; j++) { int k = o_triangles3[i, j]; if (passMask[k] <= -1) { pass = false; } } if (pass) { for (int j = 0; j < 3; j++) { int k = o_triangles3[i, j]; int newi = passMask[k]; newTriangles.Add(newi); } } } List<List<int>> newSubMeshIndices = new List<List<int>>(); for (int i = 0; i < o_indices.Count; i++) { newSubMeshIndices.Add(new List<int>()); for (int j = 0; j < o_indices[i].Length; j++) { if ((j % 3) == 0) { int j2 = j; bool pass = true; for (int j3 = 0; j3 < 3; j3++) { int k = o_indices[i][j2]; if (passMask[k] <= -1) { pass = false; } j2 = j2 + 1; } if (pass) { j2 = j; for (int j3 = 0; j3 < 3; j3++) { int k = o_indices[i][j2]; newSubMeshIndices[i].Add(passMask[k]); j2 = j2 + 1; } } } } } newMesh.Clear(); newMesh.vertices = newVertices.ToArray(); newMesh.normals = newNormals.ToArray(); newMesh.uv = newUv.ToArray(); newMesh.triangles = newTriangles.ToArray(); newMesh.subMeshCount = o_indices.Count; for (int i = 0; i < o_indices.Count; i++) { newMesh.SetIndices(newSubMeshIndices[i].ToArray(), o_topology[i], i); } newMesh.RecalculateBounds(); } void DestroyMesh() { StartCoroutine(DestrAll()); } bool randomiseDestructionOrder = true; IEnumerator DestrAll() { SetPassMaskBelow(nClustersTot + 1); maskOrig1 = new int[passMask.Length]; int[] clustRemovals = new int[nClustersTot + 1]; for (int i = 0; i < clustRemovals.Length; i++) { clustRemovals[i] = i; } if (randomiseDestructionOrder) { RandomiseArrayConverging(clustRemovals, clustRemovals.Length, 0, clustRemovals.Length - 5); } int iDestrPrinting = 0; for (int i = nClustersTot; i >= -nPiecesToKeep; i--) { if (i >= 0) { isDestroyMeshRunning = true; StartCoroutine(DestroyMesh(clustRemovals[i])); while (isDestroyMeshRunning) { yield return new WaitForEndOfFrame(); } } if ((i <= nClustersTot - nPiecesToKeep) || (i < 0)) { if (destructionPieces.Count > 0) { Mesh destMesh = destructionPiecesMesh[0]; destructionPiecesMesh.RemoveAt(0); if (destMesh != null) { Destroy(destMesh); } GameObject dest = destructionPieces[0]; destructionPieces.RemoveAt(0); Destroy(dest); } } if ((fileWriteMode == 1) || (fileWriteMode == 2)) { int totId = (nClustersTot + nPiecesToKeep) - i; int nFrac = (nClustersTot + nPiecesToKeep) / numDestroyFrames; if (totId % nFrac == 0) { List<GameObject> meshesToSave = new List<GameObject>(); List<Mesh> meshesToSaveM = new List<Mesh>(); meshesToSave.Add(this.gameObject); meshesToSaveM.Add(originalMeshRuntime); for (int i2 = 0; i2 < destructionPieces.Count; i2++) { meshesToSave.Add(destructionPieces[i2]); meshesToSaveM.Add(destructionPiecesMesh[i2]); } iDestrPrinting++; WriteCurrentDestroyIntoFile(meshesToSave, meshesToSaveM, iDestrPrinting); } } yield return new WaitForSeconds(0.2f); } yield return null; } List<GameObject> destructionPieces = new List<GameObject>(); List<Mesh> destructionPiecesMesh = new List<Mesh>(); int[] maskOrig1; public int nPiecesToKeep = 60; public float initialForceScaler = 0f; bool isDestroyMeshRunning = false; public bool reproduceError = true; IEnumerator DestroyMesh(int iDestr) { isDestroyMeshRunning = true; Mesh msh = new Mesh(); SetPassMaskExclude(iDestr); CopyMask(maskOrig1, passMask); SetMesh(originalMeshRuntime); MeshCollider colHere = GetComponent<MeshCollider>(); if (colHere != null) { Destroy(colHere); this.gameObject.AddComponent<MeshCollider>(); } SetPassMaskBetween(iDestr - 1, iDestr + 1); SetMesh(msh); CopyMask(passMask, maskOrig1); if ((msh.vertices.Length > 0) && (msh.triangles.Length > 0)) { GameObject go = new GameObject("newMesh"); go.transform.position = transform.position; go.transform.rotation = transform.rotation; go.transform.localScale = transform.localScale; MeshFilter mf = go.AddComponent<MeshFilter>(); mf.mesh = msh; MeshRenderer mr = go.AddComponent<MeshRenderer>(); Material[] materialsHere = GetComponent<MeshRenderer>().materials; mr.materials = materialsHere; if (reproduceError == false) { mr.enabled = false; } yield return new WaitForEndOfFrame(); MeshCollider col = go.AddComponent<MeshCollider>(); col.convex = true; col.sharedMesh = msh; yield return new WaitForEndOfFrame(); Rigidbody rb = go.AddComponent<Rigidbody>(); rb.maxDepenetrationVelocity = 0.1f; rb.drag = 0.05f; rb.AddForce(initialForceScaler * Random.insideUnitSphere, ForceMode.VelocityChange); destructionPieces.Add(go); destructionPiecesMesh.Add(msh); } yield return new WaitForEndOfFrame(); isDestroyMeshRunning = false; } void RandomiseArrayConverging(int[] array, int nToRandomise, int low, int high) { int n = array.Length; for (int i = 0; i < nToRandomise; i++) { int randId1 = Random.Range(0, n); float randP = Random.Range(0f, 0.1f); int randId2 = (int)(1.0f * randId1 - randP * n); if (randId1 != randId2) { if ((randId1 > low) && (randId1 < high)) { if ((randId2 > low) && (randId2 < high)) { int t = array[randId1]; array[randId1] = array[randId2]; array[randId2] = t; } } } } } void CopyMask(int[] in1, int[] in2) { for (int i = 0; i < in1.Length; i++) { in1[i] = in2[i]; } } // Based on https://begeeben.wordpress.com/2012/08/21/heap-sort-in-c/ public static int[] HeapSort(float[] input1) { //Build-Max-Heap int heapSize = input1.Length; int[] iorig = new int[heapSize]; float[] input = new float[heapSize]; for (int i = 0; i < iorig.Length; i++) { iorig[i] = i; input[i] = input1[i]; } for (int p = (heapSize - 1) / 2; p >= 0; p--) { MaxHeapify(input, iorig, heapSize, p); } for (int i = input.Length - 1; i > 0; i--) { //Swap float temp = input[i]; input[i] = input[0]; input[0] = temp; int itemp = iorig[i]; iorig[i] = iorig[0]; iorig[0] = itemp; heapSize--; MaxHeapify(input, iorig, heapSize, 0); } return iorig; } static void MaxHeapify(float[] input, int[] iorig, int heapSize, int index) { int left = (index + 1) * 2 - 1; int right = (index + 1) * 2; int largest = 0; if (left < heapSize && input[left] > input[index]) { largest = left; } else { largest = index; } if (right < heapSize && input[right] > input[largest]) { largest = right; } if (largest != index) { float temp = input[index]; input[index] = input[largest]; input[largest] = temp; int itemp = iorig[index]; iorig[index] = iorig[largest]; iorig[largest] = itemp; MaxHeapify(input, iorig, heapSize, largest); } } // File writer public int fileWriteMode = -1; // 0 - build // 1 - destroy // 2 = build and destroy public string filePath; public int numBuildFrames = 10; public int numDestroyFrames = 10; void WriteCurrentBuildIntoFile(int i) { #if UNITY_EDITOR #if !UNITY_WEBPLAYER RefreshDirectories(); Mesh msh = originalMeshRuntime; Mesh newMesh = new Mesh(); newMesh.vertices = msh.vertices; newMesh.normals = msh.normals; newMesh.uv = msh.uv; newMesh.triangles = msh.triangles; newMesh.subMeshCount = msh.subMeshCount; for (int j = 0; j < msh.subMeshCount; j++) { newMesh.SetIndices(msh.GetIndices(j), msh.GetTopology(j), j); } newMesh.RecalculateBounds(); if (newMesh == null) { Debug.Log("newMesh == null"); } string dirName = "Assets/models/BuildDestroyAmimations/" + filePath + "/"; UnityEditor.AssetDatabase.CreateAsset(newMesh, dirName + i.ToString() + "b.asset"); UnityEditor.AssetDatabase.Refresh(); #endif #endif } void WriteCurrentDestroyIntoFile(List<GameObject> meshesList, List<Mesh> meshListM, int iStep) { #if UNITY_EDITOR #if !UNITY_WEBPLAYER List<Vector3> masterVertices = new List<Vector3>(); List<Vector3> masterNormals = new List<Vector3>(); List<Vector2> masterUV = new List<Vector2>(); List<int> masterTriangles = new List<int>(); List<List<int>> masterIndices = new List<List<int>>(); List<MeshTopology> masterTopology = new List<MeshTopology>(); for (int k = 0; k < meshesList.Count; k++) { Mesh msh = meshListM[k]; int nVertsNow = masterVertices.Count; Vector3[] vertices1 = msh.vertices; Vector3[] normals1 = msh.normals; Vector2[] uv1 = msh.uv; Transform tr = meshesList[k].transform; Vector3 scale = tr.localScale; Quaternion thisRotInv = Quaternion.Euler(-transform.rotation.eulerAngles); for (int i = 0; i < vertices1.Length; i++) { Vector3 vertNew = tr.TransformPoint(vertices1[i]); vertNew = new Vector3(vertNew.x / scale.x, vertNew.y / scale.y, vertNew.z / scale.z); vertNew = thisRotInv * vertNew; masterVertices.Add(vertNew); masterNormals.Add(normals1[i]); masterUV.Add(uv1[i]); } int[] triangles1 = msh.triangles; for (int i = 0; i < triangles1.Length; i++) { masterTriangles.Add(triangles1[i] + nVertsNow); } for (int i = 0; i < msh.subMeshCount; i++) { int[] inds1 = msh.GetIndices(i); masterTopology.Add(msh.GetTopology(i)); if (nVertsNow == 0) { masterIndices.Add(new List<int>()); } for (int j = 0; j < inds1.Length; j++) { masterIndices[i].Add(inds1[j] + nVertsNow); } } } Mesh masterMesh = new Mesh(); masterMesh.Clear(); masterMesh.vertices = masterVertices.ToArray(); masterMesh.normals = masterNormals.ToArray(); masterMesh.uv = masterUV.ToArray(); masterMesh.triangles = masterTriangles.ToArray(); masterMesh.subMeshCount = masterIndices.Count; for (int i = 0; i < masterIndices.Count; i++) { masterMesh.SetIndices(masterIndices[i].ToArray(), masterTopology[i], i); } masterMesh.RecalculateBounds(); RefreshDirectories(); string dirName = "Assets/models/BuildDestroyAmimations/" + filePath + "/"; UnityEditor.AssetDatabase.CreateAsset(masterMesh, dirName + iStep.ToString() + "d.asset"); UnityEditor.AssetDatabase.Refresh(); #endif #endif } Mesh CopyMesh(Mesh oldMesh) { Mesh newMesh = new Mesh(); newMesh.Clear(); newMesh.vertices = oldMesh.vertices; newMesh.normals = oldMesh.normals; newMesh.uv = oldMesh.uv; newMesh.triangles = oldMesh.triangles; newMesh.subMeshCount = oldMesh.subMeshCount; for (int i = 0; i < oldMesh.subMeshCount; i++) { newMesh.SetIndices(oldMesh.GetIndices(i), oldMesh.GetTopology(i), i); } newMesh.RecalculateBounds(); return newMesh; } void RefreshDirectories() { #if UNITY_EDITOR #if !UNITY_WEBPLAYER string pth = @Application.dataPath + "/models/BuildDestroyAmimations/" + filePath; if (!Directory.Exists(pth)) { Directory.CreateDirectory(pth); } UnityEditor.AssetDatabase.Refresh(); #endif #endif } }
26.064457
103
0.430121
[ "MIT" ]
chanfort/BuildingBuildDestroyAnimations
Assets/Scripts/BuildDestroyAnimationManager.cs
28,308
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using UnityEngine; using MJ = MoPubInternal.ThirdParty.MiniJSON; /// <summary> /// Support classes used by the <see cref="MoPub"/> Unity API for publishers. /// </summary> public abstract class MoPubBase : MoPubBaseInternal { public enum AdPosition { TopLeft, TopCenter, TopRight, Centered, BottomLeft, BottomCenter, BottomRight } public static class Consent { /// <summary> /// User's consent for providing personal tracking data for ad tailoring. /// </summary> /// <remarks> /// The enum values match the iOS SDK enum. /// </remarks> public enum Status { /// <summary> /// Status is unknown. Either the status is currently updating or the SDK initialization has not completed. /// </summary> Unknown = 0, /// <summary> /// Consent is denied. /// </summary> Denied, /// <summary> /// Advertiser tracking is disabled. /// </summary> DoNotTrack, /// <summary> /// Your app has attempted to grant consent on the user's behalf, but your whitelist status is not verfied /// with the ad server. /// </summary> PotentialWhitelist, /// <summary> /// User has consented. /// </summary> Consented } // The Android SDK uses these strings to indicate consent status. private static class Strings { public const string ExplicitYes = "explicit_yes"; public const string ExplicitNo = "explicit_no"; public const string Unknown = "unknown"; public const string PotentialWhitelist = "potential_whitelist"; public const string Dnt = "dnt"; } // Helper string to convert Android SDK consent status strings to our consent enum. // Also handles integer values. public static Status FromString(string status) { switch (status) { case Strings.ExplicitYes: return Status.Consented; case Strings.ExplicitNo: return Status.Denied; case Strings.Dnt: return Status.DoNotTrack; case Strings.PotentialWhitelist: return Status.PotentialWhitelist; case Strings.Unknown: return Status.Unknown; default: try { return (Status) Enum.Parse(typeof(Status), status); } catch { Debug.LogError("Unknown consent status string: " + status); return Status.Unknown; } } } } /// <summary> /// The maximum size, in density-independent pixels (DIPs), an ad should have. /// </summary> public enum MaxAdSize { Width300Height50, Width300Height250, Width320Height50, Width336Height280, Width728Height90, Width970Height90, Width970Height250, ScreenWidthHeight50, ScreenWidthHeight90, ScreenWidthHeight250, ScreenWidthHeight280 } public enum LogLevel { Debug = 20, Info = 30, None = 70 } /// <summary> /// Data object holding any SDK initialization parameters. /// </summary> public class SdkConfiguration { /// <summary> /// Any ad unit that your app uses. /// </summary> public string AdUnitId; /// <summary> /// Used for rewarded video initialization. This holds each custom event's unique settings. /// </summary> public MediatedNetwork[] MediatedNetworks; /// <summary> /// Allow supported SDK networks to collect user information on the basis of legitimate interest. /// Can also be set via MoPub.<see cref="MoPub.SdkConfiguration"/> on /// MoPub.<see cref="MoPubUnityEditor.InitializeSdk(MoPub.SdkConfiguration)"/> /// </summary> public bool AllowLegitimateInterest; /// <summary> /// MoPub SDK log level. Defaults to MoPub.<see cref="MoPub.LogLevel.None"/> /// </summary> public LogLevel LogLevel { get { return _logLevel != 0 ? _logLevel : LogLevel.None; } set { _logLevel = value; } } private LogLevel _logLevel; public string AdditionalNetworksString { get { var cn = from n in MediatedNetworks ?? Enumerable.Empty<MediatedNetwork>() where n is MediatedNetwork && !(n is SupportedNetwork) where !String.IsNullOrEmpty(n.AdapterConfigurationClassName) select n.AdapterConfigurationClassName; return String.Join(",", cn.ToArray()); } } public string NetworkConfigurationsJson { get { var nc = from n in MediatedNetworks ?? Enumerable.Empty<MediatedNetwork>() where n.NetworkConfiguration != null where !String.IsNullOrEmpty(n.AdapterConfigurationClassName) select n; return MJ.Json.Serialize(nc.ToDictionary(n => n.AdapterConfigurationClassName, n => n.NetworkConfiguration)); } } public string MediationSettingsJson { get { var ms = from n in MediatedNetworks ?? Enumerable.Empty<MediatedNetwork>() where n.MediationSettings != null where !String.IsNullOrEmpty(n.MediationSettingsClassName) select n; return MJ.Json.Serialize(ms.ToDictionary(n => n.MediationSettingsClassName, n => n.MediationSettings)); } } public string MoPubRequestOptionsJson { get { var ro = from n in MediatedNetworks ?? Enumerable.Empty<MediatedNetwork>() where n.MoPubRequestOptions != null where !String.IsNullOrEmpty(n.AdapterConfigurationClassName) select n; return MJ.Json.Serialize(ro.ToDictionary(n => n.AdapterConfigurationClassName, n => n.MoPubRequestOptions)); } } // Allow looking up an entry in the MediatedNetwork array using the network name, which is presumed to be // part of the AdapterConfigurationClassName value. public MediatedNetwork this[string networkName] { get { return MediatedNetworks.FirstOrDefault(mn => mn.AdapterConfigurationClassName == networkName || mn.AdapterConfigurationClassName == networkName + "AdapterConfiguration" || mn.AdapterConfigurationClassName.EndsWith("." + networkName) || mn.AdapterConfigurationClassName.EndsWith("." + networkName + "AdapterConfiguration")); } } } public class LocalMediationSetting : Dictionary<string, object> { public string MediationSettingsClassName { get; set; } public LocalMediationSetting() { } public LocalMediationSetting(string adVendor) { #if UNITY_IOS MediationSettingsClassName = adVendor + "InstanceMediationSettings"; #else MediationSettingsClassName = "com.mopub.mobileads." + adVendor + "RewardedVideo$" + adVendor + "MediationSettings"; #endif } public LocalMediationSetting(string android, string ios) : #if UNITY_IOS this(ios) #else this(android) #endif {} public static string ToJson(IEnumerable<LocalMediationSetting> localMediationSettings) { var ms = from n in localMediationSettings ?? Enumerable.Empty<LocalMediationSetting>() where n != null && !String.IsNullOrEmpty(n.MediationSettingsClassName) select n; return MJ.Json.Serialize(ms.ToDictionary(n => n.MediationSettingsClassName, n => n)); } // Shortcut class names so you don't have to remember the right ad vendor string (also to not misspell it). public class AdColony : LocalMediationSetting { public AdColony() : base("AdColony") { #if UNITY_ANDROID MediationSettingsClassName = "com.mopub.mobileads.AdColonyRewardedVideo$AdColonyInstanceMediationSettings"; #endif } } public class AdMob : LocalMediationSetting { public AdMob() : base(android: "GooglePlayServices", ios: "MPGoogle") { } } public class Chartboost : LocalMediationSetting { public Chartboost() : base("Chartboost") { } } public class Vungle : LocalMediationSetting { public Vungle() : base("Vungle") { } } } // Networks that are supported by MoPub. public class SupportedNetwork : MediatedNetwork { protected SupportedNetwork(string adVendor) { #if UNITY_IOS AdapterConfigurationClassName = adVendor + "AdapterConfiguration"; MediationSettingsClassName = adVendor + "GlobalMediationSettings"; #else AdapterConfigurationClassName = "com.mopub.mobileads." + adVendor + "AdapterConfiguration"; MediationSettingsClassName = "com.mopub.mobileads." + adVendor + "RewardedVideo$" + adVendor + "MediationSettings"; #endif } public class AdColony : SupportedNetwork { public AdColony() : base("AdColony") { #if UNITY_ANDROID MediationSettingsClassName = "com.mopub.mobileads.AdColonyRewardedVideo$AdColonyGlobalMediationSettings"; #endif } } public class AdMob : SupportedNetwork { public AdMob() : base("GooglePlayServices") { #if UNITY_IOS AdapterConfigurationClassName = "GoogleAdMobAdapterConfiguration"; MediationSettingsClassName = "MPGoogleGlobalMediationSettings"; #endif } } public class AppLovin : SupportedNetwork { public AppLovin() : base("AppLovin") { } } public class Chartboost : SupportedNetwork { public Chartboost() : base("Chartboost") { } } public class Facebook : SupportedNetwork { public Facebook() : base("Facebook") { } } public class Fyber : SupportedNetwork { public Fyber() : base("Fyber") { } } public class Flurry : SupportedNetwork { public Flurry() : base("Flurry") { } } public class InMobi : SupportedNetwork { public InMobi() : base("InMobi") { } } public class IronSource : SupportedNetwork { public IronSource() : base("IronSource") { } } public class Mintegral : SupportedNetwork { public Mintegral() : base("Mintegral") { } } public class Ogury : SupportedNetwork { public Ogury() : base("Ogury") { } } public class Pangle : SupportedNetwork { public Pangle() : base("Pangle") { } } public class Snap : SupportedNetwork { public Snap() : base("SnapAd") { } } public class Tapjoy : SupportedNetwork { public Tapjoy() : base("Tapjoy") { } } public class Unity : SupportedNetwork { public Unity() : base("UnityAds") { } } public class Verizon : SupportedNetwork { public Verizon() : base("Verizon") { } } public class Vungle : SupportedNetwork { public Vungle() : base("Vungle") { } } } public struct Reward { public string Label; public int Amount; public override string ToString() { return String.Format("\"{0} {1}\"", Amount, Label); } public bool IsValid() { return !String.IsNullOrEmpty(Label) && Amount > 0; } } public struct ImpressionData { public string AppVersion; public string AdUnitId; public string AdUnitName; public string AdUnitFormat; public string ImpressionId; public string Currency; public double? PublisherRevenue; public string AdGroupId; public string AdGroupName; public string AdGroupType; public int? AdGroupPriority; public string Country; public string Precision; public string NetworkName; public string NetworkPlacementId; public string JsonRepresentation; public static ImpressionData FromJson(string json) { var impData = new ImpressionData(); if (string.IsNullOrEmpty(json)) return impData; var fields = MJ.Json.Deserialize(json) as Dictionary<string, object>; if (fields == null) return impData; object obj; double parsedDouble; int parsedInt; if (fields.TryGetValue("app_version", out obj) && obj != null) impData.AppVersion = obj.ToString(); if (fields.TryGetValue("adunit_id", out obj) && obj != null) impData.AdUnitId = obj.ToString(); if (fields.TryGetValue("adunit_name", out obj) && obj != null) impData.AdUnitName = obj.ToString(); if (fields.TryGetValue("adunit_format", out obj) && obj != null) impData.AdUnitFormat = obj.ToString(); if (fields.TryGetValue("id", out obj) && obj != null) impData.ImpressionId = obj.ToString(); if (fields.TryGetValue("currency", out obj) && obj != null) impData.Currency = obj.ToString(); if (fields.TryGetValue("publisher_revenue", out obj) && obj != null && double.TryParse(MoPubUtils.InvariantCultureToString(obj), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedDouble)) impData.PublisherRevenue = parsedDouble; if (fields.TryGetValue("adgroup_id", out obj) && obj != null) impData.AdGroupId = obj.ToString(); if (fields.TryGetValue("adgroup_name", out obj) && obj != null) impData.AdGroupName = obj.ToString(); if (fields.TryGetValue("adgroup_type", out obj) && obj != null) impData.AdGroupType = obj.ToString(); if (fields.TryGetValue("adgroup_priority", out obj) && obj != null && int.TryParse(MoPubUtils.InvariantCultureToString(obj), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedInt)) impData.AdGroupPriority = parsedInt; if (fields.TryGetValue("country", out obj) && obj != null) impData.Country = obj.ToString(); if (fields.TryGetValue("precision", out obj) && obj != null) impData.Precision = obj.ToString(); if (fields.TryGetValue("network_name", out obj) && obj != null) impData.NetworkName = obj.ToString(); if (fields.TryGetValue("network_placement_id", out obj) && obj != null) impData.NetworkPlacementId = obj.ToString(); impData.JsonRepresentation = json; return impData; } } // Data structure to register and initialize a mediated network. public class MediatedNetwork { public string AdapterConfigurationClassName { get; set; } public string MediationSettingsClassName { get; set; } public Dictionary<string, string> NetworkConfiguration { get; set; } public Dictionary<string, object> MediationSettings { get; set; } public Dictionary<string, string> MoPubRequestOptions { get; set; } } }
37.289954
130
0.57393
[ "Apache-2.0" ]
JunGroupProductions/mopub-unity-sdk
unity-sample-app/Assets/MoPub/Scripts/MoPubBase.cs
16,335
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Requests the group's voice messaging settings /// The response is either GroupVoiceMessagingGroupGetVoicePortalResponse14 or ErrorResponse. /// Replaced by GroupVoiceMessagingGroupGetVoicePortalRequest15 /// <see cref="GroupVoiceMessagingGroupGetVoicePortalResponse14"/> /// <see cref="ErrorResponse"/> /// <see cref="GroupVoiceMessagingGroupGetVoicePortalRequest15"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:16201""}]")] public class GroupVoiceMessagingGroupGetVoicePortalRequest14 : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.GroupVoiceMessagingGroupGetVoicePortalResponse14> { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:16201")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _groupId; [XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:16201")] [MinLength(1)] [MaxLength(30)] public string GroupId { get => _groupId; set { GroupIdSpecified = true; _groupId = value; } } [XmlIgnore] protected bool GroupIdSpecified { get; set; } } }
32.8125
193
0.648095
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupVoiceMessagingGroupGetVoicePortalRequest14.cs
2,100
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace BeforeWebForms.ControlSamples.GridView { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } // The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public List<Customer> GetCustomers() { var customers = new List<Customer>(); var c1 = new Customer { CustomerID = 1, FirstName = "John", LastName = "Smith", CompanyName = "Virus" }; var c2 = new Customer { CustomerID = 2, FirstName = "Jose", LastName = "Rodriguez", CompanyName = "Boring" }; var c3 = new Customer { CustomerID = 3, FirstName = "Jason", LastName = "Ramirez", CompanyName = "Fun Machines" }; customers.Add(c1); customers.Add(c2); customers.Add(c3); return customers; } } }
18.934426
70
0.649351
[ "MIT" ]
FritzAndFriends/BlazorWebFormsComponents
samples/BeforeWebForms/ControlSamples/GridView/Default.aspx.cs
1,157
C#
using OfficeDevPnP.SPOnline.CmdletHelpAttributes; using OfficeDevPnP.SPOnline.Commands.Base; using Microsoft.SharePoint.Client; using System.Management.Automation; using System; namespace OfficeDevPnP.SPOnline.Commands { [Cmdlet(VerbsCommon.Set, "SPOMinimalDownloadStrategy")] [CmdletHelp("Activates or deactivates the minimal downloading strategy.")] public class SetMDS : SPOWebCmdlet { [Parameter(ParameterSetName = "On", Mandatory = true)] public SwitchParameter On; [Parameter(ParameterSetName = "Off", Mandatory = true)] public SwitchParameter Off; [Parameter(Mandatory = false)] public SwitchParameter Force; protected override void ExecuteCmdlet() { if (On) { this.SelectedWeb.Features.Add(new Guid(Properties.Resources.MDSFeatureGuid), Force, FeatureDefinitionScope.None); } else { this.SelectedWeb.Features.Remove(new Guid(Properties.Resources.MDSFeatureGuid), Force); } ClientContext.ExecuteQuery(); } } }
30.567568
129
0.656057
[ "Apache-2.0" ]
HappySolutions/PnP
Solutions/OfficeDevPnP.SPOnline/Commands/Web/SetMDS.cs
1,133
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Lextm.SharpSnmpLib.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lextm.SharpSnmpLib.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] SNMPV2_CONF { get { object obj = ResourceManager.GetObject("SNMPV2_CONF", resourceCulture); return ((byte[])(obj)); } } internal static byte[] SNMPV2_MIB { get { object obj = ResourceManager.GetObject("SNMPV2_MIB", resourceCulture); return ((byte[])(obj)); } } internal static byte[] SNMPV2_SMI { get { object obj = ResourceManager.GetObject("SNMPV2_SMI", resourceCulture); return ((byte[])(obj)); } } internal static byte[] SNMPV2_TC { get { object obj = ResourceManager.GetObject("SNMPV2_TC", resourceCulture); return ((byte[])(obj)); } } internal static byte[] SNMPV2_TM { get { object obj = ResourceManager.GetObject("SNMPV2_TM", resourceCulture); return ((byte[])(obj)); } } } }
40.454545
185
0.556305
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/sharpsnmp/SharpSnmpLib/Properties/Resources.Designer.cs
4,007
C#
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Fabric; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceFabric.Actors.Runtime; namespace Termite { [EventSource(Name = "MyCompany-TermiteModel-Termite")] internal sealed class ActorEventSource : EventSource { public static readonly ActorEventSource Current = new ActorEventSource(); static ActorEventSource() { // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized. // This problem will be fixed in .NET Framework 4.6.2. Task.Run(() => { }); } // Instance constructor is private to enforce singleton semantics private ActorEventSource() : base() { } #region Keywords // Event keywords can be used to categorize events. // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property). // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them. public static class Keywords { public const EventKeywords HostInitialization = (EventKeywords)0x1L; } #endregion #region Events // Define an instance method for each event you want to record and apply an [Event] attribute to it. // The method name is the name of the event. // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed). // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event. // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent(). // Put [NonEvent] attribute on all methods that do not define an event. // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx [NonEvent] public void Message(string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); Message(finalMessage); } } private const int MessageEventId = 1; [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] public void Message(string message) { if (this.IsEnabled()) { WriteEvent(MessageEventId, message); } } [NonEvent] public void ActorMessage(Actor actor, string message, params object[] args) { if (this.IsEnabled() && actor.Id != null && actor.ActorService != null && actor.ActorService.Context != null && actor.ActorService.Context.CodePackageActivationContext != null) { string finalMessage = string.Format(message, args); ActorMessage( actor.GetType().ToString(), actor.Id.ToString(), actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.PartitionId, actor.ActorService.Context.ReplicaId, actor.ActorService.Context.NodeContext.NodeName, finalMessage); } } // For very high-frequency events it might be advantageous to raise events using WriteEventCore API. // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code. // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties. private const int ActorMessageEventId = 2; [Event(ActorMessageEventId, Level = EventLevel.Informational, Message = "{9}")] private #if UNSAFE unsafe #endif void ActorMessage( string actorType, string actorId, string applicationTypeName, string applicationName, string serviceTypeName, string serviceName, Guid partitionId, long replicaOrInstanceId, string nodeName, string message) { #if !UNSAFE WriteEvent( ActorMessageEventId, actorType, actorId, applicationTypeName, applicationName, serviceTypeName, serviceName, partitionId, replicaOrInstanceId, nodeName, message); #else const int numArgs = 10; fixed (char* pActorType = actorType, pActorId = actorId, pApplicationTypeName = applicationTypeName, pApplicationName = applicationName, pServiceTypeName = serviceTypeName, pServiceName = serviceName, pNodeName = nodeName, pMessage = message) { EventData* eventData = stackalloc EventData[numArgs]; eventData[0] = new EventData { DataPointer = (IntPtr) pActorType, Size = SizeInBytes(actorType) }; eventData[1] = new EventData { DataPointer = (IntPtr) pActorId, Size = SizeInBytes(actorId) }; eventData[2] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) }; eventData[3] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) }; eventData[4] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) }; eventData[5] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) }; eventData[6] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) }; eventData[7] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) }; eventData[8] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) }; eventData[9] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) }; WriteEventCore(ActorMessageEventId, numArgs, eventData); } #endif } private const int ActorHostInitializationFailedEventId = 3; [Event(ActorHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Actor host initialization failed", Keywords = Keywords.HostInitialization)] public void ActorHostInitializationFailed(string exception) { WriteEvent(ActorHostInitializationFailedEventId, exception); } #endregion #region Private Methods #if UNSAFE private int SizeInBytes(string s) { if (s == null) { return 0; } else { return (s.Length + 1) * sizeof(char); } } #endif #endregion } }
45.464706
258
0.603053
[ "MIT" ]
Haishi2016/ProgrammingServiceFabric
V1-Samples/Chapter-18/TermiteModel/Termite/ActorEventSource.cs
7,731
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; public partial class Components1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties : Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IComponents1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IComponents1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalpropertiesInternal { /// <summary> /// Creates an new <see cref="Components1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties" /> instance. /// </summary> public Components1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties() { } } public partial interface IComponents1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties : Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IJsonSerializable { } internal partial interface IComponents1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalpropertiesInternal { } }
44.571429
160
0.792468
[ "MIT" ]
Arsasana/azure-powershell
src/Functions/generated/api/Models/Api20190801/Components1Tr4JxgSchemasContinuouswebjobPropertiesSettingsAdditionalproperties.cs
1,221
C#
using System; using UnityEngine; using UnityEngine.UI; namespace MenuSystem.Components { public class IntField : MonoBehaviour { public event FieldChangedHandler OnChanged; public int Min = 0; public int Max = 100; public string PresetSuffix = ""; public float[] Presets = null; [Space(3)] [SerializeField] private Text _valueText = null; [SerializeField] private Button _expandBtn = null; [SerializeField] private int _startValue = 50; public int Value => int.Parse(_valueText.text); public float Normalized => (float)(Value - Min) / (Max - Min); public bool Interactable { get => _expandBtn.interactable; set => _expandBtn.interactable = value; } private void Start() { SetValue(_startValue); _expandBtn.onClick.AddListener(Expand); } private void Expand() => SliderMenu.Use(this); public void SetValue(int value) { value = Mathf.Clamp(value, Min, Max); _valueText.text = value.ToString(); OnChanged?.Invoke(value); } public void SetValue(float value) { var actualValue = ((Max - Min) * value) + Min; var val = (int)Math.Round(actualValue); SetValue(val); } } public delegate void FieldChangedHandler(int value); }
26.763636
70
0.569293
[ "BSD-3-Clause" ]
empire-ai/Unity-Menusystem
Assets/Menu System/Scripts/Component Scripts/IntField.cs
1,474
C#
namespace ClassLib058 { public class Class039 { public static string Property => "ClassLib058"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib058/Class039.cs
120
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; class Utils { public static long GetTime() { return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; } public static bool IsRemoteObject(GameObject go) { MocapRigidBodyTransformer transformer = go.GetComponent<MocapRigidBodyTransformer>(); return transformer != null; } public static string GetHrri(GameObject go) { HrriComponent hrriComponent = go.GetComponent<HrriComponent>(); return hrriComponent ? hrriComponent.hrri : null; } public static void ChangeObjectMaterial(GameObject go, Material material) { go.GetComponentsInChildren<Renderer>().ToList().ForEach(r => { if (r.gameObject.name != "Line" && r.gameObject.name != "Head") { r.material = material; } }); } public static void ChangeAlpha(GameObject go, float alpha) { Renderer[] renderers = go.GetComponentsInChildren<Renderer>(); foreach (var rend in renderers.ToList()) if (rend) { // Change the material of all hit colliders // to use a transparent shader. Shader s = Shader.Find("Transparent/Diffuse"); rend.material.shader = s; Color tempColor = rend.material.color; tempColor.a = alpha; rend.material.color = tempColor; } } public static void ChangeObjectLayer(GameObject go, int layer) { go.GetComponentsInChildren<Transform>().ToList().ForEach(c => { //Debug.Log("component.gameObject: " + c.gameObject.name); c.gameObject.layer = layer; }); } }
29.936508
93
0.598621
[ "MIT" ]
jonasauda/im_in_control
vr_app/Assets/Scripts/Utils.cs
1,888
C#
namespace Zapdate.Server.Core.Errors { public enum ErrorCode { // code 0 to 1000 are reserved for infrastructure FieldValidation = 1000, UserNotFound, InvalidPassword, InvalidToken, InvalidKeyPassword, UpdatePackageWithVersionAlreadyExists, ProjectNotFound, UpdatePackageNotFound, Identity_DefaultError = 1500, Identity_ConcurrencyFailure, Identity_PasswordMismatch, Identity_InvalidToken, Identity_LoginAlreadyAssociated, Identity_InvalidUserName, Identity_InvalidEmail, Identity_DuplicateUserName, Identity_DuplicateEmail, Identity_InvalidRoleName, Identity_DuplicateRoleName, Identity_UserAlreadyHasPassword, Identity_UserLockoutNotEnabled, Identity_UserAlreadyInRole, Identity_UserNotInRole, Identity_PasswordTooShort, Identity_PasswordRequiresNonAlphanumeric, Identity_PasswordRequiresDigit, Identity_PasswordRequiresLower, Identity_PasswordRequiresUpper, FileNotFound = 2000, } }
28.525
57
0.694128
[ "MIT" ]
Anapher/Zapdate
src/Zapdate.Server.Core/Errors/ErrorCode.cs
1,141
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net; using Amazon.Redshift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeEvents operation /// </summary> internal class DescribeEventsResponseUnmarshaller : XmlResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { DescribeEventsResponse response = new DescribeEventsResponse(); while (context.Read()) { if (context.IsStartElement) { if(context.TestExpression("DescribeEventsResult", 2)) { response.DescribeEventsResult = DescribeEventsResultUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context); } } } return response; } public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); return new AmazonRedshiftException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DescribeEventsResponseUnmarshaller instance; public static DescribeEventsResponseUnmarshaller GetInstance() { if (instance == null) { instance = new DescribeEventsResponseUnmarshaller(); } return instance; } } }
35.675325
163
0.62541
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.Redshift/Model/Internal/MarshallTransformations/DescribeEventsResponseUnmarshaller.cs
2,747
C#
using HtmlAgilityPack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using TVS.API; namespace TVSPlayer { public enum TorrentQuality { Standart, HD, FHD, UHD } public class Torrent { public string Magnet { get; set; } public string Name { get; set; } public TorrentQuality Quality { get; set; } public int Seeders { get; set; } public int Leech { get; set; } public string Size { get; set; } public Series Series { get; set; } public int seriesId; public int episodeId; public string URL { get; set; } public Episode Episode { get; set; } public bool HasFinished { get; set; } = false; public bool IsSequential { get; set; } = false; public string FinishedAt { get; set; } = "-"; /// <summary> /// Searches for torrents with any quality. Use with causion - you might get banned /// </summary> /// <param name="series">Series to search for</param> /// <param name="episode">Episode to serach for</param> /// <returns></returns> public async static Task<List<Torrent>> Search(Series series, Episode episode) { return await Task.Run(() => { string url = GetUrl(series.seriesName, episode.airedSeason, episode.airedEpisodeNumber); HtmlWeb htmlWeb = new HtmlWeb(); HtmlDocument htmlDocument = htmlWeb.Load(url); List<HtmlNode> rows = new List<HtmlNode>(); try { rows = htmlDocument.DocumentNode.SelectSingleNode("//table").ChildNodes[3].SelectNodes("//tr").ToList(); } catch (Exception) { return null; } rows.RemoveAt(0); List<Torrent> tList = new List<Torrent>(); foreach (HtmlNode row in rows) { Torrent t = new Torrent(); t.Quality = TorrentQuality.Standart; t.Name = row.ChildNodes[1].ChildNodes[1].InnerHtml; if (t.Name.Contains("720p")) { t.Quality = TorrentQuality.HD; } if (t.Name.Contains("1080p")) { t.Quality = TorrentQuality.FHD; } if (t.Name.Contains("2160p")) { t.Quality = TorrentQuality.UHD; } t.URL = "http://1337x.to" + row.ChildNodes[1].ChildNodes[1].Attributes[0].Value; t.Seeders = Int32.Parse(row.ChildNodes[3].InnerText); t.Leech = Int32.Parse(row.ChildNodes[5].InnerText); t.Size = row.ChildNodes[9].ChildNodes[0].InnerText; t.Series = series; t.Episode = episode; tList.Add(t); } return tList; }); } /// <summary> /// Searches 1337x.to for torrents with specified quality. Use with causion - you might get banned /// </summary> /// <param name="series">Series to search for</param> /// <param name="episode">Episode to search for</param> /// <param name="quality">Quality to search for</param> /// <returns></returns> public async static Task<List<Torrent>> Search(Series series, Episode episode, TorrentQuality quality) { return (await Search(series, episode))?.Where(x => x.Quality == quality).ToList(); } /// <summary> /// Searches 1337x.to for a single torrent with any quality. Use with causion - you might get banned /// </summary> /// <param name="series">Series to search for</param> /// <param name="episode">Episode to search for</param> /// <returns>The one with most seeders</returns> public async static Task<Torrent> SearchSingle(Series series, Episode episode) { return (await Search(series, episode))?.OrderByDescending(x => x.Seeders).FirstOrDefault(); } /// <summary> /// Searches 1337x.to for a single torrent with specified quality. Use with causion - you might get banned /// </summary> /// <param name="series">Series to search for</param> /// <param name="episode">Episode to search for</param> /// <param name="quality">Quality to search for</param> /// <returns>The one with most seeders</returns> public async static Task<Torrent> SearchSingle(Series series, Episode episode, TorrentQuality quality) { var tor = await Search(series, episode); if (tor != null) { return tor.Where(x => x.Quality == quality).OrderByDescending(x => x.Seeders).FirstOrDefault(); } return null; } private static string GetUrl(string show, int? season, int? episode) { string url = RemoveYear(show).Replace(" ", "+"); if (season < 10) { url += episode < 10 ? "+S0" + season + "E0" + episode : "+S0" + season + "E" + episode; } else { url += episode < 10 ? "+S" + season + "E0" + episode : "+S" + season + "E" + episode; } return "http://1337x.to/search/" + url + "/1/"; } private static string RemoveYear(string text) { Regex reg = new Regex(@"\([0-9]{4}\)"); Match regMatch = reg.Match(text); return regMatch.Success ? reg.Replace(text, "") : text; } } }
43.94697
124
0.545078
[ "MIT" ]
Kaharonus/TVS-Player
TVSPlayer/Classes/Torrent.cs
5,803
C#
using System; using System.Threading.Tasks; using CSharpFunctionalExtensions; using Microsoft.AspNetCore.Mvc; namespace CreditService.WebApi.Extensions { public static class HttpExtensions { public static async Task<IActionResult> ToHttpResponse<T>(this Task<Result<T>> task) { try { var result = await task; return result.IsSuccess ? (IActionResult)new OkObjectResult(result.Value) : (IActionResult)new BadRequestObjectResult(result.Error); } catch (Exception) { throw; } } } }
25.111111
92
0.563422
[ "MIT" ]
TheRisingEdge/CreditService
CreditService/CreditService.WebApi/Extensions/HttpExtensions.cs
680
C#
using Sandbox.Jobs; using System.Collections.Generic; namespace Sandbox.Jobs.Category { public class JobsCategory : NetworkComponent { public string Name { get; } public string Description { get; } public string Icon { get; } public List<Job> JobsList { get; } public int JobsCount {get; private set;} public JobsCategory( string Name, string Description = "", string Icon = "" ) { this.Name = Name; this.Description = Description; this.Icon = $"materials/xnrp/categ/{Icon}"; this.JobsList = new(); } public void AddJob( Job job ) { this.JobsList.Add( job ); if(job.ShowInJobMenu == true) this.JobsCount++; } public void AddBulkJobs( params Job[] list ) { foreach ( Job job in list ) { this.AddJob( job ); } } } }
29
109
0.676393
[ "MIT" ]
rayzox57000/xnrp
code/jobCategory/JobsCategory.cs
754
C#
// =============================================================================== // Alachisoft (R) NosDB Sample Code. // =============================================================================== // Copyright © Alachisoft. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. // =============================================================================== using System; namespace NosDB.Samples.EntityObjects { public class OrderDetail { public long ProductID { get; set; } public double UnitPrice { get; set; } public short Quantity { get; set; } public Single Discount { get; set; } } }
35.041667
83
0.485137
[ "Apache-2.0" ]
Alachisoft/NosDB-Samples
samples/dotnet/EntityObjects/EntityObjects/OrderDetail.cs
844
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; using System.IO; using Microsoft.Kusto.ServiceLayer.QueryExecution.Contracts; namespace Microsoft.Kusto.ServiceLayer.QueryExecution.DataStorage { /// <summary> /// Abstract class for implementing writers that save results to file. Stores some basic info /// that all save as writer would need. /// </summary> public abstract class SaveAsStreamWriter : IFileStreamWriter { /// <summary> /// Stores the internal state for the writer that will be necessary for any writer. /// </summary> /// <param name="stream">The stream that will be written to</param> /// <param name="requestParams">The SaveAs request parameters</param> protected SaveAsStreamWriter(Stream stream, SaveResultsRequestParams requestParams) { FileStream = stream; var saveParams = requestParams; if (requestParams.IsSaveSelection) { // ReSharper disable PossibleInvalidOperationException IsSaveSelection verifies these values exist ColumnStartIndex = saveParams.ColumnStartIndex.Value; ColumnEndIndex = saveParams.ColumnEndIndex.Value; ColumnCount = saveParams.ColumnEndIndex.Value - saveParams.ColumnStartIndex.Value + 1; // ReSharper restore PossibleInvalidOperationException } } #region Properties /// <summary> /// Index of the first column to write to the output file /// </summary> protected int? ColumnStartIndex { get; private set; } /// <summary> /// Number of columns to write to the output file /// </summary> protected int? ColumnCount { get; private set; } /// <summary> /// Index of the last column to write to the output file /// </summary> protected int? ColumnEndIndex { get; private set; } /// <summary> /// The file stream to use to write the output file /// </summary> protected Stream FileStream { get; private set; } #endregion /// <summary> /// Not implemented, do not use. /// </summary> [Obsolete] public int WriteRow(StorageDataReader dataReader) { throw new InvalidOperationException("This type of writer is meant to write values from a list of cell values only."); } /// <summary> /// Writes a row of data to the output file using the format provided by the implementing class. /// </summary> /// <param name="row">The row of data to output</param> /// <param name="columns">The list of columns to output</param> public abstract void WriteRow(IList<DbCellValue> row, IList<DbColumnWrapper> columns); /// <summary> /// Not implemented, do not use. /// </summary> [Obsolete] public void Seek(long offset) { throw new InvalidOperationException("SaveAs writers are meant to be written once contiguously."); } /// <summary> /// Flushes the file stream buffer /// </summary> public void FlushBuffer() { FileStream.Flush(); } #region IDisposable Implementation private bool disposed; /// <summary> /// Disposes the instance by flushing and closing the file stream /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { FileStream.Dispose(); } disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
32.927419
129
0.592946
[ "MIT" ]
ConnectionMaster/sqltoolsservice
src/Microsoft.Kusto.ServiceLayer/QueryExecution/DataStorage/SaveAsWriterBase.cs
4,085
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Requests the details of a specified service pack migration task. /// The response is either ServiceProviderServicePackMigrationTaskGetResponse14sp4 /// or ErrorResponse. /// /// Replaced By: ServiceProviderServicePackMigrationTaskGetRequest21 in AS data mode /// <see cref="ServiceProviderServicePackMigrationTaskGetResponse14sp4"/> /// <see cref="ErrorResponse"/> /// <see cref="ServiceProviderServicePackMigrationTaskGetRequest21"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""de4d76f01f337fe4694212ec9f771753:2874""}]")] public class ServiceProviderServicePackMigrationTaskGetRequest14sp4 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"de4d76f01f337fe4694212ec9f771753:2874")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _taskName; [XmlElement(ElementName = "taskName", IsNullable = false, Namespace = "")] [Group(@"de4d76f01f337fe4694212ec9f771753:2874")] [MinLength(1)] [MaxLength(80)] public string TaskName { get => _taskName; set { TaskNameSpecified = true; _taskName = value; } } [XmlIgnore] protected bool TaskNameSpecified { get; set; } } }
31.878788
130
0.638783
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/ServiceProviderServicePackMigrationTaskGetRequest14sp4.cs
2,104
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("RutokenPkcs11Interop.Tests.Resource", IsApplication=true)] namespace RutokenPkcs11Interop.Tests { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::RutokenPkcs11Interop.Tests.Resource.Id.OptionHostName; global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::RutokenPkcs11Interop.Tests.Resource.Id.OptionPort; global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::RutokenPkcs11Interop.Tests.Resource.Id.OptionRemoteServer; global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::RutokenPkcs11Interop.Tests.Resource.Id.OptionsButton; global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultFullName; global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultMessage; global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultResultState; global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultRunSingleMethodTest; global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultStackTrace; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsFailed; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsId; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsIgnored; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsInconclusive; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsMessage; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsPassed; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::RutokenPkcs11Interop.Tests.Resource.Id.ResultsResult; global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::RutokenPkcs11Interop.Tests.Resource.Id.RunTestsButton; global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::RutokenPkcs11Interop.Tests.Resource.Id.TestSuiteListView; global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::RutokenPkcs11Interop.Tests.Resource.Layout.options; global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::RutokenPkcs11Interop.Tests.Resource.Layout.results; global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::RutokenPkcs11Interop.Tests.Resource.Layout.test_result; global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::RutokenPkcs11Interop.Tests.Resource.Layout.test_suite; } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050001 public const int OptionHostName = 2131034113; // aapt resource value: 0x7f050002 public const int OptionPort = 2131034114; // aapt resource value: 0x7f050000 public const int OptionRemoteServer = 2131034112; // aapt resource value: 0x7f050010 public const int OptionsButton = 2131034128; // aapt resource value: 0x7f05000b public const int ResultFullName = 2131034123; // aapt resource value: 0x7f05000d public const int ResultMessage = 2131034125; // aapt resource value: 0x7f05000c public const int ResultResultState = 2131034124; // aapt resource value: 0x7f05000a public const int ResultRunSingleMethodTest = 2131034122; // aapt resource value: 0x7f05000e public const int ResultStackTrace = 2131034126; // aapt resource value: 0x7f050006 public const int ResultsFailed = 2131034118; // aapt resource value: 0x7f050003 public const int ResultsId = 2131034115; // aapt resource value: 0x7f050007 public const int ResultsIgnored = 2131034119; // aapt resource value: 0x7f050008 public const int ResultsInconclusive = 2131034120; // aapt resource value: 0x7f050009 public const int ResultsMessage = 2131034121; // aapt resource value: 0x7f050005 public const int ResultsPassed = 2131034117; // aapt resource value: 0x7f050004 public const int ResultsResult = 2131034116; // aapt resource value: 0x7f05000f public const int RunTestsButton = 2131034127; // aapt resource value: 0x7f050011 public const int TestSuiteListView = 2131034129; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int options = 2130903040; // aapt resource value: 0x7f030001 public const int results = 2130903041; // aapt resource value: 0x7f030002 public const int test_result = 2130903042; // aapt resource value: 0x7f030003 public const int test_suite = 2130903043; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f040000 public const int ApplicationName = 2130968576; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
35.317708
150
0.73352
[ "Apache-2.0" ]
pavelkhrulev/RutokenPkcs11Interop
src/RutokenPkcs11Interop.Android/RutokenPkcs11Interop.Android.Tests/Resources/Resource.Designer.cs
6,781
C#
namespace Bell54 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.label1 = new System.Windows.Forms.Label(); this.timeLabel = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.listView1 = new System.Windows.Forms.ListView(); this.button3 = new System.Windows.Forms.Button(); this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button4 = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.button5 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.button8 = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog2 = new System.Windows.Forms.OpenFileDialog(); this.SuspendLayout(); // // button1 // this.button1.Enabled = false; this.button1.Location = new System.Drawing.Point(13, 13); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "START"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(95, 12); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 1; this.button2.Text = "STOP"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 1000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(488, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(60, 24); this.label1.TabIndex = 2; this.label1.Text = "TIME:"; // // timeLabel // this.timeLabel.AutoSize = true; this.timeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.timeLabel.Location = new System.Drawing.Point(554, 13); this.timeLabel.Name = "timeLabel"; this.timeLabel.Size = new System.Drawing.Size(60, 24); this.timeLabel.TabIndex = 3; this.timeLabel.Text = "TIME:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.Green; this.label3.Location = new System.Drawing.Point(311, 10); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(50, 24); this.label3.TabIndex = 6; this.label3.Text = "RUN"; this.label3.Click += new System.EventHandler(this.label3_Click); // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(216, 12); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(89, 24); this.label4.TabIndex = 5; this.label4.Text = "STATUS:"; this.label4.Click += new System.EventHandler(this.label4_Click); // // listView1 // this.listView1.FullRowSelect = true; this.listView1.GridLines = true; this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listView1.HideSelection = false; this.listView1.LabelWrap = false; this.listView1.Location = new System.Drawing.Point(13, 42); this.listView1.MultiSelect = false; this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(1210, 334); this.listView1.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listView1.TabIndex = 7; this.listView1.UseCompatibleStateImageBehavior = false; // // button3 // this.button3.Location = new System.Drawing.Point(73, 452); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 8; this.button3.Text = "Add Item"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.addItem); // // dateTimePicker1 // this.dateTimePicker1.CustomFormat = "HH:mm:ss"; this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dateTimePicker1.Location = new System.Drawing.Point(73, 396); this.dateTimePicker1.Name = "dateTimePicker1"; this.dateTimePicker1.ShowUpDown = true; this.dateTimePicker1.Size = new System.Drawing.Size(81, 20); this.dateTimePicker1.TabIndex = 9; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(16, 402); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(33, 13); this.label5.TabIndex = 10; this.label5.Text = "Time:"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(16, 431); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(51, 13); this.label6.TabIndex = 11; this.label6.Text = "MP3 File:"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(73, 426); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(299, 20); this.textBox1.TabIndex = 12; // // button4 // this.button4.Location = new System.Drawing.Point(297, 452); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 23); this.button4.TabIndex = 13; this.button4.Text = "Delete Item"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.deleteItem); // // openFileDialog1 // this.openFileDialog1.FileName = "openFileDialog1"; this.openFileDialog1.Filter = "MP3|*.mp3"; // // button5 // this.button5.Location = new System.Drawing.Point(378, 424); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(75, 23); this.button5.TabIndex = 14; this.button5.Text = "Choose MP3"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.chooseFile); // // button7 // this.button7.Location = new System.Drawing.Point(1016, 10); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(75, 23); this.button7.TabIndex = 18; this.button7.Text = "Test Sound"; this.button7.UseVisualStyleBackColor = true; this.button7.Click += new System.EventHandler(this.button7_Click); // // button8 // this.button8.Location = new System.Drawing.Point(658, 426); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(75, 23); this.button8.TabIndex = 19; this.button8.Text = "Save List"; this.button8.UseVisualStyleBackColor = true; this.button8.Click += new System.EventHandler(this.saveList); // // button9 // this.button9.Location = new System.Drawing.Point(752, 426); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(75, 23); this.button9.TabIndex = 20; this.button9.Text = "Load List"; this.button9.UseVisualStyleBackColor = true; this.button9.Click += new System.EventHandler(this.LoadList); // // saveFileDialog1 // this.saveFileDialog1.DefaultExt = "txt"; this.saveFileDialog1.Filter = "Bells List|*.csv"; // // openFileDialog2 // this.openFileDialog2.FileName = "openFileDialog2"; this.openFileDialog2.Filter = "Bells List|*.csv"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1235, 517); this.Controls.Add(this.button9); this.Controls.Add(this.button8); this.Controls.Add(this.button7); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.textBox1); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.dateTimePicker1); this.Controls.Add(this.button3); this.Controls.Add(this.listView1); this.Controls.Add(this.label3); this.Controls.Add(this.label4); this.Controls.Add(this.timeLabel); this.Controls.Add(this.label1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Bell54"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label timeLabel; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.Button button3; private System.Windows.Forms.DateTimePicker dateTimePicker1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button4; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button7; private System.Windows.Forms.Button button8; private System.Windows.Forms.Button button9; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.OpenFileDialog openFileDialog2; } }
45.235294
169
0.574267
[ "MIT" ]
mushketer888/Bell54
Bell54/Form1.Designer.cs
13,844
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Solnet.Programs; using Solnet.Rpc; using Solnet.Rpc.Builders; using Solnet.Rpc.Utilities; using Solnet.Rpc.Models; using Solnet.Wallet; using Solnet.Wallet.Bip39; using System.Collections.Generic; using System.Text; using System; using System.Threading; using Solnet.Metaplex; namespace Solnet.Metaplex.Test { [TestClass] public class MetatadaProgramTest { private string MnemonicWords = "volcano denial gloom bid lounge answer gas prevent deer magnet enrich message divide page slab category outer idle foster journey panel furnace brand leave"; public static void PrintByteArray(byte[] bytes) { var sb = new StringBuilder("\nnew byte[] { "); foreach (var b in bytes) { sb.Append(b + ", "); } sb.Append("}\n"); Console.WriteLine(sb.ToString()); } //[TestMethod] public void MintToken() { var rpcClient = ClientFactory.GetClient(Cluster.DevNet); //, logger); //1. connect to wallet var wallet = new Wallet.Wallet(MnemonicWords); var fromAccount = wallet.Account; var mintAccount = wallet.GetAccount(223); var tokenAccount = wallet.GetAccount(334); Console.WriteLine($"Wallet key : { fromAccount.PublicKey } "); var balance = rpcClient.GetBalance( wallet.Account.PublicKey ); Console.WriteLine($"Balance: {0} ", balance.Result.Value); Console.WriteLine($"Mint key : { mintAccount.PublicKey.ToString() } "); var blockHash = rpcClient.GetRecentBlockHash(); var rentMint = rpcClient.GetMinimumBalanceForRentExemption( TokenProgram.MintAccountDataSize, Rpc.Types.Commitment.Confirmed ); var rentToken = rpcClient.GetMinimumBalanceForRentExemption( TokenProgram.TokenAccountDataSize, Rpc.Types.Commitment.Confirmed ); Console.WriteLine($"Token key : { tokenAccount.PublicKey.ToString() } "); //2. create a mint and a token var instr1 = SystemProgram.CreateAccount( fromAccount, mintAccount, rentMint.Result, TokenProgram.MintAccountDataSize, TokenProgram.ProgramIdKey ); var instr2 = TokenProgram.InitializeMint( mintAccount.PublicKey, 0, fromAccount.PublicKey ); var instr3 = SystemProgram.CreateAccount( fromAccount, tokenAccount, rentToken.Result, TokenProgram.TokenAccountDataSize, TokenProgram.ProgramIdKey ); var instr4 = TokenProgram.InitializeAccount( tokenAccount.PublicKey, mintAccount.PublicKey, fromAccount.PublicKey ); var instr5 = TokenProgram.MintTo( mintAccount.PublicKey, tokenAccount, 1, fromAccount.PublicKey ); byte[] TX1 = new TransactionBuilder() .SetRecentBlockHash(blockHash.Result.Value.Blockhash) .SetFeePayer(fromAccount) .AddInstruction(instr1) // create .AddInstruction(instr2) // initMint .AddInstruction(instr3) // createaccount .AddInstruction(instr4) // initAccount .AddInstruction(instr5) // mintTo //.AddInstruction(instr6) // Create Metadata .Build(new List<Account> { fromAccount, mintAccount, tokenAccount }); Console.WriteLine($"TX1.Length { TX1.Length }"); var txSim = rpcClient.SimulateTransaction(TX1); Console.WriteLine($"Simulation: \n { txSim.RawRpcResponse } "); var tx = rpcClient.SendTransaction(TX1); Console.WriteLine($"Send: \n { tx.RawRpcResponse } "); } //[TestMethod] public void TestCreateMetadataAccount() { var rpcClient = ClientFactory.GetClient(Cluster.DevNet); //, logger); var blockHash = rpcClient.GetRecentBlockHash(); var wallet = new Wallet.Wallet(MnemonicWords); var fromAccount = wallet.Account; var mintAccount = wallet.GetAccount(223); var tokenAccount = wallet.GetAccount(334); //PDA METADATA byte[] metadataAddress = new byte[32]; int nonce; AddressExtensions.TryFindProgramAddress( new List<byte[]>() { Encoding.UTF8.GetBytes("metadata"), MetadataProgram.ProgramIdKey, mintAccount.PublicKey }, MetadataProgram.ProgramIdKey, out metadataAddress, out nonce ); Console.WriteLine($"PDA METADATA: {new PublicKey(metadataAddress)}"); //PDA MASTER EDITION byte[] masterEditionAddress = new byte[32]; //int nonce; AddressExtensions.TryFindProgramAddress( new List<byte[]>() { Encoding.UTF8.GetBytes("metadata"), MetadataProgram.ProgramIdKey, mintAccount.PublicKey, Encoding.UTF8.GetBytes("edition") }, MetadataProgram.ProgramIdKey, out masterEditionAddress, out nonce ); Console.WriteLine($"PDA MASTER: {new PublicKey(masterEditionAddress)}"); //CREATORS var c1 = new Creator( fromAccount.PublicKey, 50); var c2 = new Creator( wallet.GetAccount(101).PublicKey, 50, false); //DATA var data = new MetadataParameters() { name = "ja sam test", symbol = "A B C", uri = "http://lutrija.hr", creators = new List<Creator>() { c1 , c2 } , sellerFeeBasisPoints = 77 }; var TX2 = new TransactionBuilder() .SetRecentBlockHash(blockHash.Result.Value.Blockhash) .SetFeePayer(fromAccount) .AddInstruction( MetadataProgram.CreateMetadataAccount( new PublicKey(metadataAddress), //PDA mintAccount.PublicKey, //MINT fromAccount.PublicKey, //mint AUTHORITY fromAccount.PublicKey, //PAYER fromAccount.PublicKey, //update Authority data, //DATA true, true //ISMUTABLE ) ) // .AddInstruction( // MetadataProgram.SignMetada( // new PublicKey(metadataAddress), // c2.key // ) // ) .AddInstruction( MetadataProgram.PuffMetada( new PublicKey(metadataAddress) ) ) .AddInstruction( MetadataProgram.CreateMasterEdition( 1, new PublicKey(masterEditionAddress), mintAccount.PublicKey, fromAccount.PublicKey, fromAccount.PublicKey, fromAccount.PublicKey, new PublicKey(metadataAddress) ) ) .Build(new List<Account> { fromAccount, wallet.GetAccount(101) }); //var txSim2 = rpcClient.SimulateTransaction(TX2); //InstructionDecoder.Register(MetadataProgram.ProgramIdKey, MetadataProgram.Decode); //List<DecodedInstruction> decodedInstructions = InstructionDecoder.DecodeInstructions( TX2 ); //Console.WriteLine($"Transaction sim: \n { txSim2.RawRpcResponse }"); } [TestMethod] public void TestGetAndDecodeMessage() { var client = Solnet.Rpc.ClientFactory.GetClient(Solnet.Rpc.Cluster.MainNet); var res = client.GetConfirmedTransaction("3tpv4udpeQ9NZhCXRkVdPz7aJqqakLPurFTLtTR6Z7UEo9gtr7UCu9rLgFEfizYwB8sQHci9CTJdZex7qSsUr2EV"); //Thread.Sleep(3000); InstructionDecoder.Register(MetadataProgram.ProgramIdKey, MetadataProgram.Decode); List<DecodedInstruction> decodedInstructions = InstructionDecoder.DecodeInstructions(res.Result); foreach ( DecodedInstruction di in decodedInstructions ) { Console.WriteLine("\n Instruction: " + di.InstructionName); Console.WriteLine("Program: " + di.ProgramName ); foreach ( KeyValuePair<string,object> kv in di.Values) { Console.WriteLine("\t" + kv.Key + ": " + kv.Value.ToString()); if ( kv.Value is List<Creator> ) { foreach ( Creator c in (List<Creator>) kv.Value ) { Console.WriteLine( "\t\tCreator Key : " + c.key.ToString()); Console.WriteLine( "\t\tCreator Share : " + c.share.ToString()); Console.WriteLine( "\t\tCreator Verified : " + c.verified.ToString()); } } } } } } }
37.25188
197
0.528308
[ "MIT" ]
pavel-leonenko/Solnet.Metaplex
Solnet.Metaplex.Test/MetadataTest.cs
9,909
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the s3control-2018-08-20.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.S3Control { /// <summary> /// Configuration for accessing Amazon S3Control service /// </summary> public partial class AmazonS3ControlConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.104.8"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonS3ControlConfig() { this.AuthenticationServiceName = "s3"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "s3-control"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-08-20"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.125
107
0.586603
[ "Apache-2.0" ]
diegofrata/aws-sdk-net
sdk/src/Services/S3Control/Generated/AmazonS3ControlConfig.cs
2,090
C#
using UnityEngine; using System.Collections; // Draw simple instructions for sample scene. // Check to see if a Myo armband is paired. public class SampleSceneGUI : MonoBehaviour { // Myo game object to connect with. // This object must have a ThalmicMyo script attached. public GameObject myo = null; // Draw some basic instructions. void OnGUI () { GUI.skin.label.fontSize = 20; ThalmicHub hub = ThalmicHub.instance; // Access the ThalmicMyo script attached to the Myo object. ThalmicMyo thalmicMyo = myo.GetComponent<ThalmicMyo> (); if (!hub.hubInitialized) { GUI.Label(new Rect (12, 8, Screen.width, Screen.height), "Cannot contact Myo Connect. Is Myo Connect running?\n" + "Press Q to try again." ); } else if (!thalmicMyo.isPaired) { GUI.Label(new Rect (12, 8, Screen.width, Screen.height), "No Myo currently paired." ); } else if (!thalmicMyo.armSynced) { GUI.Label(new Rect (12, 8, Screen.width, Screen.height), "Perform the Sync Gesture." ); } else { GUI.Label (new Rect (12, 8, Screen.width, Screen.height), "Fist: Vibrate Myo armband\n" + "Wave in: Set box material to blue\n" + "Wave out: Set box material to green\n" + "Double tap: Reset box material\n" + "Fingers spread: Set forward direction" ); } } void Update () { ThalmicHub hub = ThalmicHub.instance; if (Input.GetKeyDown ("q")) { hub.ResetHub(); } } }
32.236364
74
0.539199
[ "MIT" ]
J0Nreynolds/MathematicaVR
unity_proj/Assets/Myo Samples/Scripts/SampleSceneGUI.cs
1,775
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Management; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Web; using Atk; using Gtk; using NewLife; using NewLife.Collections; using NewLife.Data; using NewLife.Reflection; using NewLife.Security; using NewLife.Serialization; using NewLife.Web; using XCoder.Util; using Object = System.Object; namespace XCoder.Tools { [DisplayName("加密解密")] public partial class FrmSecurity : HBox, IXForm { #region 窗体初始化 public FrmSecurity() { InitializeComponent(); // 动态调节宽度高度,兼容高DPI //this.FixDpi(); } #endregion #region 辅助 /// <summary>从字符串中获取字节数组</summary> /// <param name="str"></param> /// <returns></returns> private Byte[] GetBytes(String str) { if (str.IsNullOrEmpty()) return new Byte[0]; try { if (str.Contains("-")) return str.ToHex(); } catch { } try { return str.ToBase64(); } catch { } return str.GetBytes(); } /// <summary>从原文中获取字节数组</summary> /// <returns></returns> private Byte[] GetSource() { var v = rtSource.Buffer.Text; //if (rbString.Checked) return v.GetBytes(); //if (rbHex.Checked) return v.ToHex(); //if (rbBase64.Checked) return v.ToBase64(); return v.GetBytes(); } private void rtSource_TextChanged(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; if (v.IsNullOrEmpty()) return; //// 单字节 //var enc = Encoding.UTF8; //if (enc.GetByteCount(v) != v.Length) //{ // rbHex.Enabled = false; // rbBase64.Enabled = false; // return; //} //try //{ // rbHex.Enabled = v.ToHex().Length > 0; //} //catch //{ // rbHex.Enabled = false; //} //try //{ // rbBase64.Enabled = v.ToBase64().Length > 0; //} //catch //{ // rbBase64.Enabled = false; //} } private Byte[] GetPass() { var v = rtPass.Buffer.Text; //if (rbString2.Checked) return v.GetBytes(); //if (rbHex2.Checked) return v.ToHex(); //if (rbBase642.Checked) return v.ToBase64(); return v.GetBytes(); } private void SetResult(params String[] rs) { var sb = new StringBuilder(); foreach (var item in rs) { if (sb.Length > 0) sb.AppendLine(); sb.Append(item); } rtResult.Buffer.Text = sb.ToString(); //SaveConfig(); } private void SetResult(Byte[] data) { //SetResult("/*HEX编码、Base64编码、Url改进Base64编码*/", data.ToHex("-"), data.ToBase64(), data.ToUrlBase64()); var list = new List<String>(); //if (cbString.Checked) list.Add(data.ToStr()); //if (cbHex.Checked) { list.Add(data.ToHex("-")); list.Add(data.ToHex(" ")); } //if (cbBase64.Checked) { list.Add(data.ToBase64()); list.Add(data.ToUrlBase64()); } SetResult(list.ToArray()); } #endregion #region 功能 private void btnExchange_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; var v2 = rtResult.Buffer.Text; // 结果区只要第一行 if (!v2.IsNullOrEmpty()) { var ss = v2.Split("\n"); var n = 0; if (ss.Length > n + 1 && ss[n].StartsWith("/*") && ss[n].EndsWith("*/")) n++; v2 = ss[n]; } rtSource.Buffer.Text = v2; rtResult.Buffer.Text = v; } private void btnHex_Click(Object sender, EventArgs e) { var buf = GetSource(); //rtResult.Buffer.Text = buf.ToHex(" ", 32); SetResult(buf.ToHex(), buf.ToHex(" ", 32), buf.ToHex("-", 32)); } private void btnHex2_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; rtResult.Buffer.Text = v.ToHex().ToStr(); } private void btnB64_Click(Object sender, EventArgs e) { var buf = GetSource(); //rtResult.Buffer.Text = buf.ToBase64(); SetResult(buf.ToBase64(), buf.ToUrlBase64()); } private void btnB642_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; var vs = v.Split("."); if (vs.Length <= 1) { var buf = v.ToBase64(); SetResult(buf.ToStr(), buf.ToHex()); } else { SetResult(vs.Select(e => e.ToBase64().ToStr()).ToArray()); } } private void btnMD5_Click(Object sender, EventArgs e) { var buf = GetSource(); var str = buf.MD5().ToHex(); rtResult.Buffer.Text = str.ToUpper() + Environment.NewLine + str.ToLower(); } private void btnMD52_Click(Object sender, EventArgs e) { var buf = GetSource(); var str = buf.MD5().ToHex(0, 8); rtResult.Buffer.Text = str.ToUpper() + Environment.NewLine + str.ToLower(); } private void btnSHA1_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = GetPass(); buf = buf.SHA1(key); SetResult(buf); } private void btnSHA256_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = GetPass(); buf = buf.SHA256(key); SetResult(buf); } private void btnSHA384_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = GetPass(); buf = buf.SHA384(key); SetResult(buf); } private void btnSHA512_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = GetPass(); buf = buf.SHA512(key); SetResult(buf); } private void btnCRC_Click(Object sender, EventArgs e) { var buf = GetSource(); //rtResult.Buffer.Text = "{0:X8}\r\n{0}".F(buf.Crc()); var rs = buf.Crc(); buf = rs.GetBytes(false); SetResult("/*数字、HEX编码、Base64编码*/", rs + "", buf.ToHex(), buf.ToBase64()); } private void btnCRC2_Click(Object sender, EventArgs e) { var buf = GetSource(); //rtResult.Buffer.Text = "{0:X4}\r\n{0}".F(buf.Crc16()); var rs = buf.Crc16(); buf = rs.GetBytes(false); SetResult("/*数字、HEX编码、Base64编码*/", rs + "", buf.ToHex(), buf.ToBase64()); } private void btnDES_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); var des = new DESCryptoServiceProvider(); buf = des.Encrypt(buf, pass); SetResult(buf); } private void btnDES2_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); var des = new DESCryptoServiceProvider(); buf = des.Decrypt(buf, pass); SetResult(buf); } private void btnAES_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); var aes = new AesCryptoServiceProvider(); buf = aes.Encrypt(buf, pass); SetResult(buf); } private void btnAES2_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); var aes = new AesCryptoServiceProvider(); buf = aes.Decrypt(buf, pass); SetResult(buf); } private void btnRC4_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); buf = buf.RC4(pass); SetResult(buf); } private void btnRC42_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = GetPass(); buf = buf.RC4(pass); SetResult(buf); } private void btnRSA_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = rtPass.Buffer.Text; if (key.Length < 100) { key = RSAHelper.GenerateKey().First(); rtPass.Buffer.Text = key; } buf = RSAHelper.Encrypt(buf, key); SetResult(buf); } private void btnRSA2_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = rtPass.Buffer.Text; try { buf = RSAHelper.Decrypt(buf, pass, true); } catch (CryptographicException) { // 换一种填充方式 buf = RSAHelper.Decrypt(buf, pass, false); } SetResult(buf); } private void btnDSA_Click(Object sender, EventArgs e) { var buf = GetSource(); var key = rtPass.Buffer.Text; if (key.Length < 100) { key = DSAHelper.GenerateKey().First(); rtPass.Buffer.Text = key; } buf = DSAHelper.Sign(buf, key); SetResult(buf); } private void btnDSA2_Click(Object sender, EventArgs e) { var buf = GetSource(); var pass = rtPass.Buffer.Text; var v = rtResult.Buffer.Text; if (v.Contains("\n\n")) v = v.Substring(null, "\n\n"); var sign = GetBytes(v); var rs = DSAHelper.Verify(buf, pass, sign); if (rs) MessageBox.Show("DSA数字签名验证通过"); else MessageBox.Show("DSA数字签名验证失败"); } private void btnUrl_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; v = HttpUtility.UrlEncode(v); rtResult.Buffer.Text = v; } private void btnUrl2_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; v = HttpUtility.UrlDecode(v); rtResult.Buffer.Text = v; } private void btnHtml_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; v = HttpUtility.HtmlEncode(v); rtResult.Buffer.Text = v; } private void btnHtml2_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; v = HttpUtility.HtmlDecode(v); rtResult.Buffer.Text = v; } private void btnTime_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; if (v.IsNullOrEmpty()) return; var sb = Pool.StringBuilder.Get(); var dt = v.ToDateTime(); if (dt.Year > 1 && dt.Year < 3000) { sb.AppendLine("Unix秒:" + dt.ToInt()); sb.AppendLine("Unix毫秒:" + dt.ToLong()); } var now = DateTime.Now; var n = v.ToLong(); if (n >= Int32.MaxValue) { dt = n.ToDateTime(); if (dt.Year > 1000 && dt.Year < 3000) sb.AppendFormat("时间:{0:yyyy-MM-dd HH:mm:ss.fff} (Unix毫秒)\r\n", dt); //sb.AppendFormat("过去:{0:yyyy-MM-dd HH:mm:ss.fff}\r\n", now.AddMilliseconds(-n)); //sb.AppendFormat("未来:{0:yyyy-MM-dd HH:mm:ss.fff}\r\n", now.AddMilliseconds(n)); } else if (n > 0) { dt = v.ToInt().ToDateTime(); if (dt.Year > 1000 && dt.Year < 3000) sb.AppendFormat("时间:{0:yyyy-MM-dd HH:mm:ss} (Unix秒)\r\n", dt); //sb.AppendFormat("过去:{0:yyyy-MM-dd HH:mm:ss}\r\n", now.AddSeconds(-n)); //sb.AppendFormat("未来:{0:yyyy-MM-dd HH:mm:ss}\r\n", now.AddSeconds(n)); } // 有可能是过去时间或者未来时间戳 if (n > 0) { sb.AppendFormat("过去:{0:yyyy-MM-dd HH:mm:ss.fff} (now.AddMilliseconds(-n))\r\n", now.AddMilliseconds(-n)); sb.AppendFormat("未来:{0:yyyy-MM-dd HH:mm:ss.fff} (now.AddMilliseconds(n))\r\n", now.AddMilliseconds(n)); if (n < Int32.MaxValue) { sb.AppendFormat("过去:{0:yyyy-MM-dd HH:mm:ss} (now.AddSeconds(-n))\r\n", now.AddSeconds(-n)); sb.AppendFormat("未来:{0:yyyy-MM-dd HH:mm:ss} (now.AddSeconds(n))\r\n", now.AddSeconds(n)); } } rtResult.Buffer.Text = sb.Put(true); } private void btnSnowflake_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text.ToLong(); if (v <= 0) return; var snow = new Snowflake(); // 指定基准时间 if (!rtPass.Buffer.Text.IsNullOrEmpty()) { var baseTime = rtPass.Buffer.Text.ToDateTime(); if (baseTime.Year > 1000) snow.StartTimestamp = baseTime; } // 计算结果 { if (!snow.TryParse(v, out var time, out var workerId, out var sequence)) throw new Exception("解码失败!"); SetResult( $"基准:{snow.StartTimestamp:yyyy-MM-dd}", $"时间:{time.ToFullString()}", $"节点:{workerId} ({workerId:X4})", $"序号:{sequence} ({sequence:X4})"); } } private void btnJWT_Click(Object sender, EventArgs e) { var v = rtSource.Buffer.Text; if (v.IsNullOrEmpty()) return; var pass = rtPass.Buffer.Text?.Trim(); var vs = v.Split('.'); if (vs.Length == 3) { var jwt = new JwtBuilder { Secret = pass }; var rs = jwt.TryDecode(v, out var message); SetResult($"验证结果:{rs}", jwt.ToJson(true)); } else if (vs.Length == 2) { var prv = new TokenProvider { Key = pass }; var rs = prv.TryDecode(v, out var user, out var expire); SetResult($"验证结果:{rs}", new { user, expire }.ToJson(true)); } else { SetResult(vs.Select(e => e.ToBase64().ToStr()).ToArray()); } } #endregion #region 机器信息 private void BtnComputerInfo_Click(Object sender, EventArgs e) { var sb = Pool.StringBuilder.Get(); var mi = MachineInfo.Current; mi.Refresh(); sb.AppendLine(mi.ToJson(true)); sb.AppendLine(); var macs = GetMacs().ToList(); if (macs.Count > 0) sb.AppendFormat("MAC:\t{0}\r\n", macs.Join(",", x => x.ToHex("-"))); var processor = GetInfo("Win32_Processor", "Name"); /*if (!processor.IsNullOrEmpty())*/ sb.AppendFormat("Processor:\t{0}\t(Win32_Processor.Name)\r\n", processor); var cpuID = GetInfo("Win32_Processor", "ProcessorId"); /*if (!cpuID.IsNullOrEmpty())*/ sb.AppendFormat("ProcessorId:\t{0}\t(Win32_Processor.ProcessorId)\r\n", cpuID); var uuid = GetInfo("Win32_ComputerSystemProduct", "UUID"); /*if (!uuid.IsNullOrEmpty())*/ sb.AppendFormat("UUID:\t{0}\t(Win32_ComputerSystemProduct.UUID)\r\n", uuid); var id = GetInfo("Win32_ComputerSystemProduct", "IdentifyingNumber"); /*if (!id.IsNullOrEmpty())*/ sb.AppendFormat("IdentifyingNumber:\t{0}\t(Win32_ComputerSystemProduct.IdentifyingNumber)\r\n", id); var bios = GetInfo("Win32_BIOS", "SerialNumber"); /*if (!bios.IsNullOrEmpty())*/ sb.AppendFormat("BIOS:\t{0}\t(Win32_BIOS.SerialNumber)\r\n", bios); var baseBoard = GetInfo("Win32_BaseBoard", "SerialNumber"); /*if (!baseBoard.IsNullOrEmpty())*/ sb.AppendFormat("BaseBoard:\t{0}\t(Win32_BaseBoard.SerialNumber)\r\n", baseBoard); var serialNumber = GetInfo("Win32_DiskDrive", "SerialNumber"); /*if (!serialNumber.IsNullOrEmpty())*/ sb.AppendFormat("DiskSerial:\t{0}\t(Win32_DiskDrive.SerialNumber)\r\n", serialNumber); //var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); //if (reg != null) //{ // var guid = reg.GetValue("MachineGuid") + ""; // /*if (!guid.IsNullOrEmpty())*/ // sb.AppendFormat("MachineGuid:\t{0}\t(SOFTWARE\\Microsoft\\Cryptography)\r\n", guid); //} #if !NET4 && !__CORE__ sb.AppendLine(); var ci = new Microsoft.VisualBasic.Devices.ComputerInfo(); foreach (var pi in ci.GetType().GetProperties()) { //if (sb.Length > 0) sb.AppendLine(); sb.AppendFormat("{0}:\t{1:n0}\r\n", pi.Name, ci.GetValue(pi)); } #endif rtResult.Buffer.Text = sb.Put(true); } private static String[] _Excludes = new[] { "Loopback", "VMware", "VBox", "Virtual", "Teredo", "Microsoft", "VPN", "VNIC", "IEEE" }; /// <summary>获取所有网卡MAC地址</summary> /// <returns></returns> public static IEnumerable<Byte[]> GetMacs() { foreach (var item in NetworkInterface.GetAllNetworkInterfaces()) { if (_Excludes.Any(e => item.Description.Contains(e))) continue; if (item.Speed < 1_000_000) continue; var addrs = item.GetIPProperties().UnicastAddresses.Where(e => e.Address.AddressFamily == AddressFamily.InterNetwork).ToArray(); if (addrs.All(e => IPAddress.IsLoopback(e.Address))) continue; var mac = item.GetPhysicalAddress()?.GetAddressBytes(); if (mac != null && mac.Length == 6) yield return mac; } } #endregion #region WMI辅助 /// <summary>获取WMI信息</summary> /// <param name="path"></param> /// <param name="property"></param> /// <returns></returns> public static String GetInfo(String path, String property) { // Linux Mono不支持WMI if (Runtime.Mono) return ""; var bbs = new List<String>(); try { var wql = String.Format("Select {0} From {1}", property, path); var cimobject = new ManagementObjectSearcher(wql); var moc = cimobject.Get(); foreach (var mo in moc) { if (mo != null && mo.Properties != null && mo.Properties[property] != null && mo.Properties[property].Value != null) bbs.Add(mo.Properties[property].Value.ToString()); } } catch { return ""; } bbs.Sort(); return bbs.Join(","); //var sb = new StringBuilder(bbs.Count * 15); //foreach (var s in bbs) //{ // if (sb.Length > 0) sb.Append(","); // sb.Append(s); //} //return sb.ToString().Trim(); } #endregion } }
30.738416
144
0.481813
[ "MIT" ]
NewLifeX/XCoder
XCoderLinux/Tools/FrmSecurity.cs
21,000
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NurseReporting.Models { public class DayEvent : Entity { public EventType Type { get; set; } public string Data { get; set; } public DayFile DayFile { get; set; } } }
19.529412
44
0.668675
[ "MIT" ]
micdevcamp/NurseReport-2
NurseReporting.Models/DayEvent.cs
334
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.ContractsLight; namespace BuildXL.Processes { /// <summary> /// Implementation of <see cref="ISandboxedProcessFileStorage"/> based off <see cref="SandboxedProcessStandardFiles"/>. /// </summary> public class StandardFileStorage : ISandboxedProcessFileStorage { private readonly SandboxedProcessStandardFiles m_sandboxedProcessStandardFiles; /// <summary> /// Create an instance of <see cref="StandardFileStorage"/>. /// </summary> public StandardFileStorage(SandboxedProcessStandardFiles sandboxedProcessStandardFiles) { Contract.Requires(sandboxedProcessStandardFiles != null); m_sandboxedProcessStandardFiles = sandboxedProcessStandardFiles; } /// <inheritdoc /> public string GetFileName(SandboxedProcessFile file) { switch (file) { case SandboxedProcessFile.StandardError: return m_sandboxedProcessStandardFiles.StandardError; case SandboxedProcessFile.StandardOutput: return m_sandboxedProcessStandardFiles.StandardOutput; default: Contract.Assert(false); return null; } } } }
37.55
124
0.631824
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/Engine/Processes/StandardFileStorage.cs
1,504
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("MvcTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MvcTest")] [assembly: AssemblyCopyright("Copyright © 2010")] [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("8bac1bdd-762e-4dc7-b7c0-c9bfc099e019")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.416667
84
0.746845
[ "MIT" ]
ChristianGutman/FileDB
MvcTest/Properties/AssemblyInfo.cs
1,350
C#
using System; using System.Collections.Generic; using System.IO; using AutoFixture; using Omnium.Public.Models; using Omnium.Public.Orders.Models; using Omnium.Public.Shipments.Models; namespace Geta.Omnium.Test.TestSupport.Fakes { public class OmniumFakesBuilder { public OmniumOrder CreateOmniumOrder() { var filePath = AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\TestSupport\\Data\\order.json"; var json = File.ReadAllText(filePath); return Newtonsoft.Json.JsonConvert.DeserializeObject<OmniumOrder>(json); } public OmniumOrderLine CreateOmniumOrderLine() { return new OmniumOrderLine { LineItemId = Guid.NewGuid().ToString(), Code = "Product-1", DisplayName = "Product 1", PlacedPrice = 45, Quantity = 20 }; } public OmniumShipment CreateOmniumShipment() { return new OmniumShipment { ShipmentId = Guid.NewGuid().ToString(), ShippingMethodName = "Express-USD", ShippingMethodId = "a07af904-6f77-4a52-8110-b327dbf479d4", LineItems = new List<OmniumOrderLine>() }; } public IEnumerable<OmniumPropertyItem> CreateOmniumProperties() { var fixture = new Fixture(); return new[] { new OmniumPropertyItem {Key = fixture.Create<string>(), Value = fixture.Create<string>()}, new OmniumPropertyItem {Key = fixture.Create<string>(), Value = fixture.Create<string>()}, new OmniumPropertyItem {Key = fixture.Create<string>(), Value = fixture.Create<string>()}, new OmniumPropertyItem {Key = fixture.Create<string>(), Value = fixture.Create<string>()}, new OmniumPropertyItem {Key = fixture.Create<string>(), Value = fixture.Create<string>()} }; } } }
34.847458
109
0.577335
[ "Apache-2.0" ]
Geta/Geta.Omnium
test/Geta.Omnium.Test/TestSupport/Fakes/OmniumFakesBuilder.cs
2,058
C#
namespace TraktNet.Objects.Get.Tests.Syncs.Playback.Json.Reader { using FluentAssertions; using System; using System.Threading.Tasks; using Trakt.NET.Tests.Utility.Traits; using TraktNet.Objects.Get.Syncs.Playback; using TraktNet.Objects.Get.Syncs.Playback.Json.Reader; using Xunit; [Category("Objects.Get.Syncs.Playback.JsonReader")] public partial class SyncPlaybackProgressItemObjectJsonReader_Tests { [Fact] public async Task Test_SyncPlaybackProgressItemObjectJsonReader_ReadObject_From_Json_String_Null() { var jsonReader = new SyncPlaybackProgressItemObjectJsonReader(); Func<Task<ITraktSyncPlaybackProgressItem>> traktPlaybackProgressItem = () => jsonReader.ReadObjectAsync(default(string)); await traktPlaybackProgressItem.Should().ThrowAsync<ArgumentNullException>(); } [Fact] public async Task Test_SyncPlaybackProgressItemObjectJsonReader_ReadObject_From_Json_String_Empty() { var jsonReader = new SyncPlaybackProgressItemObjectJsonReader(); var traktPlaybackProgressItem = await jsonReader.ReadObjectAsync(string.Empty); traktPlaybackProgressItem.Should().BeNull(); } } }
39.65625
133
0.725768
[ "MIT" ]
henrikfroehling/Trakt.NET
Source/Tests/Trakt.NET.Objects.Get.Tests/Syncs/Playback/Json/Reader/SyncPlaybackProgressItemObjectJsonReader/SyncPlaybackProgressItemObjectJsonReader_Json_String_Tests.cs
1,271
C#
namespace YeelightAPI.Models.ColorFlow { /// <summary> /// Mode of the color flow /// </summary> public enum ColorFlowMode { /// <summary> /// RGB color /// </summary> Color = 1, /// <summary> /// Color temperature /// </summary> ColorTemperature = 2, /// <summary> /// Sleep (timer) /// </summary> Sleep = 7 } }
18.913043
39
0.448276
[ "Apache-2.0" ]
BionicCode/YeelightAPI
YeelightAPI/Models/ColorFlow/ColorFlowMode.cs
437
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("WA3P Player")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WA3P Player")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("303f5554-1fb6-4a9c-8a4a-8811d352b37a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.567568
84
0.746043
[ "Unlicense" ]
GamingLiamStudios/WA3P-CSPlayer
WA3P Player/Properties/AssemblyInfo.cs
1,393
C#
namespace Json.Schema.DataGeneration { internal interface IRequirementsGatherer { void AddRequirements(RequirementsContext context, JsonSchema schema); } }
23
71
0.819876
[ "MIT" ]
WeihanLi/json-everything
JsonSchema.DataGeneration/IRequirementsGatherer.cs
163
C#
// <copyright file="IFtpServer.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Collections.Generic; namespace FubarDev.FtpServer { /// <summary> /// The interface that must be implemented by the FTP server. /// </summary> public interface IFtpServer : IPausableFtpService { /// <summary> /// This event is raised when the connection is ready to be configured. /// </summary> event EventHandler<ConnectionEventArgs> ConfigureConnection; /// <summary> /// This event is raised when the listener was started. /// </summary> event EventHandler<ListenerStartedEventArgs> ListenerStarted; /// <summary> /// Gets the public IP address (required for <c>PASV</c> and <c>EPSV</c>). /// </summary> string? ServerAddress { get; } /// <summary> /// Gets the port on which the FTP server is listening for incoming connections. /// </summary> /// <remarks> /// This value is only final after the <see cref="ListenerStarted"/> event was raised. /// </remarks> int Port { get; } /// <summary> /// Gets the max allows active connections. /// </summary> /// <remarks> /// This will cause connections to be refused if count is exceeded. /// 0 (default) means no control over connection count. /// </remarks> int MaxActiveConnections { get; } /// <summary> /// Gets a value indicating whether server ready to receive incoming connections. /// </summary> bool Ready { get; } /// <summary> /// Gets the FTP server statistics. /// </summary> IFtpServerStatistics Statistics { get; } /// <summary> /// Starts the FTP server in the background. /// </summary> [Obsolete("User IFtpServerHost.StartAsync instead.")] void Start(); /// <summary> /// Stops the FTP server. /// </summary> /// <remarks> /// The FTP server cannot be started again after it was stopped. /// </remarks> [Obsolete("User IFtpServerHost.StopAsync instead.")] void Stop(); IEnumerable<IFtpConnection> GetConnections(); } }
31.893333
94
0.583194
[ "Apache-2.0" ]
nsaxelby/EasyFileSender
FubarSrc/FubarDev.FtpServer.Abstractions/IFtpServer.cs
2,392
C#
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Conversations.V1; namespace Twilio.Tests.Rest.Conversations.V1 { [TestFixture] public class UserTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Conversations, "/v1/Users", "" ); request.AddPostParam("Identity", Serialize("identity")); request.AddHeaderParam("X-Twilio-Webhook-Enabled", Serialize(UserResource.WebhookEnabledTypeEnum.True)); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { UserResource.Create("identity", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"sid\": \"USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"role_sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"identity\": \"admin\",\"friendly_name\": \"name\",\"attributes\": \"{ \\\"duty\\\": \\\"tech\\\" }\",\"is_online\": null,\"date_created\": \"2019-12-16T22:18:37Z\",\"date_updated\": \"2019-12-16T22:18:38Z\",\"url\": \"https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = UserResource.Create("identity", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Conversations, "/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); request.AddHeaderParam("X-Twilio-Webhook-Enabled", Serialize(UserResource.WebhookEnabledTypeEnum.True)); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { UserResource.Update("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"role_sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"identity\": \"admin\",\"friendly_name\": \"new name\",\"attributes\": \"{ \\\"duty\\\": \\\"tech\\\", \\\"team\\\": \\\"internals\\\" }\",\"is_online\": null,\"date_created\": \"2019-12-16T22:18:37Z\",\"date_updated\": \"2019-12-16T22:18:38Z\",\"url\": \"https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = UserResource.Update("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Conversations, "/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); request.AddHeaderParam("X-Twilio-Webhook-Enabled", Serialize(UserResource.WebhookEnabledTypeEnum.True)); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { UserResource.Delete("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = UserResource.Delete("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", xTwilioWebhookEnabled: Serialize(UserResource.WebhookEnabledTypeEnum.True), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Conversations, "/v1/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { UserResource.Fetch("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"role_sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"identity\": \"admin\",\"friendly_name\": \"name\",\"attributes\": \"{ \\\"duty\\\": \\\"tech\\\" }\",\"is_online\": null,\"date_created\": \"2019-12-16T22:18:37Z\",\"date_updated\": \"2019-12-16T22:18:38Z\",\"url\": \"https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = UserResource.Fetch("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Conversations, "/v1/Users", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { UserResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://conversations.twilio.com/v1/Users?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://conversations.twilio.com/v1/Users?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"users\"},\"users\": [{\"sid\": \"USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"role_sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"identity\": \"admin\",\"friendly_name\": \"name\",\"attributes\": \"{ \\\"duty\\\": \\\"tech\\\" }\",\"is_online\": null,\"date_created\": \"2019-12-16T22:18:37Z\",\"date_updated\": \"2019-12-16T22:18:38Z\",\"url\": \"https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},{\"sid\": \"USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"role_sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"identity\": \"agent0034\",\"friendly_name\": \"John from customs\",\"attributes\": \"{ \\\"duty\\\": \\\"agent\\\" }\",\"is_online\": false,\"date_created\": \"2020-03-24T20:38:21Z\",\"date_updated\": \"2020-03-24T20:38:21Z\",\"url\": \"https://conversations.twilio.com/v1/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}" )); var response = UserResource.Read(client: twilioRestClient); Assert.NotNull(response); } } }
54.293269
1,386
0.597007
[ "MIT" ]
charliesantos/twilio-csharp
test/Twilio.Test/Rest/Conversations/V1/UserResourceTest.cs
11,293
C#
using System.Drawing; namespace Dyes { public interface IWriter { void Write(object input); void WriteLine(object input); void WriteLine(); void WriteColor(Color color, int width); void WriteColorLine(Color color, int width); } }
20.214286
52
0.628975
[ "MIT" ]
itsresool/dyes
src/Dyes/IWriter.cs
283
C#
/* The MIT License (MIT) * * Original Work Copyright (c) 2014 Pawel Drozdowski * Modified Work Copyright (c) 2015 William Hallatt * * 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. */ namespace TspLibNet { using Graph.Edges; using Graph.EdgeWeights; using Graph.FixedEdges; using Graph.Nodes; using Tours; /// <summary> /// Represents possible TSPLIB problem types. /// </summary> public enum ProblemType { /// <summary> Symmetric TSP </summary> TSP, /// <summary> Aymmetric TSP </summary> ATSP, /// <summary> Hamiltonian Cycle Problem </summary> HCP, /// <summary> Sequential Ordering Problem </summary> SOP, /// <summary> Capacitated Vehicle Routing Problem </summary> CVRP } /// <summary> /// Interface for a graph based problems /// </summary> public interface IProblem { /// <summary> /// Represents the problem type (TSP, ATSP, etc). /// </summary> ProblemType Type { get; } /// <summary> /// Gets file name - Identifies the data file. /// </summary> string Name { get; } /// <summary> /// Gets file comment - additional comments from problem author /// </summary> string Comment { get; } /// <summary> /// Gets tour distance for a given problem /// </summary> /// <param name="tour">Tour to check</param> /// <returns>Tour distance</returns> double TourDistance(ITour tour); /// <summary> /// Gets nodes provider /// </summary> INodeProvider NodeProvider { get; } /// <summary> /// Gets Edges provider /// </summary> IEdgeProvider EdgeProvider { get; } /// <summary> /// Gets Edge Weights Provider /// </summary> IEdgeWeightsProvider EdgeWeightsProvider { get; } /// <summary> /// Gets Fixed Edges Provider /// </summary> IFixedEdgesProvider FixedEdgesProvider { get; } } }
31.19
82
0.628086
[ "MIT" ]
LiPan1998/TSPLib.Net
TspLibNet/TspLibNet/IProblem.cs
3,121
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Data; using System.Globalization; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// <para> /// Represents the mapping between a .NET <see cref="TimeOnly" /> type and a database type. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// </summary> public class TimeOnlyTypeMapping : RelationalTypeMapping { /// <summary> /// Initializes a new instance of the <see cref="TimeOnlyTypeMapping" /> class. /// </summary> /// <param name="storeType"> The name of the database type. </param> /// <param name="dbType"> The <see cref="DbType" /> to be used. </param> public TimeOnlyTypeMapping( string storeType, DbType? dbType = null) : base(storeType, typeof(TimeOnly), dbType) { } /// <summary> /// Initializes a new instance of the <see cref="TimeOnlyTypeMapping" /> class. /// </summary> /// <param name="parameters"> Parameter object for <see cref="RelationalTypeMapping" />. </param> protected TimeOnlyTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } /// <summary> /// Creates a copy of this mapping. /// </summary> /// <param name="parameters"> The parameters for this mapping. </param> /// <returns> The newly created mapping. </returns> protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new TimeOnlyTypeMapping(parameters); /// <inheritdoc /> protected override string GenerateNonNullSqlLiteral(object value) { var timeOnly = (TimeOnly)value; return timeOnly.Ticks % TimeSpan.TicksPerSecond == 0 ? FormattableString.Invariant($@"TIME '{value:HH\:mm\:ss}'") : FormattableString.Invariant($@"TIME '{value:HH\:mm\:ss\.FFFFFFF}'"); } } }
38.274194
105
0.602613
[ "MIT" ]
FelicePollano/efcore
src/EFCore.Relational/Storage/TimeOnlyTypeMapping.cs
2,373
C#
/* Copyright (c) 2019 Integrative Software LLC Created: 5/2019 Author: Pablo Carbonell */ using System.Drawing; using System.Windows.Forms; namespace Electrolite.Windows.Main { sealed class Transparenter { readonly Color TransparentColor = Color.LimeGreen; readonly Form _parent; Panel _panel; Color _defaultColor; public Transparenter(Form parent) { _parent = parent; } public void MakeTransparent() { _parent.SuspendLayout(); _panel = new Panel { BackColor = TransparentColor, Dock = DockStyle.Fill }; _defaultColor = _parent.BackColor; _parent.AllowTransparency = true; _parent.BackColor = TransparentColor; _parent.TransparencyKey = TransparentColor; _parent.FormBorderStyle = FormBorderStyle.None; _parent.Controls.Add(_panel); _panel.BringToFront(); _parent.ResumeLayout(); } public void MakeOpaque() { _parent.SuspendLayout(); _parent.FormBorderStyle = FormBorderStyle.Sizable; _panel.Visible = false; _parent.Controls.Remove(_panel); _parent.BackColor = _defaultColor; _parent.AllowTransparency = false; _parent.ResumeLayout(); } } }
26.592593
62
0.580084
[ "Apache-2.0" ]
integrativesoft/electrolite
Electrolite.Windows/Main/Transparenter.cs
1,438
C#
// Copyright (c) pCYSl5EDgo. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MessagePack; namespace ComplexTestClasses { [Union(0, typeof(ImplementorStruct))] [Union(1, typeof(ImplementorGenericStruct<int>))] [Union(2, typeof(ImplementorGenericStruct<string>))] [Union(3, typeof(ImplementorGenericStruct<ImplementorStruct>))] public interface IUnionBase { int Value { get; } } }
32.0625
102
0.701754
[ "MIT" ]
pCYSl5EDgo/MSPack-Processor
tests/ComplexTestClasses/IUnionBase.cs
515
C#
using Microsoft.AspNetCore.Components; using PBApplication.Responses; using PBApplication.Responses.Abstractions; using PBApplication.Services.Abstractions; using PBFrontend.UI.Miscellaneous.Loading; using System; using System.Threading.Tasks; namespace PBFrontend.UI.Authorization.ForgotPassword { public partial class ForgotPasswordFrame : SessionChild { [Parameter] public RenderFragment ChildContent { get; set; } [CascadingParameter] protected LoadingFrame LoadingParent { get; set; } public IEventfulUserService.ForgotPasswordRequest Request { get; set; } = new IEventfulUserService.ForgotPasswordRequest(); public IResponse Response { get; set; } = new Response(); public async Task Submit() { async Task<IResponse> submit() { var hasher = await SessionParent.ServiceContext.GetService<IHashingService>().GetNewPasswordPreHasher(); var request = new IEventfulUserService.ForgotPasswordRequest() { Email = Request.Email, Name = Request.Name, NewPassword = String.IsNullOrEmpty(Request.NewPassword) ? String.Empty : hasher.Hash(Request.NewPassword), NewPasswordPreHasherId = hasher.Id }; return await SessionParent.ServiceContext.GetService<IUserService>().ForgotPassword(request); } async Task<IResponse> load() { if (LoadingParent == null) { return await submit(); } else { return await LoadingParent.Load(submit); } } Response = await load(); await InvokeAsync(StateHasChanged); } } }
28.12963
125
0.736669
[ "MIT" ]
PaulBraetz/PBAppRepository
PBFrontend/UI/Authorization/ForgotPassword/ForgotPasswordFrame.razor.cs
1,521
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Hyperledger.Aries.Agents; using Hyperledger.Aries.Configuration; using Hyperledger.Aries.Extensions; using Hyperledger.Aries.Features.Handshakes.Common; using Hyperledger.Aries.Storage; using Microsoft.Extensions.Options; namespace Hyperledger.Aries.Routing.Edge { public partial class EdgeClientService : IEdgeClientService { private const string MediatorInboxIdTagName = "MediatorInboxId"; private const string MediatorInboxKeyTagName = "MediatorInboxKey"; private const string MediatorConnectionIdTagName = "MediatorConnectionId"; private readonly IHttpClientFactory httpClientFactory; private readonly IProvisioningService provisioningService; private readonly IWalletRecordService recordService; private readonly IWalletRecordService walletRecordService; private readonly IWalletService walletService; private readonly IMessageService messageService; private readonly AgentOptions agentoptions; public EdgeClientService( IHttpClientFactory httpClientFactory, IProvisioningService provisioningService, IWalletRecordService recordService, IMessageService messageService, IWalletRecordService walletRecordService, IWalletService walletService, IOptions<AgentOptions> agentOptions) { this.httpClientFactory = httpClientFactory; this.provisioningService = provisioningService; this.recordService = recordService; this.walletRecordService = walletRecordService; this.walletService = walletService; this.messageService = messageService; this.agentoptions = agentOptions.Value; } public virtual async Task AddRouteAsync(IAgentContext agentContext, string routeDestination) { var connection = await GetMediatorConnectionAsync(agentContext); if (connection != null) { var createInboxMessage = new AddRouteMessage { RouteDestination = routeDestination }; await messageService.SendAsync(agentContext, createInboxMessage, connection); } } public virtual async Task CreateInboxAsync(IAgentContext agentContext, Dictionary<string, string> metadata = null) { var provisioning = await provisioningService.GetProvisioningAsync(agentContext.Wallet); if (provisioning.GetTag(MediatorInboxIdTagName) != null) { return; } var connection = await GetMediatorConnectionAsync(agentContext); var createInboxMessage = new CreateInboxMessage { Metadata = metadata }; var response = await messageService.SendReceiveAsync<CreateInboxResponseMessage>(agentContext, createInboxMessage, connection); provisioning.SetTag(MediatorInboxIdTagName, response.InboxId); provisioning.SetTag(MediatorInboxKeyTagName, response.InboxKey); await recordService.UpdateAsync(agentContext.Wallet, provisioning); } internal async Task<ConnectionRecord> GetMediatorConnectionAsync(IAgentContext agentContext) { var provisioning = await provisioningService.GetProvisioningAsync(agentContext.Wallet); if (provisioning.GetTag(MediatorConnectionIdTagName) == null) { return null; } var connection = await recordService.GetAsync<ConnectionRecord>(agentContext.Wallet, provisioning.GetTag(MediatorConnectionIdTagName)); if (connection == null) throw new AriesFrameworkException(ErrorCode.RecordNotFound, "Couldn't locate a connection to mediator agent"); if (connection.State != ConnectionState.Connected) throw new AriesFrameworkException(ErrorCode.RecordInInvalidState, $"You must be connected to the mediator agent. Current state is {connection.State}"); return connection; } public virtual async Task<AgentPublicConfiguration> DiscoverConfigurationAsync(string agentEndpoint) { var httpClient = httpClientFactory.CreateClient(); var response = await httpClient.GetAsync($"{agentEndpoint}/.well-known/agent-configuration").ConfigureAwait(false); var responseJson = await response.Content.ReadAsStringAsync(); return responseJson.ToObject<AgentPublicConfiguration>(); } public virtual async Task<(int, IEnumerable<InboxItemMessage>)> FetchInboxAsync(IAgentContext agentContext) { var connection = await GetMediatorConnectionAsync(agentContext); if (connection == null) { throw new InvalidOperationException("This agent is not configured with a mediator"); } var createInboxMessage = new GetInboxItemsMessage(); var response = await messageService.SendReceiveAsync<GetInboxItemsResponseMessage>(agentContext, createInboxMessage, connection); var processedItems = new List<string>(); var unprocessedItem = new List<InboxItemMessage>(); foreach (var item in response.Items) { try { await agentContext.Agent.ProcessAsync(agentContext, new PackedMessageContext(item.Data)); processedItems.Add(item.Id); } catch (AriesFrameworkException e) when (e.ErrorCode == ErrorCode.InvalidMessage) { processedItems.Add(item.Id); } catch (Exception) { unprocessedItem.Add(item); } } if (processedItems.Any()) { await messageService.SendAsync(agentContext, new DeleteInboxItemsMessage { InboxItemIds = processedItems }, connection); } return (processedItems.Count, unprocessedItem); } public virtual async Task AddDeviceAsync(IAgentContext agentContext, AddDeviceInfoMessage message) { var connection = await GetMediatorConnectionAsync(agentContext); if (connection != null) { await messageService.SendAsync(agentContext, message, connection); } } } }
45.041379
214
0.66881
[ "Apache-2.0" ]
lissi-id/aries-framework-dotnet
src/Hyperledger.Aries.Routing.Edge/EdgeClientService.cs
6,533
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ProvaBlazor.Areas.Identity.Pages.Account.Manage { public class GenerateRecoveryCodesModel : PageModel { private readonly UserManager<IdentityUser> _userManager; private readonly ILogger<GenerateRecoveryCodesModel> _logger; public GenerateRecoveryCodesModel( UserManager<IdentityUser> userManager, ILogger<GenerateRecoveryCodesModel> logger) { _userManager = userManager; _logger = logger; } [TempData] public string[] RecoveryCodes { get; set; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); if (!isTwoFactorEnabled) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled."); } return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!isTwoFactorEnabled) { throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled."); } var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId); StatusMessage = "You have generated new recovery codes."; return RedirectToPage("./ShowRecoveryCodes"); } } }
36.819444
153
0.632214
[ "MIT" ]
FITSTIC/Hackathon_SampleCode_19_21
ProvaBlazor/ProvaBlazor/Areas/Identity/Pages/Account/Manage/GenerateRecoveryCodes.cshtml.cs
2,653
C#
// <copyright> // Copyright Southeast Christian Church // // Licensed under the Southeast Christian Church License (the "License"); // you may not use this file except in compliance with the License. // A copy of the License shoud be included with this file. // // 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> // // <copyright> // Copyright by the Spark Development Network // // Licensed under the Rock Community License (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.rockrms.com/license // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // using System; using System.ComponentModel; using System.Data; using System.Data.Entity; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Rock; using Rock.Attribute; using Rock.Data; using Rock.Model; using Rock.Web.UI; using Rock.Web.UI.Controls; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; using System.Reflection; using Rock.Web.Cache; using System.Diagnostics; using Newtonsoft.Json; namespace RockWeb.Blocks.Reporting.NextGen { /// <summary> /// Block to execute a sql command and display the result (if any). /// </summary> [DisplayName("Believe Leader")] [Category("SECC > Reporting > NextGen")] [Description("A report for managing the trip attendeeds for NextGen's Bible & Beach Trip.")] [GroupField("Group", "The group for managing the members of this trip.", true)] [LinkedPage("Registrant Page", "The page for viewing the registrant.", true)] [LinkedPage("Group Member Detail Page", "The page for editing the group member.", true)] [GroupTypeField("MSM Group Type", "The HSM Group Type to use for the HSM Group Field.", true)] [CustomCheckboxListField("Signature Document Templates", "The signature document templates to include.", "select id as value, name as text from SignatureDocumentTemplate")] public partial class BelieveLeader : RockBlock { string keyPrefix = ""; #region Control Methods /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { keyPrefix = string.Format("{0}-{1}-", GetType().Name, BlockId); base.OnLoad(e); gReport.Actions.CommunicateClick += Actions_CommunicateClick; if (string.IsNullOrWhiteSpace(GetAttributeValue("Group"))) { ShowMessage("Block not configured. Please configure to use.", "Configuration Error", "panel panel-danger"); return; } gReport.GridRebind += gReport_GridRebind; if (!Page.IsPostBack) { cmpCampus.DataSource = CampusCache.All(); cmpCampus.DataBind(); cmpCampus.Items.Insert(0, new ListItem("All Campuses", "")); BindGrid(); LoadGridFilters(); } } /// <summary> /// Handles the GridRebind event of the gReport control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void gReport_GridRebind(object sender, EventArgs e) { BindGrid(); } #endregion #region Internal Methods /// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var registrationRegistrantService = new RegistrationRegistrantService(rockContext); var eiogmService = new EventItemOccurrenceGroupMapService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var signatureDocumentServce = new SignatureDocumentService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); int[] signatureDocumentIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates"))) { signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); var group = new GroupService(rockContext).Get(bbGroup); if (group.Name.Contains("Week 2")) { cmpCampus.Visible = true; } Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid(); int? hsmGroupTypeId = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id; var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList(); hlGroup.NavigateUrl = "/group/" + group.Id; var attributeIds = attributeService.Queryable() .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) || (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) || (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue))) .Select(a => a.Id).ToList(); var gmTmpqry = groupMemberService.Queryable() .Where(gm => (gm.GroupId == group.Id)); var qry = gmTmpqry .GroupJoin(registrationRegistrantService.Queryable(), obj => obj.Id, rr => rr.GroupMemberId, (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 }, av => new { PersonId = av.EntityId, av.AttributeId }, (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() }) .GroupJoin(attributeValueService.Queryable(), obj => obj.GroupMember.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School=obj.School/*, Location = obj.Location */}) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.FirstOrDefault().Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School/*, Location = obj.Location */ }); var qry2 = gmTmpqry .GroupJoin( groupMemberService.Queryable() .Join(groupService.Queryable(), gm => new { Id = gm.GroupId, GroupTypeId = 10 }, g => new { g.Id, g.GroupTypeId }, (gm, g) => new { GroupMember = gm, Group = g }) .Join(groupLocationService.Queryable(), obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 }, gl => new { gl.GroupId, gl.GroupLocationTypeValueId }, (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl }) .Join(locationService.Queryable(), obj => obj.GroupLocation.LocationId, l => l.Id, (obj, l) => new { GroupMember = obj.GroupMember, Location = l }), gm => gm.PersonId, glgm => glgm.GroupMember.PersonId, (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() } ) .GroupJoin(signatureDocumentServce.Queryable() .Join(personAliasService.Queryable(), sd => sd.AppliesToPersonAliasId, pa => pa.Id, (sd, pa) => new { SignatureDocument = sd, Alias = pa }), obj => obj.GroupMember.PersonId, sd => sd.Alias.PersonId, (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds }) .GroupJoin(phoneNumberService.Queryable(), obj => obj.GroupMember.PersonId, p => p.PersonId, (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn }); if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix)))) { string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower(); qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable(); } decimal? lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); decimal? upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); if (lowerVal != null && upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal && q.RegistrationRegistrant.Select( rr => rr.Registration.BalanceDue ).FirstOrDefault() <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select( rr => rr.Registration.BalanceDue ).FirstOrDefault() >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select( rr => rr.Registration.BalanceDue ).FirstOrDefault() <= upperVal).AsQueryable(); } else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue)) { if (group.Name.Contains("Week 2")) { qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).AsQueryable(); } } var stopwatch = new Stopwatch(); stopwatch.Start(); var tmp = qry.ToList(); var tmp2 = qry2.ToList(); lStats.Text = "Query Runtime: " + stopwatch.Elapsed; stopwatch.Reset(); stopwatch.Start(); var newQry = tmp.Select(g => new { Id = g.GroupMember.Id, RegisteredBy = new ModelValue<Person>(g.RegistrationRegistrant.Select( rr => rr.Registration.PersonAlias.Person ).FirstOrDefault()), Registrant = new ModelValue<Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.Select( rr => rr.RegistrationId ).FirstOrDefault(), Group = new ModelValue<Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group), DOB = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "", Address = new ModelValue<Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()), Email = g.Person.Email, Gender = g.Person.Gender, // (B & B Registration) GraduationYearProfile = g.Person.GraduationYear, // (Person Profile) HomePhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), CellPhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), GroupMemberData = new Func<GroupMemberAttributes>(() => { GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues); return gma; })(), RegistrantData = new Func<RegistrantAttributes>(() => { RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant.FirstOrDefault(), g.RegistrationAttributeValues); return row; })(), School = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Get(g.School.AsGuid()) != null?DefinedValueCache.Get(g.School.AsGuid()).Value:"", LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(), Departure = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(), Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving")|| group.Name.ToLower().Contains("leader")? "Leader":"Student", // MSMGroup = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()), Person = g.Person, AddressStreet = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location!=null?gm.Location.Street1:"").FirstOrDefault(), AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(), RegistrantName = g.Person.FullName, }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable(); lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed; stopwatch.Stop(); gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields; var mergeFields = new List<String>(); mergeFields.Add("Id"); mergeFields.Add("RegisteredBy"); mergeFields.Add("Group"); mergeFields.Add("Registrant"); mergeFields.Add("Age"); mergeFields.Add("GraduationYear"); mergeFields.Add("DOB"); mergeFields.Add("Address"); mergeFields.Add("Email"); mergeFields.Add("Gender"); mergeFields.Add("GraduationYearProfile"); mergeFields.Add("HomePhone"); mergeFields.Add("CellPhone"); mergeFields.Add("GroupMemberData"); mergeFields.Add("RegistrantData"); mergeFields.Add("LegalRelease"); mergeFields.Add("Departure"); mergeFields.Add("Campus"); mergeFields.Add("Role"); mergeFields.Add("MSMGroup"); gReport.CommunicateMergeFields = mergeFields; /* if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix)))) { string poa = GetUserPreference(string.Format("{0}POA", keyPrefix)); if (poa == "[Blank]") { poa = ""; } newQry = newQry.Where(q => q.GroupMemberData.POA == poa); } */ SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName)); } gReport.DataBind(); } private void Actions_CommunicateClick(object sender, EventArgs e) { var rockPage = Page as RockPage; BindGrid(); var redirectUrl = rockPage.Response.Output.ToString(); if (redirectUrl != null) { Regex rgx = new Regex(".*/(\\d*)"); string result = rgx.Replace(redirectUrl, "$1"); var recipients = GetDuplicatePersonData(); if (recipients.Any()) { // Create communication var communicationRockContext = new RockContext(); var communicationService = new CommunicationService(communicationRockContext); var communicationRecipientService = new CommunicationRecipientService(communicationRockContext); var personAliasService = new PersonAliasService(communicationRockContext); var communication = communicationService.Queryable().Where(c => c.SenderPersonAliasId == rockPage.CurrentPersonAliasId).OrderByDescending(c => c.Id).FirstOrDefault(); communication.IsBulkCommunication = false; foreach(var recipient in recipients) { PersonAlias a = personAliasService.Queryable().Where(p => p.PersonId == p.AliasPersonId && p.PersonId == recipient.Key).FirstOrDefault(); var communicationRecipient = new CommunicationRecipient { CommunicationId = communication.Id, PersonAliasId = a.Id, AdditionalMergeValues = recipient.Value }; communicationRecipientService.Add(communicationRecipient); communicationRockContext.SaveChanges(); } } } } /// <summary> /// This method gets any people that are duplicates. For this report, we want to include them too. /// </summary> /// <returns></returns> private List<KeyValuePair<int, Dictionary<string, object>>> GetDuplicatePersonData() { var personData = new List<KeyValuePair<int, Dictionary<string, object>>>(); if (gReport.PersonIdField != null) { // The ToList() is potentially needed for Linq cases. var keysSelected = gReport.SelectedKeys.ToList(); string dataKeyColumn = gReport.DataKeyNames.FirstOrDefault() ?? "Id"; // get access to the List<> and its properties IList data = gReport.DataSourceAsList; if (data != null) { Type oType = data.GetType().GetProperty("Item").PropertyType; PropertyInfo idProp = !string.IsNullOrEmpty(dataKeyColumn) ? oType.GetProperty(dataKeyColumn) : null; var personIdProp = new List<PropertyInfo>(); var propPath = gReport.PersonIdField.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); while (propPath.Any()) { var property = oType.GetProperty(propPath.First()); if (property != null) { personIdProp.Add(property); oType = property.PropertyType; } propPath = propPath.Skip(1).ToList(); } foreach (var item in data) { if (!personIdProp.Any()) { while (propPath.Any()) { var property = item.GetType().GetProperty(propPath.First()); if (property != null) { personIdProp.Add(property); } propPath = propPath.Skip(1).ToList(); } } if (idProp == null) { idProp = item.GetType().GetProperty(dataKeyColumn); } if (personIdProp.Any() && idProp != null) { var personIdObjTree = new List<object>(); personIdObjTree.Add(item); bool propFound = true; foreach (var prop in personIdProp) { object obj = prop.GetValue(personIdObjTree.Last(), null); if (obj != null) { personIdObjTree.Add(obj); } else { propFound = false; break; } } if (propFound && personIdObjTree.Last() is int) { int personId = (int)personIdObjTree.Last(); if (personData.Where(pd => pd.Key == personId).Any()) { int id = (int)idProp.GetValue(item, null); // Add the personId if none are selected or if it's one of the selected items. if (!keysSelected.Any() || keysSelected.Contains(id)) { var mergeValues = new Dictionary<string, object>(); foreach (string mergeField in gReport.CommunicateMergeFields) { object obj = item.GetPropertyValue(mergeField); if (obj != null) { mergeValues.Add(mergeField.Replace('.', '_'), obj); } } personData.Add(new KeyValuePair<int, Dictionary<string, object>>(personId, mergeValues)); } } else { personData.Add(new KeyValuePair<int, Dictionary<string, object>>(personId, null)); } } } } } } return personData.Where(pd => pd.Value != null).ToList(); } private void GReport_GetRecipientMergeFields(object sender, GetRecipientMergeFieldsEventArgs e) { // Nothing here } /// <summary> /// Loads the grid filter values. /// </summary> private void LoadGridFilters() { txtPersonName.Text = GetUserPreference(string.Format("{0}PersonName", keyPrefix)); nreBalanceOwed.LowerValue = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); nreBalanceOwed.UpperValue = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); ddlPOA.DataSource = new List<string> { "", "[Blank]", "Yes", "N/A" }; ddlPOA.DataBind(); ddlPOA.SelectedValue = GetUserPreference(string.Format("{0}POA", keyPrefix)); } private void ShowMessage(string message, string header = "Information", string cssClass = "panel panel-warning") { pnlMain.Visible = false; pnlInfo.Visible = true; ltHeading.Text = header; ltBody.Text = message; pnlInfo.CssClass = cssClass; } protected void btnReopen_Command(object sender, CommandEventArgs e) { using (RockContext rockContext = new RockContext()) { WorkflowService workflowService = new WorkflowService(rockContext); Workflow workflow = workflowService.Get(e.CommandArgument.ToString().AsInteger()); if (workflow != null && !workflow.IsActive) { workflow.Status = "Active"; workflow.CompletedDateTime = null; // Find the summary activity and activate it. WorkflowActivityType workflowActivityType = workflow.WorkflowType.ActivityTypes.Where(at => at.Name.Contains("Summary")).FirstOrDefault(); WorkflowActivity workflowActivity = WorkflowActivity.Activate( WorkflowActivityTypeCache.Get( workflowActivityType.Id ), workflow, rockContext); } rockContext.SaveChanges(); } BindGrid(); LoadGridFilters(); } #endregion protected void gReport_RowSelected(object sender, RowEventArgs e) { iGroupMemberIframe.Src = LinkedPageUrl("GroupMemberDetailPage", new Dictionary<string, string>() { { "GroupMemberId", e.RowKeyValues[0].ToString() } }); mdEditRow.Show(); mdEditRow.Footer.Visible = false; } class GroupMemberAttributes : IComparable { public GroupMemberAttributes(GroupMember groupMember, Person person, IEnumerable<AttributeValue> attributeValues) { GroupMember = groupMember; AttributeValues = attributeValues; Person = person; } [Newtonsoft.Json.JsonIgnore] public GroupMember GroupMember { get; set; } [Newtonsoft.Json.JsonIgnore] public Person Person { get; set; } private IEnumerable<AttributeValue> AttributeValues { get; set; } public int Id { get { return GroupMember.Id; } } public String GeneralNotes { get { return GetAttributeValue("GeneralNotes"); } } public String RoomingNotes { get { return GetAttributeValue("RoomingNotes"); } } public String MedicalNotes { get { return GetAttributeValue("MedicalNotes"); } } public String TravelNotes { get { return GetAttributeValue("TravelNotes"); } } public String SpecialNotes { get { return GetAttributeValue("SpecialNotes"); } } public String TravelExceptions { get { return GetAttributeValue("TravelExceptions"); } } public String Group { get { return GetAttributeValue("Group1"); } } public String Dorm { get { return GetAttributeValue("Dorm"); } } public String Room { get { return GetAttributeValue("Room"); } } public String Bus { get { return GetAttributeValue("BusAssignment"); } } public String Departure { get { return GetAttributeValue("Departure"); } } public String CoLeaders { get { return GetAttributeValue("CoLeaders"); } } public String LeadingLocation { get { return GetAttributeValue("LeadingLocation"); } } public int CompareTo(object obj) { return Id.CompareTo(obj); } private String GetAttributeValue(string key) { return AttributeValues.Where(av => av.AttributeKey == key).Select(av => av.Value).FirstOrDefault(); } } class RegistrantAttributes : IComparable { public RegistrantAttributes(RegistrationRegistrant registrant, IEnumerable<AttributeValue> attributeValues) { Registrant = registrant; AttributeValues = attributeValues; } [Newtonsoft.Json.JsonIgnore] public RegistrationRegistrant Registrant { get; set; } private IEnumerable<AttributeValue> AttributeValues { get; set; } public int Id { get { return Registrant.Id; } } public String ConfirmationEmail { get { return Registrant != null ? Registrant.Registration.ConfirmationEmail : ""; } } public Decimal BalanceOwed { get { return Registrant != null ? Registrant.Registration.BalanceDue : 0; } } public String BirthDate { get { return GetAttributeValue("Birthdate").AsDateTime().HasValue ? GetAttributeValue("Birthdate").AsDateTime().Value.ToShortDateString() : null; } } public String Grade { get { return GetAttributeValue("grade"); } } public String ParentName { get { return GetAttributeValue("ParentGuardianName"); } } public String ParentCell { get { return GetAttributeValue("parentcell"); } } public String EmName { get { return GetAttributeValue("EmergencyContactName"); } } public String EmCell { get { return GetAttributeValue("EmergCellPhone"); } } public String School { get { return GetAttributeValue("Schoolifnotlistedabove"); } } public String OthersInGroup { get { return GetAttributeValue("inyourgroup"); } } public String Church { get { return GetAttributeValue("HomeChurchyouregularlyattend"); } } public String Blankenbakerhour { get { return GetAttributeValue("Blankenbakerhour"); } } public string Campus { get { if (!String.IsNullOrEmpty(GetAttributeValue("Whichcampusdoyouwanttodepartforcampfromandroomwith"))) { return GetAttributeValue("Whichcampusdoyouwanttodepartforcampfromandroomwith"); } else if(!String.IsNullOrEmpty(GetAttributeValue("Campus"))) { if (GetAttributeValue("Campus").AsGuidOrNull() == null) { return GetAttributeValue("Campus"); } else { return CampusCache.Get(GetAttributeValue("Campus").AsGuid()).Name; } } return ""; } } public bool RoomMSMGroup { get { return GetAttributeValue("roomMSMGroup").AsBoolean(); } } public String Allergies { get { return GetAttributeValue("foodallergies"); } } public String AllergySeverity { get { return GetAttributeValue("howsevere"); } } public String HowManaged { get { return GetAttributeValue("howmanage"); } } public String OtherAllergies { get { return GetAttributeValue("Listother"); } } public String MedicalInfo { get { return GetAttributeValue("medallergies"); } } public String OTCMeds { get { return GetAttributeValue("Dispensepain"); } } public String Insurance { get { return GetAttributeValue("MedInsCo")+": "+GetAttributeValue("PolicyNumber"); } } public String Physiciansname { get { return GetAttributeValue("Physiciansname"); } } public String Photo { get { return GetAttributeValue("PhotoOptional"); } } public int CompareTo(object obj) { return Id.CompareTo(obj); } private String GetAttributeValue(string key) { return AttributeValues.Where(av => av.AttributeKey == key).Select(av => av.Value).FirstOrDefault(); } } [Serializable] class ModelValue<T> where T : IModel { public ModelValue(T model) { if (model != null) { Id = model.Id; Value = model.ToString(); Model = model; } } public int Id { get; set;} public string Value { get; set;} public override string ToString() { return Value??""; } [Newtonsoft.Json.JsonIgnore] public T Model { get; set; } } protected void btnRegistration_Click(object sender, RowEventArgs e) { var key = e.RowKeyValues[1].ToString(); NavigateToLinkedPage("RegistrantPage", new Dictionary<string, string>() { { "RegistrationId", key } }); } protected void gfReport_ApplyFilterClick(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(txtPersonName.Text)) SetUserPreference(string.Format("{0}PersonName", keyPrefix), txtPersonName.Text); else DeleteUserPreference(string.Format("{0}PersonName", keyPrefix)); if (nreBalanceOwed.LowerValue.HasValue) SetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix), nreBalanceOwed.LowerValue.Value.ToString()); else DeleteUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)); if (nreBalanceOwed.UpperValue.HasValue) SetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix), nreBalanceOwed.UpperValue.Value.ToString()); else DeleteUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)); if (!string.IsNullOrWhiteSpace(ddlPOA.SelectedValue)) SetUserPreference(string.Format("{0}POA", keyPrefix), ddlPOA.SelectedValue); else DeleteUserPreference(string.Format("{0}POA", keyPrefix)); BindGrid(); } protected void gfReport_ClearFilterClick(object sender, EventArgs e) { DeleteUserPreference(string.Format("{0}PersonName", keyPrefix)); DeleteUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)); DeleteUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)); DeleteUserPreference(string.Format("{0}POA", keyPrefix)); LoadGridFilters(); BindGrid(); } } }
48.498759
423
0.54001
[ "ECL-2.0" ]
secc/RockPlugins
Plugins/org.secc.Reporting/org_secc/Reporting/NextGen/BelieveLeader.ascx.cs
39,092
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ppt2x")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ppt2x")] [assembly: System.Reflection.AssemblyTitleAttribute("ppt2x")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Создано классом WriteCodeFragment MSBuild.
40.458333
92
0.648816
[ "BSD-3-Clause" ]
ipetrovanton/b2x
Shell/ppt2x/obj/Debug/netcoreapp2.0/ppt2x.AssemblyInfo.cs
1,119
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Algorithm.Framework; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Data.Market; using QuantConnect.Indicators; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Demonstration algorithm showing how to easily convert an old algorithm into the framework. /// /// 1. Make class derive from QCAlgorithmFrameworkBridge instead of QCAlgorithm. /// 2. When making orders, also create insights for the correct direction (up/down), can also set insight prediction period/magnitude/direction /// 3. Profit :) /// </summary> /// <meta name="tag" content="indicators" /> /// <meta name="tag" content="indicator classes" /> /// <meta name="tag" content="plotting indicators" /> public class ConvertToFrameworkAlgorithm : QCAlgorithmFrameworkBridge, IRegressionAlgorithmDefinition // 1. Derive from QCAlgorithmFrameworkBridge { private MovingAverageConvergenceDivergence _macd; private readonly string _symbol = "SPY"; public readonly int FastEmaPeriod = 12; public readonly int SlowEmaPeriod = 26; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2004, 01, 01); SetEndDate(2015, 01, 01); AddSecurity(SecurityType.Equity, _symbol, Resolution.Daily); // define our daily macd(12,26) with a 9 day signal _macd = MACD(_symbol, FastEmaPeriod, SlowEmaPeriod, 9, MovingAverageType.Exponential, Resolution.Daily); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">TradeBars IDictionary object with your stock data</param> public void OnData(TradeBars data) { // wait for our indicator to be ready if (!_macd.IsReady) return; var holding = Portfolio[_symbol]; var signalDeltaPercent = (_macd - _macd.Signal) / _macd.Fast; var tolerance = 0.0025m; // if our macd is greater than our signal, then let's go long if (holding.Quantity <= 0 && signalDeltaPercent > tolerance) { // 2. Call EmitInsights with insights created in correct direction, here we're going long // The EmitInsights method can accept multiple insights separated by commas EmitInsights( // Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days Insight.Price(_symbol, TimeSpan.FromDays(FastEmaPeriod), InsightDirection.Up) ); // longterm says buy as well SetHoldings(_symbol, 1.0); } // if our macd is less than our signal, then let's go short else if (holding.Quantity >= 0 && signalDeltaPercent < -tolerance) { // 2. Call EmitInsights with insights created in correct direction, here we're going short // The EmitInsights method can accept multiple insights separated by commas EmitInsights( // Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days Insight.Price(_symbol, TimeSpan.FromDays(FastEmaPeriod), InsightDirection.Down) ); // shortterm says sell as well SetHoldings(_symbol, -1.0); } // plot both lines Plot("MACD", _macd, _macd.Signal); Plot(_symbol, "Open", data[_symbol].Open); Plot(_symbol, _macd.Fast, _macd.Slow); } /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "85"}, {"Average Win", "4.86%"}, {"Average Loss", "-4.22%"}, {"Compounding Annual Return", "-3.118%"}, {"Drawdown", "53.000%"}, {"Expectancy", "-0.053"}, {"Net Profit", "-29.441%"}, {"Sharpe Ratio", "-0.084"}, {"Loss Rate", "56%"}, {"Win Rate", "44%"}, {"Profit-Loss Ratio", "1.15"}, {"Alpha", "0.046"}, {"Beta", "-3.045"}, {"Annual Standard Deviation", "0.181"}, {"Annual Variance", "0.033"}, {"Information Ratio", "-0.194"}, {"Tracking Error", "0.181"}, {"Treynor Ratio", "0.005"}, {"Total Fees", "$756.66"}, {"Total Insights Generated", "85"}, {"Total Insights Closed", "85"}, {"Total Insights Analysis Completed", "84"}, {"Long Insight Count", "42"}, {"Short Insight Count", "43"}, {"Long/Short Ratio", "97.67%"}, {"Estimated Monthly Alpha Value", "$-570702.8"}, {"Total Accumulated Estimated Alpha Value", "$-76440090"}, {"Mean Population Estimated Insight Value", "$-899295.2"}, {"Mean Population Direction", "53.5714%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "43.5549%"}, {"Rolling Averaged Population Magnitude", "0%"} }; } }
45.013333
151
0.603969
[ "Apache-2.0" ]
TradingAlgoritmico/Lean
Algorithm.CSharp/ConvertToFrameworkAlgorithm.cs
6,752
C#
namespace CurriculumParser { /// <summary> /// Тип дисциплины(базовая, электив, факультатив) /// </summary> public enum DisciplineType { Base = 1, Elective = 2, Facultative = 3 } }
19.083333
53
0.554585
[ "Apache-2.0" ]
resueman/curriculum-parser
CurriculumParser/DisciplineType.cs
269
C#
using System; using NLog; namespace DistributedLoggingTracing.WebApi { public static class LoggerExtensions { public static void Log(this ILogger logger, ICorrelationInfo correlationInfo, LogLevel logLevel, string message) { var logEventInfo = new LogEventInfo(logLevel, "", message); logEventInfo.FillWithTimestamp(); logEventInfo.FillWithCorrelationInfo(correlationInfo); logger.Log(logEventInfo); } public static void Trace(this ILogger logger, TraceInfo traceInfo, string message) { var logEventInfo = new LogEventInfo(LogLevel.Trace, "", message); logEventInfo.FillWithTimestamp(); logEventInfo.FillWithCorrelationInfo(traceInfo.CorrelationInfo); logEventInfo.FillWithParentCallInfo(traceInfo.ParentCallInfo); logEventInfo.FillWithCallInfo(traceInfo.CallInfo); logger.Log(logEventInfo); } private static void FillWithTimestamp(this LogEventInfo logEventInfo) { logEventInfo.Properties["occurredOn"] = DateTime.UtcNow.ToString("O"); } private static void FillWithCorrelationInfo(this LogEventInfo logEventInfo, ICorrelationInfo correlationInfo) { logEventInfo.Properties["requestId"] = correlationInfo.RequestId; logEventInfo.Properties["parentCallId"] = correlationInfo.ParentCallId; logEventInfo.Properties["callId"] = correlationInfo.CallId; } private static void FillWithParentCallInfo(this LogEventInfo logEventInfo, HttpRequestDetails parentCallInfo) { if (parentCallInfo == HttpRequestDetails.Empty) return; logEventInfo.Properties["parentCallUri"] = parentCallInfo.Uri; logEventInfo.Properties["parentCallMethod"] = parentCallInfo.Method; } private static void FillWithCallInfo(this LogEventInfo logEventInfo, HttpRequestDetails callInfo) { logEventInfo.Properties["callUri"] = callInfo.Uri; logEventInfo.Properties["callMethod"] = callInfo.Method; logEventInfo.Properties["callDuration"] = callInfo.Duration; } } }
40.872727
120
0.677046
[ "MIT" ]
luigiberrettini/distributed-logging-and-tracing-kata
src/WebApi/LoggerExtensions.cs
2,250
C#
using System; using System.Diagnostics; namespace Unity.Burst.Intrinsics { public unsafe static partial class X86 { /// <summary> /// SSE3 intrinsics /// </summary> public static class Sse3 { /// <summary> /// Evaluates to true at compile time if SSE3 intrinsics are supported. /// </summary> public static bool IsSse3Supported { get { return false; } } // _mm_addsub_ps /// <summary> Alternatively add and subtract packed single-precision (32-bit) floating-point elements in "a" to/from packed elements in "b", and store the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 addsub_ps(v128 a, v128 b) { v128 dst = default(v128); dst.Float0 = a.Float0 - b.Float0; dst.Float1 = a.Float1 + b.Float1; dst.Float2 = a.Float2 - b.Float2; dst.Float3 = a.Float3 + b.Float3; return dst; } // _mm_addsub_pd /// <summary> Alternatively add and subtract packed double-precision (64-bit) floating-point elements in "a" to/from packed elements in "b", and store the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 addsub_pd(v128 a, v128 b) { v128 dst = default(v128); dst.Double0 = a.Double0 - b.Double0; dst.Double1 = a.Double1 + b.Double1; return dst; } // _mm_hadd_pd /// <summary> Horizontally add adjacent pairs of double-precision (64-bit) floating-point elements in "a" and "b", and pack the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 hadd_pd(v128 a, v128 b) { v128 dst = default(v128); dst.Double0 = a.Double0 + a.Double1; dst.Double1 = b.Double0 + b.Double1; return dst; } // _mm_hadd_ps /// <summary> Horizontally add adjacent pairs of single-precision (32-bit) floating-point elements in "a" and "b", and pack the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 hadd_ps(v128 a, v128 b) { v128 dst = default(v128); dst.Float0 = a.Float0 + a.Float1; dst.Float1 = a.Float2 + a.Float3; dst.Float2 = b.Float0 + b.Float1; dst.Float3 = b.Float2 + b.Float3; return dst; } // _mm_hsub_pd /// <summary> Horizontally subtract adjacent pairs of double-precision (64-bit) floating-point elements in "a" and "b", and pack the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 hsub_pd(v128 a, v128 b) { v128 dst = default(v128); dst.Double0 = a.Double0 - a.Double1; dst.Double1 = b.Double0 - b.Double1; return dst; } // _mm_hsub_ps /// <summary> Horizontally add adjacent pairs of single-precision (32-bit) floating-point elements in "a" and "b", and pack the results in "dst". </summary> /// <param name="a">Vector a</param> /// <param name="b">Vector b</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 hsub_ps(v128 a, v128 b) { v128 dst = default(v128); dst.Float0 = a.Float0 - a.Float1; dst.Float1 = a.Float2 - a.Float3; dst.Float2 = b.Float0 - b.Float1; dst.Float3 = b.Float2 - b.Float3; return dst; } // _mm_movedup_pd /// <summary> Duplicate the low double-precision (64-bit) floating-point element from "a", and store the results in "dst". </summary> /// <param name="a">Vector a</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 movedup_pd(v128 a) { // Burst IR is fine v128 dst = default(v128); dst.Double0 = a.Double0; dst.Double1 = a.Double0; return dst; } // _mm_movehdup_ps /// <summary> Duplicate odd-indexed single-precision (32-bit) floating-point elements from "a", and store the results in "dst". </summary> /// <param name="a">Vector a</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 movehdup_ps(v128 a) { // Burst IR is fine v128 dst = default(v128); dst.Float0 = a.Float1; dst.Float1 = a.Float1; dst.Float2 = a.Float3; dst.Float3 = a.Float3; return dst; } // _mm_moveldup_ps /// <summary> Duplicate even-indexed single-precision (32-bit) floating-point elements from "a", and store the results in "dst". </summary> /// <param name="a">Vector a</param> /// <returns>Vector</returns> [DebuggerStepThrough] public static v128 moveldup_ps(v128 a) { // Burst IR is fine v128 dst = default(v128); dst.Float0 = a.Float0; dst.Float1 = a.Float0; dst.Float2 = a.Float2; dst.Float3 = a.Float2; return dst; } } } }
40.057692
195
0.522644
[ "MIT" ]
Alex-Greenen/Spectral-Animation-Unity-Unity
Library/PackageCache/com.unity.burst@1.6.0-pre.2/Runtime/Intrinsics/x86/Sse3.cs
6,249
C#
// Copyright 2017 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Utility; using System; namespace NodaTime.Calendars { /// <summary> /// See <see cref="CalendarSystem.Badi" /> for details about the Badíʿ calendar. /// </summary> internal sealed class BadiYearMonthDayCalculator : YearMonthDayCalculator { // named constants to avoid use of raw numbers in the code private const int AverageDaysPer10Years = 3652; // Ideally 365.2425 per year... private const int DaysInAyyamiHaInLeapYear = 5; private const int DaysInAyyamiHaInNormalYear = 4; internal const int DaysInMonth = 19; private const int FirstYearOfStandardizedCalendar = 172; private const int GregorianYearOfFirstBadiYear = 1844; /// <remarks> /// There are 19 months in a year. Between the 18th and 19th month are the "days of Ha" (Ayyam-i-Ha). /// In order to make everything else in Noda Time work appropriately, Ayyam-i-Ha are counted as /// extra days at the end of month 18. /// </remarks> internal const int Month18 = 18; private const int Month19 = 19; private const int MonthsInYear = 19; private const int UnixEpochDayAtStartOfYear1 = -45941; private const int BadiMaxYear = 1000; // current lookup tables are pre-calculated for a thousand years private const int BadiMinYear = 1; /// <summary> /// This is the base64 representation of information for years 172 to 1000. /// NazRuzDate falls on March 19, 20, 21, or 22. /// DaysInAyymiHa can be 4,5. /// For each year, the value in the array is (NawRuzDate - 19) + 10 * (DaysInAyyamiHa - 4) /// </summary> static byte[] YearInfoRaw = Convert.FromBase64String( "AgELAgIBCwICAQsCAgEBCwIBAQsCAQELAgEBCwIBAQsCAQELAgEBCwIBAQELAQEBCwEBAQsBAQELAQEB" + "CwEBAQsBAQELAQEBCwEBAQEKAQEBCgEBAQsCAgILAgICCwICAgsCAgILAgICCwICAgELAgIBCwICAQsC" + "AgELAgIBCwICAQsCAgELAgIBCwICAQELAgEBCwIBAQsCAQELAgEBCwIBAQsCAQELAgEBCwIBAQELAQEB" + "CwEBAQsCAgIMAgICDAICAgwCAgIMAgICDAICAgILAgICCwICAgsCAgILAgICCwICAgsCAgILAgICCwIC" + "AgELAgIBCwICAQsCAgELAgIBCwICAQsCAgELAgIBCwICAQELAgEBCwIBAQsCAgIMAwICDAMCAgwDAgIM" + "AwICDAMCAgIMAgICDAICAgwCAgIMAgICDAICAgwCAgIMAgICDAICAgILAgICCwICAgsCAgILAgICCwIC" + "AgsCAgILAgICAQsCAgELAgIBCwICAQsCAgELAgIBCwICAQsCAgELAgIBCwICAQELAgEBCwIBAQsCAQEL" + "AgEBCwIBAQsCAQELAgEBCwIBAQELAQEBCwEBAQsBAQELAQEBCwEBAQsBAQELAQEBCwEBAQEKAQEBCgEB" + "AQoBAQELAgICCwICAgsCAgILAgICAQsCAgELAgIBCwICAQsCAgELAgIBCwICAQsCAgELAgIBAQsCAQEL" + "AgEBCwIBAQsCAQELAgEBCwIBAQsCAQELAgEBAQsBAQELAQEBCwEBAQsBAQELAgICDAICAgwCAgIMAgIC" + "AgsCAgILAgICCwICAgsCAgILAgICCwICAgsCAgILAgICAQsCAgELAgIBCwICAQsCAgELAgIBCwICAQsC" + "AgELAgIBAQsCAQELAgEBCwIBAQsCAQELAgICDAMCAgwDAgIMAwICAgwCAgIMAgICDAICAgwCAgIMAgIC" + "DAICAgwCAgIMAgICAgsCAgILAgICCwICAgsCAgILAgICCwICAgsCAgILAgICAQsCAgELAgIBCwICAQsC" + "AgELAgIBCwICAQsCAgELAgIBAQsCAQELAgEBCwIBAQsCAQELAgEBCwIBAQsCAQELAg=="); static BadiYearMonthDayCalculator() { Preconditions.DebugCheckState( FirstYearOfStandardizedCalendar + YearInfoRaw.Length == BadiMaxYear + 1, "Invalid compressed data. Length: " + YearInfoRaw.Length); } internal BadiYearMonthDayCalculator() : base(BadiMinYear, BadiMaxYear - 1, AverageDaysPer10Years, UnixEpochDayAtStartOfYear1) { } internal static int GetDaysInAyyamiHa(int year) { Preconditions.CheckArgumentRange(nameof(year), year, BadiMinYear, BadiMaxYear); if (year < FirstYearOfStandardizedCalendar) { return CalendarSystem.Iso.YearMonthDayCalculator.IsLeapYear(year + GregorianYearOfFirstBadiYear) ? DaysInAyyamiHaInLeapYear : DaysInAyyamiHaInNormalYear; } int num = YearInfoRaw[year - FirstYearOfStandardizedCalendar]; return num > 10 ? DaysInAyyamiHaInLeapYear : DaysInAyyamiHaInNormalYear; } private static int GetNawRuzDayInMarch(int year) { Preconditions.CheckArgumentRange(nameof(year), year, BadiMinYear, BadiMaxYear); if (year < FirstYearOfStandardizedCalendar) { return 21; } const int dayInMarchForOffsetToNawRuz = 19; int num = YearInfoRaw[year - FirstYearOfStandardizedCalendar]; return dayInMarchForOffsetToNawRuz + (num % 10); } protected override int CalculateStartOfYearDays(int year) { Preconditions.CheckArgumentRange(nameof(year), year, BadiMinYear, BadiMaxYear); // The epoch is the same regardless of calendar system, so if we work out when the // start of the Badíʿ year is in terms of the Gregorian year, we can just use that // date's days-since-epoch value. var gregorianYear = year + GregorianYearOfFirstBadiYear - 1; var nawRuz = new LocalDate(gregorianYear, 3, GetNawRuzDayInMarch(year)); return nawRuz.DaysSinceEpoch; } protected override int GetDaysFromStartOfYearToStartOfMonth(int year, int month) { var daysFromStartOfYearToStartOfMonth = DaysInMonth * (month - 1); if (month == Month19) { daysFromStartOfYearToStartOfMonth += GetDaysInAyyamiHa(year); } return daysFromStartOfYearToStartOfMonth; } internal override YearMonthDay AddMonths(YearMonthDay start, int months) { if (months == 0) { return start; } var movingBackwards = months < 0; var thisMonth = start.Month; var thisYear = start.Year; var thisDay = start.Day; var nextDay = thisDay; // TODO: It's not clear that this is correct. If we add 19 months, // it's probably okay to stay in Ayyam-i-Ha. if (IsInAyyamiHa(start)) { nextDay = thisDay - DaysInMonth; if (movingBackwards) { thisMonth++; } } var nextYear = thisYear; var nextMonthNum = thisMonth + months; if (nextMonthNum > MonthsInYear) { nextYear = thisYear + nextMonthNum / MonthsInYear; nextMonthNum = nextMonthNum % MonthsInYear; } else if (nextMonthNum < 1) { nextMonthNum = MonthsInYear - nextMonthNum; nextYear = thisYear - nextMonthNum / MonthsInYear; nextMonthNum = MonthsInYear - nextMonthNum % MonthsInYear; } if (nextYear < MinYear || nextYear > MaxYear) { throw new OverflowException("Date computation would overflow calendar bounds."); } var result = new YearMonthDay(nextYear, nextMonthNum, nextDay); return result; } internal override int GetDaysInMonth(int year, int month) { Preconditions.CheckArgumentRange(nameof(year), year, BadiMinYear, BadiMaxYear); return month == Month18 ? DaysInMonth + GetDaysInAyyamiHa(year) : DaysInMonth; } internal override int GetDaysInYear(int year) => 361 + GetDaysInAyyamiHa(year); internal override int GetDaysSinceEpoch(YearMonthDay target) { var month = target.Month; var year = target.Year; var firstDay0OfYear = CalculateStartOfYearDays(year) - 1; var daysSinceEpoch = firstDay0OfYear + (month - 1) * DaysInMonth + target.Day; if (month == Month19) { daysSinceEpoch += GetDaysInAyyamiHa(year); } return daysSinceEpoch; } internal override int GetMonthsInYear(int year) => MonthsInYear; internal override YearMonthDay GetYearMonthDay(int year, int dayOfYear) { Preconditions.CheckArgumentRange(nameof(dayOfYear), dayOfYear, 1, GetDaysInYear(year)); var firstOfLoftiness = 1 + DaysInMonth * Month18 + GetDaysInAyyamiHa(year); if (dayOfYear >= firstOfLoftiness) { return new YearMonthDay(year, Month19, dayOfYear - firstOfLoftiness + 1); } var month = Math.Min(1 + (dayOfYear - 1) / DaysInMonth, Month18); var day = dayOfYear - (month - 1) * DaysInMonth; return new YearMonthDay(year, month, day); } internal bool IsInAyyamiHa(YearMonthDay ymd) => ymd.Month == Month18 && ymd.Day > DaysInMonth; internal override bool IsLeapYear(int year) => GetDaysInAyyamiHa(year) != DaysInAyyamiHaInNormalYear; internal override int MonthsBetween(YearMonthDay start, YearMonthDay end) { int startMonth = start.Month; int startYear = start.Year; int endMonth = end.Month; int endYear = end.Year; int diff = (endYear - startYear) * MonthsInYear + endMonth - startMonth; // If we just add the difference in months to start, what do we get? YearMonthDay simpleAddition = AddMonths(start, diff); // Note: this relies on naive comparison of year/month/date values. if (start <= end) { // Moving forward: if the result of the simple addition is before or equal to the end, // we're done. Otherwise, rewind a month because we've overshot. return simpleAddition <= end ? diff : diff - 1; } else { // Moving backward: if the result of the simple addition (of a non-positive number) // is after or equal to the end, we're done. Otherwise, increment by a month because // we've overshot backwards. return simpleAddition >= end ? diff : diff + 1; } } internal override YearMonthDay SetYear(YearMonthDay start, int newYear) { Preconditions.CheckArgumentRange(nameof(newYear), newYear, BadiMinYear, BadiMaxYear); var month = start.Month; var day = start.Day; if (IsInAyyamiHa(start)) { // Moving a year while within Ayyam-i-Ha is not well defined. // In this implementation, if starting on day 5, end on day 4 (stay in Ayyam-i-Ha) var daysInThisAyyamiHa = GetDaysInAyyamiHa(newYear); return new YearMonthDay(newYear, month, Math.Min(day, DaysInMonth + daysInThisAyyamiHa)); } return new YearMonthDay(newYear, month, day); } internal override void ValidateYearMonthDay(int year, int month, int day) { Preconditions.CheckArgumentRange(nameof(year), year, BadiMinYear, BadiMaxYear); Preconditions.CheckArgumentRange(nameof(month), month, 1, MonthsInYear); int daysInMonth = month == Month18 ? DaysInMonth + GetDaysInAyyamiHa(year) : DaysInMonth; Preconditions.CheckArgumentRange(nameof(day), day, 1, daysInMonth); } } }
41.821429
112
0.622716
[ "Apache-2.0" ]
Rody66/nodatime
src/NodaTime/Calendars/BadiYearMonthDayCalculator.cs
11,716
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.PdfSharp.com // http://sourceforge.net/projects/pdfsharp // // 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 using System; using System.Diagnostics; using System.Globalization; using PdfSharpCore.Pdf.IO; namespace PdfSharpCore.Pdf { /// <summary> /// Represents a direct unsigned integer value. /// </summary> [DebuggerDisplay("({Value})")] public sealed class PdfUInteger : PdfNumber, IConvertible { /// <summary> /// Initializes a new instance of the <see cref="PdfUInteger" /> class. /// </summary> public PdfUInteger() { } /// <summary> /// Initializes a new instance of the <see cref="PdfUInteger" /> class. /// </summary> public PdfUInteger(uint value) { Value = value; } /// <summary> /// Gets the value as integer. /// </summary> public uint Value { // This class must behave like a value type. Therefore it cannot be changed (like System.String). get; } /// <summary> /// Returns the unsigned integer as string. /// </summary> public override string ToString() { // ToString is impure but does not change the value of _value. // ReSharper disable ImpureMethodCallOnReadonlyValueField return Value.ToString(CultureInfo.InvariantCulture); // ReSharper restore ImpureMethodCallOnReadonlyValueField } /// <summary> /// Writes the integer as string. /// </summary> internal override void WriteObject(PdfWriter writer) { writer.Write(this); } #region IConvertible Members /// <summary> /// Converts the value of this instance to an equivalent 64-bit unsigned integer. /// </summary> public ulong ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(Value); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit signed integer. /// </summary> public sbyte ToSByte(IFormatProvider provider) { throw new InvalidCastException(); } /// <summary> /// Converts the value of this instance to an equivalent double-precision floating-point number. /// </summary> public double ToDouble(IFormatProvider provider) { return Value; } /// <summary> /// Returns an undefined DateTime structure. /// </summary> public DateTime ToDateTime(IFormatProvider provider) { // TODO: Add PdfUInteger.ToDateTime implementation return new DateTime(); } /// <summary> /// Converts the value of this instance to an equivalent single-precision floating-point number. /// </summary> public float ToSingle(IFormatProvider provider) { return Value; } /// <summary> /// Converts the value of this instance to an equivalent Boolean value. /// </summary> public bool ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(Value); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit signed integer. /// </summary> public int ToInt32(IFormatProvider provider) { return Convert.ToInt32(Value); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit unsigned integer. /// </summary> public ushort ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(Value); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit signed integer. /// </summary> public short ToInt16(IFormatProvider provider) { return Convert.ToInt16(Value); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.String"></see>. /// </summary> string IConvertible.ToString(IFormatProvider provider) { return Value.ToString(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit unsigned integer. /// </summary> public byte ToByte(IFormatProvider provider) { return Convert.ToByte(Value); } /// <summary> /// Converts the value of this instance to an equivalent Unicode character. /// </summary> public char ToChar(IFormatProvider provider) { return Convert.ToChar(Value); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit signed integer. /// </summary> public long ToInt64(IFormatProvider provider) { return Value; } /// <summary> /// Returns type code for 32-bit integers. /// </summary> public TypeCode GetTypeCode() { return TypeCode.Int32; } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"></see> number. /// </summary> public decimal ToDecimal(IFormatProvider provider) { return Value; } /// <summary> /// Returns null. /// </summary> public object ToType(Type conversionType, IFormatProvider provider) { // TODO: Add PdfUInteger.ToType implementation return null; } /// <summary> /// Converts the value of this instance to an equivalent 32-bit unsigned integer. /// </summary> public uint ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(Value); } #endregion } }
31.947826
112
0.587235
[ "MIT" ]
aavilaco/PdfSharpCore
PdfSharpCore/Pdf/PdfUInteger.cs
7,348
C#
/* Copyright 2010-2014 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver.GeoJsonObjectModel; using Xunit; namespace MongoDB.Driver.Tests.GeoJsonObjectModel { public class GeoJsonMultiPolygonTests { [Fact] public void TestExampleFromSpec() { var multiPolygon = GeoJson.MultiPolygon<GeoJson2DCoordinates>( GeoJson.PolygonCoordinates(GeoJson.Position(102.0, 2.0), GeoJson.Position(103.0, 2.0), GeoJson.Position(103.0, 3.0), GeoJson.Position(102.0, 3.0), GeoJson.Position(102.0, 2.0)), GeoJson.PolygonCoordinates<GeoJson2DCoordinates>( GeoJson.LinearRingCoordinates(GeoJson.Position(102.0, 2.0), GeoJson.Position(103.0, 2.0), GeoJson.Position(103.0, 3.0), GeoJson.Position(102.0, 3.0), GeoJson.Position(102.0, 2.0)), GeoJson.LinearRingCoordinates(GeoJson.Position(102.0, 2.0), GeoJson.Position(103.0, 2.0), GeoJson.Position(103.0, 3.0), GeoJson.Position(102.0, 3.0), GeoJson.Position(102.0, 2.0)))); var exterior1 = "[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]"; var exterior2 = "[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]"; var hole2 = "[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]"; var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[#x1], [#x2, #h2]] }".Replace("#x1", exterior1).Replace("#x2", exterior2).Replace("#h2", hole2).Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon2D() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Position(1.0, 2.0), GeoJson.Position(3.0, 4.0), GeoJson.Position(5.0, 6.0), GeoJson.Position(1.0, 2.0)), GeoJson.PolygonCoordinates(GeoJson.Position(2.0, 3.0), GeoJson.Position(4.0, 5.0), GeoJson.Position(6.0, 7.0), GeoJson.Position(2.0, 3.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0]]], [[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0], [2.0, 3.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon2DGeographic() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Geographic(1.0, 2.0), GeoJson.Geographic(3.0, 4.0), GeoJson.Geographic(5.0, 6.0), GeoJson.Geographic(1.0, 2.0)), GeoJson.PolygonCoordinates(GeoJson.Geographic(2.0, 3.0), GeoJson.Geographic(4.0, 5.0), GeoJson.Geographic(6.0, 7.0), GeoJson.Geographic(2.0, 3.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0]]], [[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0], [2.0, 3.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon2DProjected() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Projected(1.0, 2.0), GeoJson.Projected(3.0, 4.0), GeoJson.Projected(5.0, 6.0), GeoJson.Projected(1.0, 2.0)), GeoJson.PolygonCoordinates(GeoJson.Projected(2.0, 3.0), GeoJson.Projected(4.0, 5.0), GeoJson.Projected(6.0, 7.0), GeoJson.Projected(2.0, 3.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0]]], [[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0], [2.0, 3.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon2DWithExtraMembers() { var multiPolygon = GeoJson.MultiPolygon( new GeoJsonObjectArgs<GeoJson2DCoordinates> { ExtraMembers = new BsonDocument("x", 1) }, GeoJson.PolygonCoordinates(GeoJson.Position(1.0, 2.0), GeoJson.Position(3.0, 4.0), GeoJson.Position(5.0, 6.0), GeoJson.Position(1.0, 2.0)), GeoJson.PolygonCoordinates(GeoJson.Position(2.0, 3.0), GeoJson.Position(4.0, 5.0), GeoJson.Position(6.0, 7.0), GeoJson.Position(2.0, 3.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0]]], [[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0], [2.0, 3.0]]]], 'x' : 1 }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon3D() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Position(1.0, 2.0, 3.0), GeoJson.Position(4.0, 5.0, 6.0), GeoJson.Position(7.0, 8.0, 9.0), GeoJson.Position(1.0, 2.0, 3.0)), GeoJson.PolygonCoordinates(GeoJson.Position(2.0, 3.0, 4.0), GeoJson.Position(5.0, 6.0, 7.0), GeoJson.Position(8.0, 9.0, 10.0), GeoJson.Position(2.0, 3.0, 4.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0]]], [[[2.0, 3.0, 4.0], [5.0, 6.0, 7.0], [8.0, 9.0, 10.0], [2.0, 3.0, 4.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon3DGeographic() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Geographic(1.0, 2.0, 3.0), GeoJson.Geographic(4.0, 5.0, 6.0), GeoJson.Geographic(7.0, 8.0, 9.0), GeoJson.Geographic(1.0, 2.0, 3.0)), GeoJson.PolygonCoordinates(GeoJson.Geographic(2.0, 3.0, 4.0), GeoJson.Geographic(5.0, 6.0, 7.0), GeoJson.Geographic(8.0, 9.0, 10.0), GeoJson.Geographic(2.0, 3.0, 4.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0]]], [[[2.0, 3.0, 4.0], [5.0, 6.0, 7.0], [8.0, 9.0, 10.0], [2.0, 3.0, 4.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon3DProjected() { var multiPolygon = GeoJson.MultiPolygon( GeoJson.PolygonCoordinates(GeoJson.Projected(1.0, 2.0, 3.0), GeoJson.Projected(4.0, 5.0, 6.0), GeoJson.Projected(7.0, 8.0, 9.0), GeoJson.Projected(1.0, 2.0, 3.0)), GeoJson.PolygonCoordinates(GeoJson.Projected(2.0, 3.0, 4.0), GeoJson.Projected(5.0, 6.0, 7.0), GeoJson.Projected(8.0, 9.0, 10.0), GeoJson.Projected(2.0, 3.0, 4.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0]]], [[[2.0, 3.0, 4.0], [5.0, 6.0, 7.0], [8.0, 9.0, 10.0], [2.0, 3.0, 4.0]]]] }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } [Fact] public void TestMultiPolygon3DWithExtraMembers() { var multiPolygon = GeoJson.MultiPolygon( new GeoJsonObjectArgs<GeoJson3DCoordinates> { ExtraMembers = new BsonDocument("x", 1) }, GeoJson.PolygonCoordinates(GeoJson.Position(1.0, 2.0, 3.0), GeoJson.Position(4.0, 5.0, 6.0), GeoJson.Position(7.0, 8.0, 9.0), GeoJson.Position(1.0, 2.0, 3.0)), GeoJson.PolygonCoordinates(GeoJson.Position(2.0, 3.0, 4.0), GeoJson.Position(5.0, 6.0, 7.0), GeoJson.Position(8.0, 9.0, 10.0), GeoJson.Position(2.0, 3.0, 4.0))); var expected = "{ 'type' : 'MultiPolygon', 'coordinates' : [[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0]]], [[[2.0, 3.0, 4.0], [5.0, 6.0, 7.0], [8.0, 9.0, 10.0], [2.0, 3.0, 4.0]]]], 'x' : 1 }".Replace("'", "\""); TestRoundTrip(expected, multiPolygon); } private void TestRoundTrip<TCoordinates>(string expected, GeoJsonMultiPolygon<TCoordinates> multiPolygon) where TCoordinates : GeoJsonCoordinates { var json = multiPolygon.ToJson(); Assert.Equal(expected, json); var rehydrated = BsonSerializer.Deserialize<GeoJsonMultiPolygon<TCoordinates>>(json); Assert.Equal(expected, rehydrated.ToJson()); } } }
62.432624
248
0.579575
[ "Apache-2.0" ]
KermitCoder/mongo-csharp-driver
tests/MongoDB.Driver.Tests/GeoJsonObjectModel/GeoJsonMultiPolygonTests.cs
8,805
C#
using Abp; using Abp.Domain.Repositories; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Tbs.DomainModels; namespace Tbs.DomainServices { public class TaskTypeCache : ITaskTypeCache, IEventHandler<EntityChangedEventData<TaskType>> { private readonly IAbpSession _abpSession; private readonly ICacheManager _cacheManager; private readonly IRepository<TaskType> _taskTypeRepository; public TaskTypeCache( ICacheManager cacheManager, IRepository<TaskType> taskTypeRepository, IAbpSession abpSession) { _cacheManager = cacheManager; _taskTypeRepository = taskTypeRepository; _abpSession = abpSession; } public virtual TaskType Get(int id) { var cacheItem = GetOrNull(id); if (cacheItem == null) { throw new AbpException("There is no taskType with given id: " + id); } return cacheItem; } public TaskType GetOrNull(int id) { var cacheKey = id + "@" + (_abpSession.TenantId ?? 0); return _cacheManager.GetCache("CachedTaskType") .Get(cacheKey, () => _taskTypeRepository.FirstOrDefault(d => d.Id == id)); } public void HandleEvent(EntityChangedEventData<TaskType> eventData) { var cacheKey = eventData.Entity.Id + "@" + (_abpSession.TenantId ?? 0); _cacheManager.GetCache("CachedTaskType").Remove(cacheKey); } } }
31.538462
96
0.617073
[ "MIT" ]
jiangyimin/Tbs
src/Tbs.Core/DomainServices/TaskTypeCache.cs
1,640
C#
namespace WebAppExample { public static class CorsPolicy { public static readonly string Test = "Testing"; } }
19.571429
56
0.627737
[ "MIT" ]
Deftextra/WebAppExample
CorsPolicy.cs
139
C#
// MIT License // // Copyright (c) 2017 dairin0d // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using UnityEngine; namespace dairin0d.Data.Colors { public struct ColorHSV { public float h, s, v, a; public ColorHSV(float h, float s, float v, float a=1f) { this.h = h; this.s = s; this.v = v; this.a = a; } public void Sanitize() { h = ((h % 1f) + 1f) % 1f; s = Mathf.Clamp01(s); v = Mathf.Clamp01(v); a = Mathf.Clamp01(a); } public Vector4 ToCoord() { float height = Mathf.Clamp01(v) - 0.5f; float radius = Mathf.Clamp01(s); float angle = (((h % 1f) + 1f) % 1f) * (Mathf.PI * 2f); return new Vector4(radius*Mathf.Cos(angle), radius*Mathf.Sin(angle), height, a); } // expects/returns values in range [0..1] public static implicit operator ColorHSV(Color c) { float minVal = Mathf.Min(Mathf.Min(c.r, c.g), c.b); float maxVal = Mathf.Max(Mathf.Max(c.r, c.g), c.b); float delta = maxVal - minVal; float v = maxVal; if (delta == 0f) return new ColorHSV(0f, 0f, v, c.a); float s = delta / maxVal; float h; if (c.r == maxVal) { h = (c.g - c.b) / (6f * delta); } else if (c.g == maxVal) { h = (1f / 3f) + (c.b - c.r) / (6f * delta); } else { h = (2f / 3f) + (c.r - c.g) / (6f * delta); } h = ((h % 1f) + 1f) % 1f; return new ColorHSV(h, s, v, c.a); } public static implicit operator ColorHSV(Color32 c) { return (Color)c; } // expects/returns values in range [0..1] public static implicit operator Color(ColorHSV c) { float s = Mathf.Clamp01(c.s); float v = Mathf.Clamp01(c.v); if (s == 0f) return new Color(v, v, v, c.a); float h = ((c.h % 1f) + 1f) % 1f; var var_h = h * 6f; var var_i = Mathf.FloorToInt(var_h); var var_1 = v * (1f - s); var var_2 = v * (1f - s * (var_h - var_i)); var var_3 = v * (1f - s * (1f - (var_h - var_i))); switch (var_i) { case 1: return new Color(var_2, v, var_1, c.a); case 2: return new Color(var_1, v, var_3, c.a); case 3: return new Color(var_1, var_2, v, c.a); case 4: return new Color(var_3, var_1, v, c.a); case 5: return new Color(v, var_1, var_2, c.a); default: return new Color(v, var_3, var_1, c.a); // 0 or 6 } } public static implicit operator Color32(ColorHSV c) { return (Color)c; } } }
33
83
0.630422
[ "MIT" ]
dairin0d/PointVoxelExperiments
Unity/PointVoxelExperiments/Assets/Data.Colors/ColorHSV.cs
3,366
C#
// Graph Engine // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading; using Trinity; using Trinity.Network; using Trinity.Utilities; using Trinity.Diagnostics; using Trinity.Win32; using Trinity.Core.Lib; using Trinity.Daemon; using Trinity.Network.Messaging; using Trinity.FaultTolerance; using System.Threading.Tasks; using System.Runtime.ExceptionServices; using System.Collections.Concurrent; using Trinity.Network.Client; namespace Trinity.Storage { #pragma warning disable 0420 internal partial class RemoteStorage : Storage, IDisposable { BlockingCollection<Network.Client.SynClient> ConnPool = new BlockingCollection<Network.Client.SynClient>(new ConcurrentQueue<Network.Client.SynClient>()); private volatile bool disposed = false; internal bool connected = false; private int retry = 0; private int m_client_count = 0; private MemoryCloud memory_cloud; public int MyServerId; internal RemoteStorage(IPEndPoint ip_endpoint, int connPerServer) { for (int i = 0; i < connPerServer; i++) { ConnectIPEndPoint(ip_endpoint); } retry = connPerServer * 3; } internal RemoteStorage(AvailabilityGroup trinityServer, int connPerServer, MemoryCloud mc, int serverId, bool nonblocking) { this.memory_cloud = mc; this.MyServerId = serverId; retry = 3; var connect_async_task = Task.Factory.StartNew(() => { for (int k = 0; k < connPerServer; k++) // make different server connections interleaved { for (int i = 0; i < trinityServer.ServerInstances.Count; i++) { ConnectIPEndPoint(trinityServer.ServerInstances[i].EndPoint); } } BackgroundThread.AddBackgroundTask(new BackgroundTask(Heartbeat, TrinityConfig.HeartbeatInterval)); mc.ReportServerConnectedEvent(serverId); }); if (!nonblocking) { try { connect_async_task.Wait(); } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } } } private void ConnectIPEndPoint(IPEndPoint ip_endpoint) { while (true) { try { var client = new Network.Client.SynClient(ip_endpoint); if (client.sock_connected) { ConnPool.Add(client); ++m_client_count; connected = true; break; } } catch (Exception) { Log.WriteLine(LogLevel.Debug, "Cannot connect to {0}", ip_endpoint); Thread.Sleep(100); } } } private int Heartbeat() { Network.Client.SynClient sc = GetClient(); TrinityErrorCode eResult = sc.Heartbeat(); PutBackClient(sc); if (TrinityErrorCode.E_SUCCESS == eResult) { if (!connected) { connected = true; memory_cloud.ReportServerConnectedEvent(MyServerId); } } else { if (connected) { connected = false; memory_cloud.ReportServerDisconnectedEvent(MyServerId); InvalidateSynClients(); } } return TrinityConfig.HeartbeatInterval; } /// <summary> /// Called when the heartbeat daemon reports a disconnection event. /// In this routine, we exhaustively take all clients, close them, /// and then put them back, so that they stay in disconnected state, /// and any send message action after the remote storage is up again /// will trigger a new connection, rather than reporting a send failure /// due to stale socket. /// /// !Note concurrent calls to this routine causes deadlock. It should be /// only called by a single heartbeat daemon. /// /// !Note this routine may cause connections to oscillate between connected/ /// disconnected state with a transient network failure. Consider the following /// sequence: /// 1. daemon detects disconnect. /// 2. daemon calls InvalidateSynClients() /// 3. RemoteStorage back online. /// 4. Senders take SynClients and restore connection. /// 5. InvalidateSynClients() closes connections /// </summary> private void InvalidateSynClients() { List<SynClient> clients = new List<SynClient>(); for (int i=0; i<m_client_count; ++i) { clients.Add(GetClient()); } foreach (var client in clients) { client.Close(); PutBackClient(client); } } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (ConnPool.Count != 0) { foreach (Network.Client.SynClient client in ConnPool) { client.Dispose(); } } this.disposed = true; } } ~RemoteStorage() { Dispose(false); } private Network.Client.SynClient GetClient() { return ConnPool.Take(); } private void PutBackClient(Network.Client.SynClient sc) { ConnPool.Add(sc); } } }
33.045455
163
0.522085
[ "MIT" ]
ZZHGit/GraphEngine
src/Trinity.Core/Storage/RemoteStorage/RemoteStorage.cs
6,543
C#
using ArcadeManager.Actions; using ArcadeManager.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ArcadeManager.Services { /// <summary> /// Interface for the downloader /// </summary> public interface IDownloader { /// <summary> /// Downloads the specified URL in the Github API. /// </summary> /// <param name="repository">The repository.</param> /// <param name="path">The path to the file.</param> /// <returns>The URL content</returns> Task<string> DownloadApiUrl(string repository, string path); /// <summary> /// Downloads a binary file /// </summary> /// <param name="repository">The repository</param> /// <param name="filePath">The file path</param> /// <param name="localPath">The local file path to save</param> /// <returns></returns> Task DownloadFile(string repository, string filePath, string localPath); /// <summary> /// Gets the contents of a file. /// </summary> /// <param name="repository">The repository.</param> /// <param name="filePath">The file path.</param> /// <returns> /// The file contents /// </returns> Task<byte[]> DownloadFile(string repository, string filePath); /// <summary> /// Downloads a JSON file and deserializes it to T /// </summary> /// <typeparam name="T">The type to deserialize into</typeparam> /// <param name="repository">The repository.</param> /// <param name="filePath">The file path.</param> /// <returns> /// The downloaded file /// </returns> Task<T> DownloadFile<T>(string repository, string filePath); /// <summary> /// Downloads the content of a text file. /// </summary> /// <param name="repository">The repository.</param> /// <param name="filePath">The file path.</param> /// <returns> /// The file contents /// </returns> Task<string> DownloadFileText(string repository, string filePath); /// <summary> /// Downloads the specified folder. /// </summary> /// <param name="repository">The repository.</param> /// <param name="folder">The folder path.</param> /// <param name="targetFolder">The target folder.</param> /// <param name="overwrite">if set to <c>true</c> overwrites existing files.</param> /// <param name="progress">A method called when a file is downloaded.</param> /// <returns></returns> Task<IEnumerable<string>> DownloadFolder(string repository, string folder, string targetFolder, bool overwrite, Action<GithubTree.Entry> progress); /// <summary> /// Returns the list of available CSV files in the specified repository folder /// </summary> /// <param name="data">The download parameters</param> /// <returns> /// The list of files /// </returns> Task<IEnumerable<CsvFile>> GetList(DownloadAction data); /// <summary> /// Lists the files in a Github folder /// </summary> /// <param name="repository">The repository</param> /// <param name="folder">The folder path</param> /// <returns> /// The list of files /// </returns> Task<GithubTree> ListFiles(string repository, string folder); } }
33.064516
149
0.666992
[ "MIT" ]
cosmo0/arcade-manager
ArcadeManager/Services/IDownloader.cs
3,077
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace System.Activities.Statements { using System; using System.Activities; using System.Activities.DynamicUpdate; using System.Activities.Internals; using System.Activities.Runtime; using System.Activities.Runtime.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.Serialization; using System.Windows.Markup; public sealed class TryCatch : NativeActivity { private CatchList catches; private Collection<Variable> variables; private readonly Variable<TryCatchState> state; private FaultCallback exceptionFromCatchOrFinallyHandler; internal const string FaultContextId = "{35ABC8C3-9AF1-4426-8293-A6DDBB6ED91D}"; public TryCatch() : base() { this.state = new Variable<TryCatchState>(); } public Collection<Variable> Variables { get { if (this.variables == null) { this.variables = new ValidatingCollection<Variable> { // disallow null values OnAddValidationCallback = item => { if (item == null) { throw FxTrace.Exception.ArgumentNull(nameof(item)); } } }; } return this.variables; } } [DefaultValue(null)] [DependsOn("Variables")] public Activity Try { get; set; } [DependsOn("Try")] public Collection<Catch> Catches { get { if (this.catches == null) { this.catches = new CatchList(); } return this.catches; } } [DefaultValue(null)] [DependsOn("Catches")] public Activity Finally { get; set; } private FaultCallback ExceptionFromCatchOrFinallyHandler { get { if (this.exceptionFromCatchOrFinallyHandler == null) { this.exceptionFromCatchOrFinallyHandler = new FaultCallback(OnExceptionFromCatchOrFinally); } return this.exceptionFromCatchOrFinallyHandler; } } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void UpdateInstance(NativeActivityUpdateContext updateContext) { TryCatchState state = updateContext.GetValue(this.state); if (state != null && !state.SuppressCancel && state.CaughtException != null && this.FindCatch(state.CaughtException.Exception) == null) { // This is a very small window of time in which we want to block update inside TryCatch. // This is in between OnExceptionFromTry faultHandler and OnTryComplete completionHandler. // A Catch handler could be found at OnExceptionFromTry before update, yet that appropriate Catch handler could have been removed during update and not be found at OnTryComplete. // In such case, the exception can be unintentionally swallowed without ever propagating it upward. // Such TryCatch state is detected by inspecting the TryCatchState private variable for SuppressCancel == false && CaughtException != Null && this.FindCatch(state.CaughtException.Exception) == null. updateContext.DisallowUpdate(SR.TryCatchInvalidStateForUpdate(state.CaughtException.Exception)); } } protected override void CacheMetadata(NativeActivityMetadata metadata) { if (Try != null) { metadata.AddChild(this.Try); } if (this.Finally != null) { metadata.AddChild(this.Finally); } var delegates = new Collection<ActivityDelegate>(); if (this.catches != null) { foreach (var item in this.catches) { var catchDelegate = item.GetAction(); if (catchDelegate != null) { delegates.Add(catchDelegate); } } } metadata.AddImplementationVariable(this.state); metadata.SetDelegatesCollection(delegates); metadata.SetVariablesCollection(this.Variables); if (this.Finally == null && this.Catches.Count == 0) { metadata.AddValidationError(SR.CatchOrFinallyExpected(this.DisplayName)); } } internal static Catch FindCatchActivity(Type typeToMatch, IList<Catch> catches) { foreach (var item in catches) { if (item.ExceptionType == typeToMatch) { return item; } } return null; } protected override void Execute(NativeActivityContext context) { var extension = context.GetExtension<ExceptionPersistenceExtension>(); if ((extension != null) && !extension.PersistExceptions) { // We will need a NoPersistProperty if we catch an exception. if (!(context.Properties.FindAtCurrentScope(NoPersistProperty.Name) is NoPersistProperty noPersistProperty)) { noPersistProperty = new NoPersistProperty(context.CurrentExecutor); context.Properties.Add(NoPersistProperty.Name, noPersistProperty); } } this.state.Set(context, new TryCatchState()); if (this.Try != null) { context.ScheduleActivity(this.Try, new CompletionCallback(OnTryComplete), new FaultCallback(OnExceptionFromTry)); } else { OnTryComplete(context, null); } } protected override void Cancel(NativeActivityContext context) { var state = this.state.Get(context); if (!state.SuppressCancel) { context.CancelChildren(); } } private void OnTryComplete(NativeActivityContext context, ActivityInstance completedInstance) { var state = this.state.Get(context); // We only allow the Try to be canceled. state.SuppressCancel = true; if (state.CaughtException != null) { var toSchedule = FindCatch(state.CaughtException.Exception); if (toSchedule != null) { state.ExceptionHandled = true; if (toSchedule.GetAction() != null) { context.Properties.Add(FaultContextId, state.CaughtException, true); toSchedule.ScheduleAction(context, state.CaughtException.Exception, new CompletionCallback(OnCatchComplete), this.ExceptionFromCatchOrFinallyHandler); return; } } } OnCatchComplete(context, null); } private void OnExceptionFromTry(NativeActivityFaultContext context, Exception propagatedException, ActivityInstance propagatedFrom) { if (propagatedFrom.IsCancellationRequested) { if (TD.TryCatchExceptionDuringCancelationIsEnabled()) { TD.TryCatchExceptionDuringCancelation(this.DisplayName); } // The Try activity threw an exception during Cancel; abort the workflow context.Abort(propagatedException); context.HandleFault(); } else { var catchHandler = FindCatch(propagatedException); if (catchHandler != null) { if (TD.TryCatchExceptionFromTryIsEnabled()) { TD.TryCatchExceptionFromTry(this.DisplayName, propagatedException.GetType().ToString()); } context.CancelChild(propagatedFrom); var state = this.state.Get(context); // If we are not supposed to persist exceptions, enter our noPersistScope var extension = context.GetExtension<ExceptionPersistenceExtension>(); if ((extension != null) && !extension.PersistExceptions) { var noPersistProperty = (NoPersistProperty)context.Properties.FindAtCurrentScope(NoPersistProperty.Name); if (noPersistProperty != null) { // The property will be exited when the activity completes or aborts. noPersistProperty.Enter(); } } state.CaughtException = context.CreateFaultContext(); context.HandleFault(); } } } private void OnCatchComplete(NativeActivityContext context, ActivityInstance completedInstance) { // Start suppressing cancel for the finally activity var state = this.state.Get(context); state.SuppressCancel = true; if (completedInstance != null && completedInstance.State != ActivityInstanceState.Closed) { state.ExceptionHandled = false; } context.Properties.Remove(FaultContextId); if (this.Finally != null) { context.ScheduleActivity(this.Finally, new CompletionCallback(OnFinallyComplete), this.ExceptionFromCatchOrFinallyHandler); } else { OnFinallyComplete(context, null); } } private void OnFinallyComplete(NativeActivityContext context, ActivityInstance completedInstance) { var state = this.state.Get(context); if (context.IsCancellationRequested && !state.ExceptionHandled) { context.MarkCanceled(); } } private void OnExceptionFromCatchOrFinally(NativeActivityFaultContext context, Exception propagatedException, ActivityInstance propagatedFrom) { if (TD.TryCatchExceptionFromCatchOrFinallyIsEnabled()) { TD.TryCatchExceptionFromCatchOrFinally(this.DisplayName); } // We allow cancel through if there is an exception from the catch or finally var state = this.state.Get(context); state.SuppressCancel = false; } private Catch FindCatch(Exception exception) { var exceptionType = exception.GetType(); Catch potentialCatch = null; foreach (var catchHandler in this.Catches) { if (catchHandler.ExceptionType == exceptionType) { // An exact match return catchHandler; } else if (catchHandler.ExceptionType.IsAssignableFrom(exceptionType)) { if (potentialCatch != null) { if (catchHandler.ExceptionType.IsSubclassOf(potentialCatch.ExceptionType)) { // The new handler is more specific potentialCatch = catchHandler; } } else { potentialCatch = catchHandler; } } } return potentialCatch; } [DataContract] internal class TryCatchState { [DataMember(EmitDefaultValue = false)] public bool SuppressCancel { get; set; } [DataMember(EmitDefaultValue = false)] public FaultContext CaughtException { get; set; } [DataMember(EmitDefaultValue = false)] public bool ExceptionHandled { get; set; } } private class CatchList : ValidatingCollection<Catch> { public CatchList() : base() { this.OnAddValidationCallback = item => { if (item == null) { throw FxTrace.Exception.ArgumentNull(nameof(item)); } }; } protected override void InsertItem(int index, Catch item) { if (item == null) { throw FxTrace.Exception.ArgumentNull(nameof(item)); } var existingCatch = TryCatch.FindCatchActivity(item.ExceptionType, this.Items); if (existingCatch != null) { throw FxTrace.Exception.Argument(nameof(item), SR.DuplicateCatchClause(item.ExceptionType.FullName)); } base.InsertItem(index, item); } protected override void SetItem(int index, Catch item) { if (item == null) { throw FxTrace.Exception.ArgumentNull(nameof(item)); } var existingCatch = TryCatch.FindCatchActivity(item.ExceptionType, this.Items); if (existingCatch != null && !object.ReferenceEquals(this[index], existingCatch)) { throw FxTrace.Exception.Argument(nameof(item), SR.DuplicateCatchClause(item.ExceptionType.FullName)); } base.SetItem(index, item); } } } }
35.052133
214
0.526568
[ "MIT" ]
wforney/corewf
src/System.Activities/Statements/TryCatch.cs
14,792
C#
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; using UnityEngine.Events; [CustomPropertyDrawer(typeof(DialogueText))] public class DialogueTextDrawer : PropertyDrawer { ///<summary> ///The height of a single line ///</summary> const float k_SingleLineHeight = 16f; /// <summary> /// The width of a label /// </summary> const float k_LabelWidth = 105f; /// <summary> /// The height of a line plus the padding /// </summary> const float k_NewLine = k_SingleLineHeight + 5f; /// <summary> /// The property being displayed /// </summary> DialogueText target; /// <summary> /// The height of this drawer /// </summary> private float height; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { target = Serialize.GetThis(property) as DialogueText; float y = position.yMin + 2; target.Message = EditorGUI.TextField(new Rect(position.xMin, y, position.width, k_SingleLineHeight), target.Message); y += k_NewLine; EditorGUI.LabelField(new Rect(position.xMin, y, k_LabelWidth, k_SingleLineHeight), "Has method"); target.HasAfterMessage = EditorGUI.Toggle(new Rect(position.xMin + k_LabelWidth, y, position.width - k_LabelWidth, k_SingleLineHeight), target.HasAfterMessage); y += k_NewLine; if (target.HasAfterMessage) { EditorGUI.PropertyField(new Rect(position.xMin, y, position.width, 75), property.FindPropertyRelative("AfterMessage")); y += 30 * target.AfterMessage.GetPersistentEventCount() + 75; } EditorGUI.LabelField(new Rect(position.xMin, y, k_LabelWidth, k_SingleLineHeight), "Ends the dialogue"); target.EndDialogue = EditorGUI.Toggle(new Rect(position.xMin + k_LabelWidth, y, position.width - k_LabelWidth, k_SingleLineHeight), target.EndDialogue); y += k_NewLine; height = y - position.yMin; target.elementHeight = height; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return target.elementHeight; } } #endif
33.728571
169
0.649725
[ "MIT" ]
rschavali02/computer-game-simulation-programming
2018/4th/Utah_Morgan/FBLAGame/Assets/Scripts/Dialouge/DialogueTextDrawer.cs
2,363
C#
namespace ET { /// <summary> /// 监视hp数值变化,改变血条值 /// </summary> [NumericWatcher(NumericType.Hp)] public class NumericWatcher_Hp_ShowUI : INumericWatcher { public void Run(EventType.NumbericChange args) { } } }
15.928571
56
0.695067
[ "MIT" ]
Alinccc/ET
Unity/Codes/Hotfix/Module/Numeric/NumericWatcher_Hp_ShowUI.cs
249
C#
using Newtonsoft.Json; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace NadekoBot.Core.Services.Impl { public class SoundCloudApiService : INService { private readonly IHttpClientFactory _httpFactory; public SoundCloudApiService(IHttpClientFactory factory) { _httpFactory = factory; } public async Task<SoundCloudVideo> ResolveVideoAsync(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); string response = ""; using (var http = _httpFactory.CreateClient()) { response = await http.GetStringAsync($"https://scapi.nadeko.bot/resolve?url={url}").ConfigureAwait(false); } var responseObj = JsonConvert.DeserializeObject<SoundCloudVideo>(response); if (responseObj?.Kind != "track") throw new InvalidOperationException("Url is either not a track, or it doesn't exist."); return responseObj; } public async Task<SoundCloudVideo> GetVideoByQueryAsync(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); var response = ""; using (var http = _httpFactory.CreateClient()) { response = await http.GetStringAsync(new Uri($"https://scapi.nadeko.bot/tracks?q={Uri.EscapeDataString(query)}")).ConfigureAwait(false); } var responseObj = JsonConvert.DeserializeObject<SoundCloudVideo[]>(response) .FirstOrDefault(s => s.Streamable is true); if (responseObj?.Kind != "track") throw new InvalidOperationException("Query yielded no results."); return responseObj; } } public class SoundCloudVideo { public string Kind { get; set; } = ""; public long Id { get; set; } = 0; public SoundCloudUser User { get; set; } = new SoundCloudUser(); public string Title { get; set; } = ""; public string FullName => User.Name + " - " + Title; public bool? Streamable { get; set; } = false; public int Duration { get; set; } [JsonProperty("permalink_url")] public string TrackLink { get; set; } = ""; [JsonProperty("artwork_url")] public string ArtworkUrl { get; set; } = ""; } public class SoundCloudUser { [JsonProperty("username")] public string Name { get; set; } } }
33.670886
152
0.591353
[ "MIT" ]
EchoEclipseWolf/NadekoModified
NadekoBot.Core/Services/Impl/SoundCloudApiService.cs
2,662
C#
using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Iana; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Security { /// <remarks> /// Utility class for creating HMac object from their names/Oids /// </remarks> public sealed class MacUtilities { private MacUtilities() { } private static readonly IDictionary algorithms = Platform.CreateHashtable(); //private static readonly IDictionary oids = Platform.CreateHashtable(); static MacUtilities() { algorithms[IanaObjectIdentifiers.HmacMD5.Id] = "HMAC-MD5"; algorithms[IanaObjectIdentifiers.HmacRipeMD160.Id] = "HMAC-RIPEMD160"; algorithms[IanaObjectIdentifiers.HmacSha1.Id] = "HMAC-SHA1"; algorithms[IanaObjectIdentifiers.HmacTiger.Id] = "HMAC-TIGER"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "HMAC-SHA1"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "HMAC-SHA224"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "HMAC-SHA256"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "HMAC-SHA384"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "HMAC-SHA512"; // TODO AESMAC? algorithms["DES"] = "DESMAC"; algorithms["DES/CFB8"] = "DESMAC/CFB8"; algorithms["DES64"] = "DESMAC64"; algorithms["DESEDE"] = "DESEDEMAC"; algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDEMAC"; algorithms["DESEDE/CFB8"] = "DESEDEMAC/CFB8"; algorithms["DESISO9797MAC"] = "DESWITHISO9797"; algorithms["DESEDE64"] = "DESEDEMAC64"; algorithms["DESEDE64WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["DESEDEISO9797ALG1MACWITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["DESEDEISO9797ALG1WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["ISO9797ALG3"] = "ISO9797ALG3MAC"; algorithms["ISO9797ALG3MACWITHISO7816-4PADDING"] = "ISO9797ALG3WITHISO7816-4PADDING"; algorithms["SKIPJACK"] = "SKIPJACKMAC"; algorithms["SKIPJACK/CFB8"] = "SKIPJACKMAC/CFB8"; algorithms["IDEA"] = "IDEAMAC"; algorithms["IDEA/CFB8"] = "IDEAMAC/CFB8"; algorithms["RC2"] = "RC2MAC"; algorithms["RC2/CFB8"] = "RC2MAC/CFB8"; algorithms["RC5"] = "RC5MAC"; algorithms["RC5/CFB8"] = "RC5MAC/CFB8"; algorithms["GOST28147"] = "GOST28147MAC"; algorithms["VMPC"] = "VMPCMAC"; algorithms["VMPC-MAC"] = "VMPCMAC"; algorithms["SIPHASH"] = "SIPHASH-2-4"; algorithms["PBEWITHHMACSHA"] = "PBEWITHHMACSHA1"; algorithms["1.3.14.3.2.26"] = "PBEWITHHMACSHA1"; } // /// <summary> // /// Returns a ObjectIdentifier for a given digest mechanism. // /// </summary> // /// <param name="mechanism">A string representation of the digest meanism.</param> // /// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns> // public static DerObjectIdentifier GetObjectIdentifier( // string mechanism) // { // mechanism = (string) algorithms[Platform.ToUpperInvariant(mechanism)]; // // if (mechanism != null) // { // return (DerObjectIdentifier)oids[mechanism]; // } // // return null; // } // public static ICollection Algorithms // { // get { return oids.Keys; } // } public static IMac GetMac( DerObjectIdentifier id) { return GetMac(id.Id); } public static IMac GetMac( string algorithm) { string upper = Platform.ToUpperInvariant(algorithm); string mechanism = (string) algorithms[upper]; if (mechanism == null) { mechanism = upper; } if (mechanism.StartsWith("PBEWITH")) { mechanism = mechanism.Substring("PBEWITH".Length); } if (mechanism.StartsWith("HMAC")) { string digestName; if (mechanism.StartsWith("HMAC-") || mechanism.StartsWith("HMAC/")) { digestName = mechanism.Substring(5); } else { digestName = mechanism.Substring(4); } return new HMac(DigestUtilities.GetDigest(digestName)); } if (mechanism == "AESCMAC") { return new CMac(new AesFastEngine()); } if (mechanism == "DESMAC") { return new CbcBlockCipherMac(new DesEngine()); } if (mechanism == "DESMAC/CFB8") { return new CfbBlockCipherMac(new DesEngine()); } if (mechanism == "DESMAC64") { return new CbcBlockCipherMac(new DesEngine(), 64); } if (mechanism == "DESEDECMAC") { return new CMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC") { return new CbcBlockCipherMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC/CFB8") { return new CfbBlockCipherMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC64") { return new CbcBlockCipherMac(new DesEdeEngine(), 64); } if (mechanism == "DESEDEMAC64WITHISO7816-4PADDING") { return new CbcBlockCipherMac(new DesEdeEngine(), 64, new ISO7816d4Padding()); } if (mechanism == "DESWITHISO9797" || mechanism == "ISO9797ALG3MAC") { return new ISO9797Alg3Mac(new DesEngine()); } if (mechanism == "ISO9797ALG3WITHISO7816-4PADDING") { return new ISO9797Alg3Mac(new DesEngine(), new ISO7816d4Padding()); } if (mechanism == "SKIPJACKMAC") { return new CbcBlockCipherMac(new SkipjackEngine()); } if (mechanism == "SKIPJACKMAC/CFB8") { return new CfbBlockCipherMac(new SkipjackEngine()); } #if INCLUDE_IDEA if (mechanism == "IDEAMAC") { return new CbcBlockCipherMac(new IdeaEngine()); } if (mechanism == "IDEAMAC/CFB8") { return new CfbBlockCipherMac(new IdeaEngine()); } #endif if (mechanism == "RC2MAC") { return new CbcBlockCipherMac(new RC2Engine()); } if (mechanism == "RC2MAC/CFB8") { return new CfbBlockCipherMac(new RC2Engine()); } if (mechanism == "RC5MAC") { return new CbcBlockCipherMac(new RC532Engine()); } if (mechanism == "RC5MAC/CFB8") { return new CfbBlockCipherMac(new RC532Engine()); } if (mechanism == "GOST28147MAC") { return new Gost28147Mac(); } if (mechanism == "VMPCMAC") { return new VmpcMac(); } if (mechanism == "SIPHASH-2-4") { return new SipHash(); } throw new SecurityUtilityException("Mac " + mechanism + " not recognised."); } public static string GetAlgorithmName( DerObjectIdentifier oid) { return (string) algorithms[oid.Id]; } public static byte[] DoFinal( IMac mac) { byte[] b = new byte[mac.GetMacSize()]; mac.DoFinal(b, 0); return b; } } }
34.053279
103
0.53773
[ "MIT" ]
krolpiotr/PHOENIX.Fakturering
itextsharp-core/srcbc/security/MacUtilities.cs
8,309
C#
using JetBrains.Annotations; using Newtonsoft.Json; namespace Crowdin.Api.Tasks { [PublicAPI] public class TaskAssignee { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("username")] public string UserName { get; set; } [JsonProperty("fullName")] public string FullName { get; set; } [JsonProperty("avatarUrl")] public string AvatarUrl { get; set; } [JsonProperty("wordsCount")] public int WordsCount { get; set; } [JsonProperty("wordsLeft")] public int WordsLeft { get; set; } } }
23.392857
45
0.554198
[ "MIT" ]
crowdin/crowdin-api-client-dotnet
src/Crowdin.Api/Tasks/TaskAssignee.cs
655
C#
#region File Description //----------------------------------------------------------------------------- // WorldObjectWriter.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler; using RolePlayingGameData; #endregion namespace RolePlayingGameProcessors { /// <summary> /// This class will be instantiated by the XNA Framework Content Pipeline /// to write the specified data type into binary .xnb format. /// /// This should be part of a Content Pipeline Extension Library project. /// </summary> [ContentTypeWriter] public class WorldObjectWriter : RolePlayingGameWriter<WorldObject> { protected override void Write(ContentWriter output, WorldObject value) { output.Write(value.Name); } } }
33.205128
79
0.659459
[ "MIT" ]
KtmarineStudios/Unity-XNA-RPG
Assets/Unity XNA RPG/Original/Scripts~/RolePlayingGameProcessors/WorldObjectWriter.cs
1,295
C#