content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Microsoft.AspNet.Identity.EntityFramework; namespace BSN.Commons.Users { public class UserClaim : IdentityUserClaim<string> { } }
15.666667
51
0.780142
[ "MIT" ]
BSVN/Commons
Source/BSN.Commons/Users/UserClaim.cs
143
C#
using UnityEngine; using UnityEditor; using System.IO; using System.Collections.Generic; using UnityEngine.Rendering; namespace Cinemachine.Editor { internal class WaveformWindow : EditorWindow { WaveformGenerator mWaveformGenerator; Texture2D mScreenshot; string mScreenshotFilename; // Controls how frequently (in seconds) the view will update. // Performance is really bad, so keep this as large as possible. public static float UpdateInterval = 0.5f; public static void SetDefaultUpdateInterval() { UpdateInterval = 0.5f; } //[MenuItem("Window/Waveform Monitor")] public static void OpenWindow() { WaveformWindow window = EditorWindow.GetWindow<WaveformWindow>(false); window.autoRepaintOnSceneChange = true; //window.position = new Rect(100, 100, 400, 400); window.Show(true); } private void OnEnable() { titleContent = new GUIContent("Waveform", CinemachineSettings.CinemachineLogoTexture); mWaveformGenerator = new WaveformGenerator(); mScreenshotFilename = Path.GetFullPath(FileUtil.GetUniqueTempPathInProject() + ".png"); ScreenCapture.CaptureScreenshot(mScreenshotFilename); EditorApplication.update += UpdateScreenshot; } private void OnDisable() { EditorApplication.update -= UpdateScreenshot; if (!string.IsNullOrEmpty(mScreenshotFilename) && File.Exists(mScreenshotFilename)) File.Delete(mScreenshotFilename); mScreenshotFilename = null; mWaveformGenerator.DestroyBuffers(); if (mScreenshot != null) DestroyImmediate(mScreenshot); mScreenshot = null; } private void OnGUI() { Rect rect = EditorGUILayout.GetControlRect(true); EditorGUIUtility.labelWidth /= 2; EditorGUI.BeginChangeCheck(); mWaveformGenerator.m_Exposure = EditorGUI.Slider( rect, "Exposure", mWaveformGenerator.m_Exposure, 0.01f, 2); if (EditorGUI.EndChangeCheck()) UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); EditorGUIUtility.labelWidth *= 2; rect.y += rect.height; rect.height = position.height - rect.height; var tex = mWaveformGenerator.Result; if (tex != null) GUI.DrawTexture(rect, tex); } float mLastUpdateTime = 0; private void UpdateScreenshot() { // Don't do this too often float now = Time.time; if (mScreenshot != null && now - mLastUpdateTime < UpdateInterval) return; mLastUpdateTime = now; if (!string.IsNullOrEmpty(mScreenshotFilename) && File.Exists(mScreenshotFilename)) { byte[] fileData = File.ReadAllBytes(mScreenshotFilename); if (mScreenshot == null) mScreenshot = new Texture2D(2, 2); mScreenshot.LoadImage(fileData); // this will auto-resize the texture dimensions. mWaveformGenerator.RenderWaveform(mScreenshot); // Capture the next one ScreenCapture.CaptureScreenshot(mScreenshotFilename); } } class WaveformGenerator { public float m_Exposure = 0.2f; RenderTexture mOutput; ComputeBuffer mData; int mThreadGroupSize; int mThreadGroupSizeX; int mThreadGroupSizeY; ComputeShader mWaveformCompute; MaterialPropertyBlock mWaveformProperties; Material mWaveformMaterial; CommandBuffer mCmd; static Mesh sFullscreenTriangle; static Mesh FullscreenTriangle { get { if (sFullscreenTriangle == null) { sFullscreenTriangle = new Mesh { name = "Fullscreen Triangle" }; sFullscreenTriangle.SetVertices(new List<Vector3> { new Vector3(-1f, -1f, 0f), new Vector3(-1f, 3f, 0f), new Vector3( 3f, -1f, 0f) }); sFullscreenTriangle.SetIndices( new [] { 0, 1, 2 }, MeshTopology.Triangles, 0, false); sFullscreenTriangle.UploadMeshData(false); } return sFullscreenTriangle; } } public WaveformGenerator() { mWaveformCompute = Resources.Load<ComputeShader>("CMWaveform"); mWaveformProperties = new MaterialPropertyBlock(); mWaveformMaterial = new Material(Resources.Load<Shader>("CMWaveform")) { name = "CMWaveformMaterial", hideFlags = HideFlags.DontSave }; mCmd = new CommandBuffer(); } void CreateBuffers(int width, int height) { if (mOutput == null || !mOutput.IsCreated() || mOutput.width != width || mOutput.height != height) { DestroyImmediate(mOutput); mOutput = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32) { anisoLevel = 0, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, useMipMap = false }; mOutput.Create(); } int count = Mathf.CeilToInt(width / (float)mThreadGroupSizeX) * mThreadGroupSizeX * height; if (mData == null) mData = new ComputeBuffer(count, sizeof(uint) << 2); else if (mData.count < count) { mData.Release(); mData = new ComputeBuffer(count, sizeof(uint) << 2); } } public void DestroyBuffers() { if (mData != null) mData.Release(); mData = null; DestroyImmediate(mOutput); mOutput = null; } public RenderTexture Result { get { return mOutput; } } public void RenderWaveform(Texture2D source) { if (mWaveformMaterial == null) return; int width = source.width; int height = source.height; int histogramResolution = 256; mThreadGroupSize = 256; mThreadGroupSizeX = 16; mThreadGroupSizeY = 16; CreateBuffers(width, histogramResolution); mCmd.Clear(); mCmd.BeginSample("CMWaveform"); var parameters = new Vector4( width, height, QualitySettings.activeColorSpace == ColorSpace.Linear ? 1 : 0, histogramResolution); // Clear the buffer on every frame int kernel = mWaveformCompute.FindKernel("KCMWaveformClear"); mCmd.SetComputeBufferParam(mWaveformCompute, kernel, "_WaveformBuffer", mData); mCmd.SetComputeVectorParam(mWaveformCompute, "_Params", parameters); mCmd.DispatchCompute(mWaveformCompute, kernel, Mathf.CeilToInt(width / (float)mThreadGroupSizeX), Mathf.CeilToInt(histogramResolution / (float)mThreadGroupSizeY), 1); // Gather all pixels and fill in our waveform kernel = mWaveformCompute.FindKernel("KCMWaveformGather"); mCmd.SetComputeBufferParam(mWaveformCompute, kernel, "_WaveformBuffer", mData); mCmd.SetComputeTextureParam(mWaveformCompute, kernel, "_Source", source); mCmd.SetComputeVectorParam(mWaveformCompute, "_Params", parameters); mCmd.DispatchCompute(mWaveformCompute, kernel, width, Mathf.CeilToInt(height / (float)mThreadGroupSize), 1); // Generate the waveform texture float exposure = Mathf.Max(0f, m_Exposure); exposure *= (float)histogramResolution / height; mWaveformProperties.SetVector(Shader.PropertyToID("_Params"), new Vector4(width, histogramResolution, exposure, 0f)); mWaveformProperties.SetBuffer(Shader.PropertyToID("_WaveformBuffer"), mData); mCmd.SetRenderTarget(mOutput); mCmd.DrawMesh( FullscreenTriangle, Matrix4x4.identity, mWaveformMaterial, 0, 0, mWaveformProperties); mCmd.EndSample("CMWaveform"); Graphics.ExecuteCommandBuffer(mCmd); } } } }
39.969828
107
0.541357
[ "MIT" ]
Axedas/hex-game
New Unity Project (1)/Library/PackageCache/com.unity.cinemachine@2.3.4/Editor/Windows/WaveformWindow.cs
9,273
C#
using AutoMapper; using MediatR; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Hosting; using rbkApiModules.Infrastructure.MediatR.Core; using System.Linq; using System.Threading.Tasks; namespace rbkApiModules.Payment.SqlServer { public class GetAllPlans { public class Command : IRequest<QueryResponse> { } public class Handler : BaseQueryHandler<Command> { private IWebHostEnvironment _env; private readonly DbContext _context; private readonly IMapper _mapper; public Handler(DbContext context, IMapper mapper, IHttpContextAccessor httpContextAccessor, IWebHostEnvironment env) : base(httpContextAccessor) { _context = context; _mapper = mapper; _env = env; } protected override async Task<object> ExecuteAsync(Command request) { var results = await _context.Set<Plan>() .OrderBy(x => x.Name) .Select(x => new PlanDto.Details() { Id = x.Id.ToString(), Name = x.Name, IsActive = x.IsActive, Duration = x.Duration, Price = x.Price, IsDefault = x.IsDefault, PaypalId = _env.IsDevelopment() ? x.PaypalSandboxId : x.PaypalId, }).ToListAsync(); return results; } } } }
32.431373
128
0.550181
[ "MIT" ]
rbasniak/rbk-api-modules
rbkApiModules.Payment.SqlServer/BusinessLogic/Queries/Plan/GetAllPlans.cs
1,654
C#
namespace XHTMLClassLibrary.BaseElements.Ruby { /// <summary> /// The "rp" tag defines what to show if a browser does NOT support ruby annotations. /// Ruby annotations are used for East Asian typography, to show the pronunciation of East Asian characters. /// Use the "rp" tag together with the "ruby" and the "rt" tags: The "ruby" element consists of one or more characters that needs an explanation/pronunciation, and an "rt" element that gives that information, and an optional "rp" element that defines what to show for browsers that not support ruby annotations. /// </summary> [HTMLItemAttribute(ElementName = "rp", SupportedStandards = HTMLElementType.HTML5 )] public class RpElement : HTMLItem , IRubyItem { public RpElement(HTMLElementType htmlStandard) : base(htmlStandard) { } protected override bool IsValidSubType(IHTMLItem item) { if (item is SimpleHTML5Text) { return item.IsValid(); } return false; } /// <summary> /// Checks it element data is valid /// </summary> /// <returns> /// true if valid /// </returns> public override bool IsValid() { return true; } } }
35.621622
315
0.614568
[ "MIT" ]
LordKiRon/fb2converters
fb2epub/HTML5ClassLibrary/BaseElements/Ruby/RpElement.cs
1,320
C#
using System; namespace Saltarelle.Compiler.JSModel.Expressions { [Serializable] public class JsThisExpression : JsExpression { private JsThisExpression() : base(ExpressionNodeType.This) { } private static JsThisExpression _instance = new JsThisExpression(); internal static new JsThisExpression This { get { return _instance; } } [System.Diagnostics.DebuggerStepThrough] public override TReturn Accept<TReturn, TData>(IExpressionVisitor<TReturn, TData> visitor, TData data) { return visitor.VisitThisExpression(this, data); } } }
30.777778
106
0.774368
[ "Apache-2.0" ]
AstrorEnales/SaltarelleCompiler
Compiler/JSModel/Expressions/JsThisExpression.cs
554
C#
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc.RazorPages; namespace MvcIdSrv.Pages { public class IndexModel : PageModel { private readonly IAuthenticationSchemeProvider schemes; public IndexModel(IAuthenticationSchemeProvider schemes) { this.schemes = schemes; } public IEnumerable<AuthenticationScheme> Schemes { get; private set; } public IEnumerable<AuthenticationScheme> RequestHandlerSchemes { get; private set; } public AuthenticationScheme DefaultAuthenticateScheme { get; private set; } public AuthenticationScheme DefaultChallengeScheme { get; private set; } public AuthenticationScheme DefaultForbidScheme { get; private set; } public AuthenticationScheme DefaultSignInScheme { get; private set; } public AuthenticationScheme DefaultSignOutScheme { get; private set; } public async Task OnGet() { Schemes = await this.schemes.GetAllSchemesAsync(); RequestHandlerSchemes = await this.schemes.GetRequestHandlerSchemesAsync(); DefaultAuthenticateScheme = await this.schemes.GetDefaultAuthenticateSchemeAsync(); DefaultChallengeScheme = await this.schemes.GetDefaultChallengeSchemeAsync(); DefaultForbidScheme = await this.schemes.GetDefaultForbidSchemeAsync(); DefaultSignInScheme = await this.schemes.GetDefaultSignInSchemeAsync(); DefaultSignOutScheme = await this.schemes.GetDefaultSignOutSchemeAsync(); } } }
41.025
95
0.723339
[ "Apache-2.0" ]
hbiarge/authentication-samples
src/03-Federation/MvcIdSrv/Pages/Index.cshtml.cs
1,643
C#
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ namespace BootstrapBlazor.Components; /// <summary> /// /// </summary> public interface IErrorLogger { /// <summary> /// 自定义 Error 处理方法 /// </summary> /// <param name="ex"></param> /// <returns></returns> Task HandlerExceptionAsync(Exception ex); /// <summary> /// 获得 是否显示 Error 提示弹窗 默认 true 显示 /// </summary> bool ShowToast { get; } /// <summary> /// 获得 Error Toast 弹窗标题 /// </summary> string? ToastTitle { get; } }
24.965517
111
0.624309
[ "Apache-2.0" ]
Ashhhhhh520/BootstrapBlazor
src/BootstrapBlazor/Components/ErrorLogger/IErrorLogger.cs
780
C#
/* The MIT License (MIT) Copyright(c) 2016 Stanislav Zhelnio Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MPSSELight { /// All comments in this file are from /// /// Application Note AN_108 /// Command Processor for MPSSE and MCU Host Bus Emulation Modes /// Document Reference No.: FT_000109 /// Version 1.5 /// Issue Date: 2011-09-09 /// /// It provides details of the op-codes used to control the Multi Purpose Synchronous Serial Engine (MPSSE) /// mode of the FT2232D, FT232H, FT2232H and FT4232H devices. public abstract class MpsseDeviceExtendedB : MpsseDeviceExtendedA { public MpsseDeviceExtendedB(String serialNumber) : base(serialNumber) { } public MpsseDeviceExtendedB(String serialNumber, MpsseParams param) : base(serialNumber, param) { } /// <summary> /// 7.1 Set I/O to only drive on a ‘0’ and tristate on a ‘1’ /// 0x9E /// LowByteEnablesForOnlyDrive0 /// HighByteEnablesForOnlyDrive0 /// This will make the I/Os only drive when the data is ‘0’ and tristate on the data /// being ‘1’ when the appropriate bit is set. Use this op-code when configuring the /// MPSSE for I2C use. /// </summary> /// <param name="low"></param> /// <param name="high"></param> public void SetIoToOnlyDriveOn0andTristateOn1(FtdiPin low, FtdiPin high) { write(MpsseCommand.SetIoToOnlyDriveOn0andTristateOn1(low, high)); } } }
39.984848
113
0.710496
[ "MIT" ]
RobertJYoung/SPI_GUI
MPSSELight/mpsse/MpsseDeviceExtendedB.cs
2,655
C#
//----------------------------------------------------------------------- // <copyright file="BestshotData.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- namespace ReimuPlugins.Th165Bestshot { using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using ReimuPlugins.Common; public sealed class BestshotData { private static readonly int[] Masks; private readonly BitVector32[] hashtagFields; [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Reviewed.")] static BestshotData() { Masks = new int[32]; Masks[0] = BitVector32.CreateMask(); for (var i = 1; i < Masks.Length; i++) { Masks[i] = BitVector32.CreateMask(Masks[i - 1]); } } public BestshotData() { this.Signature = string.Empty; this.Weekday = 0; this.Dream = 0; this.Width = 0; this.Height = 0; this.Width2 = 0; this.Height2 = 0; this.HalfWidth = 0; this.HalfHeight = 0; this.SlowRate = 0; this.DateTime = 0; this.Score = 0; this.hashtagFields = new BitVector32[3]; this.Score2 = 0; this.NumViewed = 0; this.NumLikes = 0; this.NumFavs = 0; this.Bitmap = null; } public string Signature { get; private set; } public short Weekday { get; private set; } public short Dream { get; private set; } public short Width { get; private set; } public short Height { get; private set; } public short Width2 { get; private set; } public short Height2 { get; private set; } public short HalfWidth { get; private set; } public short HalfHeight { get; private set; } public float SlowRate { get; private set; } public uint DateTime { get; private set; } public float Angle { get; private set; } // -PI .. +PI [rad] public int Score { get; private set; } // 0x0000_0001: (logical OR of bit 1, 2, 3?) // 0x0000_0002: 敵が見切れてる // 0x0000_0004: 敵を収めたよ // 0x0000_0008: 敵がど真ん中 // 0x0000_0010: 自撮り! // 0x0000_0020: ツーショット! // 0x0000_0040: (always 0b0?) // 0x0000_0080: ちょっと危なかった // 0x0000_0100: マジで危なかった // 0x0000_0200: 死ぬかと思った // 0x0000_0400: 赤色多いな // 0x0000_0800: 紫色多いね // 0x0000_1000: 青色多いよ // 0x0000_2000: 水色多いし // 0x0000_4000: 緑色多いねぇ // 0x0000_8000: 黄色多いなぁ // 0x0001_0000: 橙色多いお // 0x0002_0000: カラフル過ぎw // 0x0004_0000: 七色全部揃った! // 0x0008_0000: (NumBullets == 0) // 0x0010_0000: (always 0b0?) // 0x0020_0000: 風景写真 // 0x03C0_0000: (always 0b1111?) // 0x0400_0000: 接写! // 0x0800_0000: かなりの接写! // 0x1000_0000: 近すぎてぶつかるー! // 0x2000_0000: (always equal to 0x0000_0001?) // 0xC000_0000: (always 0b00?) public int Hashtags1 => this.hashtagFields[0].Data; public bool EnemyIsInFrame => this.hashtagFields[0][Masks[0]]; // Not used public bool EnemyIsPartlyInFrame => this.hashtagFields[0][Masks[1]]; public bool WholeEnemyIsInFrame => this.hashtagFields[0][Masks[2]]; public bool EnemyIsInMiddle => this.hashtagFields[0][Masks[3]]; public bool IsSelfie => this.hashtagFields[0][Masks[4]]; public bool IsTwoShot => this.hashtagFields[0][Masks[5]]; public bool BitDangerous => this.hashtagFields[0][Masks[7]]; public bool SeriouslyDangerous => this.hashtagFields[0][Masks[8]]; public bool ThoughtGonnaDie => this.hashtagFields[0][Masks[9]]; public bool ManyReds => this.hashtagFields[0][Masks[10]]; public bool ManyPurples => this.hashtagFields[0][Masks[11]]; public bool ManyBlues => this.hashtagFields[0][Masks[12]]; public bool ManyCyans => this.hashtagFields[0][Masks[13]]; public bool ManyGreens => this.hashtagFields[0][Masks[14]]; public bool ManyYellows => this.hashtagFields[0][Masks[15]]; public bool ManyOranges => this.hashtagFields[0][Masks[16]]; public bool TooColorful => this.hashtagFields[0][Masks[17]]; public bool SevenColors => this.hashtagFields[0][Masks[18]]; public bool NoBullet => this.hashtagFields[0][Masks[19]]; // Not used public bool IsLandscapePhoto => this.hashtagFields[0][Masks[21]]; public bool Closeup => this.hashtagFields[0][Masks[26]]; public bool QuiteCloseup => this.hashtagFields[0][Masks[27]]; public bool TooClose => this.hashtagFields[0][Masks[28]]; // 0x0000_0001: (always 0b0?) // 0x0000_0002: 敵が丸見えw // 0x0000_000C: (always 0b00?) // 0x0000_0010: 弾多すぎw // 0x0000_0020: 弾幕ふざけすぎww // 0x0000_0040: (ちょっ、密度濃すぎwww) // 0x0000_0080: 追い打ちしたよ! // 0x0000_0100: 座薬www // 0x0000_0200: 蛾みたいな蝶だ! // 0x0000_0400: 敵は無傷だ // 0x0000_0800: 敵はまだ余裕がある // 0x0000_1000: 敵がだいぶ弱ってる // 0x0000_2000: 敵が瀕死だ // 0x0000_4000: トドメをさしたよ! // 0x0000_8000: スリーショット! // 0x0001_0000: 二人まとめて撮影した! // 0x0002_0000: 二人が重なってるww // 0x0004_0000: 並んでピース // 0x0008_0000: (二人が近すぎるw) // 0x0010_0000: アチチ、焦げちゃうよ // 0x0020_0000: 弾、大きすぎでしょw // 0x0040_0000: 刃物投げんな // 0x0080_0000: うねうねだー! // 0x0100_0000: 光が止まって見える! // 0x0200_0000: スーパームーン! // 0x0400_0000: うぉっ、まぶし! // 0x0800_0000: ぐあ、眩しすぎるー! // 0x1000_0000: うあー、目が、目がー! // 0x2000_0000: 二人まとめてトドメ! // 0x4000_0000: (はっ!夢だったか) // 0x8000_0000: 岩の弾幕とかww public int Hashtags2 => this.hashtagFields[1].Data; public bool EnemyIsInFullView => this.hashtagFields[1][Masks[1]]; public bool TooManyBullets => this.hashtagFields[1][Masks[4]]; public bool TooPlayfulBarrage => this.hashtagFields[1][Masks[5]]; public bool TooDense => this.hashtagFields[1][Masks[6]]; // FIXME public bool Chased => this.hashtagFields[1][Masks[7]]; public bool IsSuppository => this.hashtagFields[1][Masks[8]]; public bool IsButterflyLikeMoth => this.hashtagFields[1][Masks[9]]; public bool EnemyIsUndamaged => this.hashtagFields[1][Masks[10]]; public bool EnemyCanAfford => this.hashtagFields[1][Masks[11]]; public bool EnemyIsWeakened => this.hashtagFields[1][Masks[12]]; public bool EnemyIsDying => this.hashtagFields[1][Masks[13]]; public bool Finished => this.hashtagFields[1][Masks[14]]; public bool IsThreeShot => this.hashtagFields[1][Masks[15]]; public bool TwoEnemiesTogether => this.hashtagFields[1][Masks[16]]; public bool EnemiesAreOverlapping => this.hashtagFields[1][Masks[17]]; public bool PeaceSignAlongside => this.hashtagFields[1][Masks[18]]; public bool EnemiesAreTooClose => this.hashtagFields[1][Masks[19]]; // FIXME public bool Scorching => this.hashtagFields[1][Masks[20]]; public bool TooBigBullet => this.hashtagFields[1][Masks[21]]; public bool ThrowingEdgedTools => this.hashtagFields[1][Masks[22]]; public bool Snaky => this.hashtagFields[1][Masks[23]]; public bool LightLooksStopped => this.hashtagFields[1][Masks[24]]; public bool IsSuperMoon => this.hashtagFields[1][Masks[25]]; public bool Dazzling => this.hashtagFields[1][Masks[26]]; public bool MoreDazzling => this.hashtagFields[1][Masks[27]]; public bool MostDazzling => this.hashtagFields[1][Masks[28]]; public bool FinishedTogether => this.hashtagFields[1][Masks[29]]; public bool WasDream => this.hashtagFields[1][Masks[30]]; // FIXME; Not used public bool IsRockyBarrage => this.hashtagFields[1][Masks[31]]; // 0x0000_0001: 弾幕を破壊する棒……? // 0x0000_0002: もふもふもふー // 0x0000_0004: わんわん写真 // 0x0000_0008: アニマルフォト // 0x0000_0010: 動物園! // 0x0000_0020: (ラブリーハート!) // 0x0000_0040: ぎゃー、雷はスマホがー // 0x0000_0080: ドンドコドンドコ // 0x0000_0100: (身体が霧状に!?) // 0x0000_0200: 何ともつまらない写真 // 0x0000_0400: (怒られちゃった……) // 0x0000_0800: 私こそが宇佐見菫子だ! // 0xFFFF_F000: (always all 0?) public int Hashtags3 => this.hashtagFields[2].Data; public bool IsStickDestroyingBarrage => this.hashtagFields[2][Masks[0]]; public bool Fluffy => this.hashtagFields[2][Masks[1]]; public bool IsDoggiePhoto => this.hashtagFields[2][Masks[2]]; public bool IsAnimalPhoto => this.hashtagFields[2][Masks[3]]; public bool IsZoo => this.hashtagFields[2][Masks[4]]; public bool IsLovelyHeart => this.hashtagFields[2][Masks[5]]; // FIXME public bool IsThunder => this.hashtagFields[2][Masks[6]]; public bool IsDrum => this.hashtagFields[2][Masks[7]]; public bool IsMisty => this.hashtagFields[2][Masks[8]]; // FIXME public bool IsBoringPhoto => this.hashtagFields[2][Masks[9]]; public bool WasScolded => this.hashtagFields[2][Masks[10]]; // FIXME public bool IsSumireko => this.hashtagFields[2][Masks[11]]; public int Score2 { get; private set; } public int BasePoint { get; private set; } // FIXME public int NumViewed { get; private set; } public int NumLikes { get; private set; } public int NumFavs { get; private set; } public int NumBullets { get; private set; } public int NumBulletsNearby { get; private set; } public int RiskBonus { get; private set; } // max(NumBulletsNearby, 2) * 40 .. min(NumBulletsNearby, 25) * 40 public float BossShot { get; private set; } // 1.20? .. 2.00 public float AngleBonus { get; private set; } // 1.00? .. 1.30 public int MacroBonus { get; private set; } // 0 .. 60? public float LikesPerView { get; private set; } public float FavsPerView { get; private set; } public int NumHashtags { get; private set; } public int NumRedBullets { get; private set; } public int NumPurpleBullets { get; private set; } public int NumBlueBullets { get; private set; } public int NumCyanBullets { get; private set; } public int NumGreenBullets { get; private set; } public int NumYellowBullets { get; private set; } public int NumOrangeBullets { get; private set; } public int NumLightBullets { get; private set; } public Bitmap Bitmap { get; private set; } public void Read(Stream input) { this.Read(input, false); } public void Read(Stream input, bool withBitmap) { using (var reader = new BinaryReader(input)) { this.Signature = Enc.CP932.GetString(reader.ReadBytes(4)); reader.ReadInt16(); // always 0x0401? this.Weekday = reader.ReadInt16(); this.Dream = reader.ReadInt16(); reader.ReadInt16(); // always 0x0100? this.Width = reader.ReadInt16(); this.Height = reader.ReadInt16(); reader.ReadInt32(); // always 0? this.Width2 = reader.ReadInt16(); this.Height2 = reader.ReadInt16(); this.HalfWidth = reader.ReadInt16(); this.HalfHeight = reader.ReadInt16(); reader.ReadInt32(); // always 0? this.SlowRate = reader.ReadSingle(); this.DateTime = reader.ReadUInt32(); reader.ReadInt32(); // always 0? this.Angle = reader.ReadSingle(); this.Score = reader.ReadInt32(); reader.ReadInt32(); // always 0? this.hashtagFields[0] = new BitVector32(reader.ReadInt32()); this.hashtagFields[1] = new BitVector32(reader.ReadInt32()); this.hashtagFields[2] = new BitVector32(reader.ReadInt32()); reader.ReadBytes(0x28); // always all 0? this.Score2 = reader.ReadInt32(); this.BasePoint = reader.ReadInt32(); this.NumViewed = reader.ReadInt32(); this.NumLikes = reader.ReadInt32(); this.NumFavs = reader.ReadInt32(); this.NumBullets = reader.ReadInt32(); this.NumBulletsNearby = reader.ReadInt32(); this.RiskBonus = reader.ReadInt32(); this.BossShot = reader.ReadSingle(); reader.ReadInt32(); // always 0? (Nice Shot?) this.AngleBonus = reader.ReadSingle(); this.MacroBonus = reader.ReadInt32(); reader.ReadInt32(); // always 0? (Front/Side/Back Shot?) reader.ReadInt32(); // always 0? (Clear Shot?) this.LikesPerView = reader.ReadSingle(); this.FavsPerView = reader.ReadSingle(); this.NumHashtags = reader.ReadInt32(); this.NumRedBullets = reader.ReadInt32(); this.NumPurpleBullets = reader.ReadInt32(); this.NumBlueBullets = reader.ReadInt32(); this.NumCyanBullets = reader.ReadInt32(); this.NumGreenBullets = reader.ReadInt32(); this.NumYellowBullets = reader.ReadInt32(); this.NumOrangeBullets = reader.ReadInt32(); this.NumLightBullets = reader.ReadInt32(); reader.ReadBytes(0x44); // always all 0? reader.ReadBytes(0x34); if (withBitmap) { this.Bitmap = ReadBitmap(input, this.Width, this.Height); } } } public void Read(string path) { this.Read(path, false); } public void Read(string path, bool withBitmap) { using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { this.Read(stream, withBitmap); } } private static Bitmap ReadBitmap(Stream input, int width, int height) { using (var extracted = new MemoryStream()) { Lzss.Extract(input, extracted); extracted.Seek(0, SeekOrigin.Begin); using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb)) { using (var locked = new BitmapLock(bitmap, ImageLockMode.WriteOnly)) { var source = extracted.ToArray(); var destination = locked.Scan0; Marshal.Copy(source, 0, destination, source.Length); } return bitmap.Clone() as Bitmap; } } } } }
35.487414
131
0.575638
[ "BSD-2-Clause" ]
fossabot/REIMU_Plugins_V2
Th165Bestshot/BestshotData.cs
16,448
C#
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 namespace Moryx.Products.Management.Implementations.Storage { public class FloatStrategyConfigurationAttribute : PropertyStrategyConfigurationAttribute { public FloatStrategyConfigurationAttribute() { ColumnType = typeof(double); SupportedTypes = new[] { typeof(float), typeof(double), typeof(decimal) }; } } }
28.736842
93
0.600733
[ "Apache-2.0" ]
milmilkat/MORYX-AbstractionLayer
src/Moryx.Products.Management/Implementations/Storage/FloatStrategyConfigurationAttribute.cs
546
C#
// Copyright (c) 2020-2021 Eli Aloni (a.k.a elix22) // Copyright (c) 2008-2015 the Urho3D project. // Copyright (c) 2015 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Diagnostics; using System.Globalization; using Urho.Resources; using Urho.Gui; using Urho; namespace Billboards { public class Sample : Application { UrhoConsole console; DebugHud debugHud; ResourceCache cache; Sprite logoSprite; UI ui; protected const float TouchSensitivity = 2; protected float Yaw { get; set; } protected float Pitch { get; set; } protected bool TouchEnabled { get; set; } protected Node CameraNode { get; set; } protected MonoDebugHud MonoDebugHud { get; set; } [Preserve] protected Sample(ApplicationOptions options = null) : base(options) {} static Sample() { Urho.Application.UnhandledException += Application_UnhandledException1; } static void Application_UnhandledException1(object sender, Urho.UnhandledExceptionEventArgs e) { if (Debugger.IsAttached && !e.Exception.Message.Contains("BlueHighway.ttf")) Debugger.Break(); e.Handled = true; } protected bool IsLogoVisible { get { return logoSprite.Visible; } set { logoSprite.Visible = value; } } static readonly Random random = new Random(); /// Return a random float between 0.0 (inclusive) and 1.0 (exclusive.) public static float NextRandom() { return (float)random.NextDouble(); } /// Return a random float between 0.0 and range, inclusive from both ends. public static float NextRandom(float range) { return (float)random.NextDouble() * range; } /// Return a random float between min and max, inclusive from both ends. public static float NextRandom(float min, float max) { return (float)((random.NextDouble() * (max - min)) + min); } /// Return a random integer between min and max - 1. public static int NextRandom(int min, int max) { return random.Next(min, max); } /// <summary> /// Joystick XML layout for mobile platforms /// </summary> protected virtual string JoystickLayoutPatch => string.Empty; protected override void Start () { Log.LogMessage += e => Debug.WriteLine($"[{e.Level}] {e.Message}"); base.Start(); if (Platform == Platforms.Android || Platform == Platforms.iOS || Options.TouchEmulation) { InitTouchInput(); } Input.Enabled = true; MonoDebugHud = new MonoDebugHud(this); MonoDebugHud.Show(); CreateLogo (); SetWindowAndTitleIcon (); CreateConsoleAndDebugHud (); Input.KeyDown += HandleKeyDown; } protected override void OnUpdate(float timeStep) { MoveCameraByTouches(timeStep); base.OnUpdate(timeStep); } /// <summary> /// Move camera for 2D samples /// </summary> protected void SimpleMoveCamera2D (float timeStep) { // Do not move if the UI has a focused element (the console) if (UI.FocusElement != null) return; // Movement speed as world units per second const float moveSpeed = 4.0f; // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (Input.GetKeyDown(Key.W)) CameraNode.Translate( Vector3.UnitY * moveSpeed * timeStep); if (Input.GetKeyDown(Key.S)) CameraNode.Translate(-Vector3.UnitY * moveSpeed * timeStep); if (Input.GetKeyDown(Key.A)) CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep); if (Input.GetKeyDown(Key.D)) CameraNode.Translate( Vector3.UnitX * moveSpeed * timeStep); if (Input.GetKeyDown(Key.PageUp)) { Camera camera = CameraNode.GetComponent<Camera>(); camera.Zoom = camera.Zoom * 1.01f; } if (Input.GetKeyDown(Key.PageDown)) { Camera camera = CameraNode.GetComponent<Camera>(); camera.Zoom = camera.Zoom * 0.99f; } } /// <summary> /// Move camera for 3D samples /// </summary> protected void SimpleMoveCamera3D (float timeStep, float moveSpeed = 10.0f) { const float mouseSensitivity = .1f; if (UI.FocusElement != null) return; var mouseMove = Input.MouseMove; Yaw += mouseSensitivity * mouseMove.X; Pitch += mouseSensitivity * mouseMove.Y; Pitch = MathHelper.Clamp(Pitch, -90, 90); CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0); if (Input.GetKeyDown (Key.W)) CameraNode.Translate ( Vector3.UnitZ * moveSpeed * timeStep); if (Input.GetKeyDown (Key.S)) CameraNode.Translate (-Vector3.UnitZ * moveSpeed * timeStep); if (Input.GetKeyDown (Key.A)) CameraNode.Translate (-Vector3.UnitX * moveSpeed * timeStep); if (Input.GetKeyDown (Key.D)) CameraNode.Translate ( Vector3.UnitX * moveSpeed * timeStep); } protected void MoveCameraByTouches (float timeStep) { if (!TouchEnabled || CameraNode == null) return; var input = Input; for (uint i = 0, num = input.NumTouches; i < num; ++i) { TouchState state = input.GetTouch(i); if (state.TouchedElement != null) continue; if (state.Delta.X != 0 || state.Delta.Y != 0) { var camera = CameraNode.GetComponent<Camera>(); if (camera == null) return; var graphics = Graphics; Yaw += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.X; Pitch += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.Y; CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0); } else { var cursor = UI.Cursor; if (cursor != null && cursor.Visible) cursor.Position = state.Position; } } } protected void SimpleCreateInstructionsWithWasd (string extra = "") { SimpleCreateInstructions("Use WASD keys and mouse/touch to move" + extra); } protected void SimpleCreateInstructions(string text = "") { var textElement = new Text() { Value = text, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; textElement.SetFont(ResourceCache.GetFont("Fonts/Anonymous Pro.ttf"), 15); UI.Root.AddChild(textElement); } void CreateLogo() { cache = ResourceCache; var logoTexture = cache.GetTexture2D("Textures/LogoLarge.png"); if (logoTexture == null) return; ui = UI; logoSprite = ui.Root.CreateSprite(); logoSprite.Texture = logoTexture; int w = logoTexture.Width; int h = logoTexture.Height; logoSprite.SetScale(256.0f / w); logoSprite.SetSize(w, h); logoSprite.SetHotSpot(0, h); logoSprite.SetAlignment(HorizontalAlignment.Left, VerticalAlignment.Bottom); logoSprite.Opacity = 0.75f; logoSprite.Priority = -100; } void SetWindowAndTitleIcon() { var icon = cache.GetImage("Textures/UrhoIcon.png"); Graphics.SetWindowIcon(icon); Graphics.WindowTitle = "UrhoSharp Sample"; } void CreateConsoleAndDebugHud() { var xml = cache.GetXmlFile("UI/DefaultStyle.xml"); console = Engine.CreateConsole(); console.DefaultStyle = xml; console.Background.Opacity = 0.8f; debugHud = Engine.CreateDebugHud(); debugHud.DefaultStyle = xml; } void HandleKeyDown(KeyDownEventArgs e) { switch (e.Key) { case Key.Esc: Exit(); return; case Key.F1: console.Toggle(); return; case Key.F2: debugHud.ToggleAll(); return; } var renderer = Renderer; switch (e.Key) { /* TBD ELI case Key.N1: var quality = renderer.TextureQuality; ++quality; if (quality > 2) quality = 0; renderer.TextureQuality = quality; break; case Key.N2: var mquality = renderer.MaterialQuality; ++mquality; if (mquality > 2) mquality = 0; renderer.MaterialQuality = mquality; break; */ case Key.N3: renderer.SpecularLighting = !renderer.SpecularLighting; break; case Key.N4: renderer.DrawShadows = !renderer.DrawShadows; break; case Key.N5: var shadowMapSize = renderer.ShadowMapSize; shadowMapSize *= 2; if (shadowMapSize > 2048) shadowMapSize = 512; renderer.ShadowMapSize = shadowMapSize; break; // shadow depth and filtering quality case Key.N6: var q = (int)renderer.ShadowQuality++; if (q > 3) q = 0; renderer.ShadowQuality = (ShadowQuality)q; break; // occlusion culling case Key.N7: var o = !(renderer.MaxOccluderTriangles > 0); renderer.MaxOccluderTriangles = o ? 5000 : 0; break; // instancing case Key.N8: renderer.DynamicInstancing = !renderer.DynamicInstancing; break; case Key.N9: Image screenshot = new Image(); Graphics.TakeScreenShot(screenshot); screenshot.SavePNG(FileSystem.ProgramDir + $"Data/Screenshot_{GetType().Name}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture)}.png"); break; } } void InitTouchInput() { TouchEnabled = true; var layout = ResourceCache.GetXmlFile("UI/ScreenJoystick_Samples.xml"); if (!string.IsNullOrEmpty(JoystickLayoutPatch)) { XmlFile patchXmlFile = new XmlFile(); patchXmlFile.FromString(JoystickLayoutPatch); layout.Patch(patchXmlFile); } var screenJoystickIndex = Input.AddScreenJoystick(layout, ResourceCache.GetXmlFile("UI/DefaultStyle.xml")); Input.SetScreenJoystickVisible(screenJoystickIndex, true); } } }
29.744928
166
0.686124
[ "MIT" ]
dertom95/Urho.Net-Samples
Billboards/Source/Sample.cs
10,262
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Reasonforscreeningduplicatebaserecord operations. /// </summary> public partial class Reasonforscreeningduplicatebaserecord : IServiceOperations<DynamicsClient>, IReasonforscreeningduplicatebaserecord { /// <summary> /// Initializes a new instance of the Reasonforscreeningduplicatebaserecord class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Reasonforscreeningduplicatebaserecord(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get spice_reasonforscreening_DuplicateBaseRecord from /// spice_reasonforscreenings /// </summary> /// <param name='spiceReasonforscreeningid'> /// key: spice_reasonforscreeningid of spice_reasonforscreening /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecordCollection>> GetWithHttpMessagesAsync(string spiceReasonforscreeningid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (spiceReasonforscreeningid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "spiceReasonforscreeningid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("spiceReasonforscreeningid", spiceReasonforscreeningid); tracingParameters.Add("top", top); tracingParameters.Add("skip", skip); tracingParameters.Add("search", search); tracingParameters.Add("filter", filter); tracingParameters.Add("count", count); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "spice_reasonforscreenings({spice_reasonforscreeningid})/spice_reasonforscreening_DuplicateBaseRecord").ToString(); _url = _url.Replace("{spice_reasonforscreeningid}", System.Uri.EscapeDataString(spiceReasonforscreeningid)); List<string> _queryParameters = new List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby)))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecordCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMduplicaterecordCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get spice_reasonforscreening_DuplicateBaseRecord from /// spice_reasonforscreenings /// </summary> /// <param name='spiceReasonforscreeningid'> /// key: spice_reasonforscreeningid of spice_reasonforscreening /// </param> /// <param name='duplicateid'> /// key: duplicateid of duplicaterecord /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecord>> DuplicateBaseRecordByKeyWithHttpMessagesAsync(string spiceReasonforscreeningid, string duplicateid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (spiceReasonforscreeningid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "spiceReasonforscreeningid"); } if (duplicateid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "duplicateid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("spiceReasonforscreeningid", spiceReasonforscreeningid); tracingParameters.Add("duplicateid", duplicateid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DuplicateBaseRecordByKey", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "spice_reasonforscreenings({spice_reasonforscreeningid})/spice_reasonforscreening_DuplicateBaseRecord({duplicateid})").ToString(); _url = _url.Replace("{spice_reasonforscreeningid}", System.Uri.EscapeDataString(spiceReasonforscreeningid)); _url = _url.Replace("{duplicateid}", System.Uri.EscapeDataString(duplicateid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMduplicaterecord>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMduplicaterecord>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.501166
566
0.574846
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/Reasonforscreeningduplicatebaserecord.cs
19,520
C#
// Copyright (c) 2017 Trevor Redfern // // This software is released under the MIT License. // https://opensource.org/licenses/MIT namespace SilverNeedle.Characters.Personalities { using SilverNeedle.Lexicon; using SilverNeedle.Serialization; public class FearTemplate : TemplateSentenceGenerator { public FearTemplate(IObjectStore data) : base(data) { } } }
22.611111
59
0.697789
[ "MIT" ]
shortlegstudio/silverneedle-web
silverneedle/lib/Characters/Personalities/FearTemplate.cs
407
C#
using System; using System.Collections.Generic; using System.Text; namespace SwitchAppDesign.AniListAPI.v2.Models { public class CharacterConnection { public CharacterEdge[] edges { get; set; } public Character[] nodes { get; set; } /// <summary> /// The pagination information /// </summary> public PageInfo pageInfo { get; set; } } }
22.222222
50
0.6225
[ "MIT" ]
SwitchAppDesign/AniListApi
PoisonIvy.AniListAPI/SwitchAppDesign.AniListAPI.v2/Models/CharacterConnection.cs
402
C#
using System.Web.Mvc; using System.Web.Routing; namespace Originarios { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Home", url: "Home", defaults: new { controller = "Home", action = "Index" } ); routes.MapRoute( name: "Contato", url: "Contato", defaults: new { controller = "Contatos", action = "Create" } ); routes.MapRoute( name: "Produtos", url: "Produtos", defaults: new { controller = "Produtos", action = "Index" } ); routes.MapRoute( name: "Produto", url: "Produto", defaults: new { controller = "Produtos", action = "Details" } ); routes.MapRoute( name: "Criar_Conta", url: "Criar_Conta", defaults: new { controller = "Account", action = "Register" } ); routes.MapRoute( name: "Logon", url: "Logon", defaults: new { controller = "Account", action = "Login" } ); routes.MapRoute( name: "Minha_Conta", url: "Minha_Conta", defaults: new { controller = "Manage", action = "Index" } ); routes.MapRoute( name: "Editar_Conta", url: "Editar_Conta", defaults: new { controller = "Manage", action = "Edit" } ); routes.MapRoute( name: "Alterar_Senha", url: "Alterar_Senha", defaults: new { controller = "Manage", action = "ChangePassword" } ); routes.MapRoute( name: "Meus_Produtos", url: "Meus_Produtos", defaults: new { controller = "Postagens", action = "Index" } ); routes.MapRoute( name: "Criar_Produto", url: "Criar_Produto", defaults: new { controller = "Postagens", action = "Create" } ); routes.MapRoute( name: "Editar_Produto", url: "Editar_Produto", defaults: new { controller = "Postagens", action = "Edit" } ); routes.MapRoute( name: "Ver_Produto", url: "Ver_Produto", defaults: new { controller = "Postagens", action = "Details" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
30.571429
99
0.443925
[ "MIT" ]
vitor-msp/originarios
Originarios/Originarios/App_Start/RouteConfig.cs
2,998
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-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// The output configuration for the processing job. /// </summary> public partial class ProcessingOutputConfig { private string _kmsKeyId; private List<ProcessingOutput> _outputs = new List<ProcessingOutput>(); /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The AWS Key Management Service (AWS KMS) key that Amazon SageMaker uses to encrypt /// the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of /// a KMS key, alias of a KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is /// applied to all outputs. /// </para> /// </summary> [AWSProperty(Max=2048)] public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property Outputs. /// <para> /// Output configuration information for a processing job. /// </para> /// </summary> [AWSProperty(Required=true, Min=0, Max=10)] public List<ProcessingOutput> Outputs { get { return this._outputs; } set { this._outputs = value; } } // Check to see if Outputs property is set internal bool IsSetOutputs() { return this._outputs != null && this._outputs.Count > 0; } } }
31.7875
107
0.619347
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/ProcessingOutputConfig.cs
2,543
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Networking.ServiceDiscovery.Dnssd { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum DnssdRegistrationStatus { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ Success, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ InvalidServiceName, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ ServerError, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ SecurityError, #endif } #endif }
28.115385
63
0.708618
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Networking.ServiceDiscovery.Dnssd/DnssdRegistrationStatus.cs
731
C#
using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; // This script is part of the BulletPro package for Unity. // Author : Simon Albou <albou.simon@gmail.com> namespace BulletPro.EditorScripts { // Base class for a DynamicParameter drawer related to the root struct. Heavily relies on inheritance. [CustomPropertyDrawer(typeof(DynamicAnimationCurveValue))] public class DynamicAnimationCurveValueDrawer : DynamicValueDrawer { public override float GetNumberOfLines(SerializedProperty property) { if (property.FindPropertyRelative("forceZeroToOne").boolValue) return 2; else return 1; } public override void DrawFixed(SerializedProperty property, SerializedProperty nonDynamicValue, GUIContent label) { if (!dynamicParameter.FindPropertyRelative("forceZeroToOne").boolValue) base.DrawFixed(property, nonDynamicValue, label); else { mainRect.height = EditorGUIUtility.singleLineHeight+1; EditorGUI.PropertyField(mainRect, nonDynamicValue, label); Rect bottomRect = new Rect(mainRect.x, mainRect.y + EditorGUIUtility.singleLineHeight+3, availableWidth, EditorGUIUtility.singleLineHeight+1); float fixCurveWidth = 70; Rect fixCurveRect = new Rect(bottomRect.x+availableWidth-fixCurveWidth, bottomRect.y, fixCurveWidth, bottomRect.height-2); float buttonSpace = 5; Rect warningRect = new Rect(bottomRect.x, bottomRect.y, bottomRect.width - (fixCurveWidth+buttonSpace), bottomRect.height); if (!BulletCurveDrawer.GoesFromZeroToOne(nonDynamicValue, true)) { string errorStr = (warningRect.width>185f?"X-axis must run from 0 to 1.":"X-axis error."); EditorGUI.LabelField(warningRect, errorStr, EditorStyles.boldLabel); Color oldColor = GUI.color; GUI.color = new Color(1.0f, 0.6f, 0.4f, 1f); if (GUI.Button(fixCurveRect, "Fix Curve", EditorStyles.miniButton)) BulletCurveDrawer.RepairCurveFromZeroToOne(nonDynamicValue, true); GUI.color = oldColor; } else { EditorGUI.BeginDisabledGroup(true); EditorGUI.LabelField(warningRect, (warningRect.width>140f?"This curve has no error.":"No error.")); if (GUI.Button(fixCurveRect, "Fix Curve", EditorStyles.miniButton)) Debug.Log("If you can see this, congratulations! I thought nobody would read the whole source code. Are you enjoying BulletPro so far?"); EditorGUI.EndDisabledGroup(); } } } } }
51.210526
161
0.635149
[ "MIT" ]
Asledorf/Software-Projects-Bullet-Hell
Assets/BulletPro/Core/Editor/PropertyDrawers/DynamicValueDrawers/DynamicAnimationCurveValueDrawer.cs
2,921
C#
namespace Sidekick.Business.Filters { public class ArmorFilter { public bool Disabled { get; set; } public ArmorFilters Filters { get; set; } = new ArmorFilters(); } }
21.777778
71
0.632653
[ "MIT" ]
cmos12345/Sidekick
src/Sidekick.Business/Filters/ArmorFilter.cs
196
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml.XPath; using Ops.NetCoe.LightFrame; namespace XC.MediaRat { public class VideoHelper { /// <summary> /// The cn media format /// </summary> public const string cnMediaFormat = "Format"; /// <summary> /// The cn duration /// </summary> public const string cnDuration = "Duration"; /// <summary> /// The cn bitrate /// </summary> public const string cnBitrate = "Bitrate"; /// <summary> /// The cn Width /// </summary> public const string cnWidth = "Width"; /// <summary> /// The cn Height /// </summary> public const string cnHeight = "Height"; ///<summary>ffProbe path</summary> private string _ffProbePath; ///<summary>ffProbe path</summary> public string FfProbePath { get { return this._ffProbePath ?? (this._ffProbePath = GetFfProbePath()); } set { this._ffProbePath = value; } } public KeyValuePairXCol<string, string> GetMetadataShell(MediaFile source) { KeyValuePairXCol<string, string> rz = new KeyValuePairXCol<string, string>(); Shell32.Shell shell = new Shell32.Shell(); Shell32.Folder objFolder; var srcFolder= Path.GetDirectoryName(source.FullName); string val; objFolder = shell.NameSpace(srcFolder); List<string> arrHeaders = new List<string>(); for (int i = 0; i < short.MaxValue; i++) { string header = objFolder.GetDetailsOf(null, i); if (String.IsNullOrEmpty(header)) break; arrHeaders.Add(header); } foreach (Shell32.FolderItem2 item in objFolder.Items()) { if (string.Compare(item.Name, source.Title, true) == 0) { rz.AddRange(GetXProp(item, "Bitrate", "Frame rate", "Duration")); for (int i = 0; i < arrHeaders.Count; i++) { val = objFolder.GetDetailsOf(item, i); if (!string.IsNullOrWhiteSpace(val)) { rz.Add(arrHeaders[i], val); } //System.Diagnostics.Debug.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(item, i)); } break; } } return rz; } IEnumerable<KeyValuePairX<string, string>> GetXProp(Shell32.FolderItem2 src, params string[] xPropNames) { foreach (var xpn in xPropNames) { var tmp = src.ExtendedProperty(xpn); if (tmp != null) { var rz = tmp.ToString(); if (!string.IsNullOrWhiteSpace(rz)) yield return new KeyValuePairX<string, string>() { Key = xpn, Value = rz }; } } } string GetFfProbePath() { const string ffProbeKey= "ffProbe.Path"; string rz=AppContext.Current.GetAppCfgItem(ffProbeKey); if (rz == null) throw new BizException(string.Format("Invalid configuration: appSetings['{0}'] must point to the ffProbe.exe", ffProbeKey)); return rz; } /// <summary> /// Gets the ff probe XML. /// </summary> /// <param name="sourcePath">The source path.</param> /// <returns></returns> /// <exception cref="Ops.NetCoe.LightFrame.BizException"></exception> public XElement GetFFProbeXml(string sourcePath) { StringBuilder sout = new StringBuilder(1024), serr = new StringBuilder(512); string args = string.Format("-i \"{0}\" -print_format xml -sexagesimal -show_error -show_format -show_streams", sourcePath); string action = null; string xtmp = null; try { action = string.Format("execute and parse results: \"{0}\" {1}", this.FfProbePath, args); OSCommand.RunAndWait(this.FfProbePath, args, (s) => sout.AppendLine(s), (s) => serr.AppendLine(s)); System.Threading.Thread.Sleep(20); // Sometimes sout is not populated to the end, need some cycles XElement xff = XElement.Parse(xtmp = sout.ToString()); return xff; } catch (Exception x) { AppContext.Current.LogTechError(string.Format("Failed to {0}", action), x); System.Diagnostics.Debug.WriteLine(xtmp); throw new BizException(x.ToShortMsg(action)); } } public bool TryGetMetadata(string sourceFile, out VideoStreamCfg videoCfg, out AudioStreamCfg audioCfg) { videoCfg = null; audioCfg = null; try { var xff = GetFFProbeXml(sourceFile); videoCfg = new VideoStreamCfg(); XElement xe = xff.Element("format"); int? tInt; int tmp=0; string tStr; TimeSpan tTs= TimeSpan.Zero; ulong sz=0; if (xe != null) { videoCfg.MediaFormat = xe.GetAttributeValue("format_name"); tInt= xe.GetAttributeInt("bit_rate"); videoCfg.Bitrate= tInt.HasValue ? tInt.Value : 0; if (xe.TryGetAttribute<ulong>("size", (x) => { sz = (ulong)x; return true; })) videoCfg.Size = sz; if (xe.TryGetAttribute<ulong>("duration", (x) => TimeSpan.TryParse(x.Value, out tTs))) videoCfg.Duration = tTs; } string codecType = null; foreach (var xs in xff.XPathSelectElements("streams/stream")) { codecType = xs.GetAttributeValue("codec_type"); switch (codecType) { case "video": { videoCfg.Codec = xs.GetAttributeValue("codec_name"); if (xs.TryGetAttribute<int>("height", (x) => int.TryParse(x.Value, out tmp))) videoCfg.Height = tmp; if (xs.TryGetAttribute<int>("width", (x) => int.TryParse(x.Value, out tmp))) videoCfg.Width = tmp; videoCfg.AspectRatio = xs.GetAttributeValue("display_aspect_ratio"); videoCfg.PixelFormat = xs.GetAttributeValue("pix_fmt"); videoCfg.FrameRate = xs.GetAttributeValue("r_frame_rate"); } break; case "audio": { audioCfg = new AudioStreamCfg(); audioCfg.Codec = xs.GetAttributeValue("codec_name"); if (xs.TryGetAttribute<int>("bit_rate", (x) => int.TryParse(x.Value, out tmp))) audioCfg.Bitrate = tmp; audioCfg.Channels = xs.GetAttributeValue("channels"); } break; } } return true; } catch (BizException bx) { return false; } catch (Exception x) { AppContext.Current.LogTechError(string.Format("Failed to get metadata for \"{0}\"", sourceFile), x); return false; } } /// <summary> /// Gets the metadata. /// </summary> /// <param name="sourcePath">The source path.</param> /// <returns></returns> /// <exception cref="Ops.NetCoe.LightFrame.BizException"></exception> public KeyValuePairXCol<string, string> GetMetadata(string sourcePath) { KeyValuePairXCol<string, string> rz = new KeyValuePairXCol<string, string>(); //StringBuilder sout = new StringBuilder(1024), serr = new StringBuilder(512); //string args = string.Format("-i \"{0}\" -print_format xml -sexagesimal -show_error -show_format -show_streams", sourcePath); string action = null; string xtmp = null; try { XElement xff = GetFFProbeXml(sourcePath); XElement xe = xff.Element("format"); //XAttribute xa; if (xe != null) { AddEntry(rz, xe, "format_name", cnMediaFormat); AddEntry(rz, xe, "duration", cnDuration); AddEntry(rz, xe, "bit_rate", cnBitrate); AddEntry(rz, xe, "size", "Size"); } string codecType = null; //, pfx=null; foreach (var xs in xff.XPathSelectElements("streams/stream")) { codecType = xs.GetAttributeValue("codec_type"); //pfx = null; switch (codecType) { case "video": { //pfx = "Video"; AddEntry(rz, xs, "codec_name", "Video Codec"); AddEntry(rz, xs, "height", "Height"); AddEntry(rz, xs, "width", "Width"); AddEntry(rz, xs, "display_aspect_ratio", "Aspect Ratio"); AddEntry(rz, xs, "pix_fmt", "Pixel Format"); AddEntry(rz, xs, "r_frame_rate", "Frame Rate"); //AddEntry(rz, xs, "duration", "Duration"); } break; case "audio": { //pfx = "Audio"; AddEntry(rz, xs, "codec_name", "Audio Codec"); AddEntry(rz, xs, "bit_rate", "Audio Bit Rate"); AddEntry(rz, xs, "channels", "Channels"); } break; //case "subtitle": { // pfx = "Subtitle"; // } // break; //default: // AppContext.Current.LogTechError(string.Format("Failed to recognise stream type '{0}' in the file \"{1}\"", this.FfProbePath, args), null); // break; } } action = string.Format("Get FileInfo for \"{0}\"", sourcePath); var fi = new FileInfo(sourcePath); if (fi != null) { rz.Add("Size", fi.Length.ToString("##,#")); rz.Add("Created", fi.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")); rz.Add("Type", fi.Extension); } else { rz.Add("Type", Path.GetExtension(sourcePath)); } } catch (BizException x) { throw; } catch (Exception x) { AppContext.Current.LogTechError(string.Format("Failed to {0}", action), x); System.Diagnostics.Debug.WriteLine(xtmp); throw new BizException(x.ToShortMsg(action)); } return rz; } /// <summary> /// Get the video file metadata. /// </summary> /// <param name="source">The source.</param> /// <returns></returns> public KeyValuePairXCol<string, string> GetMetadata(MediaFile source) { return GetMetadata(source.FullName); } void AddEntry(KeyValuePairXCol<string, string> trg, XElement src, XName attrName, string propName) { string vl = src.GetAttributeValue(attrName); if (!string.IsNullOrEmpty(vl)) { trg.Add(propName, vl); } } } public class VideoStreamCfg { /// <summary> /// Gets or sets the media format. /// </summary> public string MediaFormat { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> public TimeSpan Duration { get; set; } /// <summary> /// Gets or sets the bitrate. /// </summary> public int Bitrate { get; set; } /// <summary> /// Gets or sets the size. /// </summary> public ulong Size { get; set; } /// <summary> /// Gets or sets the video codec (e.g. h264). /// </summary> public string Codec { get; set; } /// <summary> /// Gets or sets the height. /// </summary> public int Height { get; set; } /// <summary> /// Gets or sets the width. /// </summary> public int Width { get; set; } /// <summary> /// Gets or sets the aspect ratio (e.g. 16:9). /// </summary> public string AspectRatio { get; set; } /// <summary> /// Gets or sets the pixel format (e.g. you420p). /// </summary> public string PixelFormat { get; set; } /// <summary> /// Gets or sets the frame rate (e.g. 30000/1001). /// </summary> public string FrameRate { get; set; } } public class AudioStreamCfg { /// <summary> /// Gets or sets the video codec (e.g. aac). /// </summary> public string Codec { get; set; } /// <summary> /// Gets or sets the bitrate. /// </summary> public int Bitrate { get; set; } /// <summary> /// Gets or sets the channels. /// </summary> public string Channels { get; set; } } }
41.967262
168
0.479682
[ "MIT" ]
xcrover/MediaRat
MediaRat/Logic/VideoHelper.cs
14,103
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 Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class ParameterNamesShouldMatchBaseDeclarationTests : DiagnosticAnalyzerTestBase { [Fact] public void VerifyNoFalsePositivesAreReported() { VerifyCSharp(@"public class TestClass { public void TestMethod() { } }"); VerifyCSharp(@"public class TestClass { public void TestMethod(string arg1, string arg2) { } }"); VerifyCSharp(@"public class TestClass { public void TestMethod(string arg1, string arg2, __arglist) { } }"); VerifyCSharp(@"public class TestClass { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }"); VerifyBasic(@"Public Class TestClass Public Sub TestMethod() End Sub End Class"); VerifyBasic(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); VerifyBasic(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) End Sub End Class"); } [Fact] public void VerifyOverrideWithWrongParameterNames() { VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)")); VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 106, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); VerifyBasic(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); VerifyBasic(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 106, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact] public void VerifyInterfaceImplementationWithWrongParameterNames() { VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2)")); VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)")); VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 97, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); VerifyBasic(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); VerifyBasic(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3() As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 96, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact] public void VerifyExplicitInterfaceImplementationWithWrongParameterNames() { VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 61, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 74, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2)")); VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 61, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 74, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)")); VerifyCSharp(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 61, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 74, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 96, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); } [Fact] public void VerifyInterfaceImplementationWithDifferentMethodName() { VerifyBasic(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); VerifyBasic(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 103, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact] public void VerifyThatInvalidOverrideIsNotReported() { VerifyCSharp(@"public class TestClass { public override void TestMethod(string arg1, string arg2) { } }", TestValidationMode.AllowCompileErrors); VerifyBasic(@"Public Class TestClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", TestValidationMode.AllowCompileErrors); } [Fact] public void VerifyOverrideWithInheritanceChain() { VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public abstract class IntermediateBaseClass : BaseClass { } public class TestClass : IntermediateBaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(12, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(12, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); VerifyBasic(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public MustInherit Class IntermediateBaseClass Inherits BaseClass End Class Public Class TestClass Inherits IntermediateBaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(12, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(12, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); } [Fact] public void VerifyNewOverrideWithInheritance() { VerifyCSharp(@"public class BaseClass { public void TestMethod(string baseArg1, string baseArg2) { } } public class TestClass : BaseClass { public new void TestMethod(string arg1, string arg2) { } }"); VerifyBasic(@"Public Class BaseClass Public Sub TestMethod(baseArg1 As String, baseArg2 As String) End Sub End Class Public Class TestClass Inherits BaseClass Public Shadows Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); } [Fact] public void VerifyBaseClassNameHasPriority() { VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string arg1, string arg2) { } }"); VerifyCSharp(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string interfaceArg1, string interfaceArg2) { } }", GetCSharpResultAt(13, 71, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg1", "arg1", "void BaseClass.TestMethod(string arg1, string arg2)"), GetCSharpResultAt(13, 93, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg2", "arg2", "void BaseClass.TestMethod(string arg1, string arg2)")); VerifyBasic(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); VerifyBasic(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) Implements ITest.TestMethod End Sub End Class", GetBasicResultAt(13, 63, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg1", "arg1", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)"), GetBasicResultAt(13, 88, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg2", "arg2", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)")); } [Fact] public void VerifyMultipleClashingInterfacesWithFullMatch() { VerifyCSharp(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } }"); VerifyBasic(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class"); } [Fact] public void VerifyMultipleClashingInterfacesWithPartialMatch() { VerifyCSharp(@"public interface ITest1 { void TestMethod(string arg1, string arg2, string arg3); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2, string otherArg3); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2, string otherArg3) { } }", GetCSharpResultAt(13, 88, "void TestClass.TestMethod(string arg1, string arg2, string otherArg3)", "otherArg3", "arg3", "void ITest1.TestMethod(string arg1, string arg2, string arg3)")); VerifyBasic(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String, arg3 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String, otherArg3 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String, otherArg3 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class", GetBasicResultAt(12, 85, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, otherArg3 As String)", "otherArg3", "arg3", "Sub ITest1.TestMethod(arg1 As String, arg2 As String, arg3 As String)")); } [Fact] public void VerifyIgnoresPropertiesWithTheSameName() { VerifyCSharp(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { int TestMethod { get; set; } } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } int ITest2.TestMethod { get; set; } }"); VerifyBasic(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Property TestMethod As Integer End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod End Sub Private Property TestMethodFromITest2 As Integer Implements ITest2.TestMethod End Class"); } [Fact] public void VerifyHandlesMultipleBaseMethodsWithTheSameName() { VerifyCSharp(@"public interface ITest { void TestMethod(string arg1); void TestMethod(string arg1, string arg2); } public class TestClass : ITest { public void TestMethod(string arg1) { } public void TestMethod(string arg1, string arg2) { } }"); VerifyBasic(@"Public Interface ITest Sub TestMethod(arg1 As String) Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Class TestClass Implements ITest Public Sub TestMethod(arg1 As String) Implements ITest.TestMethod End Sub Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); } private static DiagnosticResult GetCSharpResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) { return GetCSharpResultAt(line, column, ParameterNamesShouldMatchBaseDeclarationAnalyzer.Rule, violatingMember, violatingParameter, baseParameter, baseMember); } private static DiagnosticResult GetBasicResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) { return GetBasicResultAt(line, column, ParameterNamesShouldMatchBaseDeclarationAnalyzer.Rule, violatingMember, violatingParameter, baseParameter, baseMember); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new ParameterNamesShouldMatchBaseDeclarationAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new ParameterNamesShouldMatchBaseDeclarationAnalyzer(); } } }
56.22913
263
0.523549
[ "Apache-2.0" ]
RikkiGibson/roslyn-analyzers
src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/ParameterNamesShouldMatchBaseDeclarationTests.cs
31,657
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Squidex.Infrastructure.EventSourcing; namespace Squidex.Domain.Apps.Events.Apps { [EventType(nameof(AppDeleted))] public sealed class AppDeleted : AppEvent { } }
32.588235
78
0.422383
[ "MIT" ]
Appleseed/squidex
backend/src/Squidex.Domain.Apps.Events/Apps/AppDeleted.cs
556
C#
//------------------------------------------------------------------------------ // <自動產生的> // 這段程式碼是由工具產生的。 // // 變更這個檔案可能會導致不正確的行為,而且如果已重新產生 // 程式碼,則會遺失變更。 // </自動產生的> //------------------------------------------------------------------------------ namespace doctor { public partial class Historyupdate { /// <summary> /// Disease 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Disease; /// <summary> /// progress 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox progress; /// <summary> /// Prescription 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Prescription; /// <summary> /// submit 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.Button submit; /// <summary> /// Bill 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.Button Bill; } }
25.015873
81
0.45368
[ "MIT" ]
neocyc/Clinic-Management-System-ASP.NET
Code/DBProject/Doctor/HistoryUpdate.aspx.designer.cs
2,100
C#
//----------------------------------------------------------------------------- // Snowballs only mode // // Copyright (c) 2017 The Platinum Team // // 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. //----------------------------------------------------------------------------- ModeInfoGroup.add(new ScriptObject(ModeInfo_snowballsOnly) { class = "ModeInfo_snowballsOnly"; superclass = "ModeInfo"; identifier = "snowballsOnly"; file = "snowball"; name = "Snowballs Only"; desc = "No gems, just straight shooting action!"; hide = 1; hasMissions = 0; }); function ClientMode_snowballsOnly::onLoad(%this) { echo("[Mode" SPC %this.name @ " Client]: Loaded!"); }
40.357143
79
0.677286
[ "MIT" ]
HiGuyMB/PlatinumQuest-Dev
Marble Blast Platinum/platinum/client/scripts/modes/snowballsOnly.cs
1,695
C#
using HtmlAgilityPack; using OpenQA.Selenium; using System; using System.IO; using System.Linq; namespace SReportLib { public class SReport { private readonly IWebDriver _driver; internal SLog sLogs; public readonly string LogsPath; internal SReport(IWebDriver driver, string logsPath) { if (!Directory.Exists(logsPath)) Directory.CreateDirectory(logsPath); LogsPath = logsPath; _driver = driver; } public void Log(string testName) { if (_driver == null) return; var tesLogFolder = Path.Combine(LogsPath, testName); if (!Directory.Exists(tesLogFolder)) Directory.CreateDirectory(tesLogFolder); else { var files = (new DirectoryInfo(tesLogFolder)).GetFiles(); foreach (var file in files) file.Delete(); } if (sLogs.HasFlag(SLog.Screenshoot)) { var screenshot = (_driver as ITakesScreenshot).GetScreenshot(); screenshot.SaveAsFile(Path.Combine(tesLogFolder, $"{nameof(SLog.Screenshoot)}.png"), ScreenshotImageFormat.Png); } if (sLogs.HasFlag(SLog.PageHtml)) { using (var webClient = new System.Net.WebClient()) using (var stream = File.CreateText(Path.Combine(tesLogFolder, $"{nameof(SLog.PageHtml)}.htm"))) { var template = new HtmlDocument(); template.LoadHtml(_driver.PageSource); var nodes = template.DocumentNode.SelectNodes("//link[not(@href='')][@rel='stylesheet']"); if (nodes?.Any() != true) return; foreach (var node in nodes) { var attr = node.GetAttributeValue("href", ""); if (attr.StartsWith("data:text/css")) continue; var isUri = !Uri.TryCreate(attr, UriKind.RelativeOrAbsolute, out var uri); if (!isUri) { Uri.TryCreate(_driver.Url, UriKind.RelativeOrAbsolute, out var newUri); attr = $@"{newUri.Authority}/{uri}"; } if (!attr.StartsWith("http://") || !attr.StartsWith("https://")) { attr = $@"http://{attr}"; } var cssValue = webClient.DownloadString(attr); var newElement = template.CreateElement("style"); newElement.InnerHtml = cssValue; newElement.Attributes.Add("type", "text/css"); node.ParentNode.ReplaceChild(newElement, node); } stream.WriteLine(template.DocumentNode.InnerHtml); } } if (sLogs.HasFlag(SLog.BrowserConsole)) { SeleniumLog(tesLogFolder, LogType.Browser); } if (sLogs.HasFlag(SLog.SeleniumClient)) { SeleniumLog(tesLogFolder, LogType.Client); } if (sLogs.HasFlag(SLog.WebDriverInstance)) { SeleniumLog(tesLogFolder, LogType.Driver); } if (sLogs.HasFlag(SLog.Profiling)) { SeleniumLog(tesLogFolder, LogType.Profiler); } if (sLogs.HasFlag(SLog.ServerMessages)) { SeleniumLog(tesLogFolder, LogType.Server); } } private void SeleniumLog(string folder, string logType) { if (!_driver.Manage().Logs.AvailableLogTypes.Any(x => x == logType)) return; var logs = _driver.Manage().Logs.GetLog(logType)?.OrderBy(x => x.Timestamp); if (logs?.Any() == true) { using (var stream = File.CreateText(Path.Combine(folder, $"{nameof(logType)}.txt"))) { foreach (var log in logs) { stream.WriteLine($"DateTime: {log.Timestamp.ToLongTimeString()}"); stream.WriteLine($"Level: {log.Level}"); stream.WriteLine($"Message: {log.Message} {Environment.NewLine}"); } } } } } }
34.235294
128
0.478952
[ "MIT" ]
igorquintaes/SReport
SReport/SReport.cs
4,658
C#
using System; using System.Collections.Generic; using System.Linq; using Panda.Data; using Panda.Models; using Panda.ViewModels; namespace Panda.Services { public class ReceiptsService : IReceiptsService { private ApplicationDbContext db; public ReceiptsService(ApplicationDbContext db) { this.db = db; } public void Create(string packageId, string recipientId) { var packageWeight = this.db.Packages.Where(x => x.Id == packageId).Select(x => x.Weight).FirstOrDefault(); var receipt = new Receipt() { Fee = 2.67M* packageWeight, IssuedOn = DateTime.UtcNow, PackageId = packageId, RecipientId = recipientId }; this.db.Receipts.Add(receipt); this.db.SaveChanges(); } public ICollection<ReceiptViewModel> GetAllReceipts(string userId) { var receipts = this.db.Receipts.Where(x => x.RecipientId == userId).Select(x => new ReceiptViewModel() { Fee = x.Fee, Id = x.Id, IssuedOn = x.IssuedOn, RecipientName = x.Recipient.Username }).ToList(); return receipts; } } }
28.021277
118
0.55429
[ "MIT" ]
tonchevaAleksandra/C-Sharp-Web-Development-SoftUni-Problems
C# Web Basic/SUS September 2020 Session/Panda/Services/ReceiptsService.cs
1,319
C#
using System; using System.Diagnostics; namespace OMP.Connector.Domain.Models { public class RequestError { public string ErrorSource { get; set; } public string ErrorMessage { get; set; } public Exception Exception { get; } public RequestError(string errorSource, Exception ex) { this.Exception = ex.Demystify(); this.ErrorMessage = ex.ToStringDemystified(); this.ErrorSource = errorSource; } public RequestError(string errorSource, string errorMessage) { this.ErrorSource = errorSource; this.ErrorMessage = errorMessage; } } }
24.25
68
0.611193
[ "MIT" ]
OpenManufacturingPlatform/iotcon-opc-ua-connector-dotnet
src/Domain/Models/RequestError.cs
681
C#
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices.Query; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.MobileServices.Sync { internal class PullAction : TableAction { private static readonly DateTimeOffset Epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); private IDictionary<string, string> parameters; private MobileServiceRemoteTableOptions options; // the supported options on remote table private PullOptions pullOptions; private readonly PullCursor cursor; private Task pendingAction; private PullStrategy strategy; public PullAction(MobileServiceTable table, MobileServiceTableKind tableKind, MobileServiceSyncContext context, string queryId, MobileServiceTableQueryDescription query, IDictionary<string, string> parameters, IEnumerable<string> relatedTables, OperationQueue operationQueue, MobileServiceSyncSettingsManager settings, IMobileServiceLocalStore store, MobileServiceRemoteTableOptions options, PullOptions pullOptions, MobileServiceObjectReader reader, CancellationToken cancellationToken) : base(table, tableKind, queryId, query, relatedTables, context, operationQueue, settings, store, cancellationToken) { this.options = options; this.parameters = parameters; this.cursor = new PullCursor(query); this.pullOptions = pullOptions; this.Reader = reader ?? new MobileServiceObjectReader(); } public MobileServiceObjectReader Reader { get; private set; } protected override Task<bool> HandleDirtyTable() { // there are pending operations on the same table so defer the action this.pendingAction = this.Context.DeferTableActionAsync(this); // we need to return in order to give PushAsync a chance to execute so we don't await the pending push return Task.FromResult(false); } protected override Task WaitPendingAction() { return this.pendingAction ?? Task.FromResult(0); } protected async override Task ProcessTableAsync() { await CreatePullStrategy(); QueryResult result; do { this.CancellationToken.ThrowIfCancellationRequested(); string query = this.Query.ToODataString(); if (this.Query.UriPath != null) { query = MobileServiceUrlBuilder.CombinePathAndQuery(this.Query.UriPath, query); } result = await this.Table.ReadAsync(query, MobileServiceTable.IncludeDeleted(parameters), this.Table.Features); await this.ProcessAll(result.Values); // process the first batch result = await FollowNextLinks(result); } // if we are not at the end of result and there is no link to get more results while (!this.EndOfResult(result) && await this.strategy.MoveToNextPageAsync()); await this.strategy.PullCompleteAsync(); } private async Task ProcessAll(JArray items) { this.CancellationToken.ThrowIfCancellationRequested(); var deletedIds = new List<string>(); var upsertList = new List<JObject>(); foreach (var token in items) { var item = token as JObject; if (item == null) { continue; } if (!this.cursor.OnNext()) { break; } string id = this.Reader.GetId(item); if (id == null) { continue; } var pendingOperation = await this.OperationQueue.GetOperationByItemIdAsync(this.Table.TableName, id); if (pendingOperation != null) { continue; } DateTimeOffset updatedAt = this.Reader.GetUpdatedAt(item).GetValueOrDefault(Epoch).ToUniversalTime(); strategy.SetUpdateAt(updatedAt); if (this.Reader.IsDeleted(item)) { deletedIds.Add(id); } else { upsertList.Add(item); } } if (upsertList.Any()) { await this.Store.UpsertAsync(this.Table.TableName, upsertList, ignoreMissingColumns: true); } if (deletedIds.Any()) { await this.Store.DeleteAsync(this.Table.TableName, deletedIds); } await this.strategy.OnResultsProcessedAsync(); } // follows next links in the query result and returns final result private async Task<QueryResult> FollowNextLinks(QueryResult result) { while (!this.EndOfResult(result) && // if we are not at the end of result IsNextLinkValid(result.NextLink, this.options)) // and there is a valid link to get more results { this.CancellationToken.ThrowIfCancellationRequested(); result = await this.Table.ReadAsync(result.NextLink); await this.ProcessAll(result.Values); // process the results as soon as we've gotten them } return result; } // mongo doesn't support skip and top yet it generates next links with top and skip private bool IsNextLinkValid(Uri link, MobileServiceRemoteTableOptions options) { if (link == null) { return false; } IDictionary<string, string> parameters = HttpUtility.ParseQueryString(link.Query); bool isValid = ValidateOption(options, parameters, ODataOptions.Top, MobileServiceRemoteTableOptions.Top) && ValidateOption(options, parameters, ODataOptions.Skip, MobileServiceRemoteTableOptions.Skip) && ValidateOption(options, parameters, ODataOptions.OrderBy, MobileServiceRemoteTableOptions.OrderBy); return isValid; } private static bool ValidateOption(MobileServiceRemoteTableOptions validOptions, IDictionary<string, string> parameters, string optionKey, MobileServiceRemoteTableOptions option) { bool hasInvalidOption = parameters.ContainsKey(optionKey) && !validOptions.HasFlag(option); return !hasInvalidOption; } private bool EndOfResult(QueryResult result) { // if we got as many as we initially wanted // or there are no more results // then we're at the end return cursor.Complete || result.Values.Count == 0; } private async Task CreatePullStrategy() { bool isIncrementalSync = !String.IsNullOrEmpty(this.QueryId); if (isIncrementalSync) { this.strategy = new IncrementalPullStrategy(this.Table, this.Query, this.QueryId, this.Settings, this.cursor, this.options, this.pullOptions); } else { this.strategy = new PullStrategy(this.Query, this.cursor, this.options, this.pullOptions); } await this.strategy.InitializeAsync(); } } }
39.355769
186
0.56731
[ "Apache-2.0" ]
AndreyMitsyk/azure-mobile-apps-net-client
src/Microsoft.Azure.Mobile.Client/Table/Sync/Queue/Actions/PullAction.cs
8,188
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.MachineLearningServices.V20210701.Outputs { [OutputType] public sealed class RegistryListCredentialsResultResponse { public readonly string Location; public readonly ImmutableArray<Outputs.PasswordResponse> Passwords; public readonly string Username; [OutputConstructor] private RegistryListCredentialsResultResponse( string location, ImmutableArray<Outputs.PasswordResponse> passwords, string username) { Location = location; Passwords = passwords; Username = username; } } }
28.029412
81
0.687303
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/MachineLearningServices/V20210701/Outputs/RegistryListCredentialsResultResponse.cs
953
C#
// using System.Collections; using System.Collections.Generic; using System.IO; using Microsoft.AspNet.Builder; using Nancy; using Nancy.Owin; using Nancy.ViewEngines.Razor; namespace ToDoList { public class Startup { public void Configure(IApplicationBuilder app) { app.UseOwin(x => x.UseNancy()); } } public class CustomRootPathProvider : IRootPathProvider { public string GetRootPath() { return Directory.GetCurrentDirectory(); } } public class RazorConfig : IRazorConfiguration { public IEnumerable<string> GetAssemblyNames() { return null; } public IEnumerable<string> GetDefaultNamespaces() { return null; } public bool AutoIncludeModelNamespace { get { return false; } } } }
18.44186
57
0.675914
[ "MIT" ]
CharlesEwel/todolistcsharp
startup.cs
793
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LibraryApi.Data; using LibraryApi.Data.Entities; using LibraryApi.Dtos; using Microsoft.EntityFrameworkCore; using WorkingDaysManagement; namespace LibraryApi.Services { public class BookService : IBookService { private readonly ApplicationDbContext _context; public BookService(ApplicationDbContext context) { this._context = context; } public async Task<GetBookDto> AddBookAsync(AddBookDto book) { //check for existing book var existingBook = await _context.Books.Where(b => b.Title.ToUpper() == book.Title.ToUpper() && b.ISBN == book.ISBN).FirstOrDefaultAsync(); if(existingBook != null) return null; var newBook = new Book { Title = book.Title, ISBN = book.ISBN, PublishYear = book.PublishYear, CoverPrice = book.CoverPrice, IsAvailable = true }; await _context.Books.AddAsync(newBook); await _context.SaveChangesAsync(); return newBook.AsGetBookDto(); } public async Task<CheckoutResponseDto> CheckoutAsync(CheckoutRequestDto checkoutRequest) { if(checkoutRequest == null || checkoutRequest.BooksId.Count == 0) return new CheckoutResponseDto{ Message = "Invalid request body", BooksCheckedOut = null }; var booksToCheckout = new List<Book>(); booksToCheckout = await _context.Books.Where(b => checkoutRequest.BooksId.Contains(b.Id) && b.IsAvailable == true) .ToListAsync(); if(booksToCheckout.Count == 0) return new CheckoutResponseDto{ Message = "Book(s) not found or unavailable for check-out", BooksCheckedOut = null }; var booksCheckedOutList = new List<Checkout>(); var response = new CheckoutResponseDto(); for (int i = 0; i < booksToCheckout.Count; i++) { booksCheckedOutList.Add(CreateCheckout(booksToCheckout[i].Id, checkoutRequest)); booksToCheckout[i].IsAvailable = false; response.BooksCheckedOut.Add(booksToCheckout[i].AsGetBookDto()); } await _context.Checkouts.AddRangeAsync(booksCheckedOutList); await _context.SaveChangesAsync(); response.Message = "Successfully checked-out book(s)"; response.DueDate = new WorkingDayHelper().FuturWorkingDays(DateTime.Now, 10); return response; } public async Task<CheckInResponseDto> CheckInAsync(CheckInRequestDto checkInRequest) { if(checkInRequest == null || checkInRequest.BooksId.Count == 0) return new CheckInResponseDto{ Message = "Invalid request body", BooksCheckedIn = null }; var checkoutDetails = new List<Checkout>(); checkoutDetails = await _context.Checkouts.Where(c => checkInRequest.BooksId.Contains(c.BookId) && c.NationalIdentificationNumber == checkInRequest.NationalIdentificationNumber) .Include(b => b.Book) .ToListAsync(); if(checkoutDetails.Count == 0) return new CheckInResponseDto{ Message = "Book(s) not found or already checked-in", BooksCheckedIn = null }; var response = new CheckInResponseDto(); var penaltyDetails = new List<LateCheckIn>(); int daysLate; for (int i = 0; i < checkoutDetails.Count; i++) { checkoutDetails[i].Book.IsAvailable = true; response.BooksCheckedIn.Add(checkoutDetails[i].Book.AsGetBookDto()); //Calculate are record check-in over due details daysLate = CalculateOverDueDays(checkoutDetails[i]); if(daysLate > 0) { penaltyDetails.Add(checkoutDetails[i].AsLateCheckInDto(daysLate)); } } await _context.LateCheckIns.AddRangeAsync(penaltyDetails); await _context.SaveChangesAsync(); response.Message = "Successfully checked-out book(s)"; return response; } public async Task<List<GetBookDto>> GetAllBooksAsync() { var books = new List<GetBookDto>(); var collection = await _context.Books.OrderBy(b => b.PublishYear).ToListAsync(); if(collection is null) return null; foreach (var book in collection) { books.Add(book.AsGetBookDto()); } return books; } public async Task<GetBookDetailDto> GetBookByIdAsync(int bookId) { var bookDetails = await _context.Books.Where(b => b.Id == bookId) .Include(c => c.CheckoutHistory.OrderByDescending(h => h.Id)) .FirstOrDefaultAsync(); if(bookDetails is null) return null; return bookDetails.AsGetBookdetailDto(); } public async Task<CheckInDetailsDto> GetCheckIndetailsAsync(string nationalIdentificationNumber, int bookId) { if(string.IsNullOrWhiteSpace(nationalIdentificationNumber)) return null; var checkoutDetail = await _context.Checkouts.Where(c => c.BookId == bookId && c.NationalIdentificationNumber == nationalIdentificationNumber) .Include(b => b.Book) .FirstOrDefaultAsync(); if(checkoutDetail is null) return null; int daysLate = CalculateOverDueDays(checkoutDetail); var response = checkoutDetail.AsCheckInDetailsDto(daysLate); return response; } public async Task<List<GetBookDto>> SearchAsync(string searchParam, bool? isAvailable) { if(string.IsNullOrWhiteSpace(searchParam) && isAvailable is null) return await GetAllBooksAsync(); var searchResult = new List<GetBookDto>(); var collection = _context.Books as IQueryable<Book>; if (isAvailable is null) { collection = collection.AsQueryable() .Where(b => b.Title.Contains(searchParam) || b.ISBN.Contains(searchParam)) .OrderBy(c => c.PublishYear); } else if(string.IsNullOrWhiteSpace(searchParam) && isAvailable.HasValue) { collection = collection.AsQueryable() .Where(b => b.IsAvailable == isAvailable.Value) .OrderBy(c => c.PublishYear); } else { collection = collection.AsQueryable() .Where(b => b.IsAvailable == isAvailable.Value && (b.Title.Contains(searchParam) || b.ISBN.Contains(searchParam))) .OrderBy(c => c.PublishYear); } var books = await collection.ToListAsync(); if (books is null) return null; foreach (var book in books) { searchResult.Add(book.AsGetBookDto()); } return searchResult; } private static Checkout CreateCheckout(int bookId, CheckoutRequestDto customerDetail) { var workingDays = new WorkingDayHelper(); return new Checkout { BookId = bookId, FullName = customerDetail.FullName, Email = customerDetail.Email, PhoneNumber = customerDetail.PhoneNumber, NationalIdentificationNumber = customerDetail.NationalIdentificationNumber, CheckoutDate = DateTime.Now, ExpectedReturnDate = workingDays.FuturWorkingDays(DateTime.Now, 10) }; } private static int CalculateOverDueDays(Checkout checkout) { var workingDays = new WorkingDayHelper(); var dateDifference = DateTime.Now - checkout.ExpectedReturnDate; if(dateDifference.Days < 0) return 0; var workingDaysOverDue = workingDays.GetSpanDays(DateTime.Now, dateDifference); return workingDaysOverDue; } } }
39.609091
189
0.569429
[ "MIT" ]
mcmubby/LibraryApiAssessment
LibraryApi/Services/BookService.cs
8,714
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MvvmWcfCrudList.Common.Messaging { /// <summary> /// Contract for EventAggregator /// </summary> public interface IEventAggregator { //Any class should be able toSubscribe to an event type void Subscribe<T>(Action<T> handler); //Any class should be able to Unsubscribe from an event type void Unsubscribe<T>(Action<T> handler); //Any class should be able to Publish an event type void Publish<T>(T evt); } }
27.636364
68
0.675987
[ "MIT" ]
amitthk/mvvmwcfcrudlist
MvvmWcfCrudList/Common/Messaging/IEventAggregator.cs
610
C#
using DevChatter.Bot.Core.Commands; using DevChatter.Bot.Core.Data; using DevChatter.Bot.Core.Data.Model; using DevChatter.Bot.Core.Games.Roulette; using DevChatter.Bot.Core.Settings; using DevChatter.Bot.Infra.Ef; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using DevChatter.Bot.Core.Games.Hangman; using DevChatter.Bot.Core.Games.RockPaperScissors; namespace DevChatter.Bot.Web.Setup { public static class SetUpDatabase { public static IRepository SetUpRepository(BotConfiguration botConfig) { DbContextOptions<AppDataContext> options = new DbContextOptionsBuilder<AppDataContext>() .UseSqlServer(botConfig.ConnectionStrings.DefaultDatabase) .Options; var appDataContext = new AppDataContext(options); EnsureDatabase(appDataContext); IRepository repository = new EfGenericRepo(appDataContext); EnsureInitialData(repository); return repository; } private static void EnsureDatabase(AppDataContext dataContext) { dataContext.Database.Migrate(); } private static void EnsureInitialData(IRepository repository) { if (!repository.List<ScheduleEntity>().Any()) { repository.Create(GetDevChatterSchedule()); } if (!repository.List<IntervalMessage>().Any()) { repository.Create(GetIntervalMessages()); } if (!repository.List<SimpleCommand>().Any()) { repository.Create(GetSimpleCommands()); } if (!repository.List<QuoteEntity>().Any()) { repository.Create(GetInitialQuotes()); } if (!repository.List<HangmanWord>().Any()) { repository.Create(GetInitialHangmanWords()); } if (!repository.List<QuizQuestion>().Any()) { repository.Create(GetInitialQuizQuestions()); } if (!repository.List<CanvasProperties>().Any()) { repository.Create(GetInitialCanvasProperties()); } CreateDefaultSettingsIfNeeded(repository); // TODO: Remove static call, so it's more testable. CommandDataInitializer.UpdateCommandData(repository); } private static List<CanvasProperties> GetInitialCanvasProperties() { var canvasProperties = new List<CanvasProperties> { new CanvasProperties { CanvasId = "hangmanCanvas", Height = 300, Width = 800, TopY = 780, LeftX = 560 }, new CanvasProperties { CanvasId = "animationCanvas", Height = 1080, Width = 1920, TopY = 0, LeftX = 0 }, new CanvasProperties { CanvasId = "votingCanvas", Height = 1080, Width = 1920, TopY = 0, LeftX = 0 }, }; return canvasProperties; } private static void CreateDefaultSettingsIfNeeded(IRepository repository) { var settingsFactory = new SettingsFactory(repository); settingsFactory.CreateDefaultSettingsIfNeeded<RouletteSettings>(); settingsFactory.CreateDefaultSettingsIfNeeded<CurrencySettings>(); settingsFactory.CreateDefaultSettingsIfNeeded<HangmanSettings>(); settingsFactory.CreateDefaultSettingsIfNeeded<RockPaperScissorsSettings>(); } private static List<QuizQuestion> GetInitialQuizQuestions() { return new List<QuizQuestion> { new QuizQuestion { MainQuestion = "Who is the best C# Twitch Streamer?", Hint1 = "We aren't wearing hats...", Hint2 = "Brendan is modest enough, wouldn't you say?", CorrectAnswer = "DevChatter", WrongAnswer1 = "CSharpFritz", WrongAnswer2 = "Certainly not any of these other choices Kappa ", WrongAnswer3 = "robbiew_yt", }, new QuizQuestion { MainQuestion = "Which of these is NOT valid in C#?", Hint1 = "Tuples are OK by me.", Hint2 = "Should I give three hints?", CorrectAnswer = "int c, int d = 3;", WrongAnswer1 = "int x = 4;", WrongAnswer2 = "(int x, int y) = (1,2);", WrongAnswer3 = "int a = 5, b = 6;", }, }; } private static List<ScheduleEntity> GetDevChatterSchedule() { return new List<ScheduleEntity> { new ScheduleEntity {ExampleDateTime = new DateTimeOffset(2018, 5, 7, 18, 0, 0, TimeSpan.Zero)}, new ScheduleEntity {ExampleDateTime = new DateTimeOffset(2018, 5, 8, 18, 0, 0, TimeSpan.Zero)}, new ScheduleEntity {ExampleDateTime = new DateTimeOffset(2018, 5, 10, 16, 0, 0, TimeSpan.Zero)}, new ScheduleEntity {ExampleDateTime = new DateTimeOffset(2018, 5, 12, 17, 0, 0, TimeSpan.Zero)} }; } private static List<HangmanWord> GetInitialHangmanWords() { return new List<HangmanWord> { new HangmanWord("apple"), new HangmanWord("banana"), new HangmanWord("orange"), new HangmanWord("mango"), new HangmanWord("watermellon"), new HangmanWord("grapes"), new HangmanWord("pizza"), new HangmanWord("pasta"), new HangmanWord("pepperoni"), new HangmanWord("cheese"), new HangmanWord("mushroom"), new HangmanWord("csharp"), new HangmanWord("javascript"), new HangmanWord("cplusplus"), new HangmanWord("nullreferenceexception"), new HangmanWord("parameter"), new HangmanWord("argument") }; } private static List<IntervalMessage> GetIntervalMessages() { var automatedMessages = new List<IntervalMessage> { new IntervalMessage("Hello and welcome! I hope you're enjoying the stream! Feel free to follow along, make suggestions, ask questions, or contribute! And make sure you click the follow button to know when the next stream is!") }; return automatedMessages; } private static List<SimpleCommand> GetSimpleCommands() { return new List<SimpleCommand> { new SimpleCommand("discord", "Hey! Checkout out our Discord here https://discord.gg/aQry9jG"), new SimpleCommand("github", "Check out our GitHub repositories here https://github.com/DevChatter/"), new SimpleCommand("emotes", "These are our current emotes: devchaHype devchaDerp devchaFail "), new SimpleCommand("lurk", "[UserDisplayName] is just lurking here, but still thinks you're all awesome!"), }; } private static List<QuoteEntity> GetInitialQuotes() { return new List<QuoteEntity> { new QuoteEntity { QuoteId = 1, DateAdded = new DateTime(2018, 3, 19), AddedBy = "Brendoneus", Author = "DevChatter", Text = "Hello world!" }, new QuoteEntity { QuoteId = 2, DateAdded = new DateTime(2018, 3, 19), AddedBy = "Brendoneus", Author = "DevChatter", Text = "Welcome to DevChatter!" }, new QuoteEntity { QuoteId = 3, DateAdded = new DateTime(2018, 3, 20), AddedBy = "cragsify", Author = "DevChatter", Text = "I swear it's not rigged!" }, }; } } }
36.911765
242
0.518611
[ "MIT" ]
DevChatter/DevChatterBot
src/DevChatter.Bot.Web/Setup/SetUpDatabase.cs
8,785
C#
using UnityEngine; namespace DarkestDimension { public class ReadOnlyAttribute : PropertyAttribute { } }
21.8
58
0.788991
[ "MIT" ]
doc97/Darkest-Dimension
Assets/Scripts/Editor/ReadOnlyAttribute.cs
109
C#
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_Disks_Insert_sync] using Google.Cloud.Compute.V1; using lro = Google.LongRunning; public sealed partial class GeneratedDisksClientSnippets { /// <summary>Snippet for Insert</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void InsertRequestObject() { // Create client DisksClient disksClient = DisksClient.Create(); // Initialize request argument(s) InsertDiskRequest request = new InsertDiskRequest { Zone = "", DiskResource = new Disk(), RequestId = "", SourceImage = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = disksClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = disksClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } } } // [END compute_v1_generated_Disks_Insert_sync] }
40.261538
111
0.64081
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/DisksClient.InsertRequestObjectSnippet.g.cs
2,617
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using NuGet.Common; using NuGet.Frameworks; using NuGet.ProjectModel; namespace NuGet.Commands.Test { public static class ProjectJsonTestHelpers { /// <summary> /// Create a restore request for the specs. Restore only the first one. /// </summary> public static async Task<RestoreRequest> GetRequestAsync( RestoreArgs restoreContext, params PackageSpec[] projects) { var dgSpec = GetDGSpec(projects); var dgProvider = new DependencyGraphSpecRequestProvider( new RestoreCommandProvidersCache(), dgSpec); var requests = await dgProvider.CreateRequests(restoreContext); return requests.Single().Request; } /// <summary> /// Create a dg file for the specs. Restore only the first one. /// </summary> public static DependencyGraphSpec GetDGSpec(params PackageSpec[] projects) { var dgSpec = new DependencyGraphSpec(); var project = EnsureRestoreMetadata(projects.First()); dgSpec.AddProject(project); dgSpec.AddRestore(project.RestoreMetadata.ProjectUniqueName); foreach (var child in projects.Skip(1)) { dgSpec.AddProject(EnsureRestoreMetadata(child)); } return dgSpec; } /// <summary> /// Add restore metadata only if not already set. /// Sets the project style to PackageReference. /// </summary> public static PackageSpec EnsureRestoreMetadata(this PackageSpec spec) { if (string.IsNullOrEmpty(spec.RestoreMetadata?.ProjectUniqueName)) { return spec.WithTestRestoreMetadata(); } return spec; } public static PackageSpec WithTestProjectReference(this PackageSpec parent, PackageSpec child, params NuGetFramework[] frameworks) { var spec = parent.Clone(); if (frameworks.Length == 0) { // Use all frameworks if none were given frameworks = spec.TargetFrameworks.Select(e => e.FrameworkName).ToArray(); } foreach (var framework in spec .RestoreMetadata .TargetFrameworks .Where(e => frameworks.Contains(e.FrameworkName))) { framework.ProjectReferences.Add(new ProjectRestoreReference() { ProjectUniqueName = child.RestoreMetadata.ProjectUniqueName, ProjectPath = child.RestoreMetadata.ProjectPath }); } return spec; } /// <summary> /// Add fake PackageReference restore metadata. /// </summary> public static PackageSpec WithTestRestoreMetadata(this PackageSpec spec) { var updated = spec.Clone(); var packageSpecFile = new FileInfo(spec.FilePath); var projectDir = packageSpecFile.Directory.FullName; var projectPath = Path.Combine(projectDir, spec.Name + ".csproj"); updated.FilePath = projectPath; updated.RestoreMetadata = new ProjectRestoreMetadata(); updated.RestoreMetadata.CrossTargeting = updated.TargetFrameworks.Count > 0; updated.RestoreMetadata.OriginalTargetFrameworks = updated.TargetFrameworks.Select(e => e.FrameworkName.GetShortFolderName()).ToList(); updated.RestoreMetadata.OutputPath = projectDir; updated.RestoreMetadata.ProjectStyle = ProjectStyle.PackageReference; updated.RestoreMetadata.ProjectName = spec.Name; updated.RestoreMetadata.ProjectUniqueName = spec.Name; updated.RestoreMetadata.ProjectPath = projectPath; updated.RestoreMetadata.ConfigFilePaths = new List<string>(); updated.RestoreMetadata.CentralPackageVersionsEnabled = spec.RestoreMetadata?.CentralPackageVersionsEnabled ?? false; foreach (var framework in updated.TargetFrameworks.Select(e => e.FrameworkName)) { updated.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(framework)); } return updated; } } }
37.395161
147
0.621523
[ "Apache-2.0" ]
Therzok/NuGet.Client
test/TestUtilities/Test.Utility/Commands/ProjectJsonTestHelpers.cs
4,637
C#
namespace IGExtensions.Common.Maps.Controls { public class ShapeStyleEditor { } }
14.571429
43
0.647059
[ "MIT" ]
Infragistics/wpf-samples
Applications/IGExtensions/IGExtensions.Common.Maps/Controls/ShapeStyleEditor.cs
102
C#
using System; using BEPUphysics.Entities; using BEPUutilities; namespace BEPUphysics.Constraints.TwoEntity.JointLimits { /// <summary> /// Prevents the connected entities from twisting relative to each other beyond given limits. /// </summary> public class TwistLimit : JointLimit, I1DImpulseConstraintWithError, I1DJacobianConstraint { private readonly JointBasis3D basisA = new JointBasis3D(); private readonly JointBasis2D basisB = new JointBasis2D(); private float accumulatedImpulse; private float biasVelocity; private Vector3 jacobianA, jacobianB; private float error; /// <summary> /// Naximum angle that entities can twist. /// </summary> protected float maximumAngle; /// <summary> /// Minimum angle that entities can twist. /// </summary> protected float minimumAngle; private float velocityToImpulse; /// <summary> /// Constructs a new constraint which prevents the connected entities from twisting relative to each other beyond given limits. /// To finish the initialization, specify the connections (ConnectionA and ConnectionB) /// as well as the BasisA, BasisB and the MinimumAngle and MaximumAngle. /// This constructor sets the constraint's IsActive property to false by default. /// </summary> public TwistLimit() { IsActive = false; } /// <summary> /// Constructs a new constraint which prevents the connected entities from twisting relative to each other beyond given limits. /// </summary> /// <param name="connectionA">First connection of the pair.</param> /// <param name="connectionB">Second connection of the pair.</param> /// <param name="axisA">Twist axis attached to the first connected entity.</param> /// <param name="axisB">Twist axis attached to the second connected entity.</param> /// <param name="minimumAngle">Minimum twist angle allowed.</param> /// <param name="maximumAngle">Maximum twist angle allowed.</param> public TwistLimit(Entity connectionA, Entity connectionB, Vector3 axisA, Vector3 axisB, float minimumAngle, float maximumAngle) { ConnectionA = connectionA; ConnectionB = connectionB; SetupJointTransforms(axisA, axisB); MinimumAngle = minimumAngle; MaximumAngle = maximumAngle; } /// <summary> /// Gets the basis attached to entity A. /// The primary axis represents the twist axis attached to entity A. /// The x axis and y axis represent a plane against which entity B's attached x axis is projected to determine the twist angle. /// </summary> public JointBasis3D BasisA { get { return basisA; } } /// <summary> /// Gets the basis attached to entity B. /// The primary axis represents the twist axis attached to entity A. /// The x axis is projected onto the plane defined by localTransformA's x and y axes /// to get the twist angle. /// </summary> public JointBasis2D BasisB { get { return basisB; } } /// <summary> /// Gets or sets the maximum angle that entities can twist. /// </summary> public float MaximumAngle { get { return maximumAngle; } set { maximumAngle = value % (MathHelper.TwoPi); if (minimumAngle > MathHelper.Pi) minimumAngle -= MathHelper.TwoPi; if (minimumAngle <= -MathHelper.Pi) minimumAngle += MathHelper.TwoPi; } } /// <summary> /// Gets or sets the minimum angle that entities can twist. /// </summary> public float MinimumAngle { get { return minimumAngle; } set { minimumAngle = value % (MathHelper.TwoPi); if (minimumAngle > MathHelper.Pi) minimumAngle -= MathHelper.TwoPi; if (minimumAngle <= -MathHelper.Pi) minimumAngle += MathHelper.TwoPi; } } #region I1DImpulseConstraintWithError Members /// <summary> /// Gets the current relative velocity between the connected entities with respect to the constraint. /// </summary> public float RelativeVelocity { get { if (isLimitActive) { float velocityA, velocityB; //Find the velocity contribution from each connection Vector3.Dot(ref connectionA.angularVelocity, ref jacobianA, out velocityA); Vector3.Dot(ref connectionB.angularVelocity, ref jacobianB, out velocityB); return velocityA + velocityB; } return 0; } } /// <summary> /// Gets the total impulse applied by this constraint. /// </summary> public float TotalImpulse { get { return accumulatedImpulse; } } /// <summary> /// Gets the current constraint error. /// </summary> public float Error { get { return error; } } #endregion #region I1DJacobianConstraint Members /// <summary> /// Gets the linear jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the first connected entity.</param> public void GetLinearJacobianA(out Vector3 jacobian) { jacobian = Toolbox.ZeroVector; } /// <summary> /// Gets the linear jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the second connected entity.</param> public void GetLinearJacobianB(out Vector3 jacobian) { jacobian = Toolbox.ZeroVector; } /// <summary> /// Gets the angular jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the first connected entity.</param> public void GetAngularJacobianA(out Vector3 jacobian) { jacobian = jacobianA; } /// <summary> /// Gets the angular jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the second connected entity.</param> public void GetAngularJacobianB(out Vector3 jacobian) { jacobian = jacobianB; } /// <summary> /// Gets the mass matrix of the constraint. /// </summary> /// <param name="outputMassMatrix">Constraint's mass matrix.</param> public void GetMassMatrix(out float outputMassMatrix) { outputMassMatrix = velocityToImpulse; } #endregion /// <summary> /// Sets up the joint transforms by automatically creating perpendicular vectors to complete the bases. /// </summary> /// <param name="worldTwistAxisA">Twist axis in world space to attach to entity A.</param> /// <param name="worldTwistAxisB">Twist axis in world space to attach to entity B.</param> public void SetupJointTransforms(Vector3 worldTwistAxisA, Vector3 worldTwistAxisB) { worldTwistAxisA.Normalize(); worldTwistAxisB.Normalize(); Vector3 worldXAxis; Vector3.Cross(ref worldTwistAxisA, ref Toolbox.UpVector, out worldXAxis); float length = worldXAxis.LengthSquared(); if (length < Toolbox.Epsilon) { Vector3.Cross(ref worldTwistAxisA, ref Toolbox.RightVector, out worldXAxis); } worldXAxis.Normalize(); //Complete A's basis. Vector3 worldYAxis; Vector3.Cross(ref worldTwistAxisA, ref worldXAxis, out worldYAxis); basisA.rotationMatrix = connectionA.orientationMatrix; basisA.SetWorldAxes(worldTwistAxisA, worldXAxis, worldYAxis); //Rotate the axis to B since it could be arbitrarily rotated. Quaternion rotation; Quaternion.GetQuaternionBetweenNormalizedVectors(ref worldTwistAxisA, ref worldTwistAxisB, out rotation); Quaternion.Transform(ref worldXAxis, ref rotation, out worldXAxis); basisB.rotationMatrix = connectionB.orientationMatrix; basisB.SetWorldAxes(worldTwistAxisB, worldXAxis); } /// <summary> /// Solves for velocity. /// </summary> public override float SolveIteration() { float velocityA, velocityB; //Find the velocity contribution from each connection Vector3.Dot(ref connectionA.angularVelocity, ref jacobianA, out velocityA); Vector3.Dot(ref connectionB.angularVelocity, ref jacobianB, out velocityB); //Add in the constraint space bias velocity float lambda = -(velocityA + velocityB) + biasVelocity - softness * accumulatedImpulse; //Transform to an impulse lambda *= velocityToImpulse; //Clamp accumulated impulse (can't go negative) float previousAccumulatedImpulse = accumulatedImpulse; accumulatedImpulse = MathHelper.Max(accumulatedImpulse + lambda, 0); lambda = accumulatedImpulse - previousAccumulatedImpulse; //Apply the impulse Vector3 impulse; if (connectionA.isDynamic) { Vector3.Multiply(ref jacobianA, lambda, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3.Multiply(ref jacobianB, lambda, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } return Math.Abs(lambda); } /// <summary> /// Do any necessary computations to prepare the constraint for this frame. /// </summary> /// <param name="dt">Simulation step length.</param> public override void Update(float dt) { basisA.rotationMatrix = connectionA.orientationMatrix; basisB.rotationMatrix = connectionB.orientationMatrix; basisA.ComputeWorldSpaceAxes(); basisB.ComputeWorldSpaceAxes(); Quaternion rotation; Quaternion.GetQuaternionBetweenNormalizedVectors(ref basisB.primaryAxis, ref basisA.primaryAxis, out rotation); //Transform b's 'Y' axis so that it is perpendicular with a's 'X' axis for measurement. Vector3 twistMeasureAxis; Quaternion.Transform(ref basisB.xAxis, ref rotation, out twistMeasureAxis); //By dotting the measurement vector with a 2d plane's axes, we can get a local X and Y value. float y, x; Vector3.Dot(ref twistMeasureAxis, ref basisA.yAxis, out y); Vector3.Dot(ref twistMeasureAxis, ref basisA.xAxis, out x); var angle = (float) Math.Atan2(y, x); float distanceFromCurrent, distanceFromMaximum; if (IsAngleValid(angle, out distanceFromCurrent, out distanceFromMaximum)) { isActiveInSolver = false; accumulatedImpulse = 0; error = 0; isLimitActive = false; return; } isLimitActive = true; //Compute the jacobian. if (error > 0) { Vector3.Add(ref basisA.primaryAxis, ref basisB.primaryAxis, out jacobianB); if (jacobianB.LengthSquared() < Toolbox.Epsilon) { //A nasty singularity can show up if the axes are aligned perfectly. //In a 'real' situation, this is impossible, so just ignore it. isActiveInSolver = false; return; } jacobianB.Normalize(); jacobianA.X = -jacobianB.X; jacobianA.Y = -jacobianB.Y; jacobianA.Z = -jacobianB.Z; } else { //Reverse the jacobian so that the solver loop is easier. Vector3.Add(ref basisA.primaryAxis, ref basisB.primaryAxis, out jacobianA); if (jacobianA.LengthSquared() < Toolbox.Epsilon) { //A nasty singularity can show up if the axes are aligned perfectly. //In a 'real' situation, this is impossible, so just ignore it. isActiveInSolver = false; return; } jacobianA.Normalize(); jacobianB.X = -jacobianA.X; jacobianB.Y = -jacobianA.Y; jacobianB.Z = -jacobianA.Z; } //****** VELOCITY BIAS ******// //Compute the correction velocity. error = ComputeAngleError(distanceFromCurrent, distanceFromMaximum); float errorReduction; springSettings.ComputeErrorReductionAndSoftness(dt, 1 / dt, out errorReduction, out softness); //biasVelocity = MathHelper.Clamp(-error * myCorrectionStrength / dt, -myMaxCorrectiveVelocity, myMaxCorrectiveVelocity); biasVelocity = MathHelper.Min(MathHelper.Max(0, Math.Abs(error) - margin) * errorReduction, maxCorrectiveVelocity); if (bounciness > 0) { float relativeVelocity; float dot; //Find the velocity contribution from each connection Vector3.Dot(ref connectionA.angularVelocity, ref jacobianA, out relativeVelocity); Vector3.Dot(ref connectionB.angularVelocity, ref jacobianB, out dot); relativeVelocity += dot; biasVelocity = MathHelper.Max(biasVelocity, ComputeBounceVelocity(-relativeVelocity)); } //The nice thing about this approach is that the jacobian entry doesn't flip. //Instead, the error can be negative due to the use of Atan2. //This is important for limits which have a unique high and low value. //****** EFFECTIVE MASS MATRIX ******// //Connection A's contribution to the mass matrix float entryA; Vector3 transformedAxis; if (connectionA.isDynamic) { Matrix3x3.Transform(ref jacobianA, ref connectionA.inertiaTensorInverse, out transformedAxis); Vector3.Dot(ref transformedAxis, ref jacobianA, out entryA); } else entryA = 0; //Connection B's contribution to the mass matrix float entryB; if (connectionB.isDynamic) { Matrix3x3.Transform(ref jacobianB, ref connectionB.inertiaTensorInverse, out transformedAxis); Vector3.Dot(ref transformedAxis, ref jacobianB, out entryB); } else entryB = 0; //Compute the inverse mass matrix velocityToImpulse = 1 / (softness + entryA + entryB); } /// <summary> /// Performs any pre-solve iteration work that needs exclusive /// access to the members of the solver updateable. /// Usually, this is used for applying warmstarting impulses. /// </summary> public override void ExclusiveUpdate() { //****** WARM STARTING ******// //Apply accumulated impulse Vector3 impulse; if (connectionA.isDynamic) { Vector3.Multiply(ref jacobianA, accumulatedImpulse, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3.Multiply(ref jacobianB, accumulatedImpulse, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } } private static float ComputeAngleError(float distanceFromCurrent, float distanceFromMaximum) { float errorFromMin = MathHelper.TwoPi - distanceFromCurrent; float errorFromMax = distanceFromCurrent - distanceFromMaximum; return errorFromMax > errorFromMin ? errorFromMin : -errorFromMax; } private float GetDistanceFromMinimum(float angle) { if (minimumAngle > 0) { if (angle >= minimumAngle) return angle - minimumAngle; if (angle > 0) return MathHelper.TwoPi - minimumAngle + angle; return MathHelper.TwoPi - minimumAngle + angle; } if (angle < minimumAngle) return MathHelper.TwoPi - minimumAngle + angle; return angle - minimumAngle; //else //if (currentAngle >= 0) // return angle - myMinimumAngle; } private bool IsAngleValid(float currentAngle, out float distanceFromCurrent, out float distanceFromMaximum) { distanceFromCurrent = GetDistanceFromMinimum(currentAngle); distanceFromMaximum = GetDistanceFromMinimum(maximumAngle); return distanceFromCurrent < distanceFromMaximum; } } }
40.492274
136
0.568718
[ "Apache-2.0" ]
Anomalous-Software/BEPUPhysics
BEPUphysics/Constraints/TwoEntity/JointLimits/TwistLimit.cs
18,345
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace NarrativePlanning { [Serializable] public class Operator : ISerializable { public String name, character, location; public String text; public Dictionary<String, TypeNode> args; public Hashtable preT { get; set; } public Hashtable preF { get; set; } public Hashtable effT { get; set; } public Hashtable effF { get; set; } public Hashtable preBPlus { get; set; } public Hashtable preBMinus { get; set; } public Hashtable preUnsure { get; set; } public Hashtable effBPlus { get; set; } public Hashtable effBMinus { get; set; } public Hashtable effUnsure { get; set; } public Hashtable privateEffects { get; set; } //public List<Literal> preT, //preF, //preBPlus, //preBMinus, //preUnsure, //effT, //effF, //effBPlus, //effBMinus, //effUnsure; public Operator() { args = new Dictionary<string, TypeNode>(); preT = new Hashtable(); preF = new Hashtable(); effT = new Hashtable(); effF = new Hashtable(); preBPlus = new Hashtable(); preBMinus = new Hashtable(); preUnsure = new Hashtable(); effBPlus = new Hashtable(); effBMinus = new Hashtable(); effUnsure = new Hashtable(); privateEffects = new Hashtable(); } public Operator(SerializationInfo info, StreamingContext context){ name = Convert.ToString(info.GetValue("name", typeof(String))); character = Convert.ToString(info.GetValue("character", typeof(String))); location = Convert.ToString(info.GetValue("location", typeof(String))); text = Convert.ToString(info.GetValue("text", typeof(String))); args = info.GetValue("args", typeof(Dictionary<String, TypeNode>)) as Dictionary<String, TypeNode>; preT = info.GetValue("preT", typeof(Hashtable)) as Hashtable; preF = info.GetValue("preF", typeof(Hashtable)) as Hashtable; effT = info.GetValue("effT", typeof(Hashtable)) as Hashtable; effF = info.GetValue("effF", typeof(Hashtable)) as Hashtable; preBPlus = info.GetValue("preBPlus", typeof(Hashtable)) as Hashtable; preBMinus = info.GetValue("preBMinus", typeof(Hashtable)) as Hashtable; preUnsure = info.GetValue("preUnsure", typeof(Hashtable)) as Hashtable; effBPlus = info.GetValue("effBPlus", typeof(Hashtable)) as Hashtable; effBMinus = info.GetValue("effBMinus", typeof(Hashtable)) as Hashtable; effUnsure = info.GetValue("effUnsure", typeof(Hashtable)) as Hashtable; privateEffects = info.GetValue("privateEffects", typeof(Hashtable)) as Hashtable; } //DO NOT GIVE THE GROUNDED VERSIONS! /// <summary> /// Creates an operator object for given string grounded operator /// </summary> /// <param name="operators">List of operators (NOT grounded)</param> /// <param name="ground">String grounded operator</param> /// <returns>The grounded operator object</returns> public static Operator getOperator(List<Operator> operators, String ground){ Operator op = null; String[] words = ground.Trim().Split(' '); foreach(Operator oper in operators){ if(oper.name.Equals(words[0])){ //found the operator object, now populate it. op = oper.clone(); op.text = ground.Trim(); Dictionary<String, TypeNode>.Enumerator dict = op.args.GetEnumerator(); for (int i = 0; i < op.args.Count; ++i){ dict.MoveNext(); //words[i+1] should be an instance of op.args[i] typenode if(dict.Current.Value.getAllInstancesStrings().Contains(words[i+1])) { if (op.character.Equals(dict.Current.Key)) op.character = words[i + 1]; if (op.location.Equals(dict.Current.Key)) op.location = words[i + 1]; Hashtable tmp = (Hashtable)op.preT.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j){ if (dict.Current.Key.Equals(terms[j])){ builder.Replace(terms[j], words[i+1]); } } op.preT.Remove(l); op.preT.Add(builder.ToString(), 1); } tmp = (Hashtable)op.preF.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.preF.Remove(l); op.preF.Add(builder.ToString(), 1); } tmp = (Hashtable)op.preBPlus.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.preBPlus.Remove(l); op.preBPlus.Add(builder.ToString(), 1); } tmp = (Hashtable)op.preBMinus.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.preBMinus.Remove(l); op.preBMinus.Add(builder.ToString(), 1); } tmp = (Hashtable)op.preUnsure.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.preUnsure.Remove(l); op.preUnsure.Add(builder.ToString(), 1); } tmp = (Hashtable)op.effT.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.effT.Remove(l); op.effT.Add(builder.ToString(), 1); } tmp = (Hashtable)op.effF.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.effF.Remove(l); op.effF.Add(builder.ToString(), 1); } tmp = (Hashtable)op.effBPlus.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.effBPlus.Remove(l); op.effBPlus.Add(builder.ToString(), 1); } tmp = (Hashtable)op.effBMinus.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.effBMinus.Remove(l); op.effBMinus.Add(builder.ToString(), 1); } tmp = (Hashtable)op.effUnsure.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.effUnsure.Remove(l); op.effUnsure.Add(builder.ToString(), 1); } tmp = (Hashtable)op.privateEffects.Clone(); foreach (String l in tmp.Keys) { String[] terms = l.Split(' '); StringBuilder builder = new StringBuilder(l); for (int j = 0; j < terms.Length; ++j) { if (dict.Current.Key.Equals(terms[j])) { builder.Replace(terms[j], words[i + 1]); } } op.privateEffects.Remove(l); op.privateEffects.Add(builder.ToString(), 1); } } else{ Console.WriteLine("there seems to be an instance mismatch!"); } } return op; } } return op; } /// <summary> /// Finds the failed version of an operator /// </summary> /// <param name="operators">List of grounded operators</param> /// <param name="trueop">The true operator</param> /// <returns>The failed operator object</returns> public static Operator getFailedOperator(List<Operator> operators, Operator trueop) { String n = trueop.name.Substring(0, trueop.name.IndexOf("true") - 1); n = n + "-false"; foreach(Operator o in operators) { if (o.name.Equals(n)) { String a = o.text.Substring(o.text.IndexOf(" ") + 1); String b = trueop.text.Substring(trueop.text.IndexOf(" ") + 1); if (a.Equals(b)) return o; } } throw new Exception("Operator not found!!"); } public Operator clone(){ Operator o = new Operator(); o.name = this.name.Clone() as String; o.character = this.character.Clone() as String; o.location = this.location.Clone() as String; o.text = this.text.Clone() as String; o.args = this.args; o.preT = this.preT.Clone() as Hashtable; o.preF = this.preF.Clone() as Hashtable; o.effT = this.effT.Clone() as Hashtable; o.effF = this.effF.Clone() as Hashtable; o.preBPlus = this.preBPlus.Clone() as Hashtable; o.preBMinus = this.preBMinus.Clone() as Hashtable; o.preUnsure = this.preUnsure.Clone() as Hashtable; o.effBPlus = this.effBPlus.Clone() as Hashtable; o.effBMinus = this.effBMinus.Clone() as Hashtable; o.effUnsure = this.effUnsure.Clone() as Hashtable; o.privateEffects = this.privateEffects.Clone() as Hashtable; return o; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("name", name); info.AddValue("character", character); info.AddValue("location", location); info.AddValue("text", text); info.AddValue("args", args); info.AddValue("preT", preT); info.AddValue("preF", preF); info.AddValue("effT", effT); info.AddValue("effF", effF); info.AddValue("preBPlus", preBPlus); info.AddValue("preBMinus", preBMinus); info.AddValue("preUnsure", preUnsure); info.AddValue("effBPlus", effBPlus); info.AddValue("effBMinus", effBMinus); info.AddValue("effUnsure", effUnsure); info.AddValue("privateEffects", privateEffects); } } }
44.405128
111
0.386534
[ "MIT" ]
rushsangs/HeadSpace
NarrativePlanning/NarrativePlanning/Operator.cs
17,320
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Biztory.EnterpriseToolkit.TableauServerUnifiedApi.Rest.Model { /// <summary> /// /// </summary> [DataContract] public class QuerySchedulesResponseSchedulesSchedule { /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] [JsonProperty(PropertyName = "state")] public string State { get; set; } /// <summary> /// Gets or Sets Priority /// </summary> [DataMember(Name="priority", EmitDefaultValue=false)] [JsonProperty(PropertyName = "priority")] public string Priority { get; set; } /// <summary> /// Gets or Sets CreatedAt /// </summary> [DataMember(Name="createdAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "createdAt")] public string CreatedAt { get; set; } /// <summary> /// Gets or Sets UpdatedAt /// </summary> [DataMember(Name="updatedAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "updatedAt")] public string UpdatedAt { get; set; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name="type", EmitDefaultValue=false)] [JsonProperty(PropertyName = "type")] public string Type { get; set; } /// <summary> /// Gets or Sets Frequency /// </summary> [DataMember(Name="frequency", EmitDefaultValue=false)] [JsonProperty(PropertyName = "frequency")] public string Frequency { get; set; } /// <summary> /// Gets or Sets NextRunAt /// </summary> [DataMember(Name="nextRunAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "nextRunAt")] public string NextRunAt { get; set; } /// <summary> /// Gets or Sets EndScheduleAt /// </summary> [DataMember(Name="endScheduleAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "endScheduleAt")] public string EndScheduleAt { get; set; } /// <summary> /// Get 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 QuerySchedulesResponseSchedulesSchedule {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Priority: ").Append(Priority).Append("\n"); sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Frequency: ").Append(Frequency).Append("\n"); sb.Append(" NextRunAt: ").Append(NextRunAt).Append("\n"); sb.Append(" EndScheduleAt: ").Append(EndScheduleAt).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
31.418803
72
0.628672
[ "Apache-2.0" ]
biztory/tableau-performance-accelerator
tableau-server-api-unified/Rest/Model/QuerySchedulesResponseSchedulesSchedule.cs
3,678
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Quicksight.Inputs { public sealed class DataSourceParametersAuroraPostgresqlGetArgs : Pulumi.ResourceArgs { /// <summary> /// The database to which to connect. /// </summary> [Input("database", required: true)] public Input<string> Database { get; set; } = null!; /// <summary> /// The host to which to connect. /// </summary> [Input("host", required: true)] public Input<string> Host { get; set; } = null!; /// <summary> /// The port to which to connect. /// </summary> [Input("port", required: true)] public Input<int> Port { get; set; } = null!; public DataSourceParametersAuroraPostgresqlGetArgs() { } } }
29.105263
89
0.609403
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Quicksight/Inputs/DataSourceParametersAuroraPostgresqlGetArgs.cs
1,106
C#
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.DevTools.ContainerAnalysis.V1.Snippets { // [START containeranalysis_v1_generated_ContainerAnalysis_TestIamPermissions_async] using Google.Api.Gax; using Google.Cloud.DevTools.ContainerAnalysis.V1; using Google.Cloud.Iam.V1; using System.Threading.Tasks; public sealed partial class GeneratedContainerAnalysisClientSnippets { /// <summary>Snippet for TestIamPermissionsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task TestIamPermissionsRequestObjectAsync() { // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Permissions = { "", }, }; // Make the request TestIamPermissionsResponse response = await containerAnalysisClient.TestIamPermissionsAsync(request); } } // [END containeranalysis_v1_generated_ContainerAnalysis_TestIamPermissions_async] }
42
113
0.708829
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.DevTools.ContainerAnalysis.V1/Google.Cloud.DevTools.ContainerAnalysis.V1.GeneratedSnippets/ContainerAnalysisClient.TestIamPermissionsRequestObjectAsyncSnippet.g.cs
2,016
C#
using System; using System.Linq; using System.Threading.Tasks; using System.Xml.Serialization; namespace Bandwidth.Iris.Model { public class Disconnect: BaseModel { private const string DisconnectNumbersPath = "disconnects"; public static Task Create(Client client, string orderName, params string[] numbers) { var order = new DisconnectTelephoneNumberOrder { Name = orderName, DisconnectTelephoneNumberOrderType = new DisconnectTelephoneNumberOrderType { TelephoneNumberList = new TelephoneNumberList { TelephoneNumbers = numbers } } }; return client.MakePostRequest(client.ConcatAccountPath(DisconnectNumbersPath), order, true); } #if !PCL public static Task Create(string orderName, params string[] numbers) { return Create(Client.GetInstance(), orderName, numbers); } #endif public async Task<Note> AddNote(string orderId, Note note) { if (orderId == null) throw new ArgumentNullException("orderId"); using (var response = await Client.MakePostRequest(Client.ConcatAccountPath(string.Format("{0}/{1}/notes", DisconnectNumbersPath, orderId)), note)) { var list = await GetNotes(orderId); var id = Client.GetIdFromLocationHeader(response.Headers.Location); return list.First(n => n.Id == id); } } public async Task<Note[]> GetNotes(string orderId) { if (orderId == null) throw new ArgumentNullException("orderId"); return (await Client.MakeGetRequest<Notes>(Client.ConcatAccountPath(string.Format("{0}/{1}/notes", DisconnectNumbersPath, orderId)))) .List; } } public class DisconnectTelephoneNumberOrder { [XmlElement("name")] public string Name { get; set; } [XmlElement("DisconnectTelephoneNumberOrderType")] public DisconnectTelephoneNumberOrderType DisconnectTelephoneNumberOrderType { get; set; } } public class DisconnectTelephoneNumberOrderType { [XmlElement("TelephoneNumberList")] public TelephoneNumberList TelephoneNumberList { get; set; } } public class TelephoneNumberList { [XmlElement("TelephoneNumber")] public string[] TelephoneNumbers { get; set; } } }
35.383562
159
0.60511
[ "MIT" ]
Bandwidth/csharp-bandwidth-iris
Bandwidth.Iris/Model/Disconnect.cs
2,585
C#
namespace Bot.Builder.Community.Components.Adapters.GoogleBusiness.Core.Model { public class UserInfo { public string DisplayName { get; set; } public string UserDeviceLocale { get; set; } } }
27.625
78
0.683258
[ "MIT" ]
Bhargav-Guduri/botbuilder-community-dotnet
libraries/Bot.Builder.Community.Components.Adapters.GoogleBusiness.Core/Model/UserInfo.cs
223
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WindowsFormsApplicationCS.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.677419
152
0.56962
[ "MIT" ]
MizardX/SetStartupProjects
src/SampleSolution/WindowsFormsApplicationCS/Properties/Settings.Designer.cs
1,078
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HandPhysicsToolkit.Utils { [RequireComponent(typeof(LineRenderer))] [ExecuteInEditMode] public class LRPath : MonoBehaviour { LineRenderer lr; public List<Transform> points = new List<Transform>(); void Start() { lr = GetComponent<LineRenderer>(); lr.useWorldSpace = true; } private void Update() { UpdateLR(); } void UpdateLR() { if (!lr || points.Find(p => p== null)) return; lr.positionCount = points.Count; for (int i = 0; i < points.Count; i++) { if (points[i] == null) continue; lr.SetPosition(i, points[i].position); } } } }
21.121951
62
0.518476
[ "MIT" ]
2kah/HPTK
Runtime/Utils/LRPath.cs
868
C#
namespace Puppy.Elastic.Model.SearchModel.Sorting { public interface ISort { void WriteJson(ElasticJsonWriter elasticCrudJsonWriter); } }
22.428571
64
0.732484
[ "Unlicense" ]
stssoftware/Puppy
Puppy.Elastic/Model/SearchModel/Sorting/ISort.cs
157
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 personalize-events-2018-03-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.PersonalizeEvents.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.PersonalizeEvents.Model.Internal.MarshallTransformations { /// <summary> /// Event Marshaller /// </summary> public class EventMarshaller : IRequestMarshaller<Event, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(Event requestObject, JsonMarshallerContext context) { if(requestObject.IsSetEventId()) { context.Writer.WritePropertyName("eventId"); context.Writer.Write(requestObject.EventId); } if(requestObject.IsSetEventType()) { context.Writer.WritePropertyName("eventType"); context.Writer.Write(requestObject.EventType); } if(requestObject.IsSetEventValue()) { context.Writer.WritePropertyName("eventValue"); context.Writer.Write(requestObject.EventValue); } if(requestObject.IsSetImpression()) { context.Writer.WritePropertyName("impression"); context.Writer.WriteArrayStart(); foreach(var requestObjectImpressionListValue in requestObject.Impression) { context.Writer.Write(requestObjectImpressionListValue); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetItemId()) { context.Writer.WritePropertyName("itemId"); context.Writer.Write(requestObject.ItemId); } if(requestObject.IsSetProperties()) { context.Writer.WritePropertyName("properties"); context.Writer.Write(requestObject.Properties); } if(requestObject.IsSetRecommendationId()) { context.Writer.WritePropertyName("recommendationId"); context.Writer.Write(requestObject.RecommendationId); } if(requestObject.IsSetSentAt()) { context.Writer.WritePropertyName("sentAt"); context.Writer.Write(requestObject.SentAt); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static EventMarshaller Instance = new EventMarshaller(); } }
33.559633
116
0.61673
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/PersonalizeEvents/Generated/Model/Internal/MarshallTransformations/EventMarshaller.cs
3,658
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Objetos.Constantes { public class EnumTipoAtributo { public enum TipoAtributo { tipo_int, tipo_long, tipo_float, tipo_double, tipo_char, tipo_string, tipo_object, tipo_DateTime, tipo_List } } }
19.6
34
0.532653
[ "MIT" ]
Viniciusalopes/ObjPessoa
csharp/Objetos/Constantes/EnumTipoAtributo.cs
492
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatform : MonoBehaviour { public Transform[] wayPoints; int currentIndex; Vector3 target; public float speed; public float stoppingDistance; List<GameObject> currentObjects; void Start() { currentIndex = wayPoints.Length - 1; currentObjects = new List<GameObject>(); NextPoint(); } void Update() { Vector3 direction = target - transform.position; float distance = direction.magnitude; if (distance <= stoppingDistance) { NextPoint(); direction = target - transform.position; } direction.Normalize(); transform.position += direction * speed * Time.deltaTime; foreach (GameObject objecti in currentObjects) { if (objecti.tag == "Player") { objecti.transform.position += direction * speed * Time.deltaTime; } else { objecti.transform.position += direction * speed * Time.deltaTime; } } } void NextPoint() { currentIndex++; currentIndex %= wayPoints.Length; target = wayPoints[currentIndex].position; } void OnTriggerEnter(Collider other) { GameObject rootObject = other.gameObject.transform.root.gameObject; if (!currentObjects.Contains(rootObject)) { currentObjects.Add(rootObject); } } void OnTriggerStay(Collider other) { GameObject rootObject = other.gameObject.transform.root.gameObject; if (!currentObjects.Contains(rootObject)) { currentObjects.Add(rootObject); } } void OnTriggerExit(Collider other) { GameObject rootObject = other.gameObject.transform.root.gameObject; if (currentObjects.Contains(rootObject)) { currentObjects.Remove(other.gameObject); } } }
24.535714
81
0.592431
[ "MIT" ]
sps1112/roaming-ruins
Assets/Scripts/MovingPlatform.cs
2,063
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceCodeFirstExercise.Data.Models { public class Employee { public Employee() { Reports = new HashSet<Report>(); } public int Id { get; set; } [MaxLength(25)] public string FirstName { get; set; } [MaxLength(25)] public string LastName { get; set; } public DateTime? Birthdate { get; set; } [Range(18,110)] public int? Age { get; set; } public int DepartmentId { get; set; } public Department Department { get; set; } public ICollection<Report> Reports { get; set; } } }
22.771429
56
0.599749
[ "MIT" ]
Alexxx2207/EntityFrameworkCore
ServiceCodeFirstExercise/ServiceCodeFirstExercise/Data/Models/Employee.cs
799
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Yandex.Outputs { [OutputType] public sealed class VpcDefaultSecurityGroupEgress { /// <summary> /// Description of the security group. /// </summary> public readonly string? Description; public readonly int? FromPort; /// <summary> /// Id of the security group. /// </summary> public readonly string? Id; /// <summary> /// Labels to assign to this security group. /// </summary> public readonly ImmutableDictionary<string, string>? Labels; public readonly int? Port; public readonly string? PredefinedTarget; public readonly string Protocol; public readonly string? SecurityGroupId; public readonly int? ToPort; public readonly ImmutableArray<string> V4CidrBlocks; public readonly ImmutableArray<string> V6CidrBlocks; [OutputConstructor] private VpcDefaultSecurityGroupEgress( string? description, int? fromPort, string? id, ImmutableDictionary<string, string>? labels, int? port, string? predefinedTarget, string protocol, string? securityGroupId, int? toPort, ImmutableArray<string> v4CidrBlocks, ImmutableArray<string> v6CidrBlocks) { Description = description; FromPort = fromPort; Id = id; Labels = labels; Port = port; PredefinedTarget = predefinedTarget; Protocol = protocol; SecurityGroupId = securityGroupId; ToPort = toPort; V4CidrBlocks = v4CidrBlocks; V6CidrBlocks = v6CidrBlocks; } } }
28.2
88
0.601418
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-yandex
sdk/dotnet/Outputs/VpcDefaultSecurityGroupEgress.cs
2,115
C#
using Microsoft.Practices.Unity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Templar.Domain.Services.Repositories; using Templar.Domain.Services.Services; using Templar.Repository.SqlServer; namespace Templar.Rest.Service.ServiceHost.Configurations { public class DependencyConfiguration { public void Configure(IUnityContainer Container) { Container.RegisterType<IClueRepository, ClueRepository>(); Container.RegisterType<IClueDomainService, ClueDomainService>(); } } }
27.772727
76
0.754501
[ "Apache-2.0" ]
Arconte/Templar
Src/Templar.Rest.Service.ServiceHost/Configurations/DependencyConfiguration.cs
613
C#
#if !NO_RUNTIME using System; using System.Reflection; namespace ProtoBuf.Serializers { sealed class MemberSpecifiedDecorator : ProtoDecoratorBase { public override Type ExpectedType { get { return Tail.ExpectedType; } } public override bool RequiresOldValue { get { return Tail.RequiresOldValue; } } public override bool ReturnsValue { get { return Tail.ReturnsValue; } } private readonly MethodInfo getSpecified, setSpecified; public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail) : base(tail) { if (getSpecified == null && setSpecified == null) throw new InvalidOperationException(); this.getSpecified = getSpecified; this.setSpecified = setSpecified; } public override void Write(object value, ProtoWriter dest) { if(getSpecified == null || (bool)getSpecified.Invoke(value, null)) { Tail.Write(value, dest); } } public override object Read(object value, ProtoReader source) { object result = Tail.Read(value, source); if (setSpecified != null) setSpecified.Invoke(value, new object[] { true }); return result; } #if FEAT_COMPILER protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { if (getSpecified == null) { Tail.EmitWrite(ctx, valueFrom); return; } using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) { ctx.LoadAddress(loc, ExpectedType); ctx.EmitCall(getSpecified); Compiler.CodeLabel done = ctx.DefineLabel(); ctx.BranchIfFalse(done, false); Tail.EmitWrite(ctx, loc); ctx.MarkLabel(done); } } protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { if (setSpecified == null) { Tail.EmitRead(ctx, valueFrom); return; } using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) { Tail.EmitRead(ctx, loc); ctx.LoadAddress(loc, ExpectedType); ctx.LoadValue(1); // true ctx.EmitCall(setSpecified); } } #endif } } #endif
34.675676
112
0.573655
[ "Apache-2.0" ]
Jessecar96/protobuf-net
protobuf-net/Serializers/MemberSpecifiedDecorator.cs
2,568
C#
namespace Swashbuckle.DynamicLocalization { using Swashbuckle.Application; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Reflection; using System.Resources; using System.Text; using System.Web.Http; using System.Web.Http.Routing; public static class SwaggerEnabledConfigurationExtensions { private static readonly string DefaultRouteTemplate = "swagger/ui/{*assetPath}"; private static string[] languageScripts; public static void EnableLocalizedSwaggerUi(this SwaggerEnabledConfiguration configuration, Action<SwaggerUiConfig> configure = null) { EnableLocalizedSwaggerUi(configuration, DefaultRouteTemplate, null, configure); } public static void EnableLocalizedSwaggerUi( this SwaggerEnabledConfiguration configuration, string routeTemplate, Action<SwaggerUiConfig> configure = null) { EnableLocalizedSwaggerUi(configuration, routeTemplate, null, configure); } public static void EnableLocalizedSwaggerUi( this SwaggerEnabledConfiguration configuration, string routeTemplate, ResourceManager resourceManager, Action<SwaggerUiConfig> configure = null) { languageScripts = Assembly.GetAssembly(typeof(SwaggerEnabledConfiguration)) .GetManifestResourceNames() .Where(a => a.StartsWith("lang\\")) .Select(a => a.Remove(0, 5)) .ToArray(); // Dirty, fragile, needless CAS-requiring hack - really would like these to be public properties: var httpConfig = (HttpConfiguration)typeof(SwaggerEnabledConfiguration).GetField("_httpConfig", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(configuration); var discoveryPaths = (IEnumerable<string>)typeof(SwaggerEnabledConfiguration).GetField("_discoveryPaths", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(configuration); var rootUrlResolver = (Func<HttpRequestMessage, string>)typeof(SwaggerEnabledConfiguration).GetField("_rootUrlResolver", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(configuration); var config = new SwaggerUiConfig(discoveryPaths, rootUrlResolver); configure?.Invoke(config); var innerHandler = new SwaggerUiHandler(config); var transformHandler = new HtmlStreamTransformHandler(innerHandler, s => new PlaceholderResolverStream(s, a => ResolvePlaceholder(resourceManager, a))); httpConfig.Routes.MapHttpRoute( name: "swagger_localizedui", routeTemplate: routeTemplate, defaults: null, constraints: new { assetPath = @".+" }, handler: transformHandler); if (routeTemplate == DefaultRouteTemplate) { httpConfig.Routes.MapHttpRoute( name: "swagger_localizedui_shortcut", routeTemplate: "swagger", defaults: null, constraints: new { uriResolution = new HttpRouteDirectionConstraint(HttpRouteDirection.UriResolution) }, handler: new RedirectHandler(rootUrlResolver, "swagger/ui/index")); } } private static string ResolvePlaceholder(ResourceManager resourceManager, string key) { if (key == "%(TranslationScripts)") { StringBuilder resultBuilder = new StringBuilder(); string cultureName = CultureInfo.CurrentUICulture.Name; if ((cultureName = GetSwaggerUiLanguageFile(cultureName)) != null) { resultBuilder.AppendLine("<script src='lang/translator-js' type='text/javascript'></script>"); resultBuilder.AppendLine($"<script src='lang/{cultureName}-js' type='text/javascript'></script>"); } return resultBuilder.ToString(); } else { // Try resource string lookup to provide a method for localisation of non-SwaggerUI page content - a poor man's rendering engine.. // Finally, we leave unrecognised keys alone - slim chance it might not have been intended as a placeholder string resourceStringValue = resourceManager?.GetString(key.Substring(2, key.Length - 3)); if (resourceStringValue != null) { return resourceStringValue; } else { return key; } } } private static string GetSwaggerUiLanguageFile(string cultureName) { if (languageScripts.Contains(cultureName + ".js")) { return cultureName; } else if (languageScripts.Contains(cultureName.Substring(0, 2) + ".js")) { return cultureName.Substring(0, 2); } else { return null; } } } }
44.268293
206
0.594858
[ "MIT" ]
sdcondon/SwashbuckleDynamicLocalization
DynamicLocalization/SwaggerEnabledConfigurationExtensions.cs
5,447
C#
using EVRTH.Scripts.DemoHelpers; using UnityEditor; using UnityEngine; namespace EVRTH.Editor { [CustomPropertyDrawer(typeof(InspectorCommentBlock))] public class CommentBlockPropertyDrawer : PropertyDrawer { private const float height = 150; private float indent = 30; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return height; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { using (new EditorProperty(position, label, property)) { EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), new GUIContent(label.text)); SerializedProperty valProperty = property.FindPropertyRelative("comment"); float labelHeight = base.GetPropertyHeight(property, label); Rect region = new Rect(position.x + indent,position.y + labelHeight,position.width - indent - 10, position.height - indent - 10); EditorGUI.BeginChangeCheck(); string newValue= EditorGUI.TextArea(region, valProperty.stringValue); if (EditorGUI.EndChangeCheck()) { valProperty.stringValue = newValue; } } } } }
37.567568
145
0.62446
[ "Apache-2.0" ]
lim-at-infinity/gibs-unity-examples
Assets/Libraries/EVRTH/Editor/CommentBlockPropertyDrawer.cs
1,392
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BackupCrrJobsOperations operations. /// </summary> internal partial class BackupCrrJobsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupCrrJobsOperations { /// <summary> /// Initializes a new instance of the BackupCrrJobsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupCrrJobsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Gets the list of CRR jobs from the target region. /// </summary> /// <param name='azureRegion'> /// Azure region to hit Api /// </param> /// <param name='parameters'> /// Backup CRR Job request /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobResource>>> ListWithHttpMessagesAsync(string azureRegion, CrrJobRequest parameters, ODataQuery<JobQueryObject> odataQuery = default(ODataQuery<JobQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (azureRegion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "azureRegion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2018-12-20"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("azureRegion", azureRegion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupCrrJobs").ToString(); _url = _url.Replace("{azureRegion}", System.Uri.EscapeDataString(azureRegion)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of CRR jobs from the target region. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.191781
375
0.564993
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/Generated/BackupCrrJobsOperations.cs
19,356
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EDO.Core.Util; namespace EDO.Core.Model { public class BookRelation :ICloneable { public static BookRelation CreateAbstract() { return new BookRelation() { BookRelationType = BookRelationType.Abstract }; } public static BookRelation CreateConcept(string conceptId) { return new BookRelation() { BookRelationType = BookRelationType.Concept, MetadataId = conceptId }; } public static BookRelation CreateQuestion(string questionId) { return new BookRelation() { BookRelationType = BookRelationType.Question, MetadataId = questionId }; } public static BookRelation CreateVariable(string variableId) { return new BookRelation() { BookRelationType = BookRelationType.Variable, MetadataId = variableId }; } public BookRelation() { } public BookRelationType BookRelationType { get; set; } public bool IsBookRelationTypeAbstract {get {return BookRelationType == BookRelationType.Abstract; }} public bool IsBookRelationTypeConcept { get { return BookRelationType == BookRelationType.Concept; } } public bool IsBookRelationTypeQuestion { get { return BookRelationType == BookRelationType.Question; } } public bool IsBookRelationTypeVariable { get { return BookRelationType == BookRelationType.Variable; } } public string MetadataId { get; set; } public object Clone() { return DeepCopy(false); } public BookRelation DeepCopy(Boolean keepId) { BookRelation newRelation = (BookRelation)MemberwiseClone(); if (keepId) { // newRelation.Id = Id; } return newRelation; } public bool EqualsValue(BookRelation other) { bool result = false; if (BookRelationType == BookRelationType.Abstract) { result = BookRelationType == other.BookRelationType; } else { result = BookRelationType == other.BookRelationType && MetadataId == other.MetadataId; } return result; } } }
31.546667
112
0.614962
[ "Apache-2.0" ]
Easy-DDI-Organizer/EDO
EDO/Core/Model/BookRelation.cs
2,368
C#
using System.Threading.Tasks; using Common.Log; using Lykke.Job.ServicesMonitoring.Core.Services; namespace Lykke.Job.ServicesMonitoring.Services { // NOTE: Sometimes, startup process which is expressed explicitly is not just better, // but the only way. If this is your case, use this class to manage startup. // For example, sometimes some state should be restored before any periodical handler will be started, // or any incoming message will be processed and so on. // Do not forget to remove As<IStartable>() and AutoActivate() from DI registartions of services, // which you want to startup explicitly. public class StartupManager : IStartupManager { private readonly ILog _log; public StartupManager(ILog log) { _log = log; } public async Task StartAsync() { // TODO: Implement your startup logic here. Good idea is to log every step await Task.CompletedTask; } } }
33.633333
107
0.674926
[ "MIT" ]
LykkeCity/Lykke.Job.ServicesMonitoring
src/Lykke.Job.ServicesMonitoring.Services/StartupManager.cs
1,011
C#
using System.Collections.Generic; namespace KdTree { public interface IKdTree<TKey, TValue> : IEnumerable<KdTreeNode<TKey, TValue>> { bool Add(TKey[] point, TValue value); bool TryFindValueAt(TKey[] point, out TValue value); TValue FindValueAt(TKey[] point); bool TryFindValue(TValue value, out TKey[] point); TKey[] FindValue(TValue value); KdTreeNode<TKey, TValue>[] RadialSearch(TKey[] center, TKey radius, int count); void RemoveAt(TKey[] point); void Clear(); KdTreeNode<TKey, TValue>[] GetNearestNeighbours(TKey[] point, int count = int.MaxValue); int Count { get; } } }
21.892857
90
0.706362
[ "MIT" ]
Unity-Technologies/KdTree
KdTreeLib/IKdTree.cs
615
C#
using BooksPF.Models; using MongoDB.Driver; using MongoDB.Driver.GridFS; namespace BooksPF.Core.Abstract { public interface IDbClient { IMongoCollection<Book> GetBooksCollection(); IMongoCollection<User> GetUsersCollection(); IMongoCollection<BookFile> GetFilesCollection(); IGridFSBucket GetBucket(); } }
23.466667
56
0.715909
[ "Unlicense" ]
1amald/BooksPF
BooksPF.Core/Abstract/IDbClient.cs
354
C#
using UnityEngine; using LibNoise.Generator; using NodeEditorFramework; using NodeEditorFramework.Utilities; namespace LibNoiseNodes { [System.Serializable] [Node(false, "Noise/Generator/Voronoi")] public class NodeModuleGeneratorVoronoi : NodeModuleBase { public override string GetID { get { return typeof(NodeModuleGeneratorVoronoi).Name.ToLower(); } } public float Displacement = 1.0f; public float Frequency = 1.0f; public int Seed = 0; public bool UseDistance; Voronoi _module = new Voronoi(); public NodeModuleGeneratorVoronoi() { // pull the defaults from the noise module Displacement = (float)_module.Displacement; Frequency = (float)_module.Frequency; Seed = _module.Seed; UseDistance = _module.UseDistance; InitModule(_module); } protected override void PreGenerate() { _module.Frequency = (float)Frequency; _module.Displacement = (float)Frequency; _module.Seed = Seed; _module.UseDistance = UseDistance; } public override Node Create(Vector2 pos) { NodeModuleGeneratorVoronoi node = CreateInstance<NodeModuleGeneratorVoronoi>(); node.rect = new Rect(pos.x, pos.y, NodeWidth, NodeHeight); node.name = "Voronoi"; node.NodeWidth = 300.0f; node.NodeHeight = 500.0f; node.CreateOutput("Output", "Module", NodeSide.Right); return node; } protected override void NodeGUIProperties() { GUILayout.BeginVertical(); Displacement = RTEditorGUI.FloatField(new GUIContent("Displacement", "Displacement value of voronoi cells"), Frequency); Frequency = RTEditorGUI.FloatField(new GUIContent("Frequency", "Frequency of the first octave"), Frequency); Seed = RTEditorGUI.IntField(new GUIContent("Seed", "Random Seed"), Seed); UseDistance = RTEditorGUI.Toggle(UseDistance, new GUIContent("UseDistance", "Apply Distance to Seed point to output value")); GUILayout.EndVertical(); } } }
34.953846
137
0.615757
[ "MIT" ]
jswigart/unity_noise_editor
NoiseNodeEditor/Assets/Node_Editor_LibNoise/Nodes/Generators/NodeModuleGeneratorVoronoi.cs
2,274
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Tasks { public class C { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var S = Scanner.Scan<string>(); var K = Scanner.Scan<long>(); var answer = '1'; var idx = 0; for (var i = 0; i < S.Length; i++) { if (S[i] == '1') continue; answer = S[i]; idx = i + 1; break; } Console.WriteLine(K < idx ? '1' : answer); } public static class Scanner { private static Queue<string> queue = new Queue<string>(); public static T Next<T>() { if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item); return (T)Convert.ChangeType(queue.Dequeue(), typeof(T)); } public static T Scan<T>() => Next<T>(); public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>()); public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>()); public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>()); public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>()); public static (T1, T2, T3, T4, T5, T6) Scan<T1, T2, T3, T4, T5, T6>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>(), Next<T6>()); public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T))); } } }
38.320755
158
0.482521
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC106/Tasks/C.cs
2,031
C#
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; namespace PrimitiveExtensions { public static class DataTableHelper { /// <summary> /// Returns page of a specified page number and size /// </summary> /// <param name="dt"></param> /// <param name="pageNum"></param> /// <param name="pageSize"></param> /// <returns></returns> public static DataTable GetPage(this DataTable dt, int pageNum, int pageSize) { DataTable dtPage = new DataTable(); if (pageNum < 1) { throw new IndexOutOfRangeException(); } if (dt.TableName.IsNullOrEmptyString()) { dt.TableName = "table1"; } MemoryStream xmlStream = new MemoryStream(); dt.WriteXmlSchema(xmlStream); xmlStream.Position = 0; StreamReader reader = new StreamReader(xmlStream); dtPage.ReadXmlSchema(reader); var pageRows = dt.Rows.Cast<System.Data.DataRow>() .Skip((pageNum - 1) * pageSize) .Take(pageSize); //.CopyToDataTable(dtPage, LoadOption.PreserveChanges); //TODO ?temp? fix until .CopyToDataTable is added to dotnetcore / dotnetstandard //https://github.com/dotnet/corefx/issues/19771 // foreach (var row in pageRows) { dtPage.Rows.Add(row.ItemArray); } return dtPage; } /// <summary> /// Sets primary key column to read only mode /// </summary> /// <param name="dt"></param> public static void SetPrimaryKeyColumnsToReadOnly(this DataTable dt) { foreach (DataColumn pkColumn in dt.GetPrimaryKeyColumns()) { pkColumn.ReadOnly = true; } } /// <summary> /// Returns a list of primary key column names of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<string> GetPrimaryKeyColumnNames(this DataTable dt) { return dt .GetPrimaryKeyColumns() .Select(a => a.ColumnName) .ToList(); } /// <summary> /// Returns lsit of primary key columns of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<DataColumn> GetPrimaryKeyColumns(this DataTable dt) { return dt.PrimaryKey.ToList(); } /// <summary> /// Returns list of non primary key column names of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<string> GetNonPrimaryKeyColumnNames(this DataTable dt) { List<string> s = new List<string>(); foreach (DataColumn c in dt.Columns) { if (!c.IsAPrimaryKeyColumn(dt)) { s.Add(c.ColumnName); } } return s; } /// <summary> /// Returns list of non primary key columns of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<DataColumn> GetNonKeyColumns(this DataTable dt) { List<DataColumn> dataColumns = new List<DataColumn>(); foreach (DataColumn column in dt.Columns) { if (!column.IsAPrimaryKeyColumn(dt)) { dataColumns.Add(column); } } return dataColumns; } /// <summary> /// Returns list of column names of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<string> GetColumnNames(this DataTable dt) { List<string> s = new List<string>(); foreach (DataColumn c in dt.Columns) { s.Add(c.ColumnName); } return s; } /// <summary> /// Returns list of column names that are non identity columns /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IEnumerable<string> GetNonIdentityColumnNames(this DataTable dt) { List<string> s = new List<string>(); foreach (DataColumn c in dt.Columns) { if (c.AutoIncrement == false) { s.Add(c.ColumnName); } } return s; } /// <summary> /// Gets a collection of SQL Statements based on the data in, and the structure of the DataTable /// </summary> /// <param name="dt"></param> /// <param name="config"></param> /// <returns></returns> public static IEnumerable<string> GetInsertSql(this DataTable dt, SqlGeneratorConfig config) { List<string> insertSqlStatements = new List<string>(); foreach (DataRow row in dt.Rows) { string sql = row.GetInsertSql(config); insertSqlStatements.Add(sql); } return insertSqlStatements; } /// <summary> /// Returns sql statement by row state to instert data into a table /// </summary> /// <param name="dt"></param> /// <param name="schemaName"></param> /// <param name="overrideTableName"></param> /// <param name="tabulate"></param> /// <returns></returns> public static IEnumerable<string> GetInsertSqlByRowState(this DataTable dt, SqlGeneratorConfig config) { List<string> insertSqlStatements = new List<string>(); List<string> valueList = new List<string>(); List<string> columnNameList = dt.GetColumnNames().ToList(); string targetTableName = dt.TableName; DataTable dtAdded = dt.GetChanges(DataRowState.Added); foreach (DataRow r in dtAdded.Rows) { insertSqlStatements.Add( r.GetInsertSql(config)); //if (r.RowState == DataRowState.Added) //{ // foreach (string columnName in columnNameList) // { // valueList.Add(r[columnName].EncodeAsSqlVariable()); // } // sql = string.Format("INSERT INTO {0}.{1} ({2}) ", schemaName, targetTableName, string.Join(", ", columnNameList)); // if (tabulate) sql += Environment.NewLine; // sql += string.Format("VALUES ({0});", string.Join(", ", valueList)); // insertSqlStatements.Add(sql); // valueList.Clear(); //} } return insertSqlStatements; } /// <summary> /// Returns sql statement by row state to delete row from a table /// </summary> /// <param name="dt"></param> /// <param name="schemaName"></param> /// <param name="overrideTableName"></param> /// <param name="tabulate"></param> /// <returns></returns> public static IEnumerable<string> GetDeleteSqlByRowState(this DataTable dt, SqlGeneratorConfig config) { if (dt.PrimaryKey.Count() == 0) throw new MissingPrimaryKeyException(dt.TableName + " does not have a Primary Key defined"); DataTable dtDeleted = dt.GetChanges(DataRowState.Deleted); if (dtDeleted == null) return new List<string>(); List<string> deleteSqlStatements = new List<string>(); foreach (DataRow r in dtDeleted.Rows) { string sql = r.GetDeleteSql(config); deleteSqlStatements.Add(sql); } return deleteSqlStatements; } /// <summary> /// Returns sql statement by row state to udpate row in a table /// </summary> /// <param name="dt"></param> /// <param name="schemaName"></param> /// <param name="overrideTableName"></param> /// <param name="tabulate"></param> /// <returns></returns> public static IEnumerable<string> GetUpdateSqlByRowState(this DataTable dt, SqlGeneratorConfig config) { if (dt.PrimaryKey.Count() == 0) throw new MissingPrimaryKeyException(dt.TableName + " does not have a Primary Key defined"); DataTable dtModified = dt.GetChanges(DataRowState.Modified); if (dtModified == null) return new List<string>(); List<string> updateSqlStatements = new List<string>(); foreach (DataRow r in dtModified.Rows) { updateSqlStatements.Add(r.GetUpdateSql(config)); } return updateSqlStatements; } /// <summary> /// Returns a string of HTML code to display a Table on a web page /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToHtmlTable(this DataTable dt) { string cellValue = ""; string tab = "\t"; StringBuilder sb = new StringBuilder(); sb.AppendLine(tab + tab + "<table>"); //headers sb.Append(tab + tab + tab + "<tr>"); foreach (DataColumn dc in dt.Columns) { sb.AppendFormat("<td>{0}</td>", dc.ColumnName); } sb.Append(tab + tab + tab + "</tr>"); //data rows foreach (DataRow row in dt.Rows) { sb.Append(tab + tab + tab + "<tr>"); foreach (DataColumn col in dt.Columns) { cellValue = row[col] != null ? row[col].ToString() : ""; if (col.DataType == typeof(System.DateTime) & cellValue != "") { try { DateTime dateTime = DateTime.Parse(cellValue); cellValue = dateTime.ToString(dateTime.Date == dateTime ? "d" : "g"); } catch (Exception) { } } sb.AppendFormat("<td>{0}</td>", cellValue); } sb.Append(tab + tab + tab + "</tr>"); } sb.AppendLine(tab + tab + "</table>"); return sb.ToString(); } /// <summary> /// Copies data from a table to another table /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="allowDeletesOnDestination"></param> public static void SimpleDataTableCopier(this DataTable source, DataTable destination, bool allowDeletesOnDestination = true) { DataTable sourceCopy = source.Copy(); sourceCopy.Load(source.CreateDataReader(), LoadOption.Upsert); destination.AcceptChanges(); //destination.OfflineCopyOfDataTable.Load(sourceCopy.CreateDataReader(), LoadOption.Upsert); destination.Merge(sourceCopy, false, MissingSchemaAction.AddWithKey); if (allowDeletesOnDestination) { foreach (DataRow r in destination.Rows) { //Console.WriteLine(r.RowState); if (r.RowState == DataRowState.Unchanged) { r.Delete(); } } } } /// <summary> /// /// Sets a best guess of a primary key /// </summary> /// <param name="dt"></param> /// <returns>Returns true if a key unique key was able to be created as the primary key. Returns false is no key was able to be found.</returns> public static bool SetBestGuessPrimaryKey(this DataTable dt) { if (dt.PrimaryKey.Count() > 0) return true; if (TryToSetPrimaryKeyBasedOnCommonNames(dt)) return true; DataColumn[] pkeys = null; var subsets = dt.GetColumnNames().ToArray().CreateSubsets(); foreach (var subset in subsets.OrderBy(a => a.Count())) { pkeys = new DataColumn[subset.Count()]; int i = 0; foreach (var columnName in subset) { pkeys[i] = dt.Columns[columnName]; i++; } try { dt.PrimaryKey = pkeys; return true; } catch (Exception) { } } return false; } /// <summary> /// Attempts to set primary key based on column names /// </summary> /// <param name="dt"></param> /// <returns></returns> private static bool TryToSetPrimaryKeyBasedOnCommonNames(DataTable dt) { DataColumn[] pkeys = null; string[] commonPKs = { "ID", "GUID", "UID", "UUID" }; foreach (var commonPkName in commonPKs) { if (dt.Columns.Contains(commonPkName)) { try { pkeys = new DataColumn[1]; pkeys[0] = dt.Columns[commonPkName]; dt.PrimaryKey = pkeys; return true; } catch (Exception) { } } } return false; } /// <summary> /// Copies a list of data table into another list of data table /// </summary> /// <param name="dtsSource"></param> /// <param name="dtsDestination"></param> public static void CopyTo(this List<DataTable> dtsSource, List<DataTable> dtsDestination) { foreach (DataTable dt in dtsSource) { dtsDestination.Add(dt.Copy()); } } /// <summary> /// Identifies and returns all the non key column names that are shared by all the datatables in the collection. Other properties of the columns are not compared and are ignored. /// </summary> /// <param name="dts"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static IEnumerable<string> GetColumnNames_Shared_NonPrimaryKey(this IEnumerable<DataTable> dts) { return GetColumns(dts, false, true); } /// <summary> /// Identifies and returns all the key column names that are shared by all the datatables in the collection. Other properties of the columns are not compared and are ignored. /// </summary> /// <param name="dts"></param> /// <param name="caseSensitive"></param> /// <returns></returns> public static IEnumerable<string> GetColumnNames_Shared_PrimaryKey(this IEnumerable<DataTable> dts) { return GetColumns(dts, true, true); } /// <summary> /// Identifies and returns all the non key column names that are shared by all the datatables in the collection. Other properties of the columns are not compared and are ignored. /// </summary> /// <param name="dts"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static IEnumerable<string> GetColumnNames_NotShared_PrimaryKey(this IEnumerable<DataTable> dts) { return GetColumns(dts, true, false); } /// <summary> /// Identifies and returns all the key column names that are shared by all the datatables in the collection. Other properties of the columns are not compared and are ignored. /// </summary> /// <param name="dts"></param> /// <param name="caseSensitive"></param> /// <returns></returns> public static IEnumerable<string> GetColumnNames_NotShared_NonPrimaryKey(this IEnumerable<DataTable> dts) { return GetColumns(dts, false, false); } public static IEnumerable<string> GetColumnNames_Shared_All(this IEnumerable<DataTable> dts) { return dts.GetColumnNames_Shared_PrimaryKey().Union(dts.GetColumnNames_Shared_NonPrimaryKey()); } public static IEnumerable<string> GetColumnNames_NotShared_All(this IEnumerable<DataTable> dts) { return dts.GetColumnNames_NotShared_PrimaryKey().Union(dts.GetColumnNames_NotShared_NonPrimaryKey()); } private static IEnumerable<string> GetColumns(IEnumerable<DataTable> dts, bool getKey = true, bool getShared = false) { Dictionary<string, int> keyColumns = new Dictionary<string, int>(); Dictionary<string, int> nonKeyColumns = new Dictionary<string, int>(); List<string> notSharedColumns = new List<string>(); List<string> sharedColumns = new List<string>(); foreach (DataTable dt in dts) { foreach (DataColumn c in dt.Columns) { string columnName = c.ColumnName; if (c.IsAPrimaryKeyColumn(dt)) { if (keyColumns.ContainsKey(columnName)) { keyColumns[columnName] = keyColumns[columnName] + 1; } else { keyColumns.Add(columnName, 1); } } else { if (nonKeyColumns.ContainsKey(columnName)) { nonKeyColumns[columnName] = nonKeyColumns[columnName] + 1; } else { nonKeyColumns.Add(columnName, 1); } } } } Dictionary<string, int> colKvp = new Dictionary<string, int>(); if (getKey) { colKvp = keyColumns; } else { colKvp = nonKeyColumns; } foreach (KeyValuePair<string, int> column in colKvp) { if (column.Value < dts.Count()) { notSharedColumns.Add(column.Key); } else { sharedColumns.Add(column.Key); } } if (getShared) { return sharedColumns; } else { return notSharedColumns; } } /// <summary> /// Renames a column name if exists in the table /// </summary> /// <param name="dt"></param> /// <param name="columnName"></param> /// <param name="newName"></param> /// <param name="deleteNewIfExists"></param> public static void RenameColumnIfExists(this DataTable dt, string columnName, string newName, bool deleteNewIfExists = true) { if (dt.Columns.Contains(newName) && deleteNewIfExists) { dt.Columns.Remove(newName); } if (dt.Columns.Contains(columnName)) { dt.Columns[columnName].ColumnName = newName; } } /// <summary> /// Deletes a column name if exists in the table /// </summary> /// <param name="dt"></param> /// <param name="columnName"></param> public static void DeleteColumnIfExists(this DataTable dt, string columnName) { if (dt.Columns.Contains(columnName)) { if (dt.Columns[columnName].IsAPrimaryKeyColumn(dt)) { } else { dt.Columns.Remove(columnName); } } //return dt; } /// <summary> /// Deletes all columns from table except the ones passed in an array /// </summary> /// <param name="dt"></param> /// <param name="columnsToKeep"></param> public static void DeleteAllColumnsButThese(this DataTable dt, string[] columnsToKeep) { List<string> colsToDelete = new List<string>(); foreach (DataColumn c in dt.Columns) { if (!columnsToKeep.Contains(c.ColumnName)) { colsToDelete.Add(c.ColumnName); } } foreach (string colToDelete in colsToDelete) { dt.DeleteColumnIfExists(colToDelete); } /*int i = 0; foreach (string s in columnsToKeep) { dt.Columns[s].SetOrdinal(i); i++; }*/ int i = 0; foreach (string s in columnsToKeep) { if (s != null) { dt.Columns[s].SetOrdinal(i); i++; } } } /// <summary> /// Deletes row from a table that are under unchanged row state /// </summary> /// <param name="dt"></param> public static void DeleteUnchangedRows(this DataTable dt) { List<DataRow> rowsToDelete = new List<DataRow>(); foreach (DataRow row in dt.Rows) { if (row.RowState == DataRowState.Unchanged) { rowsToDelete.Add(row); } } foreach (DataRow row in rowsToDelete) { row.Delete(); } } /// <summary> /// Adds a column if does not exist in the table /// </summary> /// <param name="dt"></param> /// <param name="columnName"></param> /// <param name="t"></param> /// <param name="expression"></param> /// <param name="deleteIfExists"></param> public static DataColumn AddColumnIfNotExists(this DataTable dt, string columnName, Type t, string expression = null, bool deleteIfExists = true) { if (!dt.Columns.Contains(columnName)) { return dt.Columns.Add(columnName, t, expression); } else { if (deleteIfExists) { dt.Columns.Remove(columnName); return dt.Columns.Add(columnName, t, expression); } else { return dt.Columns[columnName]; } } } /// <summary> /// Sets column ordinal if the column exist /// </summary> /// <param name="dt"></param> /// <param name="columnName"></param> /// <param name="ordinal"></param> public static void SetColumnOrdinalIfExists(this DataTable dt, string columnName, int ordinal) { if (dt.Columns.Contains(columnName)) { if (dt.Columns.Count >= ordinal) { dt.Columns[columnName].SetOrdinal(ordinal); } } //return dt; } /// <summary> /// Returns true if the table name exist in the list of data table /// </summary> /// <param name="dts"></param> /// <param name="tableName"></param> /// <returns></returns> public static bool ContainsTableName(this IEnumerable<DataTable> dts, string tableName) { foreach (DataTable dt in dts) { if (dt.TableName == tableName) { return true; } } return false; } /// <summary> /// Returns the primary key value of a data row /// </summary> /// <param name="row"></param> /// <param name="delimeter"></param> /// <param name="useOriginalRowStateIfAvailable"></param> /// <returns></returns> public static string GetPrimaryKeyValueListText(this DataRow row, char delimeter = ';', bool useOriginalRowStateIfAvailable = true) { DataTable dt = row.Table; if (dt == null) { throw new Exception("This row doesn't below to a table"); } if (dt.PrimaryKey == null) { throw new Exception("This table doesn't have a primary key"); } DataColumn[] columns = dt.PrimaryKey; string pkValue = GetValueListText(row, columns, useOriginalRowStateIfAvailable, delimeter); return pkValue; } /// <summary> /// Returns the column values of a data row seprated by delimeter /// </summary> /// <param name="row"></param> /// <param name="columns"></param> /// <param name="useOriginalRowStateIfAvailable"></param> /// <param name="delimeter"></param> /// <returns></returns> public static string GetValueListText(this DataRow row, DataColumn[] columns, bool useOriginalRowStateIfAvailable = true, char delimeter = ';') { string pkValue = ""; object fieldValue; string fieldValueAsString; foreach (DataColumn c in columns) { if (row.HasVersion(DataRowVersion.Original) & useOriginalRowStateIfAvailable) { fieldValue = row[c.ColumnName, DataRowVersion.Original]; } else { fieldValue = row[c.ColumnName]; } //if (formatDatesForSQL && c.DataType == typeof(DateTime) && fieldValue != null) //{ // if (DateTime.TryParse(fieldValue.ToString(), out dateValue)) // { // if (dateValue.TimeOfDay.Ticks == 0) // { // fieldValueAsString = dateValue.ToString("yyyy-MM-dd"); // } // else // { // fieldValueAsString = dateValue.ToString("yyyy-MM-dd HH:mm:ss.fff"); // } // } // else // { // fieldValueAsString = fieldValue.ToString(); // } //} //else //{ fieldValueAsString = fieldValue.ToString(); //} pkValue += delimeter + fieldValueAsString; } pkValue = pkValue.RemoveBefore(1); return pkValue; } /// <summary> /// Returns an object array with data and structure of a table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static object[,] ToArray(this DataTable dt) { object[,] myArray = new object[dt.Rows.Count, dt.Columns.Count]; int irow = 0; int icol = 0; foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) { myArray[irow, icol] = row[col]; //if (myArray[irow,icol].GetType() = ) // { // // } icol = icol + 1; } irow = irow + 1; icol = 0; } return myArray; } //public static int GetBytes(this DataTable dt, int pageNum, int pageSize) /// <summary> /// Returns storage bytes value of a data table /// </summary> /// <param name="dt"></param> /// <returns></returns> public static int GetBytes(this DataTable dt) { int numberOfBytes = 0; using (DataTableReader reader = new DataTableReader(dt)) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { Console.Write(reader[i] + " "); byte[] stringArray = Encoding.UTF8.GetBytes(reader[i].ToString()); numberOfBytes += stringArray.Length; /*var test = reader.GetStream(i); Stream stream = reader.GetStream(i); int byteCtr = stream.ReadByte(); if (byteCtr != -1) { numberOfBytes++; }*/ } //Console.WriteLine(); } } //string breakpoint = ""; return numberOfBytes; } } }
33.691704
187
0.483113
[ "Apache-2.0" ]
SSAgov/primitive-extensions
src/PrimitiveExtensions/DataTableExtensions.cs
30,055
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Qualitycheck.Transform; using Aliyun.Acs.Qualitycheck.Transform.V20190115; namespace Aliyun.Acs.Qualitycheck.Model.V20190115 { public class UpdateUserConfigRequest : RpcAcsRequest<UpdateUserConfigResponse> { public UpdateUserConfigRequest() : base("Qualitycheck", "2019-01-15", "UpdateUserConfig", "Qualitycheck", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Qualitycheck.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Qualitycheck.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string jsonStr; public string JsonStr { get { return jsonStr; } set { jsonStr = value; DictionaryUtil.Add(QueryParameters, "JsonStr", value); } } public override UpdateUserConfigResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UpdateUserConfigResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
35.125
142
0.70863
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-qualitycheck/Qualitycheck/Model/V20190115/UpdateUserConfigRequest.cs
2,248
C#
using System; using System.Collections.Generic; using System.Linq; using ESAPICommander.ArgumentConfig; using ESAPICommander.Logger; using ESAPIProxy; namespace ESAPICommander.Commands { public class DvhCommandDirector : BaseCommandDirector { private readonly DvhArgOptions _options; private List<string> _results = new List<string>(); public override void ProcessRequest() { try { var patient = _esapi.GetPatient(); _results = _esapi.ExtractDVHs(_options.Course, _options.Plan, _options.Structures.ToArray()); } catch (Exception e) { Console.WriteLine(e); throw; } } public override void PostProcess() { throw new System.NotImplementedException(); } public DvhCommandDirector(DvhArgOptions options, ESAPIManager esapi, ILog log) : base(esapi, log, options.PIZ) { _options = options; } } }
26.375
118
0.593365
[ "MIT" ]
isachpaz/ESAPICommander
ESAPICommander/Commands/DvhCommandDirector.cs
1,057
C#
using Microsoft.Practices.Prism.Logging; using PowerCreator.LiveClient.Log; namespace PowerCreator.LiveClient.Desktop { public partial class Bootstrapper { private readonly LoggerAdapter _logger = new LoggerAdapter(); protected override ILoggerFacade CreateLogger() { return _logger; } } }
21.8125
69
0.684814
[ "MIT" ]
schifflee/LiveClient
PowerCreator.LiveClient.Desktop/PowerCreatorLiveClientBootstrapper.Desktop.cs
351
C#
namespace NServiceBus.Router.Deduplication.Outbox { using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using Logging; using Transport; class OutboxPersister { static ILog log = LogManager.GetLogger<OutboxPersister>(); int epochSize; string sourceKey; string destinationKey; LinkStateTable linkStateTable; OutboxSequence sequence; LinkState linkState; long highestSeq; public OutboxPersister(int epochSize, string sourceKey, string destinationKey) { linkStateTable = new LinkStateTable(sourceKey); sequence = new OutboxSequence(sourceKey, destinationKey); this.epochSize = epochSize; this.sourceKey = sourceKey; this.destinationKey = destinationKey; } public async Task Store(CapturedTransportOperation operation, Action triggerAdvance, SqlConnection conn, SqlTransaction trans) { var localState = linkState; var seq = await sequence.GetNextValue(conn, trans).ConfigureAwait(false); InterlocedEx.ExchangeIfGreaterThan(ref highestSeq, seq); if (localState.IsStale(seq)) { var freshLinkState = await linkStateTable.Get(operation.Destination, conn, trans).ConfigureAwait(false); UpdateCachedLinkState(freshLinkState); localState = linkState; } if (localState.ShouldAdvance(seq)) { triggerAdvance(); } if (localState.IsStale(seq)) { throw new ProcessCurrentMessageLaterException("Link state is stale. Processing current message later."); } var tableName = localState.GetTableName(seq); var table = new OutboxTable(tableName); try { operation.OutgoingMessage.Headers[RouterDeduplicationHeaders.SequenceNumber] = seq.ToString(); operation.OutgoingMessage.Headers[RouterDeduplicationHeaders.SequenceKey] = sourceKey; operation.AssignTable(tableName); operation.AssignSequence(seq); var persistentOperation = Convert(operation); await table.Insert(persistentOperation, seq, conn, trans).ConfigureAwait(false); } catch (SqlException e) { if (e.Number == 547) //Constraint violation. We used very old seq and that value cannot be used any more because the epoch has advanced. { var freshLinkState = await linkStateTable.Get(operation.Destination, conn, trans).ConfigureAwait(false); UpdateCachedLinkState(freshLinkState); throw new ProcessCurrentMessageLaterException("Link state is stale. Processing current message later."); } throw; } catch (Exception ex) { log.Debug($"Unhandled exception while storing outbox operation with sequence {seq}", ex); throw; } } void UpdateCachedLinkState(LinkState freshLinkState) { lock (this) { if (freshLinkState.Epoch > linkState.Epoch) { linkState = freshLinkState; } } } public async Task Initialize(Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { LinkState initializedState; using (var initTransaction = conn.BeginTransaction()) { //Ensure only one process can enter here var lockedLinkState = await linkStateTable.Lock(destinationKey, conn, initTransaction).ConfigureAwait(false); //Initialize if not already initialized initializedState = await InitializeLinkState(lockedLinkState, conn, initTransaction).ConfigureAwait(false); initTransaction.Commit(); } //Announce if initialized var announcedState = await AnnounceInitializeOrAdvance(initializedState, dispatch, conn).ConfigureAwait(false); linkState = announcedState; } async Task<LinkState> AnnounceInitializeOrAdvance(LinkState initializedState, Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { if (initializedState.IsEpochAnnounced) { return initializedState; } return initializedState.Epoch == 1 ? await AnnounceInitialize(initializedState, dispatch, conn).ConfigureAwait(false) : await AnnounceAdvance(initializedState, dispatch, conn).ConfigureAwait(false); } async Task<LinkState> AnnounceInitialize(LinkState initializedState, Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { var (announcedLinkState, initializeMessage) = initializedState.AnnounceInitialize(sourceKey); log.Debug($"Sending initialize message for {destinationKey}."); await dispatch(initializeMessage).ConfigureAwait(false); await linkStateTable.Update(destinationKey, announcedLinkState, conn, null).ConfigureAwait(false); return announcedLinkState; } async Task<LinkState> InitializeLinkState(LinkState lockedLinkState, SqlConnection conn, SqlTransaction initTransaction) { if (!lockedLinkState.Initialized) { var initializedState = lockedLinkState.Initialize( OutboxTable.Left(sourceKey, destinationKey), OutboxTable.Right(sourceKey, destinationKey), epochSize); await initializedState.HeadSession.CreateConstraint(conn, initTransaction); await initializedState.TailSession.CreateConstraint(conn, initTransaction); await linkStateTable.Update(destinationKey, initializedState, conn, initTransaction).ConfigureAwait(false); return initializedState; } return lockedLinkState; } public async Task<LinkState> TryAdvance(Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { var newState = await Advance(dispatch, conn).ConfigureAwait(false); UpdateCachedLinkState(newState); return newState; } async Task<LinkState> Advance(Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { //Let's actually check if our values are correct. var queriedLinkState = await linkStateTable.Get(destinationKey, conn); if (!queriedLinkState.ShouldAdvance(highestSeq)) { return queriedLinkState; } log.Debug($"Attempting advance epoch for destination {destinationKey} based on link state {linkState}."); if (!queriedLinkState.IsEpochAnnounced) { return await AnnounceAdvance(queriedLinkState, dispatch, conn).ConfigureAwait(false); } var tableName = queriedLinkState.TailSession.Table; var table = new OutboxTable(tableName); if (await table.HasHoles(queriedLinkState.TailSession, conn).ConfigureAwait(false)) { var holes = await table.FindHoles(queriedLinkState.TailSession, conn).ConfigureAwait(false); if (holes.Any()) { await PlugHoles(table, holes, dispatch, conn).ConfigureAwait(false); } } var (advanced, newState) = await TryAdvanceEpochInDatabase(conn, tableName, queriedLinkState); if (advanced) { return await AnnounceAdvance(newState, dispatch, conn).ConfigureAwait(false); } return newState; } async Task<LinkState> AnnounceAdvance(LinkState newState, Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { var (announcedState, announceMessage) = newState.AnnounceAdvance(sourceKey); log.Debug($"Sending advance message for {destinationKey}."); await dispatch(announceMessage).ConfigureAwait(false); await linkStateTable.Update(destinationKey, announcedState, conn, null).ConfigureAwait(false); log.Info($"Link {destinationKey} epoch advance announced."); return announcedState; } async Task PlugHoles(OutboxTable table, List<(long Id, HoleType Type)> holes, Func<OutgoingMessage, Task> dispatch, SqlConnection conn) { log.Debug($"Outbox table {table.Name} seems to have holes in the sequence. Attempting to plug them."); //Plug missing row holes by inserting dummy rows foreach (var hole in holes.Where(h => h.Type == HoleType.MissingRow)) { //If we blow here it means that some other process inserted rows after we looked for holes. We backtrack and come back log.Debug($"Plugging hole {hole.Id} with a dummy message row."); await table.PlugHole(hole.Id, conn).ConfigureAwait(false); } //Dispatch all the holes and mark them as dispatched foreach (var hole in holes) { OutgoingMessage message; if (hole.Type == HoleType.MissingRow) { message = CreatePlugMessage(hole.Id); log.Debug($"Dispatching dummy message row {hole.Id}."); } else { message = await table.LoadMessageById(hole.Id, conn).ConfigureAwait(false); log.Debug($"Dispatching message {hole.Id} with ID {message.MessageId}."); } await dispatch(message).ConfigureAwait(false); await table.MarkAsDispatched(hole.Id, conn, null).ConfigureAwait(false); } } async Task<(bool, LinkState)> TryAdvanceEpochInDatabase(SqlConnection conn, string tableName, LinkState queriedLinkState) { log.Debug($"Closing outbox table {tableName}."); using (var advanceTransaction = conn.BeginTransaction()) { //Ensure only one process can enter here var lockedLinkState = await linkStateTable.Lock(destinationKey, conn, advanceTransaction); if (lockedLinkState.Epoch != queriedLinkState.Epoch) { log.Debug($"Link state for {destinationKey} does not match previously read value. Cannot advance the epoch."); return (false, lockedLinkState); } var newState = lockedLinkState.Advance(epochSize); var table = new OutboxTable(tableName); await newState.HeadSession.CreateConstraint(conn, advanceTransaction).ConfigureAwait(false); //Here we have all holes plugged and no possibility of inserting new rows. We can truncate log.Debug($"Truncating table {tableName}."); await table.Truncate(conn, advanceTransaction).ConfigureAwait(false); await lockedLinkState.TailSession.DropConstraint(conn, advanceTransaction).ConfigureAwait(false); log.Debug($"Updating state for destinationKey {destinationKey} to {newState}"); await linkStateTable.Update(destinationKey, newState, conn, advanceTransaction).ConfigureAwait(false); advanceTransaction.Commit(); return (true, newState); } } OutgoingMessage CreatePlugMessage(long seq) { var headers = new Dictionary<string, string> { [RouterDeduplicationHeaders.SequenceNumber] = seq.ToString(), [RouterDeduplicationHeaders.SequenceKey] = sourceKey, [RouterDeduplicationHeaders.Plug] = "true" }; var message = new OutgoingMessage(Guid.NewGuid().ToString(), headers, new byte[0]); return message; } public static Task MarkAsDispatched(CapturedTransportOperation operation, SqlConnection conn, SqlTransaction trans) { return new OutboxTable(operation.Table).MarkAsDispatched(operation.Sequence, conn, trans); } static PersistentOutboxTransportOperation Convert(CapturedTransportOperation operation) { var message = operation.OutgoingMessage; var persistentOp = new PersistentOutboxTransportOperation(message.MessageId, message.Body, message.Headers); return persistentOp; } } }
42.048701
152
0.614779
[ "MIT" ]
HEskandari/NServiceBus.Router
src/NServiceBus.Router.SqlServer/Outbox/OutboxPersister.cs
12,953
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ResumeTemplate { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
28.947368
143
0.618182
[ "MIT" ]
samialam8/MyResumeTemplate
ResumeTemplate/ResumeTemplate/Startup.cs
1,650
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 cloudfront-2016-01-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// A complex type that contains information about the objects that you want to invalidate. /// </summary> public partial class Paths { private List<string> _items = new List<string>(); private int? _quantity; /// <summary> /// Gets and sets the property Items. A complex type that contains a list of the objects /// that you want to invalidate. /// </summary> public List<string> Items { get { return this._items; } set { this._items = value; } } // Check to see if Items property is set internal bool IsSetItems() { return this._items != null && this._items.Count > 0; } /// <summary> /// Gets and sets the property Quantity. The number of objects that you want to invalidate. /// </summary> public int Quantity { get { return this._quantity.GetValueOrDefault(); } set { this._quantity = value; } } // Check to see if Quantity property is set internal bool IsSetQuantity() { return this._quantity.HasValue; } } }
30.385714
108
0.632816
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/CloudFront/Generated/Model/Paths.cs
2,127
C#
using System.Web.Mvc; namespace BolaoNet.MVC.Areas.Apostas { public class ApostasAreaRegistration : AreaRegistration { public override string AreaName { get { return "Apostas"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Apostas_default", "Apostas/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
24.041667
75
0.509532
[ "MIT" ]
Thoris/BolaoNet
BolaoNet.MVC/Areas/Apostas/ApostasAreaRegistration.cs
579
C#
using System; using System.Drawing; using System.Drawing.Imaging; namespace KaptchaNET.Options { public class CaptchaOptions { /// <summary> /// The width of the captcha in pixel. /// </summary> public int Width { get; set; } = 250; /// <summary> /// The height of the captcha in pixel. /// </summary> public int Height { get; set; } = 100; /// <summary> /// The minimum length of the word. /// </summary> public int MinWordLength { get; set; } = 5; /// <summary> /// The maximum length of the word. /// </summary> public int MaxWordLength { get; set; } = 8; /// <summary> /// The color of the background. /// </summary> public Color BackgroundColor { get; set; } = Color.White; /// <summary> /// The color of the foreground. /// </summary> public Color ForegroundColor { get; set; } = Color.Black; /// <summary> /// Gets or sets the internal image size factor (for better image quality). /// </summary> public float Scale { get; set; } = 2; /// <summary> /// The maximum letter rotation clockwise in degree. /// </summary> public int MaxRotationAngle { get; set; } = 30; /// <summary> /// The minimum letter rotation counter clockwise in degree. /// </summary> public int MinRotationAngle { get; set; } = -30; /// <summary> /// Timeout for captcha validation. /// </summary> public TimeSpan Timeout { get; set; } = new TimeSpan(0, 5, 0); /// <summary> /// Image format for the captcha. /// </summary> public ImageFormat ImageFormat { get; set; } = ImageFormat.Png; /// <summary> /// Charset used for text generation. /// </summary> public char[] Charset { get; set; } = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } }
28.971429
89
0.530572
[ "MIT" ]
twsI/Kaptcha.NET
src/Kaptcha.NET/Options/CaptchaOptions.cs
2,030
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.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="DetectorDefinition" /> /// </summary> public partial class DetectorDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="DetectorDefinition" /// type/>. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="DetectorDefinition" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="DetectorDefinition" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="DetectorDefinition" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="DetectorDefinition" />.</param> /// <returns> /// an instance of <see cref="DetectorDefinition" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDetectorDefinition ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDetectorDefinition).IsAssignableFrom(type)) { return sourceValue; } try { return DetectorDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return DetectorDefinition.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return DetectorDefinition.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.897959
249
0.591034
[ "MIT" ]
AlanFlorance/azure-powershell
src/Functions/generated/api/Models/Api20190801/DetectorDefinition.TypeConverter.cs
7,483
C#
// https://gmlwjd9405.github.io/2018/05/10/data-structure-heap.html using System; using System.Collections.Generic; class MainClass { public static void Main (string[] args) { Action<object> print = Console.WriteLine; var h = new MinHeap(); h.Insert(7); print(h.Stringify() == "7"); h.Insert(1); print(h.Stringify() == "1 7"); h.Insert(3); h.Insert(2); h.Insert(5); h.Insert(1); h.Insert(8); h.Insert(0); print(h.Stringify() == "0 1 1 2 5 3 8 7"); h.Remove(1); print(h.Stringify() == "0 2 1 7 5 3 8"); print(h.Find(o => o == 2) == 2); // 있냐 없냐 확인 h.Insert(1); h.Remove(0); print(h.RemoveTop() == 1); print(h.RemoveTop() == 1); print(h.RemoveTop() == 2); print(h.Stringify() == "3 5 8 7"); print(h.RemoveTop() == 3); print(h.RemoveTop() == 5); print(h.RemoveTop() == 7); print(h.RemoveTop() == 8); print(h.Stringify() == ""); try { print(h.RemoveTop()); } catch {} } } public class MinHeap { List<int> list; public MinHeap() { list = new List<int>(); } public void Insert(int v) { list.Add(v); HeapifyUp(list.Count - 1); } public void HeapifyUp(int i) { if (i < 1) return; int p = Parent(i); if (list[p] > list[i]) { list.Swap(p, i); HeapifyUp(p); } } public int RemoveTop() { // 숙제 (극단적일 경우를 생각해야함) if (list.Count > 0) { int v = list[0]; list[0] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); HeapifyDown(0); return v; } else { throw new InvalidOperationException("No Data"); } } public void Remove(int v) { // 숙제 (동일한 것 있으면 첫 번째 것 삭제, v param은 value) if (list.Count > 0) { int index = list.FindIndex(o=>o==v); if (index != -1) { list[index] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); HeapifyDown(index); } } } void HeapifyDown(int p) { // 숙제 if (list.Count <= 1) return; int l = LChild(p); int r = RChild(p); if (IsLeaf(p)) return; if (r > list.Count - 1) { // Only l if (list[l] < list[p]) { list.Swap(l, p); return; } } else { // l and r exist if (list[l] <= list[r]) { if (list[l] < list[p]) { list.Swap(l, p); HeapifyDown(l); } } else { if (list[r] < list[p]) { list.Swap(r, p); HeapifyDown(r); } } } } // print(h.Find(o=>o==2) == 2); // Func<int, bool> f == Predicate<T> (return 값이 true,false인 param 1개인 조건문일 때 사용) public int Find(Predicate<int> f) { int i = list.FindIndex(f); if (i != -1) return list[i]; else return -1; } public string Stringify() { return list.Stringify(); } int Parent(int i) {return (i - 1) / 2;} int LChild(int i) {return 2 * (i + 1) - 1;} int RChild(int i) {return LChild(i) + 1;} bool IsLeaf(int i) {return LChild(i) > list.Count - 1;} } public static class ClassExtension { public static string Stringify<T>(this IEnumerable<T> list) { return String.Join(" ", list); } public static IList<T> Swap<T>(this IList<T> list, int i, int j) { T temp = list[i]; list[i] = list[j]; list[j] = temp; return list; } } /* Zero base P(i) = (i - 1) / 2 L(i) = 2 * (i + 1) - 1 R(i) = L(i) + 1 insert Remove (숙제) HeapifyUp */
21.3625
82
0.515799
[ "MIT" ]
Bomnamul/DataStructureAlgoCSharp
Class/51-DS-MinHeap-Priority-Queue/main.cs
3,522
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Text.RegularExpressions; using static Microsoft.Rest.ClientRuntime.PowerShell.PsProxyOutputExtensions; using static Microsoft.Rest.ClientRuntime.PowerShell.PsProxyTypeExtensions; namespace Microsoft.Rest.ClientRuntime.PowerShell { internal class OutputTypeOutput { public PSTypeName[] OutputTypes { get; } public OutputTypeOutput(IEnumerable<PSTypeName> outputTypes) { OutputTypes = outputTypes.ToArray(); } public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; } internal class CmdletBindingOutput { public VariantGroup VariantGroup { get; } public CmdletBindingOutput(VariantGroup variantGroup) { VariantGroup = variantGroup; } public override string ToString() { var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; var pbText = $"PositionalBinding={false.ToPsBool()}"; var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; } } internal class ParameterOutput { public Parameter Parameter { get; } public bool HasMultipleVariantsInVariantGroup { get; } public bool HasAllVariantsInParameterGroup { get; } public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) { Parameter = parameter; HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; } public override string ToString() { var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; } } internal class AliasOutput { public string[] Aliases { get; } public bool IncludeIndent { get; } public AliasOutput(string[] aliases, bool includeIndent = false) { Aliases = aliases; IncludeIndent = includeIndent; } public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; } internal class ValidateNotNullOutput { public bool HasValidateNotNull { get; } public ValidateNotNullOutput(bool hasValidateNotNull) { HasValidateNotNull = hasValidateNotNull; } public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; } internal class ArgumentCompleterOutput { public CompleterInfo CompleterInfo { get; } public ArgumentCompleterOutput(CompleterInfo completerInfo) { CompleterInfo = completerInfo; } public override string ToString() => CompleterInfo != null ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" : String.Empty; } internal class DefaultInfoOutput { public bool HasDefaultInfo { get; } public DefaultInfo DefaultInfo { get; } public DefaultInfoOutput(ParameterGroup parameterGroup) { HasDefaultInfo = parameterGroup.HasDefaultInfo; DefaultInfo = parameterGroup.DefaultInfo; } public override string ToString() { var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; } } internal class ParameterTypeOutput { public Type ParameterType { get; } public ParameterTypeOutput(Type parameterType) { ParameterType = parameterType; } public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; } internal class ParameterNameOutput { public string ParameterName { get; } public bool IsLast { get; } public ParameterNameOutput(string parameterName, bool isLast) { ParameterName = parameterName; IsLast = isLast; } public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; } internal class BeginOutput { public VariantGroup VariantGroup { get; } public BeginOutput(VariantGroup variantGroup) { VariantGroup = variantGroup; } public override string ToString() => $@"begin {{ {Indent}try {{ {Indent}{Indent}$outBuffer = $null {Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ {Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 {Indent}{Indent}}} {Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName {GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} {Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) {Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} {Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) {Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) {Indent}}} catch {{ {Indent}{Indent}throw {Indent}}} }} "; private string GetParameterSetToCmdletMapping() { var sb = new StringBuilder(); sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); foreach (var variant in VariantGroup.Variants) { sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); } sb.Append($"{Indent}{Indent}}}"); return sb.ToString(); } private string GetDefaultValuesStatements() { var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); var sb = new StringBuilder(); foreach (var defaultInfo in defaultInfos) { var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); var parameterName = defaultInfo.ParameterGroup.ParameterName; sb.AppendLine(); sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); sb.Append($"{Indent}{Indent}}}"); } return sb.ToString(); } } internal class ProcessOutput { public override string ToString() => $@"process {{ {Indent}try {{ {Indent}{Indent}$steppablePipeline.Process($_) {Indent}}} catch {{ {Indent}{Indent}throw {Indent}}} }} "; } internal class EndOutput { public override string ToString() => $@"end {{ {Indent}try {{ {Indent}{Indent}$steppablePipeline.End() {Indent}}} catch {{ {Indent}{Indent}throw {Indent}}} }} "; } internal class HelpCommentOutput { public VariantGroup VariantGroup { get; } public CommentInfo CommentInfo { get; } public HelpCommentOutput(VariantGroup variantGroup) { VariantGroup = variantGroup; CommentInfo = variantGroup.CommentInfo; } public override string ToString() { var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; return $@"<# .Synopsis {CommentInfo.Synopsis.ToDescriptionFormat(false)} .Description {CommentInfo.Description.ToDescriptionFormat(false)} .Example To view examples, please use the -Online parameter with Get-Help or navigate to: {CommentInfo.OnlineVersion}{inputsText}{outputsText}{notesText} .Link {CommentInfo.OnlineVersion}{relatedLinksText} #> "; } } internal class ParameterDescriptionOutput { public string Description { get; } public ParameterDescriptionOutput(string description) { Description = description; } public override string ToString() => !String.IsNullOrEmpty(Description) ? Description.ToDescriptionFormat(false).NormalizeNewLines() .Split(new [] { Environment.NewLine }, StringSplitOptions.None) .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") : String.Empty; } internal class ProfileOutput { public string ProfileName { get; } public ProfileOutput(string profileName) { ProfileName = profileName; } public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; } internal class DescriptionOutput { public string Description { get; } public DescriptionOutput(string description) { Description = description; } public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; } internal class ParameterCategoryOutput { public ParameterCategory Category { get; } public ParameterCategoryOutput(ParameterCategory category) { Category = category; } public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; } internal class InfoOutput { public InfoAttribute Info { get; } public Type ParameterType { get; } public InfoOutput(InfoAttribute info, Type parameterType) { Info = info; ParameterType = parameterType; } public override string ToString() { // Rendering of InfoAttribute members that are not used currently /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ var requiredText = Info.Required ? "Required" : String.Empty; var unwrappedType = ParameterType.Unwrap(); var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); var possibleTypesText = hasValidPossibleTypes ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" : String.Empty; var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; } } internal class PropertySyntaxOutput { public string ParameterName { get; } public Type ParameterType { get; } public bool IsMandatory { get; } public int? Position { get; } public bool IncludeSpace { get; } public bool IncludeDash { get; } public PropertySyntaxOutput(Parameter parameter) { ParameterName = parameter.ParameterName; ParameterType = parameter.ParameterType; IsMandatory = parameter.IsMandatory; Position = parameter.Position; IncludeSpace = true; IncludeDash = true; } public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) { ParameterName = complexInterfaceInfo.Name; ParameterType = complexInterfaceInfo.Type; IsMandatory = complexInterfaceInfo.Required; Position = null; IncludeSpace = false; IncludeDash = false; } public override string ToString() { var leftOptional = !IsMandatory ? "[" : String.Empty; var leftPositional = Position != null ? "[" : String.Empty; var rightPositional = Position != null ? "]" : String.Empty; var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; var rightOptional = !IsMandatory ? "]" : String.Empty; var space = IncludeSpace ? " " : String.Empty; var dash = IncludeDash ? "-" : String.Empty; return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; } } internal static class PsProxyOutputExtensions { public const string NoParameters = "__NoParameters"; public const string AllParameterSets = "__AllParameterSets"; public const string HalfIndent = " "; public const string Indent = HalfIndent + HalfIndent; public const string ItemSeparator = ", "; public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; public static string ToPsType(this Type type) { var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); var typeText = type.ToString(); var match = regex.Match(typeText); return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; } public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); // https://stackoverflow.com/a/5284606/294804 private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"<br>", "\r\n", "\n"}); public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; public static string JoinIgnoreEmpty(this IEnumerable<string> values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); // https://stackoverflow.com/a/41961738/294804 public static string ToSyntaxTypeName(this Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; } if (type.IsGenericType) { var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); return $"{type.Name.Split('`').First()}<{genericTypes}>"; } return type.Name; } public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable<PSTypeName> outputTypes) => new OutputTypeOutput(outputTypes); public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) { string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; var nested = complexInterfaceInfo.NestedInfos.Select(ni => { var nestedIndent = $"{currentIndent}{HalfIndent}"; return ni.IsComplexInterface ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); return String.Join(Environment.NewLine, nested); } } }
44.960784
325
0.664501
[ "MIT" ]
dcaro/autorest.powershell
powershell/resources/psruntime/BuildTime/Models/PsProxyOutputs.cs
22,934
C#
namespace DotNetSix { using System; using BCrypt.Net; using System.Diagnostics; class Program { // Vectors stored string, salt, expected hash // These are taken from the original BCrypt.net project and are used to avoid breakage static readonly string[,] _testVectors = { { "", "$2a$06$DCq7YPn5Rq63x1Lad4cll.", "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s." }, { "", "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.", "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye" }, { "", "$2a$10$k1wbIrmNyFAPwPVPSVa/ze", "$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW" }, { "", "$2a$12$k42ZFHFWqBp3vWli.nIn8u", "$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO" }, { "a", "$2a$06$m0CrhHm10qJ3lXRY.5zDGO", "$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe" }, { "a", "$2a$08$cfcvVd2aQ8CMvoMpP2EBfe", "$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V." }, { "a", "$2a$10$k87L/MF28Q673VKh8/cPi.", "$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u" }, { "a", "$2a$12$8NJH3LsPrANStV6XtBakCe", "$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS" }, { "abc", "$2a$06$If6bvum7DFjUnE9p2uDeDu", "$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i" }, { "abc", "$2a$08$Ro0CUfOqk6cXEKf3dyaM7O", "$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm" }, { "abc", "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.", "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi" }, { "abc", "$2a$12$EXRkfkdmXn2gzds2SSitu.", "$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q" }, { "abcdefghijklmnopqrstuvwxyz", "$2a$06$.rCVZVOThsIa97pEDOxvGu", "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC" }, { "abcdefghijklmnopqrstuvwxyz", "$2a$08$aTsUwsyowQuzRrDqFflhge", "$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz." }, { "abcdefghijklmnopqrstuvwxyz", "$2a$10$fVH8e28OQRj9tqiDXs1e1u", "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq" }, { "abcdefghijklmnopqrstuvwxyz", "$2a$12$D4G5f18o7aMMfwasBL7Gpu", "$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG" }, { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$06$fPIsBO8qRqkjj273rfaOI.", "$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO" }, { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$08$Eq2r4G/76Wv39MzSX262hu", "$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW" }, { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$10$LgfYWkbzEvQ4JakH7rOvHe", "$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS" }, { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$12$WApznUOJfkEGSmYRfnkrPO", "$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC" } }; static void Main(string[] args) { for (int ji = 0; ji < _testVectors.Length / 3; ji++) { var hashInfo = BCrypt.InterrogateHash(_testVectors[ji, 2]); Console.WriteLine("{0}, {1}", hashInfo.WorkFactor, hashInfo.Version); } Console.WriteLine("BCrypt.HashPassword(): "); var sw = Stopwatch.StartNew(); for (int i = 0; i < _testVectors.Length / 3; i++) { string plain = _testVectors[i, 0]; string salt = _testVectors[i, 1]; string expected = _testVectors[i, 2]; string hashed = BCrypt.HashPassword(plain, salt); Console.Write(hashed == expected ? "T" : "F"); } Console.WriteLine("---"); Console.WriteLine(sw.ElapsedMilliseconds); Console.WriteLine("---"); Console.ReadKey(); } } }
71.672131
153
0.556038
[ "MIT" ]
ChrisMcKee/bcrypt.net
IntegrationTest/TestVariousVersionsOfDotNet/DotNet6/Program.cs
4,374
C#
using System; using System.ComponentModel.DataAnnotations; using Umbraco.RestApi.Links; namespace Umbraco.RestApi.Models { public class MemberRepresentation : UmbracoRepresentation { public MemberRepresentation(ILinkTemplate linkTemplate, Action<UmbracoRepresentation> createHypermediaCallback) : base(createHypermediaCallback) { _linkTemplate = linkTemplate; } public MemberRepresentation(Action<UmbracoRepresentation> createHypermediaCallback) : base(createHypermediaCallback) { } public MemberRepresentation() { } public MemberRepresentation(ILinkTemplate linkTemplate) { _linkTemplate = linkTemplate; } [Required] [Display(Name = "userName")] public string UserName { get; set; } [Required] [Display(Name = "email")] public string Email { get; set; } private readonly ILinkTemplate _linkTemplate; protected override void CreateHypermedia() { if (_linkTemplate == null) throw new NullReferenceException("LinkTemplate is null"); base.CreateHypermedia(); Href = _linkTemplate.Self.CreateLink(new { id = Id }).Href; Rel = _linkTemplate.Self.Rel; Links.Add(_linkTemplate.Root); Links.Add(_linkTemplate.MetaData.CreateLink(new { id = Id })); if (_linkTemplate.Upload != null) { Links.Add(_linkTemplate.Upload.CreateLink(new { id = Id })); } } } }
28.578947
119
0.606507
[ "MIT" ]
DecisionTechnologies/UmbracoRestApi
src/Umbraco.RestApi/Models/MemberRepresentation.cs
1,631
C#
using System; using System.Threading; using Nemo.Fn; namespace Nemo.Logging { public class AuditLog<T> { public AuditLog(string action, T oldValue, T newValue) { Id = Guid.NewGuid(); Action = action; OldValue = oldValue; NewValue = newValue; DateCreated = DateTime.UtcNow; } public Guid Id { get; private set; } public DateTime DateCreated { get; private set; } public string CreatedBy => Thread.CurrentPrincipal?.Identity?.Name; public string Action { get; private set; } public T OldValue { get; private set; } public T NewValue { get; private set; } public string Notes { get; set; } } }
17.403509
75
0.439516
[ "MIT" ]
MingLu8/Nemo
src/Nemo/Logging/AuditLog.cs
994
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License // Version 2.0. // // 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 Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using UProveCrypto; using UProveCrypto.Math; // ignore warnings for obsolete methods #pragma warning disable 0618 namespace UProveUnitTest { public class PreIssuanceData { public GroupElement Gamma { get; set; } public FieldZqElement Beta0 { get; set; } } /// <summary> /// Unit tests for the collaborative issuance feature ///</summary> [TestClass()] public class CollaborativeIssuanceTests { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } static IssuerKeyAndParameters sourceIkap, ikap; static IssuerParameters sourceIp, ip; #region Additional test attributes // Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { // initialize source params IssuerSetupParameters sourceIsp = new IssuerSetupParameters(); sourceIsp.UidP = encoding.GetBytes("source issuer UID"); sourceIsp.UseRecommendedParameterSet = true; sourceIsp.NumberOfAttributes = 2; sourceIsp.S = encoding.GetBytes("source spec"); sourceIkap = sourceIsp.Generate(); sourceIp = sourceIkap.IssuerParameters; // initialize collab issuer params IssuerSetupParameters isp = new IssuerSetupParameters(); isp.UidP = encoding.GetBytes("collab issuer UID"); isp.UseRecommendedParameterSet = true; isp.NumberOfAttributes = 3; isp.S = encoding.GetBytes("collab spec"); ikap = isp.Generate(); ip = ikap.IssuerParameters; } // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion private static System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); // If true, we serialize/deserialize the collaborative issuance PreIssuanceProofs private static bool TEST_SERIALIZATION = true; PreIssuanceData PreIssuance(ProverPreIssuanceParameters ppip, IssuerPreIssuanceParameters ipip) { byte[] message = encoding.GetBytes("Optional Message"); UProveCrypto.Math.FieldZqElement beta0; ppip.Validate(); PreIssuanceProof proof = PreIssuanceProof.CreateProof(ppip, out beta0, message); if (TEST_SERIALIZATION) { string _proof = ip.Serialize<PreIssuanceProof>(proof); proof = ip.Deserialize<PreIssuanceProof>(_proof); } GroupElement gamma = null; try { gamma = PreIssuanceProof.VerifyProof(ipip, proof, message); } catch (InvalidUProveArtifactException e) { Assert.Fail("Invalid proof: " + e.Message); } PreIssuanceData pid = new PreIssuanceData(); pid.Gamma = gamma; pid.Beta0 = beta0; return pid; } UProveKeyAndToken[] IssueSourceToken(byte[][] attributes) { byte[] tokenInformation = new byte[] { }; IssuerProtocolParameters ipp = new IssuerProtocolParameters(sourceIkap); ipp.Attributes = attributes; ipp.TokenInformation = tokenInformation; Issuer issuer = ipp.CreateIssuer(); FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage(); ProverProtocolParameters ppp = new ProverProtocolParameters(sourceIp); ppp.Attributes = attributes; ppp.TokenInformation = tokenInformation; Prover prover = ppp.CreateProver(); SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1); ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2); return prover.GenerateTokens(msg3); } /// <summary> /// Unit test with one unknown attribute, all other attributes known /// </summary> [TestMethod] public void CollaborativeIssuanceNoCarryOver() { byte[] tokenInformation = new byte[] { }; ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[][] { encoding.GetBytes("New attribute 1"), encoding.GetBytes("Secret attribute 2"), encoding.GetBytes("New attribute 3")}; ppip.U = new int[] { 2 }; ppip.K = new int[] { 1, 3 }; ppip.TI = tokenInformation; IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[][] { encoding.GetBytes("New attribute 1"), null, encoding.GetBytes("New attribute 3") }; ipip.U = ppip.U; ipip.K = ppip.K; ipip.TI = tokenInformation; PreIssuance(ppip, ipip); } /// <summary> /// Test where there is a carry-over and known attributes, but no unkonwn ones /// </summary> [TestMethod] public void CollaborativeIssuanceNoUnknown() { // Regular Issuance: we need a token to use in the collaborative issuance protocol byte[][] attributes = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2") }; UProveKeyAndToken[] upkt = IssueSourceToken(attributes); // Collaborative Issuance ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("New attribute 2"), encoding.GetBytes("New attribute 3") }; ppip.CarryOverAttribute(new int[] { 1 }, new int[] { 1 }, sourceIp, upkt[0], attributes); ppip.K = new int[] { 2, 3 }; IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[][] { null, encoding.GetBytes("New attribute 2"), encoding.GetBytes("New attribute 3") }; ipip.CarryOverAttribute(new int[] { 1 }, new int[] { 1 }, sourceIp, upkt[0].Token); ipip.K = ppip.K; PreIssuance(ppip, ipip); } /// <summary> /// Test where all the attributes are Unknown (no carry-over or known) /// </summary> [TestMethod] public void CollaborativeIssuanceAllUnknown() { ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[][] { encoding.GetBytes("Secret attribute 1"), encoding.GetBytes("Secret attribute 2"), encoding.GetBytes("Secret attribute 3")}; ppip.U = new int[] { 1, 2, 3 }; IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[][] { null, null, null }; ipip.U = ppip.U; PreIssuance(ppip, ipip); } /// <summary> /// Test with a carry-over, and all other attributes unknown /// </summary> [TestMethod] public void CollaborativeIssuanceTestNoKnown() { // Regular Issuance: we need a token to use in the collaborative issuance protocol byte[][] attributes = new byte[][] { encoding.GetBytes("carried-over attribute"), encoding.GetBytes("Attribute 2") }; UProveKeyAndToken[] upkt = IssueSourceToken(attributes); // Collaborative Issuance ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[][] { encoding.GetBytes("New attribute 1"), encoding.GetBytes("carried-over attribute"), encoding.GetBytes("New attribute 3") }; ppip.CarryOverAttribute(new int[] { 1 }, new int[] { 2 }, sourceIp, upkt[0], attributes); ppip.U = new int[] { 1, 3 }; IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[][] { null, null, null }; ipip.CarryOverAttribute(new int[] { 1 }, new int[] { 2 }, sourceIp, upkt[0].Token); ipip.U = ppip.U; PreIssuance(ppip, ipip); } /// <summary> /// Test carrying-over all attributes /// </summary> [TestMethod] public void CollaborativeIssuanceTestCarryAllOver() { // Regular Issuance: we need a token to use in the collaborative issuance protocol byte[][] attributes = new byte[][] { encoding.GetBytes("carried-over attribute 1"), encoding.GetBytes("carried-over attribute 2") }; UProveKeyAndToken[] upkt = IssueSourceToken(attributes); // Collaborative Issuance, carrying-over two attributes ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[][] { encoding.GetBytes("New attribute 1"), encoding.GetBytes("carried-over attribute 2"), encoding.GetBytes("carried-over attribute 1") }; ppip.CarryOverAttribute(new int[] { 1, 2 }, new int[] { 3, 2 }, sourceIp, upkt[0], attributes); ppip.U = new int[] { 1 }; IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[][] { null, null, null }; ipip.CarryOverAttribute(new int[] { 1, 2 }, new int[] { 3, 2 }, sourceIp, upkt[0].Token); ipip.U = ppip.U; PreIssuance(ppip, ipip); } /// <summary> /// Test with a carry-over, an unknown and the rest known attributes /// </summary> [TestMethod] public void CollaborativeIssuanceTestFull() { byte[][] attributes = new byte[][] { encoding.GetBytes("A1"), encoding.GetBytes("A2") }; UProveKeyAndToken[] upkt = IssueSourceToken(attributes); // carry over one attribute to various positions for (int sourceIndex = 0; sourceIndex < attributes.Length; sourceIndex++) { for (int destinationIndex = 0; destinationIndex < 3; destinationIndex++) { // Collaborative Issuance // First the Prover creates a PreIssuanceProof int[] sourceIndices = new int[] { sourceIndex + 1 }; int[] destinationIndices = new int[] { destinationIndex + 1 }; ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip); ppip.Attributes = new byte[3][]; ppip.CarryOverAttribute(sourceIndices, destinationIndices, sourceIp, upkt[0], attributes); ppip.U = new int[] { ((destinationIndex + 1) % 3) + 1 }; ppip.K = new int[] { ((destinationIndex + 2) % 3) + 1 }; ppip.Attributes[destinationIndex] = attributes[sourceIndex]; ppip.Attributes[ppip.U[0] - 1] = encoding.GetBytes("unknown"); ppip.Attributes[ppip.K[0] - 1] = encoding.GetBytes("known"); byte[] message = encoding.GetBytes("Optional Message"); // The verifier will only have the token, not the keyAndToken IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip); ipip.Attributes = new byte[3][]; ipip.CarryOverAttribute(sourceIndices, destinationIndices, sourceIp, upkt[0].Token); ipip.U = ppip.U; ipip.K = ppip.K; ipip.Attributes[destinationIndex] = null; // carried-over ipip.Attributes[ppip.U[0] - 1] = null; ipip.Attributes[ppip.K[0] - 1] = encoding.GetBytes("known"); PreIssuanceData pid = PreIssuance(ppip, ipip); // Issuance (collaborative, using blindedGamma) IssuerProtocolParameters ipp2 = new IssuerProtocolParameters(ikap); ipp2.Gamma = pid.Gamma; Issuer issuer2 = ipp2.CreateIssuer(); FirstIssuanceMessage msg1_2 = issuer2.GenerateFirstMessage(); ProverProtocolParameters ppp2 = new ProverProtocolParameters(ip); ppp2.SetBlindedGamma(pid.Gamma, pid.Beta0); Prover prover2 = ppp2.CreateProver(); SecondIssuanceMessage msg2_2 = prover2.GenerateSecondMessage(msg1_2); ThirdIssuanceMessage msg3_2 = issuer2.GenerateThirdMessage(msg2_2); UProveKeyAndToken[] upkt_2 = prover2.GenerateTokens(msg3_2); // Create a presentation proof for each token, disclosing everything, to make sure the new token works for (int i = 0; i < upkt_2.Length; i++) { int[] disclosed = { 1, 2, 3 }; int[] committed = { }; PresentationProof P = PresentationProof.Generate(ip, disclosed, message, null, null, upkt_2[i], ppip.Attributes); P.Verify(ip, disclosed, message, null, upkt_2[i].Token); // verify that carried-over attribute was properly set Assert.IsTrue(P.DisclosedAttributes[destinationIndex].SequenceEqual<byte>(attributes[sourceIndex])); Assert.IsTrue(P.DisclosedAttributes[ppip.U[0] - 1].SequenceEqual<byte>(encoding.GetBytes("unknown"))); Assert.IsTrue(P.DisclosedAttributes[ppip.K[0] - 1].SequenceEqual<byte>(encoding.GetBytes("known"))); } } } } // Test for the CA-RA split case. (a party trusted by the issuer provides the gamma value to the // Issuer, and the attributes to the Prover) // TODO: we should probably have a serializable object to store gamma so that it can be sent from the RA to the CA. [TestMethod] public void CollaborativeIssuanceTrustedGamma() { // Issuance byte[][] attributes = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2"), encoding.GetBytes("Attribute 3") }; ProverProtocolParameters ppp = new ProverProtocolParameters(ip); ppp.Attributes = attributes; Prover prover = ppp.CreateProver(); IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap); ipp.Gamma = ProtocolHelper.ComputeIssuanceInput(ip, attributes, null, null); // computed by some other party. Issuer issuer = ipp.CreateIssuer(); FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage(); SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1); ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2); UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3); // use the token to make sure everything is ok int[] disclosed = new int[0]; byte[] message = encoding.GetBytes("this is the presentation message, this can be a very long message"); UProveCrypto.Math.FieldZqElement[] unused; byte[] scope = null; PresentationProof proof = PresentationProof.Generate(ip, disclosed, null, 1, scope, message, null, null, upkt[0], attributes, out unused); proof.Verify(ip, disclosed, null, 1, scope, message, null, upkt[0].Token); } }// end class } // end namespace
47.369748
178
0.592928
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/uprove-csharp-sdk
UProveUnitTest/CollaborativeIssuanceTests.cs
16,913
C#
/* [REMOVE THIS LINE] * [REMOVE THIS LINE] To use this template, make a copy and remove the lines that start * [REMOVE THIS LINE] with "[REMOVE THIS LINE]". Then add your code where the comments indicate. * [REMOVE THIS LINE] If your code references scripts or assets that are outside of the Plugins * [REMOVE THIS LINE] folder, move this script outside of the Plugins folder, too. * [REMOVE THIS LINE] using UnityEngine; using System.Collections; using PixelCrushers.DialogueSystem; public class PersistentDataTemplate : MonoBehaviour //<--Copy this file. Rename the file and class name. { public void OnRecordPersistentData() { // Add your code here to record data into the Lua environment. // Typically, you'll record the data using a line similar to: // DialogueLua.SetVariable("someVarName", someData); // or: // DialogueLua.SetActorField("myName", "myFieldName", myData); // // Note that you can use this static method to get the actor // name associated with this GameObject: // var actorName = OverrideActorName.GetActorName(transform); } public void OnApplyPersistentData() { // Add your code here to get data from Lua and apply it (usually to the game object). // Typically, you'll use a line similar to: // myData = DialogueLua.GetActorField(name, "myFieldName").AsSomeType; // // When changing scenes, OnApplyPersistentData() is typically called at the same // time as Start() methods. If your code depends on another script having finished // its Start() method, use a coroutine to wait one frame. For example, in // OnApplyPersistentData() call StartCoroutine(DelayedApply()); // Then define DelayedApply() as: // IEnumerator DelayedApply() { // yield return null; // Wait 1 frame for other scripts to initialize. // <your code here> // } } public void OnEnable() { // This optional code registers this GameObject with the PersistentDataManager. // One of the options on the PersistentDataManager is to only send notifications // to registered GameObjects. The default, however, is to send to all GameObjects. // If you set PersistentDataManager to only send notifications to registered // GameObjects, you need to register this component using the line below or it // won't receive notifications to save and load. PersistentDataManager.RegisterPersistentData(this.gameObject); } public void OnDisable() { // Unsubscribe the GameObject from PersistentDataManager notifications: PersistentDataManager.RegisterPersistentData(this.gameObject); } //--- Uncomment this method if you want to implement it: //public void OnLevelWillBeUnloaded() //{ // This will be called before loading a new level. You may want to add code here // to change the behavior of your persistent data script. For example, the // IncrementOnDestroy script disables itself because it should only increment // the variable when it's destroyed during play, not because it's being // destroyed while unloading the old level. //} } /**/
42.64557
105
0.665479
[ "Apache-2.0" ]
NGTO-WONG/KishiStory
Assets/Plugins/Pixel Crushers/Dialogue System/Templates/Scripts/PersistentDataTemplate.cs
3,371
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; #pragma warning disable 1591 namespace Microsoft.WSMan.Management { #region "public Api" #region WsManEnumFlags /// <summary><para>_WSManEnumFlags enumeration.</para></summary> [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [TypeLibType((short)0)] public enum WSManEnumFlags { /// <summary><para><c>WSManFlagNonXmlText</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManFlagNonXmlText = 1, /// <summary><para><c>WSManFlagReturnObject</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary> WSManFlagReturnObject = 0, /// <summary><para><c>WSManFlagReturnEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 2.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] WSManFlagReturnEPR = 2, /// <summary><para><c>WSManFlagReturnObjectAndEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 4.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] WSManFlagReturnObjectAndEPR = 4, /// <summary><para><c>WSManFlagHierarchyDeep</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary> WSManFlagHierarchyDeep = 0, /// <summary><para><c>WSManFlagHierarchyShallow</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 32.</para></summary> WSManFlagHierarchyShallow = 32, /// <summary><para><c>WSManFlagHierarchyDeepBasePropsOnly</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary> WSManFlagHierarchyDeepBasePropsOnly = 64, /// <summary><para><c>WSManFlagAssociationInstance </c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary> WSManFlagAssociationInstance = 128 } #endregion WsManEnumFlags #region WsManSessionFlags /// <summary><para>WSManSessionFlags enumeration.</para></summary> /// [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [TypeLibType((short)0)] public enum WSManSessionFlags { /// <summary><para><c>no flag</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManNone = 0, /// <summary><para><c>WSManFlagUTF8</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManFlagUtf8 = 1, /// <summary><para><c>WSManFlagCredUsernamePassword</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4096.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] WSManFlagCredUserNamePassword = 4096, /// <summary><para><c>WSManFlagSkipCACheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8192.</para></summary> WSManFlagSkipCACheck = 8192, /// <summary><para><c>WSManFlagSkipCNCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16384.</para></summary> WSManFlagSkipCNCheck = 16384, /// <summary><para><c>WSManFlagUseNoAuthentication</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 32768.</para></summary> WSManFlagUseNoAuthentication = 32768, /// <summary><para><c>WSManFlagUseDigest</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 65536.</para></summary> WSManFlagUseDigest = 65536, /// <summary><para><c>WSManFlagUseNegotiate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 131072.</para></summary> WSManFlagUseNegotiate = 131072, /// <summary><para><c>WSManFlagUseBasic</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 262144.</para></summary> WSManFlagUseBasic = 262144, /// <summary><para><c>WSManFlagUseKerberos</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 524288.</para></summary> WSManFlagUseKerberos = 524288, /// <summary><para><c>WSManFlagNoEncryption</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1048576.</para></summary> WSManFlagNoEncryption = 1048576, /// <summary><para><c>WSManFlagEnableSPNServerPort</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4194304.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Spn")] WSManFlagEnableSpnServerPort = 4194304, /// <summary><para><c>WSManFlagUTF16</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8388608.</para></summary> WSManFlagUtf16 = 8388608, /// <summary><para><c>WSManFlagUseCredSsp</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16777216.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ssp")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] WSManFlagUseCredSsp = 16777216, /// <summary><para><c>WSManFlagUseClientCertificate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 2097152.</para></summary> WSManFlagUseClientCertificate = 2097152, /// <summary><para><c>WSManFlagSkipRevocationCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 33554432.</para></summary> WSManFlagSkipRevocationCheck = 33554432, /// <summary><para><c>WSManFlagAllowNegotiateImplicitCredentials</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 67108864.</para></summary> WSManFlagAllowNegotiateImplicitCredentials = 67108864, /// <summary><para><c>WSManFlagUseSsl</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 134217728.</para></summary> WSManFlagUseSsl = 134217728 } #endregion WsManSessionFlags #region AuthenticationMechanism /// <summary>WSManEnumFlags enumeration</summary> /// [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] public enum AuthenticationMechanism { /// <summary> /// Use no authentication /// </summary> None = 0x0, /// <summary> /// Use Default authentication /// </summary> Default = 0x1, /// <summary> /// Use digest authentication for a remote operation /// </summary> Digest = 0x2, /// <summary> /// Use negotiate authentication for a remote operation (may use kerberos or ntlm) /// </summary> Negotiate = 0x4, /// <summary> /// Use basic authentication for a remote operation /// </summary> Basic = 0x8, /// <summary> /// Use kerberos authentication for a remote operation /// </summary> Kerberos = 0x10, /// <summary> /// Use client certificate authentication for a remote operation /// </summary> ClientCertificate = 0x20, /// <summary> /// Use CredSSP authentication for a remote operation /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")] Credssp = 0x80, } #endregion AuthenticationMechanism #region IWsMan /// <summary><para><c>IWSMan</c> interface.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [Guid("190D8637-5CD3-496D-AD24-69636BB5A3B5")] [ComImport] [TypeLibType((short)4304)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSMan { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>CreateSession</c> method of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); [DispId(1)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); #else [return: MarshalAs(UnmanagedType.IDispatch)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); #endif /// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); // [DispId(2)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateConnectionOptions(); /// <summary><para><c>CommandLine</c> property of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; // string CommandLine { // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>Error</c> property of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; // [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWsMan #region IWSManConnectionOptions /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("F704E861-9E52-464F-B786-DA5EB2320FDD")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] public interface IWSManConnectionOptions { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>UserName</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>UserName</c> property was the following: <c>BSTR UserName</c>;</para></remarks> // IDL: BSTR UserName; string UserName { // IDL: HRESULT UserName ([out, retval] BSTR* ReturnValue); [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT UserName (BSTR value); [DispId(1)] set; } /// <summary><para><c>Password</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Password</c> property was the following: <c>BSTR Password</c>;</para></remarks> // IDL: BSTR Password; [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] string Password { // IDL: HRESULT Password (BSTR value); [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] [DispId(2)] set; } } /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("EF43EDF7-2A48-4d93-9526-8BD6AB6D4A6B")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IWSManConnectionOptionsEx : IWSManConnectionOptions { /// <summary><para><c>CertificateThumbprint</c> property of <c>IWSManConnectionOptionsEx</c> interface.</para></summary> string CertificateThumbprint { [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; [DispId(1)] set; } } /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("F500C9EC-24EE-48ab-B38D-FC9A164C658E")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManConnectionOptionsEx2 : IWSManConnectionOptionsEx { /// <summary><para><c>SetProxy</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(4)] void SetProxy(int accessType, int authenticationMechanism, [In, MarshalAs(UnmanagedType.BStr)] string userName, [In, MarshalAs(UnmanagedType.BStr)] string password); /// <summary><para><c>ProxyIEConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(5)] int ProxyIEConfig(); /// <summary><para><c>ProxyWinHttpConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(6)] int ProxyWinHttpConfig(); /// <summary><para><c>ProxyAutoDetect</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(7)] int ProxyAutoDetect(); /// <summary><para><c>ProxyNoProxyServer</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(8)] int ProxyNoProxyServer(); /// <summary><para><c>ProxyAuthenticationUseNegotiate</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(9)] int ProxyAuthenticationUseNegotiate(); /// <summary><para><c>ProxyAuthenticationUseBasic</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(10)] int ProxyAuthenticationUseBasic(); /// <summary><para><c>ProxyAuthenticationUseDigest</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(11)] int ProxyAuthenticationUseDigest(); }; #endregion IWSManConnectionOptions #region IWSManEnumerator /// <summary><para><c>IWSManEnumerator</c> interface.</para></summary> [Guid("F3457CA9-ABB9-4FA5-B850-90E8CA300E7F")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManEnumerator { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>ReadItem</c> method of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>ReadItem</c> method was the following: <c>HRESULT ReadItem ([out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT ReadItem ([out, retval] BSTR* ReturnValue); [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] string ReadItem(); /// <summary><para><c>AtEndOfStream</c> property of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>AtEndOfStream</c> property was the following: <c>BOOL AtEndOfStream</c>;</para></remarks> // IDL: BOOL AtEndOfStream; bool AtEndOfStream { // IDL: HRESULT AtEndOfStream ([out, retval] BOOL* ReturnValue); [DispId(2)] [return: MarshalAs(UnmanagedType.Bool)] get; } /// <summary><para><c>Error</c> property of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(8)] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWSManEnumerator #region IWSManEx /// <summary><para><c>IWSManEx</c> interface.</para></summary> [Guid("2D53BDAA-798E-49E6-A1AA-74D01256F411")] [ComImport] [TypeLibType((short)4304)] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] public interface IWSManEx { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>CreateSession</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); [DispId(1)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); #else [return: MarshalAs(UnmanagedType.IDispatch)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); #endif /// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); [DispId(2)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateConnectionOptions(); /// <summary> /// /// </summary> /// <returns></returns> string CommandLine { // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>Error</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>CreateResourceLocator</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateResourceLocator</c> method was the following: <c>HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] [DispId(5)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateResourceLocator([MarshalAs(UnmanagedType.BStr)] string strResourceLocator); /// <summary><para><c>SessionFlagUTF8</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUTF8</c> method was the following: <c>HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] [DispId(6)] int SessionFlagUTF8(); /// <summary><para><c>SessionFlagCredUsernamePassword</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagCredUsernamePassword</c> method was the following: <c>HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [DispId(7)] int SessionFlagCredUsernamePassword(); /// <summary><para><c>SessionFlagSkipCACheck</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagSkipCACheck</c> method was the following: <c>HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue); [DispId(8)] int SessionFlagSkipCACheck(); /// <summary><para><c>SessionFlagSkipCNCheck</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagSkipCNCheck</c> method was the following: <c>HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue); [DispId(9)] int SessionFlagSkipCNCheck(); /// <summary><para><c>SessionFlagUseDigest</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseDigest</c> method was the following: <c>HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue); [DispId(10)] int SessionFlagUseDigest(); /// <summary><para><c>SessionFlagUseNegotiate</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseNegotiate</c> method was the following: <c>HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue); [DispId(11)] int SessionFlagUseNegotiate(); /// <summary><para><c>SessionFlagUseBasic</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseBasic</c> method was the following: <c>HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue); [DispId(12)] int SessionFlagUseBasic(); /// <summary><para><c>SessionFlagUseKerberos</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseKerberos</c> method was the following: <c>HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue); [DispId(13)] int SessionFlagUseKerberos(); /// <summary><para><c>SessionFlagNoEncryption</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagNoEncryption</c> method was the following: <c>HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue); [DispId(14)] int SessionFlagNoEncryption(); /// <summary><para><c>SessionFlagEnableSPNServerPort</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagEnableSPNServerPort</c> method was the following: <c>HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] [DispId(15)] int SessionFlagEnableSPNServerPort(); /// <summary><para><c>SessionFlagUseNoAuthentication</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseNoAuthentication</c> method was the following: <c>HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue); [DispId(16)] int SessionFlagUseNoAuthentication(); /// <summary><para><c>EnumerationFlagNonXmlText</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagNonXmlText</c> method was the following: <c>HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue); [DispId(17)] int EnumerationFlagNonXmlText(); /// <summary><para><c>EnumerationFlagReturnEPR</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] [DispId(18)] int EnumerationFlagReturnEPR(); /// <summary><para><c>EnumerationFlagReturnObjectAndEPR</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObjectAndEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] [DispId(19)] int EnumerationFlagReturnObjectAndEPR(); /// <summary><para><c>GetErrorMessage</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>GetErrorMessage</c> method was the following: <c>HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue); [DispId(20)] [return: MarshalAs(UnmanagedType.BStr)] string GetErrorMessage(uint errorNumber); /// <summary><para><c>EnumerationFlagHierarchyDeep</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeep</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue); [DispId(21)] int EnumerationFlagHierarchyDeep(); /// <summary><para><c>EnumerationFlagHierarchyShallow</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyShallow</c> method was the following: <c>HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue); [DispId(22)] int EnumerationFlagHierarchyShallow(); /// <summary><para><c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue); [DispId(23)] int EnumerationFlagHierarchyDeepBasePropsOnly(); /// <summary><para><c>EnumerationFlagReturnObject</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObject</c> method was the following: <c>HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue); [DispId(24)] int EnumerationFlagReturnObject(); /// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; [DispId(28)] int EnumerationFlagAssociationInstance(); /// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; [DispId(29)] int EnumerationFlagAssociatedInstance(); } #endregion IWsManEx #region IWsManResourceLocator /// <summary><para><c>IWSManResourceLocator</c> interface.</para></summary> [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] [Guid("A7A1BA28-DE41-466A-AD0A-C4059EAD7428")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManResourceLocator { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>resourceUri</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Set the resource URI. Must contain path only -- query string is not allowed here.</para></summary> /// <remarks><para>An original IDL definition of <c>resourceUri</c> property was the following: <c>BSTR resourceUri</c>;</para></remarks> // Set the resource URI. Must contain path only -- query string is not allowed here. // IDL: BSTR resourceUri; [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] string ResourceUri { // IDL: HRESULT resourceUri (BSTR value); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [DispId(1)] set; // IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>AddSelector</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add selector to resource locator</para></summary> /// <remarks><para>An original IDL definition of <c>AddSelector</c> method was the following: <c>HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue)</c>;</para></remarks> // Add selector to resource locator // IDL: HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "sel")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] [DispId(2)] void AddSelector([MarshalAs(UnmanagedType.BStr)] string resourceSelName, object selValue); /// <summary><para><c>ClearSelectors</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all selectors</para></summary> /// <remarks><para>An original IDL definition of <c>ClearSelectors</c> method was the following: <c>HRESULT ClearSelectors (void)</c>;</para></remarks> // Clear all selectors // IDL: HRESULT ClearSelectors (void); [DispId(3)] void ClearSelectors(); /// <summary><para><c>FragmentPath</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the fragment path</para></summary> /// <remarks><para>An original IDL definition of <c>FragmentPath</c> property was the following: <c>BSTR FragmentPath</c>;</para></remarks> // Gets the fragment path // IDL: BSTR FragmentPath; string FragmentPath { // IDL: HRESULT FragmentPath ([out, retval] BSTR* ReturnValue); [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT FragmentPath (BSTR value); [DispId(4)] set; } /// <summary><para><c>FragmentDialect</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the Fragment dialect</para></summary> /// <remarks><para>An original IDL definition of <c>FragmentDialect</c> property was the following: <c>BSTR FragmentDialect</c>;</para></remarks> // Gets the Fragment dialect // IDL: BSTR FragmentDialect; string FragmentDialect { // IDL: HRESULT FragmentDialect ([out, retval] BSTR* ReturnValue); [DispId(5)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT FragmentDialect (BSTR value); [DispId(5)] set; } /// <summary><para><c>AddOption</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add option to resource locator</para></summary> /// <remarks><para>An original IDL definition of <c>AddOption</c> method was the following: <c>HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply)</c>;</para></remarks> // Add option to resource locator // IDL: HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Option")] [DispId(6)] void AddOption([MarshalAs(UnmanagedType.BStr)] string OptionName, object OptionValue, int mustComply); /// <summary><para><c>MustUnderstandOptions</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Sets the MustUnderstandOptions value</para></summary> /// <remarks><para>An original IDL definition of <c>MustUnderstandOptions</c> property was the following: <c>long MustUnderstandOptions</c>;</para></remarks> // Sets the MustUnderstandOptions value // IDL: long MustUnderstandOptions; int MustUnderstandOptions { // IDL: HRESULT MustUnderstandOptions ([out, retval] long* ReturnValue); [DispId(7)] get; // IDL: HRESULT MustUnderstandOptions (long value); [DispId(7)] set; } /// <summary><para><c>ClearOptions</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all options</para></summary> /// <remarks><para>An original IDL definition of <c>ClearOptions</c> method was the following: <c>HRESULT ClearOptions (void)</c>;</para></remarks> // Clear all options // IDL: HRESULT ClearOptions (void); [DispId(8)] void ClearOptions(); /// <summary><para><c>Error</c> property of <c>IWSManResourceLocator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(9)] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWsManResourceLocator #region IWSManSession /// <summary><para><c>IWSManSession</c> interface.</para></summary> [Guid("FC84FC58-1286-40C4-9DA0-C8EF6EC241E0")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public interface IWSManSession { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>Get</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Get</c> method was the following: <c>HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] string Get(object resourceUri, int flags); /// <summary><para><c>Put</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Put</c> method was the following: <c>HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(2)] [return: MarshalAs(UnmanagedType.BStr)] string Put(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); /// <summary><para><c>Create</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Create</c> method was the following: <c>HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] string Create(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); /// <summary><para><c>Delete</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Delete</c> method was the following: <c>HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags)</c>;</para></remarks> // IDL: HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags); [DispId(4)] void Delete(object resourceUri, int flags); /// <summary> /// /// </summary> /// <param name="actionURI"></param> /// <param name="resourceUri"></param> /// <param name="parameters"></param> /// <param name="flags"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] [DispId(5)] String Invoke([MarshalAs(UnmanagedType.BStr)] string actionURI, [In] object resourceUri, [MarshalAs(UnmanagedType.BStr)] string parameters, [In] int flags); /// <summary><para><c>Enumerate</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Enumerate</c> method was the following: <c>HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue); [DispId(6)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object Enumerate(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string filter, [MarshalAs(UnmanagedType.BStr)] string dialect, int flags); /// <summary><para><c>Identify</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Identify</c> method was the following: <c>HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(7)] [return: MarshalAs(UnmanagedType.BStr)] string Identify(int flags); /// <summary><para><c>Error</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(8)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>BatchItems</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>BatchItems</c> property was the following: <c>long BatchItems</c>;</para></remarks> // IDL: long BatchItems; int BatchItems { // IDL: HRESULT BatchItems ([out, retval] long* ReturnValue); [DispId(9)] get; // IDL: HRESULT BatchItems (long value); [DispId(9)] set; } /// <summary><para><c>Timeout</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Timeout</c> property was the following: <c>long Timeout</c>;</para></remarks> // IDL: long Timeout; int Timeout { // IDL: HRESULT Timeout ([out, retval] long* ReturnValue); [DispId(10)] get; // IDL: HRESULT Timeout (long value); [DispId(10)] set; } } #endregion IWSManSession #region IWSManResourceLocatorInternal /// <summary><para><c>IWSManResourceLocatorInternal</c> interface.</para></summary> [Guid("EFFAEAD7-7EC8-4716-B9BE-F2E7E9FB4ADB")] [ComImport] [TypeLibType((short)400)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] public interface IWSManResourceLocatorInternal { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif } #endregion IWSManResourceLocatorInternal /// <summary><para><c>WSMan</c> interface.</para></summary> [Guid("BCED617B-EC03-420b-8508-977DC7A686BD")] [ComImport] #if CORECLR [ClassInterface(ClassInterfaceType.None)] #else [ClassInterface(ClassInterfaceType.AutoDual)] #endif public class WSManClass { } #region IGroupPolicyObject /// <summary><para><c>GPClass</c> interface.</para></summary> [Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")] [ComImport] [ClassInterface(ClassInterfaceType.None)] public class GPClass { } [ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IGroupPolicyObject { void New( [MarshalAs(UnmanagedType.LPWStr)] string pszDomainName, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, uint dwFlags); void OpenDSGPO( [MarshalAs(UnmanagedType.LPWStr)] string pszPath, uint dwFlags); void OpenLocalMachineGPO(uint dwFlags); void OpenRemoteMachineGPO( [MarshalAs(UnmanagedType.LPWStr)] string pszComputerName, uint dwFlags); void Save( [MarshalAs(UnmanagedType.Bool)] bool bMachine, [MarshalAs(UnmanagedType.Bool)] bool bAdd, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuidExtension, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid); void Delete(); void GetName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); void GetDisplayName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); void SetDisplayName( [MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetPath( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); void GetDSPath( uint dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); void GetFileSysPath( uint dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); IntPtr GetRegistryKey(uint dwSection); uint GetOptions(); void SetOptions(uint dwOptions, uint dwMask); void GetMachineName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); uint GetPropertySheetPages(out IntPtr hPages); } #endregion IGroupPolicyObject /// <summary><para><c>GpoNativeApi</c></para></summary> public sealed class GpoNativeApi { private GpoNativeApi() { } [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern System.IntPtr EnterCriticalPolicySection( [In, MarshalAs(UnmanagedType.Bool)] bool bMachine); [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool LeaveCriticalPolicySection( [In] System.IntPtr hSection); } #endregion } #pragma warning restore 1591
47.826957
349
0.668824
[ "MIT" ]
bechirslimene/PowerShell
src/Microsoft.WSMan.Management/Interop.cs
55,001
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Resources; using ICSharpCode.Core; using ICSharpCode.SharpDevelop; using ICSharpCode.UnitTesting; using NUnit.Framework; namespace UnitTesting.Tests.Tree { [TestFixture] public class TestResultIgnoreTaskWithNoMessageTestFixture { Task task; [TestFixtureSetUp] public void SetUpFixture() { ResourceManager rm = new ResourceManager("UnitTesting.Tests.Strings", GetType().Assembly); ResourceService.RegisterNeutralStrings(rm); } [SetUp] public void Init() { TestResult testResult = new TestResult("MyNamespace.MyTests"); testResult.ResultType = TestResultType.Ignored; task = TestResultTask.Create(testResult, null); } [Test] public void TaskMessageEqualsIsTakenFromStringResource() { Assert.AreEqual("Test case 'MyNamespace.MyTests' was not executed.", task.Description); } } }
26.375
103
0.759242
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/Analysis/UnitTesting/Test/Tree/TestResultIgnoreTaskWithNoMessageTestFixture.cs
1,057
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.ApplicationCache { /// <summary> /// Returns array of frame identifiers with manifest urls for each frame containing a document associated with some application cache. /// </summary> [CommandResponse(ProtocolName.ApplicationCache.GetFramesWithManifests)] public class GetFramesWithManifestsCommandResponse { /// <summary> /// Gets or sets Array of frame identifiers with manifest urls for each frame containing a document associated with some application cache. /// </summary> public FrameWithManifest[] FrameIds { get; set; } } }
35.894737
141
0.78739
[ "MIT" ]
brewdente/AutoWebPerf
MasterDevs.ChromeDevTools/Protocol/ApplicationCache/GetFramesWithManifestsCommandResponse.cs
682
C#
// =============================================================================== // Alachisoft (R) NCache 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 Alachisoft.NCache.Runtime; using Alachisoft.NCache.Sample.Data; using Alachisoft.NCache.Client; using System; using System.Configuration; using Alachisoft.NCache.Runtime.Caching; namespace Alachisoft.NCache.Samples { /// <summary> /// Class that provides the functionality of the sample /// </summary> public class BasicOperations { private static ICache _cache; /// <summary> /// Executing this method will perform all the operations of the sample /// </summary> public static void Run() { // Initialize cache InitializeCache(); // Create a simple customer object Customer customer = CreateNewCustomer(); string key = GetKey(customer); // Adding item synchronously AddObjectToCache(key, customer); // Get the object from cache customer = GetObjectFromCache(key); // Modify the object and update in cache UpdateObjectInCache(key, customer); // Delete the existing object RemoveObjectFromCache(key); // Dispose the cache once done _cache.Dispose(); } /// <summary> /// This method initializes the cache /// </summary> private static void InitializeCache() { string cache = ConfigurationManager.AppSettings["CacheID"]; if (String.IsNullOrEmpty(cache)) { Console.WriteLine("The CacheID cannot be null or empty."); return; } // Initialize an instance of the cache to begin performing operations: _cache = NCache.Client.CacheManager.GetCache(cache); // Print output on console Console.WriteLine(string.Format("\nCache '{0}' is initialized.", cache)); } /// <summary> /// This method adds object in the cache using synchronous api /// </summary> /// <param name="key"> String key to be added in cache </param> /// <param name="customer"> Instance of Customer that will be added to cache </param> private static void AddObjectToCache(string key, Customer customer) { // creating time span for setting expiration interval TimeSpan expirationInterval = new TimeSpan(0, 1, 0); // creating expiration interval with absolute type to assign to cache item Expiration expiration = new Expiration(ExpirationType.Absolute); expiration.ExpireAfter = expirationInterval; //Populating cache item and adding new expiration CacheItem item = new CacheItem(customer); item.Expiration = expiration; // Adding cacheitem to cache with an absolute expiration of 1 minute _cache.Add(key, item); // Print output on console Console.WriteLine("\nObject is added to cache."); } /// <summary> /// This method gets an object from the cache using synchronous api /// </summary> /// <param name="key"> String key to get object from cache</param> /// <returns> returns instance of Customer retrieved from cache</returns> private static Customer GetObjectFromCache(string key) { Customer cachedCustomer = _cache.Get<Customer>(key); // Print output on console Console.WriteLine("\nObject is fetched from cache"); PrintCustomerDetails(cachedCustomer); return cachedCustomer; } /// <summary> /// This method updates object in the cache using synchronous api /// </summary> /// <param name="key"> String key to be updated in cache</param> /// <param name="customer"> Instance of Customer that will be updated in the cache</param> private static void UpdateObjectInCache(string key, Customer customer) { // Update item customer.CompanyName = "Gourmet Lanchonetes"; // create expiration time of 30 seconds TimeSpan expirationInterval = new TimeSpan(0, 0, 30); // create expiration interval with sliding type Expiration expiration = new Expiration(ExpirationType.Sliding); expiration.ExpireAfter = expirationInterval; // create cache item with required data and add expiration CacheItem item = new CacheItem(customer); item.Expiration = expiration; // insert to cache _cache.Insert(key, customer); // Print output on console Console.WriteLine("\nObject is updated in cache."); } /// <summary> /// Delete an object in the cache using synchronous api /// </summary> /// <param name="key"> String key to be deleted from cache</param> private static void RemoveObjectFromCache(string key) { // Remove the existing customer _cache.Remove(key); // Print output on console Console.WriteLine("\nObject is removed from cache."); } /// <summary> /// Generates instance of Customer to be used in this sample /// </summary> /// <returns> returns instance of Customer </returns> private static Customer CreateNewCustomer() { return new Customer { CustomerID = "DAVJO", ContactName = "David Johnes", CompanyName = "Lonesome Pine Restaurant", ContactNo = "12345-6789", Address = "Silicon Valley, Santa Clara, California", }; } /// <summary> /// Generates a string key for specified customer /// </summary> /// <param name="customer"> Instance of Customer to generate a key</param> /// <returns> returns a key </returns> private static string GetKey(Customer customer) { return string.Format("Customer:{0}", customer.CustomerID); } /// <summary> /// This method prints detials of customer type. /// </summary> /// <param name="customer"></param> private static void PrintCustomerDetails(Customer customer) { if (customer == null) return; Console.WriteLine(); Console.WriteLine("Customer Details are as follows: "); Console.WriteLine("ContactName: " + customer.ContactName); Console.WriteLine("CompanyName: " + customer.CompanyName); Console.WriteLine("Contact No: " + customer.ContactNo); Console.WriteLine("Address: " + customer.Address); Console.WriteLine(); } } }
36.940299
98
0.573064
[ "Apache-2.0" ]
Alachisoft/NCache
Samples/dotnetcore/BasicOperations/BasicOperations/BasicOperations.cs
7,428
C#
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * 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.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Capitalization /// </summary> [DataContract] public partial class Capitalization : IEquatable<Capitalization>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Capitalization" /> class. /// </summary> /// <param name="SmallCamel">SmallCamel.</param> /// <param name="CapitalCamel">CapitalCamel.</param> /// <param name="SmallSnake">SmallSnake.</param> /// <param name="CapitalSnake">CapitalSnake.</param> /// <param name="SCAETHFlowPoints">SCAETHFlowPoints.</param> /// <param name="ATT_NAME">Name of the pet .</param> public Capitalization(string SmallCamel = default(string), string CapitalCamel = default(string), string SmallSnake = default(string), string CapitalSnake = default(string), string SCAETHFlowPoints = default(string), string ATT_NAME = default(string)) { this.SmallCamel = SmallCamel; this.CapitalCamel = CapitalCamel; this.SmallSnake = SmallSnake; this.CapitalSnake = CapitalSnake; this.SCAETHFlowPoints = SCAETHFlowPoints; this.ATT_NAME = ATT_NAME; } /// <summary> /// Gets or Sets SmallCamel /// </summary> [DataMember(Name="smallCamel", EmitDefaultValue=false)] public string SmallCamel { get; set; } /// <summary> /// Gets or Sets CapitalCamel /// </summary> [DataMember(Name="CapitalCamel", EmitDefaultValue=false)] public string CapitalCamel { get; set; } /// <summary> /// Gets or Sets SmallSnake /// </summary> [DataMember(Name="small_Snake", EmitDefaultValue=false)] public string SmallSnake { get; set; } /// <summary> /// Gets or Sets CapitalSnake /// </summary> [DataMember(Name="Capital_Snake", EmitDefaultValue=false)] public string CapitalSnake { get; set; } /// <summary> /// Gets or Sets SCAETHFlowPoints /// </summary> [DataMember(Name="SCA_ETH_Flow_Points", EmitDefaultValue=false)] public string SCAETHFlowPoints { get; set; } /// <summary> /// Name of the pet /// </summary> /// <value>Name of the pet </value> [DataMember(Name="ATT_NAME", EmitDefaultValue=false)] public string ATT_NAME { 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 Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Capitalization); } /// <summary> /// Returns true if Capitalization instances are equal /// </summary> /// <param name="other">Instance of Capitalization to be compared</param> /// <returns>Boolean</returns> public bool Equals(Capitalization other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.SmallCamel == other.SmallCamel || this.SmallCamel != null && this.SmallCamel.Equals(other.SmallCamel) ) && ( this.CapitalCamel == other.CapitalCamel || this.CapitalCamel != null && this.CapitalCamel.Equals(other.CapitalCamel) ) && ( this.SmallSnake == other.SmallSnake || this.SmallSnake != null && this.SmallSnake.Equals(other.SmallSnake) ) && ( this.CapitalSnake == other.CapitalSnake || this.CapitalSnake != null && this.CapitalSnake.Equals(other.CapitalSnake) ) && ( this.SCAETHFlowPoints == other.SCAETHFlowPoints || this.SCAETHFlowPoints != null && this.SCAETHFlowPoints.Equals(other.SCAETHFlowPoints) ) && ( this.ATT_NAME == other.ATT_NAME || this.ATT_NAME != null && this.ATT_NAME.Equals(other.ATT_NAME) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.SmallCamel != null) hash = hash * 59 + this.SmallCamel.GetHashCode(); if (this.CapitalCamel != null) hash = hash * 59 + this.CapitalCamel.GetHashCode(); if (this.SmallSnake != null) hash = hash * 59 + this.SmallSnake.GetHashCode(); if (this.CapitalSnake != null) hash = hash * 59 + this.CapitalSnake.GetHashCode(); if (this.SCAETHFlowPoints != null) hash = hash * 59 + this.SCAETHFlowPoints.GetHashCode(); if (this.ATT_NAME != null) hash = hash * 59 + this.ATT_NAME.GetHashCode(); return hash; } } /// <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) { yield break; } } }
38.290476
259
0.557269
[ "Apache-2.0" ]
FedeParola/swagger-codegen
samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Capitalization.cs
8,041
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using WebAssembly.Runtime.Compilation; namespace WebAssembly.Runtime { /// <summary> /// Creates a new instance of a compiled WebAssembly module. /// </summary> /// <typeparam name="TExports">The type of the exports object.</typeparam> /// <param name="imports">Run-time imports.</param> /// <returns>The instance.</returns> /// <exception cref="ArgumentNullException"><paramref name="imports" /> cannot be null.</exception> public delegate Instance<TExports> InstanceCreator<TExports>(IDictionary<string, IDictionary<string, RuntimeImport>> imports) where TExports : class; /// <summary> /// Provides compilation functionality. Use <see cref="Module"/> for robust inspection and modification capability. /// </summary> public static class Compile { /// <summary> /// Uses streaming compilation to create an executable <see cref="Instance{TExports}"/> from a binary WebAssembly source. /// </summary> /// <param name="path">The path to the file that contains a WebAssembly binary stream.</param> /// <returns>The module.</returns> /// <exception cref="ArgumentNullException"><paramref name="path"/> cannot be null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white space, or contains one or more invalid characters; or, /// <paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. /// </exception> /// <exception cref="NotSupportedException"><paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.</exception> /// <exception cref="FileNotFoundException">The file indicated by <paramref name="path"/> could not be found.</exception> /// <exception cref="DirectoryNotFoundException">The specified <paramref name="path"/> is invalid, such as being on an unmapped drive.</exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception> /// <exception cref="ModuleLoadException">An error was encountered while reading the WebAssembly file.</exception> public static InstanceCreator<TExports> FromBinary<TExports>(string path) where TExports : class { return FromBinary<TExports>(path, new CompilerConfiguration()); } /// <summary> /// Uses streaming compilation to create an executable <see cref="Instance{TExports}"/> from a binary WebAssembly source. /// </summary> /// <param name="path">The path to the file that contains a WebAssembly binary stream.</param> /// <param name="configuration">Configures the compiler.</param> /// <returns>The module.</returns> /// <exception cref="ArgumentNullException">No parameters can be null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white space, or contains one or more invalid characters; or, /// <paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment. /// </exception> /// <exception cref="NotSupportedException"><paramref name="path"/> refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.</exception> /// <exception cref="FileNotFoundException">The file indicated by <paramref name="path"/> could not be found.</exception> /// <exception cref="DirectoryNotFoundException">The specified <paramref name="path"/> is invalid, such as being on an unmapped drive.</exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception> /// <exception cref="ModuleLoadException">An error was encountered while reading the WebAssembly file.</exception> public static InstanceCreator<TExports> FromBinary<TExports>(string path, CompilerConfiguration configuration) where TExports : class { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4 * 1024, FileOptions.SequentialScan); return FromBinary<TExports>(stream, configuration); } /// <summary> /// Uses streaming compilation to create an executable <see cref="Instance{TExports}"/> from a binary WebAssembly source. /// </summary> /// <param name="input">The source of data. The stream is left open after reading is complete.</param> /// <returns>A function that creates instances on demand.</returns> /// <exception cref="ArgumentNullException"><paramref name="input"/> cannot be null.</exception> public static InstanceCreator<TExports> FromBinary<TExports>(Stream input) where TExports : class { return FromBinary<TExports>(input, new CompilerConfiguration()); } /// <summary> /// Uses streaming compilation to create an executable <see cref="Instance{TExports}"/> from a binary WebAssembly source. /// </summary> /// <param name="input">The source of data. The stream is left open after reading is complete.</param> /// <param name="configuration">Configures the compiler.</param> /// <returns>A function that creates instances on demand.</returns> /// <exception cref="ArgumentNullException">No parameters can be null.</exception> public static InstanceCreator<TExports> FromBinary<TExports>(Stream input, CompilerConfiguration configuration) where TExports : class { var exportInfo = typeof(TExports).GetTypeInfo(); if (!exportInfo.IsPublic && !exportInfo.IsNestedPublic) throw new CompilerException($"Export type {exportInfo.FullName} must be public so that the compiler can inherit it."); ConstructorInfo constructor; using (var reader = new Reader(input)) { try { constructor = FromBinary( reader, configuration, typeof(Instance<TExports>), typeof(TExports) ); } catch (OverflowException x) #if DEBUG when (!System.Diagnostics.Debugger.IsAttached) #endif { throw new ModuleLoadException("Overflow encountered.", reader.Offset, x); } catch (EndOfStreamException x) #if DEBUG when (!System.Diagnostics.Debugger.IsAttached) #endif { throw new ModuleLoadException("Stream ended unexpectedly.", reader.Offset, x); } catch (Exception x) when ( !(x is CompilerException) && !(x is ModuleLoadException) #if DEBUG && !System.Diagnostics.Debugger.IsAttached #endif ) { throw new ModuleLoadException(x.Message, reader.Offset, x); } } return (IDictionary<string, IDictionary<string, RuntimeImport>> imports) => { try { return (Instance<TExports>)constructor.Invoke(new object[] { imports }); } catch (TargetInvocationException x) #if DEBUG when (!System.Diagnostics.Debugger.IsAttached) #endif { ExceptionDispatchInfo.Capture(x.InnerException ?? x).Throw(); throw; } }; } private struct Local { public Local(Reader reader) { this.Count = reader.ReadVarUInt32(); this.Type = (WebAssemblyValueType)reader.ReadVarInt7(); } public readonly uint Count; public readonly WebAssemblyValueType Type; } private static ConstructorInfo FromBinary( Reader reader, CompilerConfiguration configuration, Type instanceContainer, Type exportContainer ) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (reader.ReadUInt32() != Module.Magic) throw new ModuleLoadException("File preamble magic value is incorrect.", 0); switch (reader.ReadUInt32()) { case 0x1: //First release // case 0xd: //Final pre-release, binary format is identical with first release. break; default: throw new ModuleLoadException("Unsupported version, only version 0x1 is accepted.", 4); } uint memoryPagesMinimum = 0; uint memoryPagesMaximum = 0; Signature[]? signatures = null; Signature[]? functionSignatures = null; KeyValuePair<string, uint>[]? exportedFunctions = null; var previousSection = Section.None; var module = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("CompiledWebAssembly"), AssemblyBuilderAccess.RunAndCollect ) .DefineDynamicModule("CompiledWebAssembly") ; const TypeAttributes classAttributes = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.BeforeFieldInit ; const MethodAttributes constructorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName ; const MethodAttributes internalFunctionAttributes = MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig ; const MethodAttributes exportedFunctionAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig ; const FieldAttributes privateReadonlyField = FieldAttributes.Private | FieldAttributes.InitOnly ; var context = new CompilationContext(configuration); var exportsBuilder = context.CheckedExportsBuilder = module.DefineType("CompiledExports", classAttributes, exportContainer); MethodBuilder? importedMemoryProvider = null; FieldBuilder? memory = null; void CreateMemoryField() { memory = context!.Memory = exportsBuilder!.DefineField("☣ Memory", typeof(UnmanagedMemory), privateReadonlyField); } ILGenerator instanceConstructorIL; { var instanceConstructor = exportsBuilder.DefineConstructor( constructorAttributes, CallingConventions.Standard, new[] { typeof(IDictionary<string, IDictionary<string, RuntimeImport>>) } ); instanceConstructorIL = instanceConstructor.GetILGenerator(); { var usableConstructor = exportContainer.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0); if (usableConstructor != null) { instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Call, usableConstructor); } } } var exports = exportsBuilder; var importedFunctions = 0; var importedGlobals = 0; MethodInfo[]? internalFunctions = null; FieldBuilder? functionTable = null; GlobalInfo[]? globals = null; MethodInfo? startFunction = null; var delegateInvokersByTypeIndex = context.DelegateInvokersByTypeIndex; var delegateRemappersByType = context.DelegateRemappersByType; var emptyTypes = Type.EmptyTypes; var preSectionOffset = reader.Offset; while (reader.TryReadVarUInt7(out var id)) //At points where TryRead is used, the stream can safely end. { if (id != 0 && (Section)id < previousSection) throw new ModuleLoadException($"Sections out of order; section {(Section)id} encounterd after {previousSection}.", preSectionOffset); var payloadLength = reader.ReadVarUInt32(); switch ((Section)id) { case Section.None: { var preNameOffset = reader.Offset; reader.ReadString(reader.ReadVarUInt32()); //Name reader.ReadBytes(payloadLength - checked((uint)(reader.Offset - preNameOffset))); //Content } break; case Section.Type: { signatures = context.Types = new Signature[reader.ReadVarUInt32()]; for (var i = 0; i < signatures.Length; i++) signatures[i] = new Signature(reader, (uint)i); } break; case Section.Import: { var count = checked((int)reader.ReadVarUInt32()); var functionImports = new List<MethodInfo>(count); var functionImportTypes = new List<Signature>(count); var globalImports = new List<GlobalInfo>(count); var missingDelegates = new List<MissingDelegateType>(); for (var i = 0; i < count; i++) { var moduleName = reader.ReadString(reader.ReadVarUInt32()); var fieldName = reader.ReadString(reader.ReadVarUInt32()); var preKindOffset = reader.Offset; var kind = (ExternalKind)reader.ReadByte(); switch (kind) { case ExternalKind.Function: { var preTypeIndexOffset = reader.Offset; var typeIndex = reader.ReadVarUInt32(); if (signatures == null) throw new InvalidOperationException(); if (typeIndex >= signatures.Length) throw new ModuleLoadException($"Requested type index {typeIndex} but only {signatures.Length} are available.", preTypeIndexOffset); var signature = signatures[typeIndex]; var del = configuration.GetDelegateForType(signature.ParameterTypes.Length, signature.ReturnTypes.Length); if (del == null) { missingDelegates.Add(new MissingDelegateType(moduleName, fieldName, signature)); continue; } var typedDelegate = del.IsGenericTypeDefinition ? del.MakeGenericType(signature.ParameterTypes.Concat(signature.ReturnTypes).ToArray()) : del; var delField = $"➡ {moduleName}::{fieldName}"; var delFieldBuilder = exportsBuilder.DefineField(delField, typedDelegate, privateReadonlyField); var invoker = exportsBuilder.DefineMethod( $"Invoke {delField}", internalFunctionAttributes, CallingConventions.Standard, signature.ReturnTypes.Length != 0 ? signature.ReturnTypes[0] : null, signature.ParameterTypes.Concat(new Type[] { exports }).ToArray() ); var invokerIL = invoker.GetILGenerator(); invokerIL.EmitLoadArg(signature.ParameterTypes.Length); invokerIL.Emit(OpCodes.Ldfld, delFieldBuilder); for (ushort arg = 0; arg < signature.ParameterTypes.Length; arg++) { invokerIL.EmitLoadArg(arg); } invokerIL.Emit(OpCodes.Callvirt, typedDelegate.GetRuntimeMethod(nameof(Action.Invoke), signature.ParameterTypes)!); invokerIL.Emit(OpCodes.Ret); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_1); instanceConstructorIL.Emit(OpCodes.Ldstr, moduleName); instanceConstructorIL.Emit(OpCodes.Ldstr, fieldName); instanceConstructorIL.Emit(OpCodes.Call, typeof(Helpers) .GetTypeInfo() .GetDeclaredMethod(nameof(Helpers.FindImport))! .MakeGenericMethod(typeof(FunctionImport)) ); instanceConstructorIL.Emit(OpCodes.Callvirt, typeof(FunctionImport) .GetTypeInfo() .GetDeclaredProperty(nameof(FunctionImport.Method))! .GetMethod!); ImportException.EmitTryCast(instanceConstructorIL, typedDelegate); instanceConstructorIL.Emit(OpCodes.Stfld, delFieldBuilder); functionImports.Add(invoker); functionImportTypes.Add(signature); } break; case ExternalKind.Table: { var preElementTypeoffset = reader.Offset; var elementType = (ElementType)reader.ReadVarInt7(); if (elementType != ElementType.FunctionReference) throw new ModuleLoadException($"{moduleName}::{fieldName} imported table type of kind of {elementType} is not recognized.", preElementTypeoffset); var limits = new ResizableLimits(reader); if (functionTable != null) throw new NotSupportedException("Unable to support multiple tables."); functionTable = context.FunctionTable = CreateFunctionTableField(exportsBuilder); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_1); instanceConstructorIL.Emit(OpCodes.Ldstr, moduleName); instanceConstructorIL.Emit(OpCodes.Ldstr, fieldName); instanceConstructorIL.Emit(OpCodes.Call, typeof(Helpers) .GetTypeInfo() .GetDeclaredMethod(nameof(Helpers.FindImport))! .MakeGenericMethod(typeof(FunctionTable)) ); instanceConstructorIL.Emit(OpCodes.Stfld, functionTable); } break; case ExternalKind.Memory: { var limits = new ResizableLimits(reader); var typedDelegate = typeof(Func<UnmanagedMemory>); var delField = $"➡ {moduleName}::{fieldName}"; var delFieldBuilder = exportsBuilder.DefineField(delField, typedDelegate, privateReadonlyField); importedMemoryProvider = exportsBuilder.DefineMethod( $"Invoke {delField}", internalFunctionAttributes, CallingConventions.Standard, typeof(UnmanagedMemory), new Type[] { exports } ); var invokerIL = importedMemoryProvider.GetILGenerator(); invokerIL.EmitLoadArg(0); invokerIL.Emit(OpCodes.Ldfld, delFieldBuilder); invokerIL.Emit(OpCodes.Callvirt, typedDelegate.GetRuntimeMethod(nameof(Func<UnmanagedMemory>.Invoke), emptyTypes)!); invokerIL.Emit(OpCodes.Ret); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_1); instanceConstructorIL.Emit(OpCodes.Ldstr, moduleName); instanceConstructorIL.Emit(OpCodes.Ldstr, fieldName); instanceConstructorIL.Emit(OpCodes.Call, typeof(Helpers) .GetTypeInfo() .GetDeclaredMethod(nameof(Helpers.FindImport))! .MakeGenericMethod(typeof(MemoryImport)) ); instanceConstructorIL.Emit(OpCodes.Callvirt, typeof(MemoryImport) .GetTypeInfo() .GetDeclaredProperty(nameof(MemoryImport.Method))! .GetMethod!); ; ImportException.EmitTryCast(instanceConstructorIL, typedDelegate); instanceConstructorIL.Emit(OpCodes.Stfld, delFieldBuilder); CreateMemoryField(); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Call, importedMemoryProvider); instanceConstructorIL.Emit(OpCodes.Stfld, memory!); } break; case ExternalKind.Global: { var contentType = (WebAssemblyValueType)reader.ReadVarInt7(); var mutable = reader.ReadVarUInt1() == 1; var typedDelegate = typeof(Func<>).MakeGenericType(new[] { contentType.ToSystemType() }); var delField = $"➡ Get {moduleName}::{fieldName}"; var delFieldBuilder = exportsBuilder.DefineField(delField, typedDelegate, privateReadonlyField); var getterInvoker = exportsBuilder.DefineMethod( $"Invoke {delField}", internalFunctionAttributes, CallingConventions.Standard, contentType.ToSystemType(), new Type[] { exports } ); var invokerIL = getterInvoker.GetILGenerator(); invokerIL.EmitLoadArg(0); invokerIL.Emit(OpCodes.Ldfld, delFieldBuilder); invokerIL.Emit(OpCodes.Callvirt, typedDelegate.GetRuntimeMethod(nameof(Func<WebAssemblyValueType>.Invoke), emptyTypes)!); invokerIL.Emit(OpCodes.Ret); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_1); instanceConstructorIL.Emit(OpCodes.Ldstr, moduleName); instanceConstructorIL.Emit(OpCodes.Ldstr, fieldName); instanceConstructorIL.Emit(OpCodes.Call, typeof(Helpers) .GetTypeInfo() .GetDeclaredMethod(nameof(Helpers.FindImport))! .MakeGenericMethod(typeof(GlobalImport)) ); instanceConstructorIL.Emit(OpCodes.Callvirt, typeof(GlobalImport) .GetTypeInfo() .GetDeclaredProperty(nameof(GlobalImport.Getter))! .GetMethod!); ImportException.EmitTryCast(instanceConstructorIL, typedDelegate); instanceConstructorIL.Emit(OpCodes.Stfld, delFieldBuilder); MethodBuilder? setterInvoker; if (!mutable) { setterInvoker = null; } else { typedDelegate = typeof(Action<>).MakeGenericType(new[] { contentType.ToSystemType() }); delField = $"➡ Set {moduleName}::{fieldName}"; delFieldBuilder = exportsBuilder.DefineField(delField, typedDelegate, privateReadonlyField); setterInvoker = exportsBuilder.DefineMethod( $"Invoke {delField}", internalFunctionAttributes, CallingConventions.Standard, null, new[] { contentType.ToSystemType(), exports } ); invokerIL = setterInvoker.GetILGenerator(); invokerIL.EmitLoadArg(1); invokerIL.Emit(OpCodes.Ldfld, delFieldBuilder); invokerIL.EmitLoadArg(0); invokerIL.Emit(OpCodes.Callvirt, typedDelegate.GetRuntimeMethod(nameof(Action<WebAssemblyValueType>.Invoke), new[] { contentType.ToSystemType() })!); invokerIL.Emit(OpCodes.Ret); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldarg_1); instanceConstructorIL.Emit(OpCodes.Ldstr, moduleName); instanceConstructorIL.Emit(OpCodes.Ldstr, fieldName); instanceConstructorIL.Emit(OpCodes.Call, typeof(Helpers) .GetTypeInfo() .GetDeclaredMethod(nameof(Helpers.FindImport))! .MakeGenericMethod(typeof(GlobalImport)) ); instanceConstructorIL.Emit(OpCodes.Callvirt, typeof(GlobalImport) .GetTypeInfo() .GetDeclaredProperty(nameof(GlobalImport.Setter))! .GetMethod!); ImportException.EmitTryCast(instanceConstructorIL, typedDelegate); instanceConstructorIL.Emit(OpCodes.Stfld, delFieldBuilder); } globalImports.Add(new GlobalInfo(contentType, true, getterInvoker, setterInvoker)); } break; default: throw new ModuleLoadException($"{moduleName}::{fieldName} imported external kind of {kind} is not recognized.", preKindOffset); } } if (missingDelegates.Count != 0) throw new MissingDelegateTypesException(missingDelegates); importedFunctions = functionImports.Count; internalFunctions = context.Methods = functionImports.ToArray(); functionSignatures = context.FunctionSignatures = functionImportTypes.ToArray(); importedGlobals = globalImports.Count; globals = context.Globals = globalImports.ToArray(); } break; case Section.Function: { var importedFunctionCount = internalFunctions == null ? 0 : internalFunctions.Length; var functionIndexSize = checked((int)(importedFunctionCount + reader.ReadVarUInt32())); if (functionSignatures != null) { Array.Resize(ref functionSignatures, functionIndexSize); context.FunctionSignatures = functionSignatures; } else { functionSignatures = context.FunctionSignatures = new Signature[functionIndexSize]; } if (importedFunctionCount != 0) { Array.Resize(ref internalFunctions, checked(functionSignatures.Length)); context.Methods = internalFunctions; } else { internalFunctions = context.Methods = new MethodInfo[functionSignatures.Length]; } if (signatures == null) throw new InvalidOperationException(); for (var i = importedFunctionCount; i < functionSignatures.Length; i++) { var signature = functionSignatures[i] = signatures[reader.ReadVarUInt32()]; var parms = signature.ParameterTypes.Concat(new Type[] { exports }).ToArray(); internalFunctions[i] = exportsBuilder.DefineMethod( $"👻 {i}", internalFunctionAttributes, CallingConventions.Standard, signature.ReturnTypes.FirstOrDefault(), parms ); } } break; case Section.Table: { var preCountOffset = reader.Offset; var count = reader.ReadVarUInt32(); for (var i = 0; i < count; i++) { var preElementTypeOffset = reader.Offset; var elementType = (ElementType)reader.ReadVarInt7(); if (elementType != ElementType.FunctionReference) throw new ModuleLoadException($"The only supported table element type is {nameof(ElementType.FunctionReference)}, found {elementType}", preElementTypeOffset); if (functionTable == null) { // It's legal to have multiple tables, but the extra tables are inaccessble to the initial version of WebAssembly. var limits = new ResizableLimits(reader); functionTable = context.FunctionTable = CreateFunctionTableField(exportsBuilder); instanceConstructorIL.EmitLoadArg(0); instanceConstructorIL.EmitLoadConstant(limits.Minimum); if (limits.Maximum.HasValue) { instanceConstructorIL.EmitLoadConstant(limits.Maximum); instanceConstructorIL.Emit(OpCodes.Newobj, typeof(uint?) .GetTypeInfo() .DeclaredConstructors .Where(constructor => { var parms = constructor.GetParameters(); return parms.Length == 1 && parms[0].ParameterType == typeof(uint); }) .Single()); ; instanceConstructorIL.Emit(OpCodes.Newobj, typeof(FunctionTable) .GetTypeInfo() .DeclaredConstructors .Where(constructor => { var parms = constructor.GetParameters(); return parms.Length == 2 && parms[0].ParameterType == typeof(uint) && parms[1].ParameterType == typeof(uint?); }) .Single()); } else { instanceConstructorIL.Emit(OpCodes.Newobj, typeof(FunctionTable) .GetTypeInfo() .DeclaredConstructors .Where(constructor => { var parms = constructor.GetParameters(); return parms.Length == 1 && parms[0].ParameterType == typeof(uint); }) .Single()); } instanceConstructorIL.Emit(OpCodes.Stfld, functionTable); } } } break; case Section.Memory: { var preCountOffset = reader.Offset; var count = reader.ReadVarUInt32(); if (count > 1) throw new ModuleLoadException("Multiple memory values are not supported.", preCountOffset); if (count != 0 && memory != null) throw new ModuleLoadException("Memory already provided via import, multiple memory values are not supported.", preCountOffset); var setFlags = (ResizableLimits.Flags)reader.ReadVarUInt32(); memoryPagesMinimum = reader.ReadVarUInt32(); if ((setFlags & ResizableLimits.Flags.Maximum) != 0) memoryPagesMaximum = Math.Min(reader.ReadVarUInt32(), uint.MaxValue / Memory.PageSize); else memoryPagesMaximum = uint.MaxValue / Memory.PageSize; CreateMemoryField(); instanceConstructorIL.Emit(OpCodes.Ldarg_0); Instructions.Int32Constant.Emit(instanceConstructorIL, (int)memoryPagesMinimum); Instructions.Int32Constant.Emit(instanceConstructorIL, (int)memoryPagesMaximum); instanceConstructorIL.Emit(OpCodes.Newobj, typeof(uint?).GetTypeInfo().DeclaredConstructors.Where(info => { var parms = info.GetParameters(); return parms.Length == 1 && parms[0].ParameterType == typeof(uint); }).First()); instanceConstructorIL.Emit(OpCodes.Newobj, typeof(UnmanagedMemory).GetTypeInfo().DeclaredConstructors.Where(info => { var parms = info.GetParameters(); return parms.Length == 2 && parms[0].ParameterType == typeof(uint) && parms[1].ParameterType == typeof(uint?); }).First()); instanceConstructorIL.Emit(OpCodes.Stfld, memory!); exportsBuilder.AddInterfaceImplementation(typeof(IDisposable)); var dispose = exportsBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot, CallingConventions.HasThis, typeof(void), emptyTypes ); var disposeIL = dispose.GetILGenerator(); disposeIL.Emit(OpCodes.Ldarg_0); disposeIL.Emit(OpCodes.Ldfld, memory!); disposeIL.Emit(OpCodes.Call, typeof(UnmanagedMemory) .GetTypeInfo() .DeclaredMethods .Where(info => info.ReturnType == typeof(void) && info.GetParameters().Length == 0 && info.Name == nameof(UnmanagedMemory.Dispose)) .First()); disposeIL.Emit(OpCodes.Ret); } break; case Section.Global: { var count = reader.ReadVarUInt32(); if (globals != null) { Array.Resize(ref globals, checked((int)(globals.Length + count))); context.Globals = globals; } else { globals = context.Globals = new GlobalInfo[count]; } var emptySignature = Signature.Empty; for (var i = 0; i < count; i++) { var contentType = (WebAssemblyValueType)reader.ReadVarInt7(); var isMutable = reader.ReadVarUInt1() == 1; var getter = exportsBuilder.DefineMethod( $"🌍 Get {i}", internalFunctionAttributes, CallingConventions.Standard, contentType.ToSystemType(), isMutable ? new Type[] { exports } : null ); var il = getter.GetILGenerator(); var getterSignature = new Signature(contentType); MethodBuilder? setter; if (isMutable == false) { context.Reset( il, getterSignature, getterSignature.RawParameterTypes ); foreach (var instruction in Instruction.ParseInitializerExpression(reader)) { instruction.Compile(context); context.Previous = instruction.OpCode; } setter = null; } else //Mutable { var field = exportsBuilder.DefineField( $"🌍 {i}", contentType.ToSystemType(), FieldAttributes.Private | (isMutable ? 0 : FieldAttributes.InitOnly) ); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, field); il.Emit(OpCodes.Ret); setter = exportsBuilder.DefineMethod( $"🌍 Set {i}", internalFunctionAttributes, CallingConventions.Standard, typeof(void), new[] { contentType.ToSystemType(), exports } ); il = setter.GetILGenerator(); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); context.Reset( instanceConstructorIL, emptySignature, emptySignature.RawParameterTypes ); context.EmitLoadThis(); var ended = false; foreach (var instruction in Instruction.ParseInitializerExpression(reader)) { if (ended) throw new CompilerException("Only a single End is allowed within an initializer expression."); if (instruction.OpCode == OpCode.End) { context.Emit(OpCodes.Stfld, field); ended = true; continue; } instruction.Compile(context); context.Previous = instruction.OpCode; } } globals[importedGlobals + i] = new GlobalInfo(contentType, isMutable, getter, setter); } } break; case Section.Export: { const MethodAttributes exportedPropertyAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual | MethodAttributes.Final; var totalExports = reader.ReadVarUInt32(); var xFunctions = new List<KeyValuePair<string, uint>>((int)Math.Min(int.MaxValue, totalExports)); for (var i = 0; i < totalExports; i++) { var name = reader.ReadString(reader.ReadVarUInt32()); var preKindOffset = reader.Offset; var kind = (ExternalKind)reader.ReadByte(); var preIndexOffset = reader.Offset; var index = reader.ReadVarUInt32(); switch (kind) { case ExternalKind.Function: xFunctions.Add(new KeyValuePair<string, uint>(name, index)); break; case ExternalKind.Table: if (index != 0) throw new ModuleLoadException($"Exported table must be of index 0, found {index}.", preIndexOffset); if (functionTable == null) throw new ModuleLoadException("Can't export a table without defining or importing one.", preKindOffset); { var tableGetter = exportsBuilder.DefineMethod("get_" + name, exportedPropertyAttributes, CallingConventions.HasThis, typeof(FunctionTable), emptyTypes ); tableGetter.SetCustomAttribute(NativeExportAttribute.Emit(ExternalKind.Table, name)); var getterIL = tableGetter.GetILGenerator(); getterIL.Emit(OpCodes.Ldarg_0); getterIL.Emit(OpCodes.Ldfld, functionTable); getterIL.Emit(OpCodes.Ret); exportsBuilder.DefineProperty(name, PropertyAttributes.None, typeof(FunctionTable), emptyTypes) .SetGetMethod(tableGetter); } break; case ExternalKind.Memory: if (index != 0) throw new ModuleLoadException($"Exported memory must be of index 0, found {index}.", preIndexOffset); if (memory == null) throw new CompilerException("Cannot export linear memory when linear memory is not defined."); { var memoryGetter = exportsBuilder.DefineMethod("get_" + name, exportedPropertyAttributes, CallingConventions.HasThis, typeof(UnmanagedMemory), emptyTypes ); memoryGetter.SetCustomAttribute(NativeExportAttribute.Emit(ExternalKind.Memory, name)); var getterIL = memoryGetter.GetILGenerator(); getterIL.Emit(OpCodes.Ldarg_0); getterIL.Emit(OpCodes.Ldfld, memory); getterIL.Emit(OpCodes.Ret); exportsBuilder.DefineProperty(name, PropertyAttributes.None, typeof(UnmanagedMemory), emptyTypes) .SetGetMethod(memoryGetter); } break; case ExternalKind.Global: if (globals == null) throw new ModuleLoadException($"Exported index {index} is global but no globals are defined.", preIndexOffset); if (index >= globals.Length) throw new ModuleLoadException($"Exported global index of {index} is greater than the number of globals {globals.Length}.", preIndexOffset); { var global = globals[index]; var property = exportsBuilder.DefineProperty(name, PropertyAttributes.None, global.Type.ToSystemType(), emptyTypes); property.SetCustomAttribute(NativeExportAttribute.Emit(ExternalKind.Global, name)); var wrappedGet = exportsBuilder.DefineMethod("get_" + name, exportedPropertyAttributes, CallingConventions.HasThis, global.Type.ToSystemType(), emptyTypes ); var wrappedGetIL = wrappedGet.GetILGenerator(); if (global.RequiresInstance) wrappedGetIL.Emit(OpCodes.Ldarg_0); wrappedGetIL.Emit(OpCodes.Call, global.Getter); wrappedGetIL.Emit(OpCodes.Ret); property.SetGetMethod(wrappedGet); var setter = global.Setter; if (setter != null) { var wrappedSet = exportsBuilder.DefineMethod("set_" + name, exportedPropertyAttributes, CallingConventions.HasThis, null, new[] { global.Type.ToSystemType() } ); var wrappedSetIL = wrappedSet.GetILGenerator(); wrappedSetIL.Emit(OpCodes.Ldarg_1); if (global.RequiresInstance) wrappedSetIL.Emit(OpCodes.Ldarg_0); wrappedSetIL.Emit(OpCodes.Call, setter); wrappedSetIL.Emit(OpCodes.Ret); property.SetSetMethod(wrappedSet); } } break; default: throw new NotSupportedException($"Unrecognized export kind {kind}."); } } exportedFunctions = xFunctions.ToArray(); } break; case Section.Start: { if (internalFunctions == null) throw new ModuleLoadException("Start section created without any functions.", preSectionOffset); var preReadOffset = reader.Offset; var startIndex = reader.ReadVarInt32(); if (startIndex >= internalFunctions.Length) throw new ModuleLoadException($"Start function of index {startIndex} exceeds available functions of {internalFunctions.Length}", preReadOffset); startFunction = internalFunctions[startIndex]; } break; case Section.Element: { if (functionTable == null) throw new ModuleLoadException("Element section found without an associated table section or import.", preSectionOffset); // Holds the function table index of where an exsting function index has been mapped, for re-use. var existingDelegates = new Dictionary<uint, uint>(); var count = reader.ReadVarUInt32(); if (count == 0) break; var localFunctionTable = instanceConstructorIL.DeclareLocal(typeof(FunctionTable)); instanceConstructorIL.EmitLoadArg(0); instanceConstructorIL.Emit(OpCodes.Ldfld, functionTable); instanceConstructorIL.Emit(OpCodes.Stloc, localFunctionTable); var getter = FunctionTable.IndexGetter; var setter = FunctionTable.IndexSetter; for (var i = 0; i < count; i++) { var preIndexOffset = reader.Offset; var index = reader.ReadVarUInt32(); if (index != 0) throw new ModuleLoadException($"Index value of anything other than 0 is not supported, {index} found.", preIndexOffset); uint offset; { var preInitializerOffset = reader.Offset; var initializer = Instruction.ParseInitializerExpression(reader).ToArray(); if (initializer.Length != 2 || initializer[0] is not Instructions.Int32Constant c || !(initializer[1] is Instructions.End)) throw new ModuleLoadException("Initializer expression support for the Element section is limited to a single Int32 constant followed by end.", preInitializerOffset); offset = (uint)c.Value; } var preElementOffset = reader.Offset; var elements = reader.ReadVarUInt32(); if (elements == 0) continue; if (functionSignatures == null || internalFunctions == null) throw new ModuleLoadException("Element section must be empty if there are no functions to reference.", preElementOffset); var isBigEnough = instanceConstructorIL.DefineLabel(); instanceConstructorIL.Emit(OpCodes.Ldloc, localFunctionTable); instanceConstructorIL.Emit(OpCodes.Call, FunctionTable.LengthGetter); instanceConstructorIL.EmitLoadConstant(checked(offset + elements)); instanceConstructorIL.Emit(OpCodes.Bge_Un, isBigEnough); instanceConstructorIL.Emit(OpCodes.Ldloc, localFunctionTable); instanceConstructorIL.EmitLoadConstant(checked(offset + elements)); instanceConstructorIL.Emit(OpCodes.Ldloc, localFunctionTable); instanceConstructorIL.Emit(OpCodes.Call, FunctionTable.LengthGetter); instanceConstructorIL.Emit(OpCodes.Sub); instanceConstructorIL.Emit(OpCodes.Call, FunctionTable.GrowMethod); instanceConstructorIL.Emit(OpCodes.Pop); instanceConstructorIL.MarkLabel(isBigEnough); for (var j = 0u; j < elements; j++) { var functionIndex = reader.ReadVarUInt32(); var signature = functionSignatures[functionIndex]; var parms = signature.ParameterTypes; var returns = signature.ReturnTypes; if (!delegateInvokersByTypeIndex.TryGetValue(signature.TypeIndex, out var invoker)) { var del = configuration.GetDelegateForType(parms.Length, returns.Length); if (del == null) throw new CompilerException($"Failed to get a delegate for type {signature}."); if (del.IsGenericType) del = del.MakeGenericType(parms.Concat(returns).ToArray()); delegateInvokersByTypeIndex.Add(signature.TypeIndex, invoker = del.GetTypeInfo().GetDeclaredMethod(nameof(Action.Invoke))!); } instanceConstructorIL.Emit(OpCodes.Ldloc, localFunctionTable); instanceConstructorIL.EmitLoadConstant(offset + j); if (existingDelegates.TryGetValue(functionIndex, out var existing)) { instanceConstructorIL.Emit(OpCodes.Ldloc, localFunctionTable); instanceConstructorIL.EmitLoadConstant(existing); instanceConstructorIL.Emit(OpCodes.Call, getter); } else { existingDelegates.Add(functionIndex, offset + j); var wrapper = exportsBuilder.DefineMethod( $"📦 {functionIndex}", MethodAttributes.Private | MethodAttributes.HideBySig, returns.Length == 0 ? typeof(void) : returns[0], parms ); var il = wrapper.GetILGenerator(); for (var k = 0; k < parms.Length; k++) il.EmitLoadArg(k + 1); il.EmitLoadArg(0); il.Emit(OpCodes.Call, internalFunctions[functionIndex]); il.Emit(OpCodes.Ret); instanceConstructorIL.EmitLoadArg(0); instanceConstructorIL.Emit(OpCodes.Ldftn, wrapper); instanceConstructorIL.Emit(OpCodes.Newobj, invoker.DeclaringType!.GetTypeInfo().DeclaredConstructors.Single()); } instanceConstructorIL.Emit(OpCodes.Call, setter); } } } break; case Section.Code: { if (functionSignatures == null) throw new InvalidOperationException(); if (internalFunctions == null) throw new InvalidOperationException(); var preBodiesIndex = reader.Offset; var functionBodies = reader.ReadVarUInt32(); if (functionBodies > 0 && (functionSignatures == null || functionSignatures.Length == importedFunctions)) throw new ModuleLoadException("Code section is invalid when Function section is missing.", preBodiesIndex); if (functionBodies != functionSignatures.Length - importedFunctions) throw new ModuleLoadException($"Code section has {functionBodies} functions described but {functionSignatures.Length - importedFunctions} were expected.", preBodiesIndex); for (var functionBodyIndex = 0; functionBodyIndex < functionBodies; functionBodyIndex++) { var signature = functionSignatures[importedFunctions + functionBodyIndex]; var byteLength = reader.ReadVarUInt32(); var startingOffset = reader.Offset; var locals = new Local[reader.ReadVarUInt32()]; for (var localIndex = 0; localIndex < locals.Length; localIndex++) locals[localIndex] = new Local(reader); var il = ((MethodBuilder)internalFunctions[importedFunctions + functionBodyIndex]).GetILGenerator(); context.Reset( il, signature, signature.RawParameterTypes.Concat( locals .SelectMany(local => Enumerable.Range(0, checked((int)local.Count)).Select(_ => local.Type)) ).ToArray() ); foreach (var local in locals.SelectMany(local => Enumerable.Range(0, checked((int)local.Count)).Select(_ => local.Type))) { il.DeclareLocal(local.ToSystemType()); } foreach (var instruction in Instruction.Parse(reader)) { instruction.Compile(context); context.Previous = instruction.OpCode; } if (reader.Offset - startingOffset != byteLength) throw new ModuleLoadException($"Instruction sequence reader ended after readering {reader.Offset - startingOffset} characters, expected {byteLength}.", reader.Offset); } } break; case Section.Data: { if (memory == null) throw new ModuleLoadException("Data section cannot be used unless a memory section is defined.", preSectionOffset); var count = reader.ReadVarUInt32(); context.Reset( instanceConstructorIL, Signature.Empty, Signature.Empty.RawParameterTypes ); var block = new Instructions.Block(BlockType.Int32); var address = instanceConstructorIL.DeclareLocal(typeof(uint)); for (var i = 0; i < count; i++) { var startingOffset = reader.Offset; { var index = reader.ReadVarUInt32(); if (index != 0) throw new ModuleLoadException($"Data index must be 0, found {index}.", startingOffset); } block.Compile(context); //Prevents "end" instruction of the initializer expression from becoming a return. foreach (var instruction in Instruction.ParseInitializerExpression(reader)) { instruction.Compile(context); context.Previous = instruction.OpCode; } context.Stack.Pop(); context.BlockContexts.Remove(context.Depth.Count); instanceConstructorIL.Emit(OpCodes.Stloc, address); var data = reader.ReadBytes(reader.ReadVarUInt32()); if (data.Length == 0) continue; //Ensure sufficient memory is allocated, error if max is exceeded. instanceConstructorIL.Emit(OpCodes.Ldloc, address); instanceConstructorIL.Emit(OpCodes.Ldc_I4, data.Length); instanceConstructorIL.Emit(OpCodes.Add_Ovf_Un); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Call, context[HelperMethod.RangeCheck8, Instructions.MemoryImmediateInstruction.CreateRangeCheck]); instanceConstructorIL.Emit(OpCodes.Pop); if (data.Length > 0x3f0000) //Limitation of DefineInitializedData, can be corrected by splitting the data. throw new NotSupportedException($"Data segment {i} is length {data.Length}, exceeding the current implementation limit of 4128768."); var field = exportsBuilder.DefineInitializedData($"☣ Data {i}", data, FieldAttributes.Assembly | FieldAttributes.InitOnly); instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Ldfld, memory); instanceConstructorIL.Emit(OpCodes.Call, UnmanagedMemory.StartGetter); instanceConstructorIL.Emit(OpCodes.Ldloc, address); instanceConstructorIL.Emit(OpCodes.Conv_I); instanceConstructorIL.Emit(OpCodes.Add_Ovf_Un); instanceConstructorIL.Emit(OpCodes.Ldsflda, field); instanceConstructorIL.Emit(OpCodes.Ldc_I4, data.Length); instanceConstructorIL.Emit(OpCodes.Cpblk); } } break; default: throw new ModuleLoadException($"Unrecognized section type {(Section)id}.", preSectionOffset); } preSectionOffset = reader.Offset; previousSection = (Section)id; } if (exportedFunctions != null && exportedFunctions.Length != 0) { if (functionSignatures == null) throw new InvalidOperationException(); if (internalFunctions == null) throw new InvalidOperationException(); for (var i = 0; i < exportedFunctions.Length; i++) { var exported = exportedFunctions[i]; var signature = functionSignatures[exported.Value]; var method = exportsBuilder.DefineMethod( NameCleaner.CleanName(exported.Key), exportedFunctionAttributes, CallingConventions.HasThis, signature.ReturnTypes.FirstOrDefault(), signature.ParameterTypes ); method.SetCustomAttribute(NativeExportAttribute.Emit(ExternalKind.Function, exported.Key)); var il = method.GetILGenerator(); for (var parm = 0; parm < signature.ParameterTypes.Length; parm++) il.Emit(OpCodes.Ldarg, parm + 1); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, internalFunctions[exported.Value]); il.Emit(OpCodes.Ret); } } if (startFunction != null) { instanceConstructorIL.Emit(OpCodes.Ldarg_0); instanceConstructorIL.Emit(OpCodes.Call, startFunction); } instanceConstructorIL.Emit(OpCodes.Ret); //Finish the constructor. var exportInfo = exportsBuilder.CreateTypeInfo(); TypeInfo instance; { var instanceBuilder = module.DefineType("CompiledInstance", classAttributes, instanceContainer); var instanceConstructor = instanceBuilder.DefineConstructor( constructorAttributes, CallingConventions.Standard, new[] { typeof(IDictionary<string, IDictionary<string, RuntimeImport>>) } ); var il = instanceConstructor.GetILGenerator(); var memoryAllocated = checked(memoryPagesMaximum * Memory.PageSize); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Newobj, exportInfo!.DeclaredConstructors.First()); il.Emit(OpCodes.Call, instanceContainer .GetTypeInfo() .DeclaredConstructors .First(info => info.GetParameters() .FirstOrDefault() ?.ParameterType == exportContainer ) ); il.Emit(OpCodes.Ret); instance = instanceBuilder.CreateTypeInfo()!; } module.CreateGlobalFunctions(); return instance.DeclaredConstructors.First(); } static FieldBuilder CreateFunctionTableField(TypeBuilder exportsBuilder) { return exportsBuilder.DefineField("☣ FunctionTable", typeof(FunctionTable), FieldAttributes.Private | FieldAttributes.InitOnly); } } }
58.858029
216
0.440462
[ "Apache-2.0" ]
LATOKEN/dotnet-webassembly
WebAssembly/Runtime/Compile.cs
75,899
C#
using Microsoft.AspNetCore.Mvc.Razor.Internal; using Abp.AspNetCore.Mvc.Views; using Abp.Runtime.Session; namespace LTMCompanyNameFree.YoyoCmsTemplate.Web.Views { public abstract class YoyoCmsTemplateRazorPage<TModel> : AbpRazorPage<TModel> { [RazorInject] public IAbpSession AbpSession { get; set; } protected YoyoCmsTemplateRazorPage() { LocalizationSourceName = YoyoCmsTemplateConsts.LocalizationSourceName; } } }
26.888889
82
0.716942
[ "MIT" ]
cnmediar/YoyoCmsFree.Template
src/aspnet-core/src/LTMCompanyNameFree.YoyoCmsTemplate.Web.Mvc/Views/YoyoCmsTemplateRazorPage.cs
486
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview { using Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.PowerShell; /// <summary>Scaling plan properties.</summary> [System.ComponentModel.TypeConverter(typeof(ScalingPlanPatchPropertiesTypeConverter))] public partial class ScalingPlanPatchProperties { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingPlanPatchProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchProperties" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ScalingPlanPatchProperties(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingPlanPatchProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchProperties" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ScalingPlanPatchProperties(content); } /// <summary> /// Creates a new instance of <see cref="ScalingPlanPatchProperties" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingPlanPatchProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ScalingPlanPatchProperties(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Description, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).FriendlyName = (string) content.GetValueForProperty("FriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).FriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).TimeZone = (string) content.GetValueForProperty("TimeZone",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).TimeZone, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolType = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Support.HostPoolType?) content.GetValueForProperty("HostPoolType",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolType, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Support.HostPoolType.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).ExclusionTag = (string) content.GetValueForProperty("ExclusionTag",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).ExclusionTag, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Schedule = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingSchedule[]) content.GetValueForProperty("Schedule",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Schedule, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingSchedule>(__y, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingScheduleTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolReference = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingHostPoolReference[]) content.GetValueForProperty("HostPoolReference",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolReference, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingHostPoolReference>(__y, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingHostPoolReferenceTypeConverter.ConvertFrom)); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingPlanPatchProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ScalingPlanPatchProperties(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Description, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).FriendlyName = (string) content.GetValueForProperty("FriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).FriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).TimeZone = (string) content.GetValueForProperty("TimeZone",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).TimeZone, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolType = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Support.HostPoolType?) content.GetValueForProperty("HostPoolType",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolType, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Support.HostPoolType.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).ExclusionTag = (string) content.GetValueForProperty("ExclusionTag",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).ExclusionTag, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Schedule = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingSchedule[]) content.GetValueForProperty("Schedule",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).Schedule, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingSchedule>(__y, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingScheduleTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolReference = (Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingHostPoolReference[]) content.GetValueForProperty("HostPoolReference",((Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingPlanPatchPropertiesInternal)this).HostPoolReference, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IScalingHostPoolReference>(__y, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ScalingHostPoolReferenceTypeConverter.ConvertFrom)); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Scaling plan properties. [System.ComponentModel.TypeConverter(typeof(ScalingPlanPatchPropertiesTypeConverter))] public partial interface IScalingPlanPatchProperties { } }
101.972414
762
0.770526
[ "MIT" ]
AndriiKalinichenko/azure-powershell
src/DesktopVirtualization/generated/api/Models/Api20210201Preview/ScalingPlanPatchProperties.PowerShell.cs
14,642
C#
using System; using System.IO; using System.Linq; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace SaveMart { public class AppInitializer { public static IApp StartApp(Platform platform) { // TODO: If the iOS or Android app being tested is included in the solution // then open the Unit Tests window, right click Test Apps, select Add App Project // and select the app projects that should be tested. // // The iOS project should have the Xamarin.TestCloud.Agent NuGet package // installed. To start the Test Cloud Agent the following code should be // added to the FinishedLaunching method of the AppDelegate: // // #if ENABLE_TEST_CLOUD // Xamarin.Calabash.Start(); // #endif if (platform == Platform.Android) { return ConfigureApp .Android // TODO: Update this path to point to your Android app and uncomment the // code if the app is not included in the solution. .ApkFile ("/Users/junecho/Desktop/apkS/SaveMart.apk") .StartApp(); } return ConfigureApp .iOS // TODO: Update this path to point to your iOS app and uncomment the // code if the app is not included in the solution. //.AppBundle ("../../../iOS/bin/iPhoneSimulator/Debug/XamarinForms.iOS.app") .StartApp(); } } }
30.418605
84
0.688073
[ "Unlicense" ]
jCho23/SaveMart
SaveMart/AppInitializer.cs
1,310
C#
using NeoGeniX.Config; using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace NeoGeniX.Controls { public class DarkLabel : Label { #region Field Region private bool _autoUpdateHeight; private bool _isGrowing; #endregion #region Property Region [Category("Layout")] [Description("Enables automatic height sizing based on the contents of the label.")] [DefaultValue(false)] public bool AutoUpdateHeight { get { return _autoUpdateHeight; } set { _autoUpdateHeight = value; if (_autoUpdateHeight) { AutoSize = false; ResizeLabel(); } } } public new bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; if (AutoSize) AutoUpdateHeight = false; } } #endregion #region Constructor Region public DarkLabel() { ForeColor = Colors.LightText; } #endregion #region Method Region private void ResizeLabel() { if (!_autoUpdateHeight || _isGrowing) return; try { _isGrowing = true; var sz = new Size(Width, int.MaxValue); sz = TextRenderer.MeasureText(Text, Font, sz, TextFormatFlags.WordBreak); Height = sz.Height + Padding.Vertical; } finally { _isGrowing = false; } } #endregion #region Event Handler Region protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); ResizeLabel(); } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); ResizeLabel(); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); ResizeLabel(); } #endregion } }
21.669811
92
0.488899
[ "Apache-2.0" ]
iAwesome404/ProshellCatalyst
Cairo Desktop/DarkUI/Controls/DarkLabel.cs
2,299
C#
using System.Collections.Generic; using System.Threading.Tasks; using Obacher.RandomOrgSharp.Core; using Obacher.RandomOrgSharp.Core.Parameter; using Obacher.RandomOrgSharp.Core.Request; using Obacher.RandomOrgSharp.Core.Response; using Obacher.RandomOrgSharp.Core.Service; using Obacher.RandomOrgSharp.JsonRPC.Request; using Obacher.RandomOrgSharp.JsonRPC.Response; namespace Obacher.RandomOrgSharp.JsonRPC.Method { /// <summary> /// This class is a wrapper class the <see cref="MethodCallBroker"/>. It setups a default set of classes to be called when making a call to random.org /// </summary> /// <remarks> /// The following is the sequence of actions that will occur during the call... /// Build the necessary JSON-RPC request string (the package that is used to retrieve a list of blob values) /// Execute the <see cref="AdvisoryDelayHandler"/> to delay the request the time recommended by random.org (based on the value in the previous response) /// Retrieve the random blob values from random.org /// Determine if an error occurred during the call and throw an exception if one did occur /// Store the advisory delay value to ensure the next request to random.org does not occur before the time requested by random.org. This will help prevent you from /// being banned from making requests to random.org /// Verify the Id returned in the response matches the id passed into the request /// Parse the response into a <see cref="DataResponseInfo{T}"/> so the blob values can be extracted /// </remarks> public class DecimalBasicMethod { protected IRandomService RandomService; protected IRequestBuilder RequestBuilder; protected IBeforeRequestCommandFactory BeforeRequestCommandFactory; protected IResponseHandlerFactory ResponseHandlerFactory; protected JsonResponseParserFactory ResponseParser; /// <summary> /// Constructor /// </summary> /// <param name="advisoryDelayHandler"> /// Class which handles the apprioriate delay before the request is called. /// It is required that this class be passed into the method because the same instance of the <see cref="AdvisoryDelayHandler"/> must be passed in on every request. /// </param> /// <param name="randomService"><see cref="IRandomService"/> to use to get random values. Defaults to <see cref="RandomOrgApiService"/></param> public DecimalBasicMethod(AdvisoryDelayHandler advisoryDelayHandler, IRandomService randomService = null) { RandomService = randomService ?? new RandomOrgApiService(); RequestBuilder = new JsonRequestBuilder(new DecimalJsonRequestBuilder()); BeforeRequestCommandFactory = new BeforeRequestCommandFactory(advisoryDelayHandler); // We need to keep this separate so we can retrieve the list of values that are returned from to the caller ResponseParser = new JsonResponseParserFactory(new GenericResponseParser<decimal>()); ResponseHandlerFactory = new ResponseHandlerFactory( new ErrorHandlerThrowException(new ErrorParser()), advisoryDelayHandler, new VerifyIdResponseHandler(), ResponseParser ); } /// <summary> /// Retrieves a list of random blob values /// </summary> /// <param name="numberOfItemsToReturn">How many random decimal fractions you need. Must be between 1 and 10,000.</param> /// <param name="numberOfDecimalPlaces">The number of decimal places to use. Must be between 1 and 20</param> /// <param name="allowDuplicates">True if duplicate values are allowed in the random values, default to <c>true</c></param> /// <returns>List of random blob values</returns> public virtual IEnumerable<decimal> GenerateDecimalsFractions(int numberOfItemsToReturn, int numberOfDecimalPlaces, bool allowDuplicates = false) { IParameters requestParameters = DecimalParameters.Create(numberOfItemsToReturn, numberOfDecimalPlaces, allowDuplicates); IMethodCallBroker broker = new MethodCallBroker(RequestBuilder, RandomService, BeforeRequestCommandFactory, ResponseHandlerFactory); broker.Generate(requestParameters); return (ResponseParser.ResponseInfo as DataResponseInfo<decimal>)?.Data; } /// <summary> /// Retrieves a list of random blob values in an asynchronous manners /// </summary> /// <param name="numberOfItemsToReturn">How many random decimal fractions you need. Must be between 1 and 10,000.</param> /// <param name="numberOfDecimalPlaces">The number of decimal places to use. Must be between 1 and 20</param> /// <param name="allowDuplicates">True if duplicate values are allowed in the random values, default to <c>true</c></param> /// <returns>List of random blob values</returns> public virtual async Task<IEnumerable<decimal>> GenerateDecimalsFractionsAsync(int numberOfItemsToReturn, int numberOfDecimalPlaces, bool allowDuplicates = false) { IParameters requestParameters = DecimalParameters.Create(numberOfItemsToReturn, numberOfDecimalPlaces, allowDuplicates); MethodCallBroker broker = new MethodCallBroker(RequestBuilder, RandomService, BeforeRequestCommandFactory, ResponseHandlerFactory); await broker.GenerateAsync(requestParameters); return (ResponseParser.ResponseInfo as DataResponseInfo<decimal>)?.Data; } } }
60.946237
172
0.711538
[ "MIT" ]
gsteinbacher/RandomOrgSharp
Obacher.RandomOrgSharp.JsonRPC/Method/DecimalBasicMethod.cs
5,670
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using YX; public class TestRuntimeGizmos : MonoBehaviour { private void OnPostRender() { RuntimeGizmos.mat = new Material(Shader.Find("Unlit/Color")); RuntimeGizmos.color = Color.green; RuntimeGizmos.DrawSphere(new Vector3(0,0,0), 1); RuntimeGizmos.color = Color.red; RuntimeGizmos.DrawSphere(new Vector3(2,2,2), 0.5f); RuntimeGizmos.DrawLine(new Vector3(-2,-2,-2), new Vector3(-4, -2, -2)); } }
29.833333
79
0.674115
[ "Apache-2.0" ]
yangxun983323204/unity-utils
Assets/Test/TestRuntimeGizmos.cs
539
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest. /// </summary> public partial class UnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest : BaseRequest, IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest { /// <summary> /// Constructs a new UnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified UnifiedRoleDefinition to the collection via POST. /// </summary> /// <param name="unifiedRoleDefinition">The UnifiedRoleDefinition to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created UnifiedRoleDefinition.</returns> public System.Threading.Tasks.Task<UnifiedRoleDefinition> AddAsync(UnifiedRoleDefinition unifiedRoleDefinition, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsync<UnifiedRoleDefinition>(unifiedRoleDefinition, cancellationToken); } /// <summary> /// Adds the specified UnifiedRoleDefinition to the collection via POST and returns a <see cref="GraphResponse{UnifiedRoleDefinition}"/> object of the request. /// </summary> /// <param name="unifiedRoleDefinition">The UnifiedRoleDefinition to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{UnifiedRoleDefinition}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<UnifiedRoleDefinition>> AddResponseAsync(UnifiedRoleDefinition unifiedRoleDefinition, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<UnifiedRoleDefinition>(unifiedRoleDefinition, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUnifiedRoleDefinitionInheritsPermissionsFromCollectionPage> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var response = await this.SendAsync<UnifiedRoleDefinitionInheritsPermissionsFromCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response?.Value?.CurrentPage != null) { response.Value.InitializeNextPageRequest(this.Client, response.NextLink); // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; return response.Value; } return null; } /// <summary> /// Gets the collection page and returns a <see cref="GraphResponse{UnifiedRoleDefinitionInheritsPermissionsFromCollectionResponse}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{UnifiedRoleDefinitionInheritsPermissionsFromCollectionResponse}"/> object.</returns> public System.Threading.Tasks.Task<GraphResponse<UnifiedRoleDefinitionInheritsPermissionsFromCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<UnifiedRoleDefinitionInheritsPermissionsFromCollectionResponse>(null, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Expand(Expression<Func<UnifiedRoleDefinition, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Select(Expression<Func<UnifiedRoleDefinition, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
47.100478
189
0.636022
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/UnifiedRoleDefinitionInheritsPermissionsFromCollectionRequest.cs
9,844
C#
using System; using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; namespace HomeControl.WebApi.Models { // Models used as parameters to AccountController actions. public class AddExternalLoginBindingModel { [Required] [Display(Name = "External access token")] public string ExternalAccessToken { get; set; } } public class ChangePasswordBindingModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class RegisterBindingModel { [Required] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class RegisterExternalBindingModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class RemoveLoginBindingModel { [Required] [Display(Name = "Login provider")] public string LoginProvider { get; set; } [Required] [Display(Name = "Provider key")] public string ProviderKey { get; set; } } public class SetPasswordBindingModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
31.835294
110
0.622321
[ "MIT" ]
tocsoft/HomeControl
HomeControl.WebApi/Models/AccountBindingModels.cs
2,708
C#
using BenchmarkDotNet.Attributes; namespace NaturalStringComparerNS { [ArtifactsPath(".\\EtcBenchmarks")] public class EtcBenchmarks : BenchmarksBase { public enum TestCase { InRange, OutFromRange } [Params(TestCase.InRange, TestCase.OutFromRange)] public TestCase TestCases; char ch; [GlobalSetup] public void Setup() { switch (TestCases) { case TestCase.InRange: ch = '5'; break; default: ch = 'a'; break; } } /// <summary> /// In the .net code this method is used to determine if a character is digit /// but the other one is faster. /// </summary> [Benchmark] public bool RangeMinus() { return (uint)(ch - '0') <= '9' - '0'; } [Benchmark] public bool Range2Compare() { return '0' <= ch && ch <= '9'; } } }
23.9375
86
0.43342
[ "MIT" ]
faddiv/Foxy.Core
StringNaturalComparer.BenchmarkDotNet/EtcBenchmarks.cs
1,102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Nricher.DependencyInjectionExtensions.HostedService; using NUnit.Framework; namespace DependencyInjectionExtensions.Tests.HostedService { public class AddHostedServiceServiceCollectionExtensionTests : ExtensionMethodsTestsBase<HostedServiceExtension> { [TestCaseSource(nameof(TestCaseData))] public void AddHostedServiceTests(Expression<Action<IServiceCollection>> addServiceAction) { GivenServiceCollectionWithExtension(); WhenAddService(addServiceAction); ThenHostedServiceAdded(); } [TestCaseSource(nameof(TestCaseData))] public void AddHostedServiceTestsOnNormalServiceCollectionTests(Expression<Action<IServiceCollection>> addServiceAction) { GivenServiceCollectionWithoutExtension(); WhenAddService(addServiceAction); ThenHostedServiceAdded(); } private static readonly IEnumerable<Expression<Action<IServiceCollection>>> TestCaseData = new Expression<Action<IServiceCollection>>[] { x => x.AddSingletonHostedService<IObjectUnderTest, HostedObjectUnderTest>(), x => x.AddSingletonHostedService<IObjectUnderTest, HostedObjectUnderTest>(y => new HostedObjectUnderTest()), x => x.AddSingletonHostedService<IObjectUnderTest, HostedObjectUnderTest>(new HostedObjectUnderTest()) }; private void ThenHostedServiceAdded() { // ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local Assert.That(ServiceCollection.Count(x => x.ServiceType == typeof(IObjectUnderTest)), Is.EqualTo(1)); Assert.That(ServiceCollection.Count(x => x.ServiceType == typeof(IHostedService)), Is.EqualTo(1)); // ReSharper restore ParameterOnlyUsedForPreconditionCheck.Local } } }
44.152174
143
0.728213
[ "Apache-2.0" ]
YanicHoegger/DependencyInjectionExtension
source/DependencyInjectionExtensions.Tests/HostedService/AddHostedServiceServiceCollectionExtensionTests.cs
2,033
C#
using System; using System.Collections.Generic; class Computer { private string name; private List<string> component; private decimal price; private List<Component> components = new List<Component>(); public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value", "Argument is null or empty!"); } this.name = value; } } public decimal Price { get { return this.price; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", "This argument is OutOfRange. Value > 0"); } this.price = value; } } public List<string> Components { get { return this.component; } set { if (value.Count == 0) { throw new ArgumentNullException("value", "This list is empty"); } this.component = value; } } public Computer(string name, List<string> component) { this.Name = name; this.Components = component; this.InitializingComponent(this.component); this.Price = TotalPrice(); } private void InitializingComponent(List<string> list) { for (int i = 0; i < list.Count; i++) { string[] line = list[i].Split(','); Component components = new Component(line[0], line[1], Convert.ToDecimal(line[2])); this.components.Add(components); } } public decimal TotalPrice() { decimal sum = 0m; for (int i = 0; i < this.components.Count; i++) { sum += this.components[i].Price; } return sum; } public override string ToString() { Console.WriteLine("Computer name = {0}", this.name); for (int i = 0; i < this.component.Count; i++) { string[] line = this.component[i].Split(','); Console.WriteLine("Name of component: {0} | Price of component: {1}", line[0].Trim(), line[2].Trim()); } Console.WriteLine("Sum of prices: {0}", this.price); return string.Empty; } }
26.397727
114
0.517004
[ "CC0-1.0" ]
ivayloivanof/OOP-CSharp
01.DefiningClasses/DefiningClassHomework/DefiningClass/PC.Catalog/Computer/Computer.cs
2,325
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JumpJump { class Program { static void Main(string[] args) { char[] psss = Console.ReadLine().ToCharArray(); int i = 0; while (true) { int x = (int)Char.GetNumericValue(psss[i]); if (psss[i] == '^') { Console.WriteLine("Jump, Jump, DJ Tomekk kommt at {0}!", i); break; } else if (psss[i] == '0') { Console.WriteLine("Too drunk to go on after {0}!", i); break; } else if ( x%2==0) { i += x; }else if (x % 2 != 0) { i -= x; } if(i>=psss.Length || i < 0) Console.WriteLine("Fell off the dancefloor at {0}!", i); { break; } } } } }
22.538462
80
0.354949
[ "MIT" ]
ilpototo/Telerick-Alpha
Conditions/JumpJump/Program.cs
1,174
C#
using UnityEngine; public class CameraBounds : MonoBehaviour { public Rect bounds; void OnDrawGizmos() { Gizmos.color = Color.white; Gizmos.DrawWireCube(bounds.center.AsVector3(0), bounds.size.AsVector3(0)); } }
19.076923
82
0.665323
[ "MIT" ]
jaburns/ggj2018
Assets/Scripts/CameraBounds.cs
250
C#
using KilyCore.EntityFrameWork.ModelEnum; using System; using System.Collections.Generic; using System.Text; /// <summary> /// 作者:刘泽华 /// 时间:2018年5月29日11点13分 /// </summary> namespace KilyCore.DataEntity.RequestMapper.Repast { public class RequestRepastIdent { /// <summary> /// 认证编号 /// </summary> public string IdentNo { get; set; } public Guid Id { get; set; } public Guid IdentId { get; set; } public Guid InfoId { get; set; } public DateTime IdentStartTime { get; set; } public DateTime IdentEndTime { get; set; } /// <summary> /// 商家名称 /// </summary> public string MerchantName { get; set; } /// <summary> /// 认证星级 /// </summary> public IdentEnum IdentStar { get; set; } /// <summary> /// 审核状态 /// </summary> public AuditEnum AuditType { get; set; } /// <summary> /// 商家类型 /// </summary> public MerchantEnum? DiningType { get; set; } /// <summary> /// 认证年限 /// </summary> public int IdentYear { get; set; } /// <summary> /// 信用代码 /// </summary> public string CommunityCode { get; set; } /// <summary> /// 法人代表 /// </summary> public string Representative { get; set; } /// <summary> /// 法人身份证 /// </summary> public string RepresentativeCard { get; set; } /// <summary> /// 报送人 /// </summary> public string SendPerson { get; set; } /// <summary> /// 报送人身份证 /// </summary> public string SendCard { get; set; } /// <summary> /// 联系方式 /// </summary> public string LinkPhone { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } /// <summary> /// 区域树查询 /// </summary> public string AreaTree { get; set; } /// <summary> /// 法人身份证 /// </summary> public string ImgCard { get; set; } /// <summary> /// 申请表 /// </summary> public string ImgApply { get; set; } /// <summary> /// 调查表 /// </summary> public string ImgResearch { get; set; } /// <summary> /// 认证协议 /// </summary> public string ImgAgreement { get; set; } /// <summary> /// 原料购买证明 /// </summary> public string ImgMaterialOrder { get; set; } /// <summary> /// 消毒证明 /// </summary> public string ImgDisinfection { get; set; } /// <summary> /// 原料储藏证明 /// </summary> public string ImgMaterialSave { get; set; } /// <summary> /// 废弃物处理证明 /// </summary> public string ImgAbandoned { get; set; } /// <summary> /// 留样证明 /// </summary> public string ImgSample { get; set; } /// <summary> /// 从业证明 /// </summary> public string ImgWorkingPerson { get; set; } /// <summary> /// 其他证明 /// </summary> public string ImgOther { get; set; } } }
27.2
54
0.465686
[ "Apache-2.0" ]
EmilyEdna/KilyCore
KilyCore.DataEntity/RequestMapper/Repast/RequestRepastIdent.cs
3,508
C#