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 Eric.Morrison.Harmony; using Eric.Morrison.Harmony.Scales; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; using System.Linq; using System.Windows.Forms; namespace NeckDiagrams { public partial class NeckControl : UserControl { List<NoteRange> NoteRanges { get; set; } = new List<NoteRange>(); Scale MusicalScale { get; set; } public PrintDocument PrintDocument { get { return this.printDocument; } } public NeckControl() { InitializeComponent(); this.Load += this.NeckControl_Load; this.Layout += this.NeckControl_Layout; } HarmonyModel Model { get { return HarmonyHelper.IoC.Container.Resolve<IHarmonyModel>() as HarmonyModel; } } private void NeckControl_Load(object sender, EventArgs e) { if (!DesignMode) { this.Model.ModelChanged += this.ModelChanged_Handler; this.Controls.Clear(); var ctls = new List<StringControl>(); var string1 = new NoteRange( new Note(NoteName.E, OctaveEnum.Octave3), new Note(NoteName.E, OctaveEnum.Octave4)); var string2 = new NoteRange( new Note(NoteName.B, OctaveEnum.Octave3), new Note(NoteName.B, OctaveEnum.Octave4)); var string3 = new NoteRange( new Note(NoteName.G, OctaveEnum.Octave2), new Note(NoteName.G, OctaveEnum.Octave3)); var string4 = new NoteRange( new Note(NoteName.D, OctaveEnum.Octave2), new Note(NoteName.D, OctaveEnum.Octave3)); var string5 = new NoteRange( new Note(NoteName.A, OctaveEnum.Octave1), new Note(NoteName.A, OctaveEnum.Octave2)); var string6 = new NoteRange( new Note(NoteName.E, OctaveEnum.Octave1), new Note(NoteName.E, OctaveEnum.Octave2)); this.NoteRanges = new List<NoteRange>() { string1, string2, string3, string4, string5, string6 }; for (int i = 0; i < this.NoteRanges.Count; ++i) { var noteRange = this.NoteRanges[i]; var ctl = new StringControl(i, noteRange, new List<NoteName>()); ctl.Dock = DockStyle.Top; ctls.Insert(0, ctl); } this.Controls.AddRange(ctls.ToArray()); this.PerformLayout(); } } private void NeckControl_MouseMove(object sender, MouseEventArgs e) { #if false var graphics = Graphics.FromHwnd(this.Handle); var rc = new Rectangle(e.X - 50, e.Y - 50, e.X + 50, e.Y + 50); using (var font = new Font(FontFamily.GenericMonospace, 20)) { graphics.FillRectangle(Brushes.White, new Rectangle(100, 100, 200, 50)); graphics.DrawString($"X={e.X}, Y={e.Y}", font, Brushes.Black, new Point(100, 100)); } #endif } private void NeckControl_Layout(object sender, LayoutEventArgs e) { var cy = this.Height / 6; foreach (var ctl in this.Controls.Cast<Control>()) { ctl.Height = cy; ctl.Width = this.Width; } } public void ModelChanged_Handler(object sender, HarmonyModel model) { new object(); } private void printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { new object(); } private void printDocument_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { new object(); } private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { this.OnPaint(new PaintEventArgs(e.Graphics, e.MarginBounds)); new object(); } private void printDocument_QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e) { new object(); } }//class }//ns
26.801527
115
0.691541
[ "MIT" ]
emorrison1962/HarmonyHelper
HarmonyHelper/NeckDiagrams/Controls/NeckControl.cs
3,513
C#
namespace MCForge.GUI { partial class Bugs { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Bugs)); this.ribbon1 = new System.Windows.Forms.Ribbon(); this.ribbonTab1 = new System.Windows.Forms.RibbonTab(); this.problem = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.email = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.name = new System.Windows.Forms.TextBox(); this.ribbonPanel1 = new System.Windows.Forms.RibbonPanel(); this.ribbonButton1 = new System.Windows.Forms.RibbonButton(); this.SuspendLayout(); // // ribbon1 // this.ribbon1.Font = new System.Drawing.Font("Segoe UI", 9F); this.ribbon1.Location = new System.Drawing.Point(0, 0); this.ribbon1.Minimized = false; this.ribbon1.Name = "ribbon1"; // // // this.ribbon1.OrbDropDown.BorderRoundness = 8; this.ribbon1.OrbDropDown.Location = new System.Drawing.Point(0, 0); this.ribbon1.OrbDropDown.Name = ""; this.ribbon1.OrbDropDown.Size = new System.Drawing.Size(527, 447); this.ribbon1.OrbDropDown.TabIndex = 0; this.ribbon1.OrbImage = null; this.ribbon1.OrbVisible = false; // // // this.ribbon1.QuickAcessToolbar.AltKey = null; this.ribbon1.QuickAcessToolbar.Image = null; this.ribbon1.QuickAcessToolbar.Tag = null; this.ribbon1.QuickAcessToolbar.Text = null; this.ribbon1.QuickAcessToolbar.ToolTip = null; this.ribbon1.QuickAcessToolbar.ToolTipImage = null; this.ribbon1.QuickAcessToolbar.ToolTipTitle = null; this.ribbon1.Size = new System.Drawing.Size(407, 138); this.ribbon1.TabIndex = 0; this.ribbon1.Tabs.Add(this.ribbonTab1); this.ribbon1.TabSpacing = 6; this.ribbon1.Text = "ribbon1"; // // ribbonTab1 // this.ribbonTab1.Panels.Add(this.ribbonPanel1); this.ribbonTab1.Tag = null; this.ribbonTab1.Text = "Bug Reports"; // // problem // this.problem.Location = new System.Drawing.Point(0, 166); this.problem.Multiline = true; this.problem.Name = "problem"; this.problem.Size = new System.Drawing.Size(407, 154); this.problem.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(134, 150); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(112, 13); this.label1.TabIndex = 2; this.label1.Text = "Describe your problem"; // // email // this.email.Location = new System.Drawing.Point(42, 330); this.email.Name = "email"; this.email.Size = new System.Drawing.Size(177, 20); this.email.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 333); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(32, 13); this.label2.TabIndex = 4; this.label2.Text = "Email"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(226, 330); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 13); this.label3.TabIndex = 5; this.label3.Text = "Name"; // // name // this.name.Location = new System.Drawing.Point(267, 330); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(128, 20); this.name.TabIndex = 6; // // ribbonPanel1 // this.ribbonPanel1.Items.Add(this.ribbonButton1); this.ribbonPanel1.Tag = null; this.ribbonPanel1.Text = "ribbonPanel1"; // // ribbonButton1 // this.ribbonButton1.AltKey = null; this.ribbonButton1.DropDownArrowDirection = System.Windows.Forms.RibbonArrowDirection.Down; this.ribbonButton1.DropDownArrowSize = new System.Drawing.Size(5, 3); this.ribbonButton1.Image = ((System.Drawing.Image)(resources.GetObject("ribbonButton1.Image"))); this.ribbonButton1.SmallImage = ((System.Drawing.Image)(resources.GetObject("ribbonButton1.SmallImage"))); this.ribbonButton1.Style = System.Windows.Forms.RibbonButtonStyle.Normal; this.ribbonButton1.Tag = null; this.ribbonButton1.Text = "Submit"; this.ribbonButton1.ToolTip = null; this.ribbonButton1.ToolTipImage = null; this.ribbonButton1.ToolTipTitle = null; // // Bugs // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.GradientActiveCaption; this.ClientSize = new System.Drawing.Size(407, 352); this.Controls.Add(this.name); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.email); this.Controls.Add(this.label1); this.Controls.Add(this.problem); this.Controls.Add(this.ribbon1); this.Name = "Bugs"; this.ShowInTaskbar = false; this.Text = "Bugs"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Ribbon ribbon1; private System.Windows.Forms.RibbonTab ribbonTab1; private System.Windows.Forms.RibbonPanel ribbonPanel1; private System.Windows.Forms.RibbonButton ribbonButton1; private System.Windows.Forms.TextBox problem; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox email; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox name; } }
41.677419
136
0.56437
[ "Unlicense" ]
MCForge/MCForge-Vanilla-Redux
GUI/Bugs.Designer.cs
7,752
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace Borg.Cms.Basic.PlugIns.Documents.Data.Migrations { public partial class two : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "DoecumentId", schema: "documents", table: "DocumentOwnerStates", newName: "DocumentId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "DocumentId", schema: "documents", table: "DocumentOwnerStates", newName: "DoecumentId"); } } }
28.678571
71
0.590286
[ "MIT" ]
mitsbits/NoBorg
src/projects/cms/Borg.Cms.Basic.PlugIns.Documents/Data/Migrations/20180203205715_two.cs
805
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 Newtonsoft.Json; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Ess.Transform; using Aliyun.Acs.Ess.Transform.V20140828; namespace Aliyun.Acs.Ess.Model.V20140828 { public class DescribeLimitationRequest : RpcAcsRequest<DescribeLimitationResponse> { public DescribeLimitationRequest() : base("Ess", "2014-08-28", "DescribeLimitation", "ess", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string resourceOwnerAccount; private long? ownerId; public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public override DescribeLimitationResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DescribeLimitationResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
30.925
134
0.69523
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ess/Ess/Model/V20140828/DescribeLimitationRequest.cs
2,474
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Rendering { [ExecuteInEditMode] public class DepthBufferRenderer : MonoBehaviour { [SerializeField] [Tooltip("If not null, depth buffer rendering output will blit to this RenderTexture. If null, normal operation will blit the depth buffer as color to the screen.")] private RenderTexture outputTexture = null; /// <summary> /// If not null, depth buffer rendering output will blit to this RenderTexture. /// If null, normal operation will blit the depth buffer as color to the screen. /// </summary> public RenderTexture OutputTexture { get => outputTexture; set => outputTexture = value; } private const string DepthShaderName = "Mixed Reality Toolkit/Depth Buffer Viewer"; #if UNITY_EDITOR private RenderTexture originalRT; private Material postProcessMaterial; private RenderTexture depthTexture; private int textureWidth, textureHeight; private Camera cam; private void Awake() { originalRT = CameraCache.Main.targetTexture; postProcessMaterial = new Material(Shader.Find(DepthShaderName)); cam = GetComponent<Camera>(); } private void OnEnable() { SetUp(); } private void SetUp() { textureWidth = Screen.width; textureHeight = Screen.height; depthTexture = new RenderTexture(textureWidth, textureHeight, 24, RenderTextureFormat.Depth); RenderTexture renderTexture = new RenderTexture(textureWidth, textureHeight, 0); postProcessMaterial.SetTexture("_DepthTex", depthTexture); cam.depthTextureMode = DepthTextureMode.Depth; cam.SetTargetBuffers(renderTexture.colorBuffer, depthTexture.depthBuffer); } private void Update() { if (textureWidth != Screen.width || textureHeight != Screen.height) { SetUp(); } } private void OnRenderImage(RenderTexture source, RenderTexture destination) { var target = OutputTexture != null ? outputTexture : destination; Graphics.Blit(source, target, postProcessMaterial); } private void OnDisable() { cam.targetTexture = originalRT; } #endif } }
33.182927
174
0.609335
[ "MIT" ]
ForrestTrepte/azure-remote-rendering
Unity/AzureRemoteRenderingShowcase/arr-showcase-app/Assets/MixedRealityToolkit/Utilities/Rendering/DepthBufferRenderer.cs
2,723
C#
using System.Xml.Serialization; using Microsoft.Xna.Framework; namespace Nez.Svg { public class SvgPolygon : SvgElement { [XmlAttribute("cx")] public float CenterX; [XmlAttribute("cy")] public float CenterY; [XmlAttribute("sides")] public int Sides; [XmlAttribute("points")] public string PointsAttribute { get => null; set => ParsePoints(value); } public System.Numerics.Vector2[] Points; void ParsePoints(string str) { var format = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; var pairs = str.Split(new char[] {' '}, System.StringSplitOptions.RemoveEmptyEntries); Points = new System.Numerics.Vector2[pairs.Length]; for (var i = 0; i < pairs.Length; i++) { var parts = pairs[i].Split(new char[] {','}, System.StringSplitOptions.RemoveEmptyEntries); Points[i] = new System.Numerics.Vector2(float.Parse(parts[0], format), float.Parse(parts[1], format)); } } public System.Numerics.Vector2[] GetTransformedPoints() { var pts = new System.Numerics.Vector2[Points.Length]; var mat = GetCombinedMatrix(); Vector2Ext.Transform(Points, ref mat, pts); return pts; } /// <summary> /// gets the points relative to the center. SVG by default uses absolute positions for points. /// </summary> /// <returns>The relative points.</returns> public System.Numerics.Vector2[] GetRelativePoints() { var pts = new System.Numerics.Vector2[Points.Length]; var center = new System.Numerics.Vector2(CenterX, CenterY); for (var i = 0; i < Points.Length; i++) pts[i] = Points[i] - center; return pts; } } }
25.359375
106
0.686383
[ "Apache-2.0", "MIT" ]
Paramecium13/Nez
Nez.Portable/Graphics/SVG/Shapes/SvgPolygon.cs
1,625
C#
using System; namespace Api.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.487805
131
0.503683
[ "MIT" ]
advancedrei/auth0.net
examples/webapi/Api/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,086
C#
using System; namespace FluentReflection.Specs { /// <summary> /// A specification for adding parameters to the current specification. /// Addition of paramters allows the invokation of constructors or /// methods that have parameters specified. /// </summary> /// <typeparam name="T">The type to return after adding parameters.</typeparam> public interface IParamSpec<T> { /// <summary> /// Add an arbitary number of parameters. The parameter types /// are taken from the specific types in the array. If the /// parameter types required are not specifically those in the /// array, use one of the generic WithParams methods /// (eg. <see cref="WithParams&lt;TParam&gt;(TParam)"/>) or /// <see cref="WithParams(Type[], object[])"/>. /// </summary> /// <param name="types">The types of the parameters in the method or constructor.</param> /// <param name="parameters">The instances to pass to the method or constructor.</param> /// <returns>Another spec specified by T.</returns> T WithParams(Type[] types, object[] parameters); T WithParams(params object[] parameters); T WithParam<TParam>(TParam parameter); T WithParams<TOne, TTwo>(TOne paramOne, TTwo paramTwo); T WithParams<TOne, TTwo, TThree>(TOne paramOne, TTwo paramTwo, TThree paramThree); } }
47.4
97
0.648383
[ "MIT" ]
apjanes/FluentReflection
src/Specs/IParamSpec.cs
1,424
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 mediaconvert-2017-08-29.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.MediaConvert.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConvert.Model.Internal.MarshallTransformations { /// <summary> /// HlsGroupSettings Marshaller /// </summary> public class HlsGroupSettingsMarshaller : IRequestMarshaller<HlsGroupSettings, 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(HlsGroupSettings requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAdMarkers()) { context.Writer.WritePropertyName("adMarkers"); context.Writer.WriteArrayStart(); foreach(var requestObjectAdMarkersListValue in requestObject.AdMarkers) { context.Writer.Write(requestObjectAdMarkersListValue); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetBaseUrl()) { context.Writer.WritePropertyName("baseUrl"); context.Writer.Write(requestObject.BaseUrl); } if(requestObject.IsSetCaptionLanguageMappings()) { context.Writer.WritePropertyName("captionLanguageMappings"); context.Writer.WriteArrayStart(); foreach(var requestObjectCaptionLanguageMappingsListValue in requestObject.CaptionLanguageMappings) { context.Writer.WriteObjectStart(); var marshaller = HlsCaptionLanguageMappingMarshaller.Instance; marshaller.Marshall(requestObjectCaptionLanguageMappingsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetCaptionLanguageSetting()) { context.Writer.WritePropertyName("captionLanguageSetting"); context.Writer.Write(requestObject.CaptionLanguageSetting); } if(requestObject.IsSetClientCache()) { context.Writer.WritePropertyName("clientCache"); context.Writer.Write(requestObject.ClientCache); } if(requestObject.IsSetCodecSpecification()) { context.Writer.WritePropertyName("codecSpecification"); context.Writer.Write(requestObject.CodecSpecification); } if(requestObject.IsSetDestination()) { context.Writer.WritePropertyName("destination"); context.Writer.Write(requestObject.Destination); } if(requestObject.IsSetDirectoryStructure()) { context.Writer.WritePropertyName("directoryStructure"); context.Writer.Write(requestObject.DirectoryStructure); } if(requestObject.IsSetEncryption()) { context.Writer.WritePropertyName("encryption"); context.Writer.WriteObjectStart(); var marshaller = HlsEncryptionSettingsMarshaller.Instance; marshaller.Marshall(requestObject.Encryption, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetManifestCompression()) { context.Writer.WritePropertyName("manifestCompression"); context.Writer.Write(requestObject.ManifestCompression); } if(requestObject.IsSetManifestDurationFormat()) { context.Writer.WritePropertyName("manifestDurationFormat"); context.Writer.Write(requestObject.ManifestDurationFormat); } if(requestObject.IsSetMinSegmentLength()) { context.Writer.WritePropertyName("minSegmentLength"); context.Writer.Write(requestObject.MinSegmentLength); } if(requestObject.IsSetOutputSelection()) { context.Writer.WritePropertyName("outputSelection"); context.Writer.Write(requestObject.OutputSelection); } if(requestObject.IsSetProgramDateTime()) { context.Writer.WritePropertyName("programDateTime"); context.Writer.Write(requestObject.ProgramDateTime); } if(requestObject.IsSetProgramDateTimePeriod()) { context.Writer.WritePropertyName("programDateTimePeriod"); context.Writer.Write(requestObject.ProgramDateTimePeriod); } if(requestObject.IsSetSegmentControl()) { context.Writer.WritePropertyName("segmentControl"); context.Writer.Write(requestObject.SegmentControl); } if(requestObject.IsSetSegmentLength()) { context.Writer.WritePropertyName("segmentLength"); context.Writer.Write(requestObject.SegmentLength); } if(requestObject.IsSetSegmentsPerSubdirectory()) { context.Writer.WritePropertyName("segmentsPerSubdirectory"); context.Writer.Write(requestObject.SegmentsPerSubdirectory); } if(requestObject.IsSetStreamInfResolution()) { context.Writer.WritePropertyName("streamInfResolution"); context.Writer.Write(requestObject.StreamInfResolution); } if(requestObject.IsSetTimedMetadataId3Frame()) { context.Writer.WritePropertyName("timedMetadataId3Frame"); context.Writer.Write(requestObject.TimedMetadataId3Frame); } if(requestObject.IsSetTimedMetadataId3Period()) { context.Writer.WritePropertyName("timedMetadataId3Period"); context.Writer.Write(requestObject.TimedMetadataId3Period); } if(requestObject.IsSetTimestampDeltaMilliseconds()) { context.Writer.WritePropertyName("timestampDeltaMilliseconds"); context.Writer.Write(requestObject.TimestampDeltaMilliseconds); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static HlsGroupSettingsMarshaller Instance = new HlsGroupSettingsMarshaller(); } }
37.144231
115
0.613513
[ "Apache-2.0" ]
HaiNguyenMediaStep/aws-sdk-net
sdk/src/Services/MediaConvert/Generated/Model/Internal/MarshallTransformations/HlsGroupSettingsMarshaller.cs
7,726
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Drawing { public sealed class SolidBrush : Brush { // GDI+ doesn't understand system colors, so we need to cache the value here. private Color _color = Color.Empty; private bool _immutable; public SolidBrush(Color color) { _color = color; IntPtr nativeBrush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateSolidFill(_color.ToArgb(), out nativeBrush); SafeNativeMethods.Gdip.CheckStatus(status); SetNativeBrushInternal(nativeBrush); } internal SolidBrush(Color color, bool immutable) : this(color) { _immutable = immutable; } internal SolidBrush(IntPtr nativeBrush) { Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null."); SetNativeBrushInternal(nativeBrush); } public override object Clone() { IntPtr clonedBrush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonedBrush); SafeNativeMethods.Gdip.CheckStatus(status); // Clones of immutable brushes are not immutable. return new SolidBrush(clonedBrush); } protected override void Dispose(bool disposing) { if (!disposing) { _immutable = false; } else if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, "Brush")); } base.Dispose(disposing); } public Color Color { get { if (_color == Color.Empty) { int colorARGB; int status = SafeNativeMethods.Gdip.GdipGetSolidFillColor(new HandleRef(this, NativeBrush), out colorARGB); SafeNativeMethods.Gdip.CheckStatus(status); _color = Color.FromArgb(colorARGB); } // GDI+ doesn't understand system colors, so we can't use GdipGetSolidFillColor in the general case. return _color; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, "Brush")); } if (_color != value) { Color oldColor = _color; InternalSetColor(value); } } } // Sets the color even if the brush is considered immutable. private void InternalSetColor(Color value) { int status = SafeNativeMethods.Gdip.GdipSetSolidFillColor(new HandleRef(this, NativeBrush), value.ToArgb()); SafeNativeMethods.Gdip.CheckStatus(status); _color = value; } } }
31.247619
127
0.562938
[ "MIT" ]
AlexGhiondea/corefx
src/System.Drawing.Common/src/System/Drawing/SolidBrush.cs
3,281
C#
using System; using Elasticsearch.Net; using FluentAssertions; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; namespace Tests.XPack.MachineLearning.CloseJob { public class CloseJobApiTests : MachineLearningIntegrationTestBase<CloseJobResponse, ICloseJobRequest, CloseJobDescriptor, CloseJobRequest> { public CloseJobApiTests(MachineLearningCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override object ExpectJson => null; protected override int ExpectStatusCode => 200; protected override Func<CloseJobDescriptor, ICloseJobRequest> Fluent => f => f; protected override HttpMethod HttpMethod => HttpMethod.POST; protected override CloseJobRequest Initializer => new CloseJobRequest(CallIsolatedValue); protected override string UrlPath => $"/_ml/anomaly_detectors/{CallIsolatedValue}/_close"; protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values) { foreach (var callUniqueValue in values) { PutJob(client, callUniqueValue.Value); OpenJob(client, callUniqueValue.Value); } } protected override LazyResponses ClientUsage() => Calls( (client, f) => client.CloseJob(CallIsolatedValue, f), (client, f) => client.CloseJobAsync(CallIsolatedValue, f), (client, r) => client.CloseJob(r), (client, r) => client.CloseJobAsync(r) ); protected override CloseJobDescriptor NewDescriptor() => new CloseJobDescriptor(CallIsolatedValue); protected override void ExpectResponse(CloseJobResponse response) => response.Closed.Should().BeTrue(); } }
38.272727
140
0.781473
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Tests/Tests/XPack/MachineLearning/CloseJob/CloseJobApiTests.cs
1,686
C#
using MigrationTools._EngineV1.Configuration; namespace MigrationTools.Engine.Containers.Tests { public class SimpleFieldMapConfigMock : IFieldMapConfig { public string WorkItemTypeName { get; set; } public string FieldMap { get { return "SimpleFieldMapMock"; } } } }
21.529412
59
0.590164
[ "MIT" ]
ACoderLife/azure-devops-migration-tools
src/MigrationTools.Tests/Core/Engine/Containers/SimpleFieldMapConfigMock.cs
368
C#
#pragma warning disable 1591 // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ [assembly: Android.Runtime.ResourceDesignerAttribute("KimonoCore.Android.Resource", IsApplication=false)] namespace KimonoCore.Android { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class String { // aapt resource value: 0x7f020000 public static int library_name = 2130837504; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
22.051724
105
0.593432
[ "MIT" ]
MarcosAC/KimonoDesigner
KimonoCore.Android/Resources/Resource.designer.cs
1,279
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using RestSharp; namespace SematimeGlue { public class SematimeGlue { private string _baseUrl = "https://apis.sematime.com/v1/"; private string _token; private string _accountId; public SematimeGlue() { } public SematimeGlue(string token, string accountId) { _token = token; _accountId = accountId; } public bool SendMessage(string message, string recipients, out string responseStatus, out string responseMessage) { try { var obj = new JObject { ["text"] = message, ["recipients"] = recipients }; var respose = PostRequest(obj); var resp = respose.Split('~'); responseStatus = respose[0].ToString(); responseMessage = respose[1].ToString(); return true; } catch (Exception e) { responseStatus = "-1"; responseMessage = e.Message; return false; } } private string PostRequest(JObject data) { var client = new RestClient($"{_baseUrl}{_accountId}"); var request = new RestRequest("/messages/single", Method.POST); request.AddParameter("text/xml", data.ToString(), ParameterType.RequestBody); request.AddHeader("AuthToken", _token); request.AddHeader("ContentType","application/json"); IRestResponse response = client.Execute(request); var content = $"{response.StatusCode}~{response.Content}"; return content; } } }
29.507692
121
0.538582
[ "MIT" ]
mwangepatrick/SematimeGlue
SematimeGlue/SematimeGlue/SematimeGlue.cs
1,920
C#
using NUnit.Framework; using Workbench.Core.Parsers; namespace Workbench.Core.Tests.Unit.Parsers { [TestFixture] public class ConstraintExpressionParserWithEmptyStatementShould { [Test] public void ParseWithEmptyStatementReturnsStatusSuccess() { var sut = CreateSut(); var expressionParseResult = sut.Parse(string.Empty); Assert.That(expressionParseResult.Status, Is.EqualTo(ParseStatus.Success)); } [Test] public void ParseWithEmptyStatementReturnsEmptyNode() { var sut = CreateSut(); var expressionParseResult = sut.Parse(string.Empty); var actualRootNode = expressionParseResult.Root; Assert.That(actualRootNode.IsEmpty, Is.True); } private static ConstraintExpressionParser CreateSut() { return new ConstraintExpressionParser(); } } }
29.46875
87
0.64263
[ "BSD-3-Clause" ]
constraint-capers/workbench
tests/Workbench.Core.Tests.Unit/Parsers/ConstraintExpressionParserWithEmptyStatementShould.cs
945
C#
using System; using System.Data.Common; using CavemanTools; namespace SqlFu { public class SProcInput { public string ProcName { get; set; } /// <summary> /// Arguments as an anonymous object, output parameters names must be prefixed with _ /// </summary> /// <example> /// new{Id=1,_OutValue=""} /// </example> public object Arguments { get; set; } public Action<DbCommand> Apply { get; set; } = Empty.ActionOf<DbCommand>(); } }
25.8
94
0.585271
[ "Apache-2.0" ]
sapiens/SqlFu
src/SqlFu/StoredProcedures/SProcInput.cs
516
C#
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using RVA = System.UInt32; namespace Mono.Cecil.PE { struct DataDirectory { public readonly RVA VirtualAddress; public readonly uint Size; public bool IsZero { get { return VirtualAddress == 0 && Size == 0; } } public DataDirectory (RVA rva, uint size) { this.VirtualAddress = rva; this.Size = size; } } }
16
51
0.649621
[ "MIT" ]
13294029724/ET
Unity/Assets/ThirdParty/ILRuntime/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs
528
C#
using DSharpPlus.Entities; using DSharpPlus.SlashCommands; using ducker.Logs; using ducker.SlashCommands.Attributes; namespace ducker.SlashCommands.AdministrationModule; public partial class AdministrationSlashCommands { [SlashCommand("tempban", "Temporarily ban mentioned member")] [RequireAdmin] public async Task TempbanCommand(InteractionContext msg, [Option("member", "Member to ban")] DiscordUser user, [Option("duration", "Ban duration in hours")] long duration, [Option("reason", "Reason for ban")] string reason = "noneReason") { await msg.CreateResponseAsync(DiscordEmoji.FromName(msg.Client, Bot.RespondEmojiName)); var member = (DiscordMember) user; await member.BanAsync(0, reason); await Log.Audit(msg.Guild, $"{msg.User.Mention} banned {user.Mention} for {duration} minutes", reason); Thread.Sleep((int) duration * 60000 * 60); await member.UnbanAsync(msg.Guild, reason); await Log.Audit(msg.Guild, $"{user.Mention} unbanned", "Ban time expired"); } }
41.423077
111
0.698236
[ "MIT" ]
jus1d/ducker
src/SlashCommands/AdministrationModule/TempbanCommand.cs
1,079
C#
using System; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; namespace WebApplication.Models { public partial class AdsGoFastContext : DbContext { partial void OnModelCreatingPartial(ModelBuilder modelBuilder) { modelBuilder.Entity<ScheduleInstance>(entity => { entity.HasOne<ScheduleMaster>(si => si.ScheduleMaster).WithMany(sm => sm.ScheduleInstances).HasForeignKey(si => si.ScheduleMasterId); }); modelBuilder.Entity<ScheduleMaster>(entity => { entity.HasAnnotation("DisplayColumn", "ScheduleDesciption"); entity.Property(e => e.ActiveYn).HasColumnName("ActiveYN"); entity.Property(e => e.ScheduleDesciption) .IsRequired() .HasMaxLength(200) .IsUnicode(false); entity.Property(e => e.ScheduleCronExpression) .IsRequired() .HasMaxLength(200); }); modelBuilder.Entity<SourceAndTargetSystems>(entity => { entity.HasAnnotation("DisplayColumn", "SystemName"); }); modelBuilder.Entity<TaskMaster>(entity => { entity.HasAnnotation("DisplayColumn", "TaskMasterName"); entity.HasMany<TaskInstance>(tm => tm.TaskInstances).WithOne(ti => ti.TaskMaster).HasForeignKey(ti => ti.TaskMasterId); entity.HasOne<TaskGroup>(tm => tm.TaskGroup).WithMany(tg => tg.TaskMasters).HasForeignKey(tm => tm.TaskGroupId); entity.HasOne<TaskType>(tm=> tm.TaskType).WithMany(tt => tt.TaskMasters).HasForeignKey(tm => tm.TaskTypeId); entity.HasOne<ScheduleMaster>(tm => tm.ScheduleMaster).WithMany(sm => sm.TaskMasters).HasForeignKey(tm => tm.ScheduleMasterId) ; entity.HasOne<SourceAndTargetSystems>(tm => tm.SourceSystem).WithMany(tt => tt.TaskMastersSource).HasForeignKey(tm => tm.SourceSystemId); entity.HasOne<SourceAndTargetSystems>(tm => tm.TargetSystem).WithMany(tt => tt.TaskMastersTarget).HasForeignKey(tm => tm.TargetSystemId); entity.Property(p => p.TaskDatafactoryIr).IsRequired(); }); modelBuilder.Entity<TaskInstance>(entity => { entity.HasAnnotation("DisplayColumn", "Description"); entity.HasOne<TaskMaster>(tm => tm.TaskMaster).WithMany(t => t.TaskInstances).HasForeignKey(t => t.TaskMasterId); entity.HasOne<ScheduleInstance>(tm => tm.ScheduleInstance).WithMany(t => t.TaskInstances).HasForeignKey(t => t.ScheduleInstanceId); entity.Property(e => e.LastExecutionStatus).HasConversion( v => v.ToString(), v => (TaskExecutionStatus)Enum.Parse(typeof(TaskExecutionStatus), v)); }); modelBuilder.Entity<TaskGroup>(entity => { entity.HasAnnotation("DisplayColumn", "TaskGroupName"); entity.Property(p => p.TaskGroupName).IsRequired(); entity.HasMany<TaskMaster>(tm => tm.TaskMasters).WithOne(tg => tg.TaskGroup).HasForeignKey(tm => tm.TaskGroupId); entity.HasOne<SubjectArea>(tg => tg.SubjectArea).WithMany(sa => sa.TaskGroups).HasForeignKey(tg => tg.SubjectAreaId); }); modelBuilder.Entity<TaskType>().Property(e => e.TaskExecutionType).HasConversion( v => v.ToString(), v => (TaskExecutionTypeEnum)Enum.Parse(typeof(TaskExecutionTypeEnum), v)); modelBuilder.Entity<SubjectArea>(entity => { entity.HasOne<SubjectAreaForm>(tg => tg.SubjectAreaForm).WithMany(sa => sa.SubjectAreas).HasForeignKey(tg => tg.SubjectAreaFormId); }); modelBuilder.Entity<TaskGroupStats>(entity => { entity.HasNoKey(); }); modelBuilder.Entity<TaskInstanceExecution>(entity => { entity.HasAnnotation("DisplayColumn", "Description"); entity.HasOne<TaskInstance>(ti => ti.TaskInstance).WithMany(ie => ie.TaskInstanceExecutions).HasForeignKey(ti => ti.TaskInstanceId); entity.HasOne<Execution>(ti => ti.Execution).WithMany(ie => ie.TaskInstanceExecutions).HasForeignKey(ti => ti.ExecutionUid); }); modelBuilder.Entity<TaskTypeMapping>(entity => { entity.HasOne<TaskType>(ti => ti.TaskType).WithMany(ie => ie.TaskTypeMappings).HasForeignKey(ti => ti.TaskTypeId); }); modelBuilder.Entity<AdfpipelineStats1>(entity => { //entity.HasOne<TaskInstanceExecution>(ti => ti.TaskInstanceExecution).WithMany(ie => ie.AdfPipelineStats) // .HasForeignKey(ti => new {ti.TaskInstanceId, ti.ExecutionUid}); }); modelBuilder.Entity<TaskMasterWaterMark>(entity => { entity.HasAnnotation("DisplayColumn", "Description"); entity.HasOne<TaskMaster>(ti => ti.TaskMaster).WithOne(); }); } } }
43.467742
153
0.59833
[ "MIT" ]
rbev/azure-data-services-go-fast-codebase
solution/WebApplication/WebApplication/Models/Customisations/AdsGoFastContext.cs
5,392
C#
using System; using System.Diagnostics; using System.Linq; namespace Rebus.AwsSnsAndSqs { #if NET45 || NETSTANDARD2_0 [AttributeUsage(AttributeTargets.Class)] public sealed class TopicNameAttribute : Attribute { public TopicNameAttribute(string topic) { if (topic == null) { throw new ArgumentNullException(nameof(topic)); } var invalidLength = topic.Length > 256 || topic.Length <= 0; var hasInvalidChar = topic.Any(c => (char.IsLetterOrDigit(c) || c == '_' || c == '-') == false); Trace.WriteLineIf(invalidLength, nameof(invalidLength)); Trace.WriteLineIf(hasInvalidChar, nameof(hasInvalidChar)); if (invalidLength || hasInvalidChar) { throw new ArgumentException(message: $"Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256. {nameof(invalidLength)}:{invalidLength}, {nameof(hasInvalidChar)}:{hasInvalidChar}", paramName: nameof(topic)); } Topic = topic; } public string Topic { get; } } #endif }
32.675676
307
0.618693
[ "MIT" ]
P47Phoenix/Rebus.AwsSnsAndSqs
Rebus.AwsSnsAndSqs/TopicNameAttribute.cs
1,211
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace WebbShopAPI.Models { /// <summary> /// Contains Id, Name, Password, LastLogin, SessionTimer, isActive, IsAdmin data for user /// </summary> public class User { [Key] public int Id { get; set; } public string Name { get; set; } public string Password { get; set; } public DateTime LastLogin { get; set; } public DateTime SessionTimer { get; set; } public bool IsActive { get; set; } public bool IsAdmin { get; set; } } }
27.521739
93
0.624013
[ "MIT" ]
marcusjobb/NET20D
OOPA/WebbshopProjekt/Mattias/WebbShopAPI-master/Inlämning2Mattias/Models/User.cs
635
C#
namespace Win.ProCosmeticos { partial class FormProductos { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.Label activoLabel; System.Windows.Forms.Label descripcionLabel; System.Windows.Forms.Label existenciaLabel; System.Windows.Forms.Label idLabel; System.Windows.Forms.Label precioLabel; System.Windows.Forms.Label tipoIdLabel; System.Windows.Forms.Label categoriaIdLabel; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormProductos)); this.listaProductosBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components); this.listaProductosBindingSource = new System.Windows.Forms.BindingSource(this.components); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); this.listaProductosBindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonCancelar = new System.Windows.Forms.ToolStripButton(); this.activoCheckBox = new System.Windows.Forms.CheckBox(); this.descripcionTextBox = new System.Windows.Forms.TextBox(); this.existenciaTextBox = new System.Windows.Forms.TextBox(); this.idTextBox = new System.Windows.Forms.TextBox(); this.precioTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.fotoPictureBox = new System.Windows.Forms.PictureBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.tipoIdComboBox = new System.Windows.Forms.ComboBox(); this.listaTiposBindingSource = new System.Windows.Forms.BindingSource(this.components); this.listaCategoriasBindingSource = new System.Windows.Forms.BindingSource(this.components); this.categoriaIdComboBox = new System.Windows.Forms.ComboBox(); activoLabel = new System.Windows.Forms.Label(); descripcionLabel = new System.Windows.Forms.Label(); existenciaLabel = new System.Windows.Forms.Label(); idLabel = new System.Windows.Forms.Label(); precioLabel = new System.Windows.Forms.Label(); tipoIdLabel = new System.Windows.Forms.Label(); categoriaIdLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingNavigator)).BeginInit(); this.listaProductosBindingNavigator.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.fotoPictureBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listaTiposBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listaCategoriasBindingSource)).BeginInit(); this.SuspendLayout(); // // activoLabel // activoLabel.AutoSize = true; activoLabel.Location = new System.Drawing.Point(121, 340); activoLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); activoLabel.Name = "activoLabel"; activoLabel.Size = new System.Drawing.Size(50, 17); activoLabel.TabIndex = 1; activoLabel.Text = "Activo:"; // // descripcionLabel // descripcionLabel.AutoSize = true; descripcionLabel.Location = new System.Drawing.Point(121, 142); descripcionLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); descripcionLabel.Name = "descripcionLabel"; descripcionLabel.Size = new System.Drawing.Size(86, 17); descripcionLabel.TabIndex = 3; descripcionLabel.Text = "Descripcion:"; // // existenciaLabel // existenciaLabel.AutoSize = true; existenciaLabel.Location = new System.Drawing.Point(121, 306); existenciaLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); existenciaLabel.Name = "existenciaLabel"; existenciaLabel.Size = new System.Drawing.Size(75, 17); existenciaLabel.TabIndex = 5; existenciaLabel.Text = "Existencia:"; // // idLabel // idLabel.AutoSize = true; idLabel.Location = new System.Drawing.Point(121, 110); idLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); idLabel.Name = "idLabel"; idLabel.Size = new System.Drawing.Size(23, 17); idLabel.TabIndex = 7; idLabel.Text = "Id:"; // // precioLabel // precioLabel.AutoSize = true; precioLabel.Location = new System.Drawing.Point(121, 274); precioLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); precioLabel.Name = "precioLabel"; precioLabel.Size = new System.Drawing.Size(52, 17); precioLabel.TabIndex = 9; precioLabel.Text = "Precio:"; // // tipoIdLabel // tipoIdLabel.AutoSize = true; tipoIdLabel.Location = new System.Drawing.Point(152, 179); tipoIdLabel.Name = "tipoIdLabel"; tipoIdLabel.Size = new System.Drawing.Size(40, 17); tipoIdLabel.TabIndex = 15; tipoIdLabel.Text = "Tipo "; // // categoriaIdLabel // categoriaIdLabel.AutoSize = true; categoriaIdLabel.Location = new System.Drawing.Point(121, 222); categoriaIdLabel.Name = "categoriaIdLabel"; categoriaIdLabel.Size = new System.Drawing.Size(69, 17); categoriaIdLabel.TabIndex = 17; categoriaIdLabel.Text = "Categoria"; // // listaProductosBindingNavigator // this.listaProductosBindingNavigator.AddNewItem = null; this.listaProductosBindingNavigator.BindingSource = this.listaProductosBindingSource; this.listaProductosBindingNavigator.CountItem = this.bindingNavigatorCountItem; this.listaProductosBindingNavigator.DeleteItem = null; this.listaProductosBindingNavigator.ImageScalingSize = new System.Drawing.Size(20, 20); this.listaProductosBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.bindingNavigatorAddNewItem, this.bindingNavigatorDeleteItem, this.listaProductosBindingNavigatorSaveItem, this.toolStripButtonCancelar}); this.listaProductosBindingNavigator.Location = new System.Drawing.Point(0, 0); this.listaProductosBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.listaProductosBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem; this.listaProductosBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem; this.listaProductosBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.listaProductosBindingNavigator.Name = "listaProductosBindingNavigator"; this.listaProductosBindingNavigator.PositionItem = this.bindingNavigatorPositionItem; this.listaProductosBindingNavigator.Size = new System.Drawing.Size(940, 27); this.listaProductosBindingNavigator.TabIndex = 0; this.listaProductosBindingNavigator.Text = "bindingNavigator1"; // // listaProductosBindingSource // this.listaProductosBindingSource.DataSource = typeof(BL.Cosmeticos.Producto); // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(48, 24); this.bindingNavigatorCountItem.Text = "de {0}"; this.bindingNavigatorCountItem.ToolTipText = "Número total de elementos"; // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorMoveFirstItem.Text = "Mover primero"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorMovePreviousItem.Text = "Mover anterior"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 27); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "Posición"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(65, 27); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "Posición actual"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 27); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorMoveNextItem.Text = "Mover siguiente"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorMoveLastItem.Text = "Mover último"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 27); // // bindingNavigatorAddNewItem // this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorAddNewItem.Text = "Agregar nuevo"; this.bindingNavigatorAddNewItem.Click += new System.EventHandler(this.bindingNavigatorAddNewItem_Click); // // bindingNavigatorDeleteItem // this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(24, 24); this.bindingNavigatorDeleteItem.Text = "Eliminar"; this.bindingNavigatorDeleteItem.Click += new System.EventHandler(this.bindingNavigatorDeleteItem_Click); // // listaProductosBindingNavigatorSaveItem // this.listaProductosBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.listaProductosBindingNavigatorSaveItem.Image = ((System.Drawing.Image)(resources.GetObject("listaProductosBindingNavigatorSaveItem.Image"))); this.listaProductosBindingNavigatorSaveItem.Name = "listaProductosBindingNavigatorSaveItem"; this.listaProductosBindingNavigatorSaveItem.Size = new System.Drawing.Size(24, 24); this.listaProductosBindingNavigatorSaveItem.Text = "Guardar datos"; this.listaProductosBindingNavigatorSaveItem.Click += new System.EventHandler(this.listaProductosBindingNavigatorSaveItem_Click); // // toolStripButtonCancelar // this.toolStripButtonCancelar.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButtonCancelar.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButtonCancelar.Image"))); this.toolStripButtonCancelar.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonCancelar.Name = "toolStripButtonCancelar"; this.toolStripButtonCancelar.Size = new System.Drawing.Size(70, 24); this.toolStripButtonCancelar.Text = "Cancelar"; this.toolStripButtonCancelar.Visible = false; this.toolStripButtonCancelar.Click += new System.EventHandler(this.toolStripButtonCancelar_Click); // // activoCheckBox // this.activoCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.listaProductosBindingSource, "Activo", true)); this.activoCheckBox.Location = new System.Drawing.Point(217, 334); this.activoCheckBox.Margin = new System.Windows.Forms.Padding(4); this.activoCheckBox.Name = "activoCheckBox"; this.activoCheckBox.Size = new System.Drawing.Size(391, 30); this.activoCheckBox.TabIndex = 2; this.activoCheckBox.UseVisualStyleBackColor = true; // // descripcionTextBox // this.descripcionTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaProductosBindingSource, "Descripcion", true)); this.descripcionTextBox.Location = new System.Drawing.Point(217, 138); this.descripcionTextBox.Margin = new System.Windows.Forms.Padding(4); this.descripcionTextBox.Name = "descripcionTextBox"; this.descripcionTextBox.Size = new System.Drawing.Size(435, 22); this.descripcionTextBox.TabIndex = 4; // // existenciaTextBox // this.existenciaTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaProductosBindingSource, "Existencia", true)); this.existenciaTextBox.Location = new System.Drawing.Point(217, 302); this.existenciaTextBox.Margin = new System.Windows.Forms.Padding(4); this.existenciaTextBox.Name = "existenciaTextBox"; this.existenciaTextBox.Size = new System.Drawing.Size(435, 22); this.existenciaTextBox.TabIndex = 6; // // idTextBox // this.idTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaProductosBindingSource, "Id", true)); this.idTextBox.Location = new System.Drawing.Point(217, 106); this.idTextBox.Margin = new System.Windows.Forms.Padding(4); this.idTextBox.Name = "idTextBox"; this.idTextBox.ReadOnly = true; this.idTextBox.Size = new System.Drawing.Size(435, 22); this.idTextBox.TabIndex = 8; // // precioTextBox // this.precioTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaProductosBindingSource, "Precio", true)); this.precioTextBox.Location = new System.Drawing.Point(217, 270); this.precioTextBox.Margin = new System.Windows.Forms.Padding(4); this.precioTextBox.Name = "precioTextBox"; this.precioTextBox.Size = new System.Drawing.Size(435, 22); this.precioTextBox.TabIndex = 10; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(537, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(0, 17); this.label1.TabIndex = 11; // // fotoPictureBox // this.fotoPictureBox.BackColor = System.Drawing.Color.Gray; this.fotoPictureBox.DataBindings.Add(new System.Windows.Forms.Binding("Image", this.listaProductosBindingSource, "Foto", true, System.Windows.Forms.DataSourceUpdateMode.Never)); this.fotoPictureBox.Location = new System.Drawing.Point(685, 86); this.fotoPictureBox.Name = "fotoPictureBox"; this.fotoPictureBox.Size = new System.Drawing.Size(223, 153); this.fotoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.fotoPictureBox.TabIndex = 13; this.fotoPictureBox.TabStop = false; this.fotoPictureBox.Click += new System.EventHandler(this.fotoPictureBox_Click); // // button1 // this.button1.Location = new System.Drawing.Point(685, 268); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(105, 35); this.button1.TabIndex = 14; this.button1.Text = "Agregar Foto"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(796, 268); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(112, 35); this.button2.TabIndex = 15; this.button2.Text = "Remover Foto"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // openFileDialog1 // this.openFileDialog1.Filter = "jpg, png |*.jpg; *.png"; this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk); // // tipoIdComboBox // this.tipoIdComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.listaProductosBindingSource, "TipoId", true)); this.tipoIdComboBox.DataSource = this.listaTiposBindingSource; this.tipoIdComboBox.DisplayMember = "Descripcion"; this.tipoIdComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.tipoIdComboBox.FormattingEnabled = true; this.tipoIdComboBox.Location = new System.Drawing.Point(213, 176); this.tipoIdComboBox.Name = "tipoIdComboBox"; this.tipoIdComboBox.Size = new System.Drawing.Size(435, 24); this.tipoIdComboBox.TabIndex = 16; this.tipoIdComboBox.ValueMember = "Id"; // // listaTiposBindingSource // this.listaTiposBindingSource.DataSource = typeof(BL.Cosmeticos.Tipo); // // listaCategoriasBindingSource // this.listaCategoriasBindingSource.DataSource = typeof(BL.Cosmeticos.Categoria); // // categoriaIdComboBox // this.categoriaIdComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.listaProductosBindingSource, "CategoriaId", true)); this.categoriaIdComboBox.DataSource = this.listaCategoriasBindingSource; this.categoriaIdComboBox.DisplayMember = "Descripcion"; this.categoriaIdComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.categoriaIdComboBox.FormattingEnabled = true; this.categoriaIdComboBox.Location = new System.Drawing.Point(215, 219); this.categoriaIdComboBox.Name = "categoriaIdComboBox"; this.categoriaIdComboBox.Size = new System.Drawing.Size(433, 24); this.categoriaIdComboBox.TabIndex = 18; this.categoriaIdComboBox.ValueMember = "Id"; // // FormProductos // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(940, 641); this.Controls.Add(categoriaIdLabel); this.Controls.Add(this.categoriaIdComboBox); this.Controls.Add(tipoIdLabel); this.Controls.Add(this.tipoIdComboBox); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.fotoPictureBox); this.Controls.Add(this.label1); this.Controls.Add(activoLabel); this.Controls.Add(this.activoCheckBox); this.Controls.Add(descripcionLabel); this.Controls.Add(this.descripcionTextBox); this.Controls.Add(existenciaLabel); this.Controls.Add(this.existenciaTextBox); this.Controls.Add(idLabel); this.Controls.Add(this.idTextBox); this.Controls.Add(precioLabel); this.Controls.Add(this.precioTextBox); this.Controls.Add(this.listaProductosBindingNavigator); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Name = "FormProductos"; this.Text = "Productos"; this.Load += new System.EventHandler(this.FormProductos_Load); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingNavigator)).EndInit(); this.listaProductosBindingNavigator.ResumeLayout(false); this.listaProductosBindingNavigator.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.fotoPictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listaTiposBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listaCategoriasBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.BindingSource listaProductosBindingSource; private System.Windows.Forms.BindingNavigator listaProductosBindingNavigator; private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.ToolStripButton listaProductosBindingNavigatorSaveItem; private System.Windows.Forms.CheckBox activoCheckBox; private System.Windows.Forms.TextBox descripcionTextBox; private System.Windows.Forms.TextBox existenciaTextBox; private System.Windows.Forms.TextBox idTextBox; private System.Windows.Forms.TextBox precioTextBox; private System.Windows.Forms.ToolStripButton toolStripButtonCancelar; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox fotoPictureBox; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.BindingSource listaTiposBindingSource; private System.Windows.Forms.ComboBox tipoIdComboBox; private System.Windows.Forms.BindingSource listaCategoriasBindingSource; private System.Windows.Forms.ComboBox categoriaIdComboBox; } }
59.034483
189
0.662899
[ "MIT" ]
amayafany28/ProyectoCosmeticos
PCosmeticos/Win.ProCosmeticos/FormProductos.Designer.cs
29,110
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ball : MonoBehaviour { private bool isSelected; private Rigidbody2D rb; private Rigidbody2D hookRb; private SpringJoint2D sj; [SerializeField] private float speed; [SerializeField] private float maxDragDistance; [SerializeField] private float releaseDelay; [SerializeField] public ColorType colorType; private ColorType initialColorType; private GameObject parentObject; private SlingShot parentSlingShot; private CircleCollider2D circleCollider2D; private SpriteRenderer spriteRenderer; private TrailRenderer trailRenderer; [SerializeField] private Gradient rainBowColor; [SerializeField] private Gradient basicGradientColor; private GameObject[] points = new GameObject[5]; void Start() { initialColorType = colorType; parentObject = transform.parent.gameObject; parentSlingShot = parentObject.GetComponent<SlingShot>(); circleCollider2D = GetComponent<CircleCollider2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); trailRenderer = GetComponent<TrailRenderer>(); rb = GetComponent<Rigidbody2D>(); sj = GetComponent<SpringJoint2D>(); sj.connectedAnchor = parentSlingShot.hook.localPosition; sj.connectedBody = parentObject.GetComponent<Rigidbody2D>(); hookRb = sj.connectedBody; releaseDelay = 1 / (sj.frequency * 4); circleCollider2D.isTrigger = true; PowerUpManager.instance.OnRainbowBallActive += TurnOnRainbowBall; PowerUpManager.instance.OnRainbowBallDeactive += TurnOffRainbowBall; if (PowerUpManager.instance.isRainbowBallActive) { TurnOnRainbowBall(); colorType = ColorType.Rainbow; } } // Update is called once per frame void FixedUpdate() { if (!GameManager.instance.isGameOver) { if (isSelected) { Drag(); } } } private void Drag() { Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); float distance = Vector2.Distance(mousePosition, hookRb.position); if (distance > maxDragDistance) { Vector2 direction = (mousePosition - hookRb.position).normalized; rb.position = hookRb.position + direction * maxDragDistance; } else { rb.position = mousePosition; } Debug.Log(rb.velocity); } private void OnMouseDown() { isSelected = true; rb.isKinematic = true; } private void OnMouseUp() { isSelected = false; rb.isKinematic = false; Release(); } public void Release() { if (Vector2.Distance(sj.connectedBody.position, rb.position) > 0.65f) { StartCoroutine(ReleaseRoutine()); } } IEnumerator ReleaseRoutine() { SoundManager.instance.PlayWithBallSource(colorType); circleCollider2D.radius = 0.5f; yield return new WaitForSeconds(releaseDelay); rb.velocity = rb.velocity * speed; sj.enabled = false; circleCollider2D.isTrigger = false; parentSlingShot.SpawnNewBall(); } public void TurnOnRainbowBall() { if (spriteRenderer != null) { spriteRenderer.sprite = PowerUpManager.instance.rainbowBallSprite; spriteRenderer.color = Color.white; } colorType = ColorType.Rainbow; if (trailRenderer != null) { trailRenderer.colorGradient = rainBowColor; } } public void TurnOffRainbowBall() { if (spriteRenderer != null) { spriteRenderer.sprite = PowerUpManager.instance.defaultBallSprite; spriteRenderer.color = ColorPicker.instance.GetColorRGBValue(initialColorType); } colorType = initialColorType; if (trailRenderer != null) { trailRenderer.endColor = ColorPicker.instance.GetColorRGBValue(initialColorType); trailRenderer.startColor = ColorPicker.instance.GetColorRGBValue(initialColorType); trailRenderer.colorGradient = basicGradientColor; } } private void OnDisable() { PowerUpManager.instance.OnRainbowBallActive -= TurnOnRainbowBall; PowerUpManager.instance.OnRainbowBallDeactive -= TurnOffRainbowBall; } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("EnemyDestroyer")) { Destroy(this.gameObject); } } }
23.507246
95
0.628442
[ "MIT" ]
Shurid16/Color-Drag-2D
Assets/Scripts/Ball.cs
4,866
C#
namespace Basset.Options { public enum ServerType { SQLite, MySQL, Postgres // Not implemented } public class DataOptions { public ServerType ServerType { get; set; } = ServerType.SQLite; public string Database { get; set; } = "basset"; public string Host { get; set; } = "localhost"; public int Port { get; set; } = 3306; public string User { get; set; } = "root"; public string Password { get; set; } = null; } }
25.8
71
0.556202
[ "MIT" ]
Aux/Basset
src/Basset.Core/Options/DataOptions.cs
518
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.CustomerInsights.V20170101 { public static class GetKpi { /// <summary> /// The KPI resource format. /// </summary> public static Task<GetKpiResult> InvokeAsync(GetKpiArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetKpiResult>("azure-nextgen:customerinsights/v20170101:getKpi", args ?? new GetKpiArgs(), options.WithVersion()); } public sealed class GetKpiArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the hub. /// </summary> [Input("hubName", required: true)] public string HubName { get; set; } = null!; /// <summary> /// The name of the KPI. /// </summary> [Input("kpiName", required: true)] public string KpiName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetKpiArgs() { } } [OutputType] public sealed class GetKpiResult { /// <summary> /// The aliases. /// </summary> public readonly ImmutableArray<Outputs.KpiAliasResponse> Aliases; /// <summary> /// The calculation window. /// </summary> public readonly string CalculationWindow; /// <summary> /// Name of calculation window field. /// </summary> public readonly string? CalculationWindowFieldName; /// <summary> /// Localized description for the KPI. /// </summary> public readonly ImmutableDictionary<string, string>? Description; /// <summary> /// Localized display name for the KPI. /// </summary> public readonly ImmutableDictionary<string, string>? DisplayName; /// <summary> /// The mapping entity type. /// </summary> public readonly string EntityType; /// <summary> /// The mapping entity name. /// </summary> public readonly string EntityTypeName; /// <summary> /// The computation expression for the KPI. /// </summary> public readonly string Expression; /// <summary> /// The KPI extracts. /// </summary> public readonly ImmutableArray<Outputs.KpiExtractResponse> Extracts; /// <summary> /// The filter expression for the KPI. /// </summary> public readonly string? Filter; /// <summary> /// The computation function for the KPI. /// </summary> public readonly string Function; /// <summary> /// the group by properties for the KPI. /// </summary> public readonly ImmutableArray<string> GroupBy; /// <summary> /// The KPI GroupByMetadata. /// </summary> public readonly ImmutableArray<Outputs.KpiGroupByMetadataResponse> GroupByMetadata; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// The KPI name. /// </summary> public readonly string KpiName; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The participant profiles. /// </summary> public readonly ImmutableArray<Outputs.KpiParticipantProfilesMetadataResponse> ParticipantProfilesMetadata; /// <summary> /// Provisioning state. /// </summary> public readonly string ProvisioningState; /// <summary> /// The hub name. /// </summary> public readonly string TenantId; /// <summary> /// The KPI thresholds. /// </summary> public readonly Outputs.KpiThresholdsResponse? ThresHolds; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// The unit of measurement for the KPI. /// </summary> public readonly string? Unit; [OutputConstructor] private GetKpiResult( ImmutableArray<Outputs.KpiAliasResponse> aliases, string calculationWindow, string? calculationWindowFieldName, ImmutableDictionary<string, string>? description, ImmutableDictionary<string, string>? displayName, string entityType, string entityTypeName, string expression, ImmutableArray<Outputs.KpiExtractResponse> extracts, string? filter, string function, ImmutableArray<string> groupBy, ImmutableArray<Outputs.KpiGroupByMetadataResponse> groupByMetadata, string id, string kpiName, string name, ImmutableArray<Outputs.KpiParticipantProfilesMetadataResponse> participantProfilesMetadata, string provisioningState, string tenantId, Outputs.KpiThresholdsResponse? thresHolds, string type, string? unit) { Aliases = aliases; CalculationWindow = calculationWindow; CalculationWindowFieldName = calculationWindowFieldName; Description = description; DisplayName = displayName; EntityType = entityType; EntityTypeName = entityTypeName; Expression = expression; Extracts = extracts; Filter = filter; Function = function; GroupBy = groupBy; GroupByMetadata = groupByMetadata; Id = id; KpiName = kpiName; Name = name; ParticipantProfilesMetadata = participantProfilesMetadata; ProvisioningState = provisioningState; TenantId = tenantId; ThresHolds = thresHolds; Type = type; Unit = unit; } } }
30.563981
168
0.573112
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/CustomerInsights/V20170101/GetKpi.cs
6,449
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; using VocabularyCard.Core.Entities; namespace VocabularyCard.Core.Repositories { public interface IDbContext : IDisposable { IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity; DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : BaseEntity; int SaveChanges(); Task<int> SaveChangesAsync(); } }
23.956522
89
0.736842
[ "MIT" ]
soriano7788/VocabularyCardProject
VocabularyCard.Core/Repositories/IDbContext.cs
553
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 kinesis-2013-12-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Kinesis.Model { /// <summary> /// Represents the result of an individual record from a <code>PutRecords</code> request. /// A record that is successfully added to a stream includes <code>SequenceNumber</code> /// and <code>ShardId</code> in the result. A record that fails to be added to the stream /// includes <code>ErrorCode</code> and <code>ErrorMessage</code> in the result. /// </summary> public partial class PutRecordsResultEntry { private string _errorCode; private string _errorMessage; private string _sequenceNumber; private string _shardId; /// <summary> /// Gets and sets the property ErrorCode. /// <para> /// The error code for an individual record result. <code>ErrorCodes</code> can be either /// <code>ProvisionedThroughputExceededException</code> or <code>InternalFailure</code>. /// </para> /// </summary> public string ErrorCode { get { return this._errorCode; } set { this._errorCode = value; } } // Check to see if ErrorCode property is set internal bool IsSetErrorCode() { return this._errorCode != null; } /// <summary> /// Gets and sets the property ErrorMessage. /// <para> /// The error message for an individual record result. An <code>ErrorCode</code> value /// of <code>ProvisionedThroughputExceededException</code> has an error message that includes /// the account ID, stream name, and shard ID. An <code>ErrorCode</code> value of <code>InternalFailure</code> /// has the error message <code>"Internal Service Failure"</code>. /// </para> /// </summary> public string ErrorMessage { get { return this._errorMessage; } set { this._errorMessage = value; } } // Check to see if ErrorMessage property is set internal bool IsSetErrorMessage() { return this._errorMessage != null; } /// <summary> /// Gets and sets the property SequenceNumber. /// <para> /// The sequence number for an individual record result. /// </para> /// </summary> public string SequenceNumber { get { return this._sequenceNumber; } set { this._sequenceNumber = value; } } // Check to see if SequenceNumber property is set internal bool IsSetSequenceNumber() { return this._sequenceNumber != null; } /// <summary> /// Gets and sets the property ShardId. /// <para> /// The shard ID for an individual record result. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string ShardId { get { return this._shardId; } set { this._shardId = value; } } // Check to see if ShardId property is set internal bool IsSetShardId() { return this._shardId != null; } } }
34.180328
119
0.590647
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Kinesis/Generated/Model/PutRecordsResultEntry.cs
4,170
C#
using System; using System.Data.SqlClient; using System.ServiceModel; using MobileService.Exception; using MobileService.Model; namespace MobileService.Database { public class DbUser { private static SqlConnection _connection; private readonly string _connectionString = "Server=kraka.ucn.dk;" + "Database=dmaa0917_1067347;User ID=dmaa0917_1067347;" + "Password=Password1!;"; private readonly DbUserType _dbUserType; public DbUser() { _dbUserType = new DbUserType(); } /// <summary> /// Create a user in database /// </summary> /// <param name="user">User</param> /// <returns>int</returns> public int Create(User user) { int id; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "INSERT INTO [User](UserName, HashPassword, Salt, UserTypeId) VALUES " + "(@UserName, @HashPassword, @Salt, @UserTypeId); SELECT SCOPE_IDENTITY()"; cmd.Parameters.AddWithValue("UserName", user.UserName); cmd.Parameters.AddWithValue("HashPassword", user.HashPassword); cmd.Parameters.AddWithValue("Salt", user.Salt); cmd.Parameters.AddWithValue("UserTypeId", user.UserType.UserTypeId); id = Convert.ToInt32(cmd.ExecuteScalar()); } _connection.Close(); } return id; } /// <summary> /// Find a user based on its id in database /// </summary> /// <param name="userId"></param> /// <returns></returns> public User FindById(int userId) { User user = null; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "SELECT * FROM [User] WHERE UserId = @UserId"; cmd.Parameters.AddWithValue("UserId", userId); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { int userTypeId = reader.GetInt32(reader.GetOrdinal("UserTypeId")); user = new User { UserId = userId, UserName = reader.GetString(reader.GetOrdinal("UserName")), HashPassword = reader.GetString(reader.GetOrdinal("HashPassword")), Salt = reader.GetString(reader.GetOrdinal("Salt")), UserType = _dbUserType.FindById(userTypeId) }; } } _connection.Close(); } if (user == null) { throw new FaultException<UserNotFoundException>(new UserNotFoundException("")); } return user; } /// <summary> /// Find a user based on its username in database /// If user tries to login it throws a login error /// </summary> /// <param name="userName">string</param> /// <param name="login">bool</param> /// <returns>User</returns> public User FindUserByUserName(string userName, bool login) { User user = null; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "SELECT * FROM [User] WHERE UserName = @UserName"; cmd.Parameters.AddWithValue("UserName", userName); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { int userTypeId = reader.GetInt32(reader.GetOrdinal("UserTypeId")); user = new User { UserId = reader.GetInt32(reader.GetOrdinal("UserId")), UserName = userName, HashPassword = reader.GetString(reader.GetOrdinal("HashPassword")), Salt = reader.GetString(reader.GetOrdinal("Salt")), UserType = _dbUserType.FindById(userTypeId) }; } if (user == null) { if (login) { throw new FaultException<UserOrPasswordException>(new UserOrPasswordException()); } throw new FaultException<UserNotFoundException>(new UserNotFoundException(userName)); } } _connection.Close(); } return user; } /// <summary> /// Find a user based on its username in database /// </summary> /// <param name="userName">string</param> /// <returns>int</returns> public int FindIdByUserName(string userName) { int userId = 0; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "SELECT * FROM [User] WHERE UserName = @UserName"; cmd.Parameters.AddWithValue("UserName", userName); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { userId = reader.GetInt32(reader.GetOrdinal("UserId")); } } _connection.Close(); } return userId; } /// <summary> /// Update a user in database /// </summary> /// <param name="user">User</param> /// <returns>bool</returns> public bool Update(User user) { int changes; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "UPDATE [User] SET UserName = @UserName, HashPassword = @HashPassword, " + "Salt = @Salt, UserTypeId = @UserTypeId WHERE UserId = @UserId"; cmd.Parameters.AddWithValue("UserName", user.UserName); cmd.Parameters.AddWithValue("HashPassword", user.HashPassword); cmd.Parameters.AddWithValue("Salt", user.Salt); cmd.Parameters.AddWithValue("UserTypeId", user.UserType.UserTypeId); cmd.Parameters.AddWithValue("UserId", user.UserId); changes = cmd.ExecuteNonQuery(); } _connection.Close(); } return changes > 0; } /// <summary> /// Delete a user in database /// </summary> /// <param name="userName">string</param> public void Delete(string userName) { int changes; using (_connection = new SqlConnection(_connectionString)) { _connection.Open(); using (SqlCommand cmd = _connection.CreateCommand()) { cmd.CommandText = "DELETE FROM [User] WHERE UserName = @UserName"; cmd.Parameters.AddWithValue("UserName", userName); changes = cmd.ExecuteNonQuery(); } _connection.Close(); } bool status = changes > 0; if (status == false) { throw new FaultException<UserNotDeletedException>(new UserNotDeletedException(userName)); } } } }
37.444934
112
0.483059
[ "Apache-2.0" ]
akhegr/Skoleprojekter
4. semester projekt/MobilSemProjekt/MobileService/MobileService.Database/DbUser.cs
8,502
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests { public class AEMExtensionTests { public AEMExtensionTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); } #if NETSTANDARD [Fact(Skip = "Get-Location in Common.ps1 is not working correctly for NETSTANDARD")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionBasicWindowsWAD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionBasicWindowsWAD"); } #if NETSTANDARD [Fact(Skip = "Resources -> ResourceManager, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionBasicWindows() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionBasicWindows"); } #if NETSTANDARD [Fact(Skip = "Unknown issue/update, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionBasicLinuxWAD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionBasicLinuxWAD"); } #if NETSTANDARD [Fact(Skip = "Unknown issue/update, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionBasicLinux() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionBasicLinux"); } #if NETSTANDARD [Fact(Skip = "Resources -> ResourceManager, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedWindowsWAD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedWindowsWAD"); } #if NETSTANDARD [Fact(Skip = "Get-Location in Common.ps1 is not working correctly for NETSTANDARD")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedWindows() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedWindows"); } #if NETSTANDARD [Fact(Skip = "Unknown issue/update, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedLinuxWAD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedLinuxWAD"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedLinux() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedLinux"); } #if NETSTANDARD [Fact(Skip = "Get-Location in Common.ps1 is not working correctly for NETSTANDARD")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedWindowsMD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedWindowsMD"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedLinuxMD() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedLinuxMD"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedLinuxMD_ESeries() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedLinuxMD_E"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAEMExtensionAdvancedLinuxMD_DSeries() { ComputeTestController.NewInstance.RunPsTest("Test-AEMExtensionAdvancedLinuxMD_D"); } } }
36.741722
153
0.64708
[ "MIT" ]
Philippe-Morin/azure-powershell
src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/AEMExtensionTests.cs
5,400
C#
namespace Zoo.Reptile { public class Lizard : Reptile { public Lizard(string name) : base(name) { } } }
11.846154
34
0.474026
[ "MIT" ]
markodjunev/Softuni
C#/C# OOP/Inheritance - Exercise/Zoo/Reptile/Lizard.cs
156
C#
//----------------------------------------------------------------------- // <copyright file="ConfigSettingsExtensions.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SonarQube.Common { /// <summary> /// Extension methods for <see cref="AnalysisConfig"/> /// </summary> public static class ConfigSettingsExtensions { /// <summary> /// The key for the setting that holds the path to a settings file /// </summary> private const string SettingsFileKey = "settings.file.path"; #region Public methods /// <summary> /// Returns the value of the specified config setting, or the supplied default value if the setting could not be found /// </summary> public static string GetConfigValue(this AnalysisConfig config, string settingId, string defaultValue) { if (config == null) { throw new ArgumentNullException("config"); } if (string.IsNullOrWhiteSpace(settingId)) { throw new ArgumentNullException("settingId"); } string result = defaultValue; ConfigSetting setting; if (config.TryGetConfigSetting(settingId, out setting)) { result = setting.Value; } return result; } /// <summary> /// Sets the value of the additional setting. The setting will be added if it does not already exist. /// </summary> public static void SetConfigValue(this AnalysisConfig config, string settingId, string value) { SetValue(config, settingId, value); } /// <summary> /// Returns a provider containing all of the analysis settings from the config. /// Optionally includes settings downloaded from the SonarQube server. /// </summary> /// <remarks>This could include settings imported from a settings file</remarks> public static IAnalysisPropertyProvider GetAnalysisSettings(this AnalysisConfig config, bool includeServerSettings) { if (config == null) { throw new ArgumentNullException("config"); } List<IAnalysisPropertyProvider> providers = new List<IAnalysisPropertyProvider>(); // Note: the order in which the providers are added determines the precedence // Add local settings if (config.LocalSettings != null) { providers.Add(new ListPropertiesProvider(config.LocalSettings)); } // Add file settings string settingsFilePath = config.GetSettingsFilePath(); if (settingsFilePath != null) { ListPropertiesProvider fileProvider = new ListPropertiesProvider(AnalysisProperties.Load(settingsFilePath)); providers.Add(fileProvider); } // Add server settings if (includeServerSettings && config.ServerSettings != null) { providers.Add(new ListPropertiesProvider(config.ServerSettings)); } IAnalysisPropertyProvider provider = null; switch(providers.Count) { case 0: provider = EmptyPropertyProvider.Instance; break; case 1: provider = providers[0]; break; default: provider = new AggregatePropertiesProvider(providers.ToArray()); break; } return provider; } public static void SetSettingsFilePath(this AnalysisConfig config, string fileName) { if (config == null) { throw new ArgumentNullException("config"); } if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException("fileName"); } config.SetValue(SettingsFileKey, fileName); } public static string GetSettingsFilePath(this AnalysisConfig config) { if (config == null) { throw new ArgumentNullException("config"); } ConfigSetting setting; if (config.TryGetConfigSetting(SettingsFileKey, out setting)) { return setting.Value; } return null; } #endregion #region Private methods /// <summary> /// Attempts to find and return the config setting with the specified id /// </summary> /// <returns>True if the setting was found, otherwise false</returns> private static bool TryGetConfigSetting(this AnalysisConfig config, string settingId, out ConfigSetting result) { Debug.Assert(config != null, "Supplied config should not be null"); Debug.Assert(!string.IsNullOrWhiteSpace(settingId), "Setting id should not be null/empty"); result = null; if (config.AdditionalConfig != null) { result = config.AdditionalConfig.FirstOrDefault(ar => ConfigSetting.SettingKeyComparer.Equals(settingId, ar.Id)); } return result != null; } /// <summary> /// Sets the value of the additional setting. The setting will be added if it does not already exist. /// </summary> private static void SetValue(this AnalysisConfig config, string settingId, string value) { if (config == null) { throw new ArgumentNullException("config"); } if (string.IsNullOrWhiteSpace(settingId)) { throw new ArgumentNullException("settingId"); } ConfigSetting setting; if (config.TryGetConfigSetting(settingId, out setting)) { setting.Value = value; } else { setting = new ConfigSetting() { Id = settingId, Value = value }; } if (config.AdditionalConfig == null) { config.AdditionalConfig = new System.Collections.Generic.List<ConfigSetting>(); } config.AdditionalConfig.Add(setting); } #endregion } }
35.562189
130
0.534555
[ "MIT" ]
Godin/sonar-msbuild-runner
SonarQube.Common/AnalysisConfig/AnalysisConfigExtensions.cs
6,950
C#
/* * Intersight REST API * * This is Intersight REST API * * OpenAPI spec version: 1.0.9-262 * * 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 = intersight.Client.SwaggerDateConverter; namespace intersight.Model { /// <summary> /// WorkflowTaskInfoList /// </summary> [DataContract] public partial class WorkflowTaskInfoList : IEquatable<WorkflowTaskInfoList>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="WorkflowTaskInfoList" /> class. /// </summary> /// <param name="Count">The number of workflowTaskInfos matching your request in total for all pages..</param> /// <param name="Results">The array of workflowTaskInfos matching your request..</param> public WorkflowTaskInfoList(int? Count = default(int?), List<WorkflowTaskInfo> Results = default(List<WorkflowTaskInfo>)) { this.Count = Count; this.Results = Results; } /// <summary> /// The number of workflowTaskInfos matching your request in total for all pages. /// </summary> /// <value>The number of workflowTaskInfos matching your request in total for all pages.</value> [DataMember(Name="Count", EmitDefaultValue=false)] public int? Count { get; set; } /// <summary> /// The array of workflowTaskInfos matching your request. /// </summary> /// <value>The array of workflowTaskInfos matching your request.</value> [DataMember(Name="Results", EmitDefaultValue=false)] public List<WorkflowTaskInfo> Results { 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 WorkflowTaskInfoList {\n"); sb.Append(" Count: ").Append(Count).Append("\n"); sb.Append(" Results: ").Append(Results).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 WorkflowTaskInfoList); } /// <summary> /// Returns true if WorkflowTaskInfoList instances are equal /// </summary> /// <param name="other">Instance of WorkflowTaskInfoList to be compared</param> /// <returns>Boolean</returns> public bool Equals(WorkflowTaskInfoList other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Count == other.Count || this.Count != null && this.Count.Equals(other.Count) ) && ( this.Results == other.Results || this.Results != null && this.Results.SequenceEqual(other.Results) ); } /// <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.Count != null) hash = hash * 59 + this.Count.GetHashCode(); if (this.Results != null) hash = hash * 59 + this.Results.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; } } }
35.22449
140
0.57725
[ "Apache-2.0" ]
ategaw-cisco/intersight-powershell
csharp/swaggerClient/src/intersight/Model/WorkflowTaskInfoList.cs
5,178
C#
using System.Collections.Generic; using Eshava.Core.Logging.Models; using System.ComponentModel.DataAnnotations; namespace Eshava.Core.Logging.Interfaces { public interface IDataRecordChangeTracker<P> { IEnumerable<DataRecordLogProperty<P>> CreateInsertLogs<T>(T dataRecord, P dataRecordId, P dataRecordParentId) where T : class; IEnumerable<DataRecordLogProperty<P>> CreateUpdateLogs<T>(T dataRecord, T dataRecordToCompare, P dataRecordId, P dataRecordParentId) where T : class; /// <summary> /// To create an deletion log the <see cref="KeyAttribute"/> must be set on one property /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dataRecordId"></param> /// <param name="dataRecordParentId"></param> /// <returns></returns> DataRecordLogProperty<P> CreateDeleteLog<T>(P dataRecordId, P dataRecordParentId) where T : class; } }
41.571429
151
0.751432
[ "MIT" ]
eshava/core
Eshava.Core.Logging/Interfaces/IDataRecordChangeTracker.cs
875
C#
using Application.DataAccessFramework; using Application.IoC.Interfaces; using System.Data; using System.Data.Entity.Infrastructure; using System.Data.Objects; namespace Application.IoC { /// <summary> /// This represents the Unit of Work entity. /// </summary> public class UnitOfWork : IUnitOfWork { //http://msdn.microsoft.com/en-us/library/bb738523.aspx //http://stackoverflow.com/questions/815586/entity-framework-using-transactions-or-savechangesfalse-and-acceptallchanges #region Constructors /// <summary> /// Initialises a new instance of the UnitOfWork object. /// </summary> /// <param name="context">Database context.</param> public UnitOfWork(ApplicationDataContext context) { this._context = context; // In order to make calls that are overidden in the caching ef-wrapper, we need to use // transactions from the connection, rather than TransactionScope. // This results in our call e.g. to commit() being intercepted // by the wrapper so the cache can be adjusted. // This won't work with the dbcontext because it handles the connection itself, so we must use the underlying ObjectContext. // http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext-api-entityconnection-can-only-be-constructed-with-a-closed-dbconnection.aspx this._objectContext = ((IObjectContextAdapter)_context).ObjectContext; if (this._objectContext.Connection.State == ConnectionState.Open) return; this._objectContext.Connection.Open(); this._transaction = this._objectContext.Connection.BeginTransaction(); } #endregion Constructors #region Properties private readonly ApplicationDataContext _context; private readonly IDbTransaction _transaction; private readonly ObjectContext _objectContext; #endregion Properties #region Methods /// <summary> /// Saves the changes. /// </summary> public void SaveChanges() { this._context.SaveChanges(); } /// <summary> /// Commits the changes. /// </summary> public void Commit() { this._context.SaveChanges(); this._transaction.Commit(); } /// <summary> /// Rollbacks the changes. /// </summary> public void Rollback() { this._transaction.Rollback(); // http://blog.oneunicorn.com/2011/04/03/rejecting-changes-to-entities-in-ef-4-1/ foreach (var entry in this._context.ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Modified: entry.State = EntityState.Unchanged; break; case EntityState.Added: entry.State = EntityState.Detached; break; case EntityState.Deleted: // Note - problem with deleted entities: // When an entity is deleted its relationships to other entities are severed. // This includes setting FKs to null for nullable FKs or marking the FKs as conceptually null (don't ask!) // if the FK property is not nullable. You'll need to reset the FK property values to // the values that they had previously in order to re-form the relationships. // This may include FK properties in other entities for relationships where the // deleted entity is the principal of the relationship–e.g. has the PK // rather than the FK. I know this is a pain–it would be great if it could be made easier in the future, but for now it is what it is. entry.State = EntityState.Unchanged; break; } } } /// <summary> /// Disposes the connection. /// </summary> public void Dispose() { if (this._objectContext.Connection.State == ConnectionState.Open) this._objectContext.Connection.Close(); } #endregion Methods } }
31
156
0.711864
[ "MIT" ]
aliencube/Web-Application-Boilerplate
SourceCodes/Boilerplates/Application.IoC/UnitOfWork.cs
3,664
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace OneFitnessVue.Model.UserMaster { [Table("Usermaster")] public class UserMasterModel { [Key] public int UserId { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailId { get; set; } public string MobileNo { get; set; } public string Gender { get; set; } public bool Status { get; set; } public string PasswordHash { get; set; } public bool IsFirstLogin { get; set; } = false; public DateTime IsFirstLoginDate { get; set; } public DateTime? CreatedOn { get; set; } = DateTime.Now; public DateTime? ModifiedOn { get; set; } public int? CreatedBy { get; set; } public int? ModifiedBy { get; set; } } }
35.37037
64
0.620942
[ "MIT" ]
guptamcts/FitnessProject
OneFitnessVueSolution/OneFitnessVue.Model/UserMaster/UserMasterModel.cs
957
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class daughter01 : Story { void op1() { Game game = GameObject.Find("game").GetComponent<Game>(); game.UpdateStatus(0, 10, 0, 0); game.AddTriggeredEvent("daughter01" + "_" + "1"); game.Next(); } void op2() { Game game = GameObject.Find("game").GetComponent<Game>(); game.UpdateStatus(0, 10, 0, 0); game.AddTriggeredEvent("daughter01" + "_" + "2"); game.Next(); } }
23.565217
65
0.581181
[ "MIT" ]
wsm1992/homeless
Assets/daughter01.cs
544
C#
using Alabo.Web.Mvc.Attributes; using System.Collections.Generic; namespace Alabo.Framework.Core.WebUis.Models.Lists { /// <summary> /// 通过列表输出,对应前端Api接口 /// </summary> [ClassProperty(Name = "链接")] public class ListOutput : BaseComponent { /// <summary> /// 样式格式,不通的数据可能显示不同的格式 /// </summary> public int StyleType { get; set; } = 1; /// <summary> /// 返回数据源的总页数 /// </summary> public long TotalSize { get; set; } /// <summary> /// Api数据列表 /// </summary> public List<ListItem> ApiDataList { get; set; } = new List<ListItem>(); } public class ListItem { /// <summary> /// 主键ID /// </summary> public object Id { get; set; } /// <summary> /// 网址 /// </summary> public string Url { get; set; } /// <summary> /// 图标或图片 /// </summary> public string Image { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 标题额外数据 /// </summary> public string Extra { get; set; } /// <summary> /// 描述,可以通过拼接完成 /// </summary> public string Intro { get; set; } } }
22.311475
79
0.457017
[ "MIT" ]
tongxin3267/alabo
src/01.framework/02-Alabo.Framework.Core/WebUis/Models/Lists/ListOutput.cs
1,513
C#
// <autogenerated /> #nullable enable using System; using System.Collections.Generic; namespace UseDeptorygen.Samples.Mixin { internal partial class MixinFactory : IMixinFactory , IDisposable { private Service2? _ResolveService2Cache; private ClientB? _ResolveClientBCache; private Service? _ResolveServiceCache; private ClientA? _ResolveClientACache; public MixinFactory() { } public Service2 ResolveService2() { return _ResolveService2Cache ??= new Service2(); } public ClientB ResolveClientB() { return _ResolveClientBCache ??= new ClientB(ResolveService2()); } public Service ResolveService() { return _ResolveServiceCache ??= new Service(); } public ClientA ResolveClientA() { return _ResolveClientACache ??= new ClientA(ResolveService()); } public void Dispose() { } } }
19.204545
66
0.727811
[ "MIT" ]
NumAniCloud/Deptorygen
Source/Deptorygen.XUnit/DataSource/UnitTests/Mixin2/Expected/MixinFactory.g.cs
847
C#
using HarmonyLib; using SolastaCommunityExpansion.CustomFeatureDefinitions; using SolastaModApi.Infrastructure; using System.Collections.Generic; using UnityEngine; namespace SolastaCommunityExpansion.Patches.PowerSharedPool { static class RulesetCharacterPatch { [HarmonyPatch(typeof(RulesetCharacter), "UsePower")] internal static class RulesetCharacter_UsePower { public static void Postfix(RulesetCharacter __instance, RulesetUsablePower usablePower) { __instance.UpdateUsageForPowerPool(usablePower, usablePower.PowerDefinition.CostPerUse); } } [HarmonyPatch(typeof(RulesetCharacter), "RepayPowerUse")] internal static class RulesetCharacter_RepayPowerUse { public static void Postfix(RulesetCharacter __instance, RulesetUsablePower usablePower) { __instance.UpdateUsageForPowerPool(usablePower, -usablePower.PowerDefinition.CostPerUse); } } public static void UpdateUsageForPowerPool(this RulesetCharacter character, RulesetUsablePower modifiedPower, int poolUsage) { if (!(modifiedPower.PowerDefinition is IPowerSharedPool)) { return; } IPowerSharedPool sharedPoolPower = (IPowerSharedPool)modifiedPower.PowerDefinition; foreach (RulesetUsablePower poolPower in character.UsablePowers) { if (poolPower.PowerDefinition == sharedPoolPower.GetUsagePoolPower()) { int maxUses = GetMaxUsesForPool(poolPower, character); int remainingUses = Mathf.Clamp(poolPower.RemainingUses - poolUsage, 0, maxUses); poolPower.SetField("remainingUses", remainingUses); AssignUsesToSharedPowersForPool(character, poolPower, remainingUses, maxUses); return; } } } [HarmonyPatch(typeof(RulesetCharacter), "GrantPowers")] internal static class RulesetCharacter_GrantPowers { public static void Postfix(RulesetCharacter __instance) { RechargeLinkedPowers(__instance, RuleDefinitions.RestType.LongRest); } } [HarmonyPatch(typeof(RulesetCharacter), "ApplyRest")] internal static class RulesetCharacter_ApplyRest { internal static void Postfix(RulesetCharacter __instance, RuleDefinitions.RestType restType, bool simulate, TimeInfo restStartTime) { if (!simulate) { RechargeLinkedPowers(__instance, restType); } // The player isn't recharging the shared pool features, just the pool. // Hide the features that use the pool from the UI. foreach (FeatureDefinition feature in __instance.RecoveredFeatures.ToArray()) { if (feature is IPowerSharedPool) { __instance.RecoveredFeatures.Remove(feature); } } } } public static void RechargeLinkedPowers(RulesetCharacter character, RuleDefinitions.RestType restType) { List<FeatureDefinitionPower> pointPoolPowerDefinitions = new List<FeatureDefinitionPower>(); foreach (RulesetUsablePower usablePower in character.UsablePowers) { if (usablePower.PowerDefinition is IPowerSharedPool) { FeatureDefinitionPower pointPoolPower = ((IPowerSharedPool)usablePower.PowerDefinition).GetUsagePoolPower(); if (!pointPoolPowerDefinitions.Contains(pointPoolPower)) { // Only add to recharge here if it (recharges on a short rest and this is a short or long rost) or // it recharges on a long rest and this is a long rest. if (((pointPoolPower.RechargeRate == RuleDefinitions.RechargeRate.ShortRest && (restType == RuleDefinitions.RestType.ShortRest || restType == RuleDefinitions.RestType.LongRest)) || (pointPoolPower.RechargeRate == RuleDefinitions.RechargeRate.LongRest && restType == RuleDefinitions.RestType.LongRest))) { pointPoolPowerDefinitions.Add(pointPoolPower); } } } } // Find the UsablePower of the point pool powers. foreach (RulesetUsablePower poolPower in character.UsablePowers) { if (pointPoolPowerDefinitions.Contains(poolPower.PowerDefinition)) { int poolSize = GetMaxUsesForPool(poolPower, character); poolPower.SetField("remainingUses", poolSize); AssignUsesToSharedPowersForPool(character, poolPower, poolSize, poolSize); } } } private static void AssignUsesToSharedPowersForPool(RulesetCharacter character, RulesetUsablePower poolPower, int remainingUses, int totalUses) { // Find powers that rely on this pool foreach (RulesetUsablePower usablePower in character.UsablePowers) { if (usablePower.PowerDefinition is IPowerSharedPool) { FeatureDefinitionPower pointPoolPower = ((IPowerSharedPool)usablePower.PowerDefinition).GetUsagePoolPower(); if (pointPoolPower == poolPower.PowerDefinition) { usablePower.SetField("maxUses", totalUses / usablePower.PowerDefinition.CostPerUse); usablePower.SetField("remainingUses", remainingUses / usablePower.PowerDefinition.CostPerUse); } } } } private static int GetMaxUsesForPool(RulesetUsablePower poolPower, RulesetCharacter character) { int totalPoolSize = poolPower.MaxUses; foreach (RulesetUsablePower modifierPower in character.UsablePowers) { if (modifierPower.PowerDefinition is IPowerPoolModifier) { FeatureDefinitionPower poolModifierDef = ((IPowerPoolModifier)modifierPower.PowerDefinition).GetUsagePoolPower(); if (poolModifierDef == poolPower.PowerDefinition) { totalPoolSize += modifierPower.MaxUses; } } } return totalPoolSize; } } }
45.390728
151
0.596148
[ "MIT" ]
CEDSS/SolastaCommunityExpansion
SolastaCommunityExpansion/Patches/PowerSharedPool/RulesetCharacterPatch.cs
6,856
C#
using System; using Scolari.Movement.MovementManaging; using Scolari.Pieces; namespace Scolari.Util { /// <summary> /// Implementation of the IPlayer interface. /// </summary> public class Player : IPlayer { public PlayerColor Color { get; } public IUser User { get; } public IPieceFactory PieceFactory { get; } public Player(IUser user, PlayerColor color) { this.User = user; this.Color = color; this.PieceFactory = new PieceFactory(this); } public override string ToString() { return "PlayerImpl [color=" + this.Color + ", user=" + this.User + "]"; } public override bool Equals(object obj) { return obj is Player player && Color == player.Color; } public override int GetHashCode() { return HashCode.Combine(Color); } } }
24.560976
84
0.525323
[ "MIT" ]
zucchero-sintattico/OOP20-Jhaturanga-C-Sharp
Scolari/Scolari/Util/Player.cs
1,009
C#
using YggdrAshill.Nuadha.Signalization; using YggdrAshill.Nuadha.Transformation; using YggdrAshill.Nuadha.Unitization; namespace YggdrAshill.Nuadha.Units { /// <summary> /// Defines <see cref="IModule"/> for pulsated button as hardware. /// </summary> public interface IPulsatedButtonHardware : IModule { /// <summary> /// Sends <see cref="Pulse"/> of <see cref="Signals.Touch"/> to software. /// </summary> IProduction<Pulse> Touch { get; } /// <summary> /// Sends <see cref="Pulse"/> of <see cref="Signals.Push"/> to software. /// </summary> IProduction<Pulse> Push { get; } } }
28.291667
81
0.606775
[ "MIT" ]
do-i-know-it/YggdrAshill.Nuadha
Units/Button/IPulsatedButtonHardware.cs
679
C#
using BrawlLib.Imaging; using BrawlLib.Internal; using BrawlLib.Internal.Drawing; using BrawlLib.Internal.IO; using BrawlLib.SSBB.Types; using BrawlLib.Wii.Textures; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace BrawlLib.SSBB.ResourceNodes { public unsafe class REFTNode : NW4RArcEntryNode, IImageSource { internal REFT* Header => (REFT*) WorkingUncompressed.Address; public override ResourceType ResourceFileType => ResourceType.REFT; [Browsable(false)] public int ImageCount => Children.Count(o => o is IImageSource i && i.ImageCount > 0); public Bitmap GetImage(int index) { return ((IImageSource) Children.Where(o => o is IImageSource i && i.ImageCount > 0).ToArray()[index]) .GetImage(0); } public override bool OnInitialize() { base.OnInitialize(); REFT* header = Header; if (_name == null) { _name = header->IdString; } return header->Table->_entries > 0; } private int _tableLen; public override int OnCalculateSize(bool force) { int size = 0x60; _tableLen = 0x8; foreach (ResourceNode n in Children) { _tableLen += n.Name.Length + 11; size += n.CalculateSize(force); } return size + (_tableLen = _tableLen.Align(0x20)); } public override void OnPopulate() { REFTypeObjectTable* table = Header->Table; REFTypeObjectEntry* Entry = table->First; for (int i = 0; i < table->_entries; i++, Entry = Entry->Next) { new REFTEntryNode {_name = Entry->Name, _offset = Entry->DataOffset, _length = Entry->DataLength + 0x20} .Initialize(this, new DataSource((byte*) table->Address + Entry->DataOffset, Entry->DataLength + 0x20)); } } public override void OnRebuild(VoidPtr address, int length, bool force) { REFT* header = (REFT*) address; header->_linkPrev = 0; header->_linkNext = 0; header->_padding = 0; header->_dataLength = length - 0x18; header->_dataOffset = 0x48; header->_header._tag = header->_tag = REFT.Tag; header->_header.Endian = Endian.Big; header->_header._version = 7; header->_header._length = length; header->_header._firstOffset = 0x10; header->_header._numEntries = 1; header->IdString = Name; REFTypeObjectTable* table = (REFTypeObjectTable*) ((byte*) header + header->_dataOffset + 0x18); table->_entries = (ushort) Children.Count; table->_pad = 0; table->_length = _tableLen; REFTypeObjectEntry* entry = table->First; int offset = _tableLen; foreach (ResourceNode n in Children) { entry->Name = n.Name; entry->DataOffset = offset; entry->DataLength = n._calcSize - 0x20; n.Rebuild((VoidPtr) table + offset, n._calcSize, force); offset += n._calcSize; entry = entry->Next; } } internal static ResourceNode TryParse(DataSource source, ResourceNode parent) { return ((REFT*) source.Address)->_tag == REFT.Tag ? new REFTNode() : null; } } public unsafe class REFTEntryNode : ResourceNode, IImageSource, IColorSource { internal REFTImageHeader* Header => (REFTImageHeader*) WorkingUncompressed.Address; public override ResourceType ResourceFileType => ResourceType.REFTImage; public int _offset; public int _length; private WiiPixelFormat _format; private WiiPaletteFormat _pltFormat; private int numColors, _imgLen, _pltLen; private int _width, _height; private uint _unk; private int _lod; private float _lodBias; internal uint _minFltr; internal uint _magFltr; [Browsable(false)] public bool HasPlt => Header->_colorCount > 0; //[Category("REFT Image")] //public uint Unknown { get { return _unk; } } [Category("REFT Image")] public WiiPixelFormat TextureFormat => _format; [Category("REFT Image")] public WiiPaletteFormat PaletteFormat => _pltFormat; [Category("REFT Image")] public int Colors => numColors; [Category("REFT Image")] public int Width => _width; [Category("REFT Image")] public int Height => _height; [Category("REFT Image")] public int ImageLength => _imgLen; [Category("REFT Image")] public int PaletteLength => _pltLen; [Category("REFT Image")] public int LevelOfDetail => _lod; [Category("REFT Image")] public MatTextureMinFilter MinFilter { get => (MatTextureMinFilter) _minFltr; set { _minFltr = (uint) value; SignalPropertyChange(); } } [Category("REFT Image")] public MatTextureMagFilter MagFilter { get => (MatTextureMagFilter) _magFltr; set { _magFltr = (uint) value; SignalPropertyChange(); } } [Category("REFT Image")] public float LODBias { get => _lodBias; set { _lodBias = value; SignalPropertyChange(); } } [Category("REFT Entry")] public int REFTOffset => _offset; [Category("REFT Entry")] public int DataLength => _length; [Browsable(false)] public int ImageCount => LevelOfDetail; public Bitmap GetImage(int index) { try { if (HasPlt) { return TextureConverter.DecodeIndexed((byte*) Header + 0x20, Width, Height, Palette, index + 1, _format); } return TextureConverter.Decode((byte*) Header + 0x20, Width, Height, index + 1, _format); } catch { return null; } } private ColorPalette _palette; [Browsable(false)] public ColorPalette Palette { get => HasPlt ? _palette ?? (_palette = TextureConverter.DecodePalette((byte*) Header + 0x20 + Header->_imagelen, Colors, _pltFormat)) : null; set { _palette = value; SignalPropertyChange(); } } #region IColorSource Members public bool HasPrimary(int id) { return false; } public ARGBPixel GetPrimaryColor(int id) { return new ARGBPixel(); } public void SetPrimaryColor(int id, ARGBPixel color) { } [Browsable(false)] public string PrimaryColorName(int id) { return null; } [Browsable(false)] public int TypeCount => 1; [Browsable(false)] public int ColorCount(int id) { return Palette != null ? Palette.Entries.Length : 0; } public ARGBPixel GetColor(int index, int id) { return Palette != null ? (ARGBPixel) Palette.Entries[index] : new ARGBPixel(); } public void SetColor(int index, int id, ARGBPixel color) { if (Palette != null) { Palette.Entries[index] = (Color) color; SignalPropertyChange(); } } public bool GetColorConstant(int id) { return false; } public void SetColorConstant(int id, bool constant) { } #endregion public override bool OnInitialize() { base.OnInitialize(); _unk = Header->_unknown; _format = (WiiPixelFormat) Header->_format; _pltFormat = (WiiPaletteFormat) Header->_pltFormat; numColors = Header->_colorCount; _imgLen = (int) Header->_imagelen; _width = Header->_width; _height = Header->_height; _pltLen = (int) Header->_pltSize; _lod = Header->_mipmap + 1; _minFltr = Header->_min_filt; _magFltr = Header->_mag_filt; return false; } public override void OnRebuild(VoidPtr address, int length, bool force) { base.OnRebuild(address, length, force); REFTImageHeader* header = (REFTImageHeader*) address; header->Set((byte) _minFltr, (byte) _magFltr, (byte) _lodBias); } public void Replace(Bitmap bmp) { FileMap tMap; if (HasPlt) { tMap = TextureConverter.Get(_format).EncodeREFTTextureIndexed(bmp, LevelOfDetail, Palette.Entries.Length, PaletteFormat, QuantizationAlgorithm.MedianCut); } else { tMap = TextureConverter.Get(_format).EncodeREFTTexture(bmp, LevelOfDetail, WiiPaletteFormat.IA8); } ReplaceRaw(tMap); } public override unsafe void Replace(string fileName) { string ext = Path.GetExtension(fileName); Bitmap bmp; if (string.Equals(ext, ".tga", StringComparison.OrdinalIgnoreCase)) { bmp = TGA.FromFile(fileName); } else if ( string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".tif", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".tiff", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".bmp", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".jpg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".jpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".gif", StringComparison.OrdinalIgnoreCase)) { bmp = (Bitmap) Image.FromFile(fileName); } else { base.Replace(fileName); return; } using (Bitmap b = bmp) { Replace(b); } } public override void Export(string outPath) { if (outPath.EndsWith(".png")) { using (Bitmap bmp = GetImage(0)) { bmp.Save(outPath, ImageFormat.Png); } } else if (outPath.EndsWith(".tga")) { using (Bitmap bmp = GetImage(0)) { bmp.SaveTGA(outPath); } } else if (outPath.EndsWith(".tiff") || outPath.EndsWith(".tif")) { using (Bitmap bmp = GetImage(0)) { bmp.Save(outPath, ImageFormat.Tiff); } } else if (outPath.EndsWith(".bmp")) { using (Bitmap bmp = GetImage(0)) { bmp.Save(outPath, ImageFormat.Bmp); } } else if (outPath.EndsWith(".jpg") || outPath.EndsWith(".jpeg")) { using (Bitmap bmp = GetImage(0)) { bmp.Save(outPath, ImageFormat.Jpeg); } } else if (outPath.EndsWith(".gif")) { using (Bitmap bmp = GetImage(0)) { bmp.Save(outPath, ImageFormat.Gif); } } else { base.Export(outPath); } } } }
31.484694
120
0.514746
[ "MIT" ]
RedStoneMatt/BrawlCrate
BrawlLib/SSBB/ResourceNodes/Graphics/REFTNode.cs
12,344
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Uses an ordered list of CameraProperties modifier functions to modify an instance of CameraProperties. /// Camera properties can be edited or overwritten. /// This is handy for easily performing tweaks to a camera for special effects. /// Delegate functions can also overwrite the properties for a set length of time. This could be used to mimic a multi camera setup. /// </summary> [System.Serializable] public class CameraPropertiesBuilderQueue { public delegate void UpdateCameraPropertiesDelegate (float deltaTime); public delegate void ModifyCameraPropertiesDelegate (ref CameraProperties SpaceCameraProperties); // [SerializeField, Disable] private List<SetCameraPropertiesDelegateQueueItem> modifiers = new List<SetCameraPropertiesDelegateQueueItem>(); /// <summary> /// Uses a sort index and a delegate to edit camera properties. /// </summary> [System.Serializable] private class SetCameraPropertiesDelegateQueueItem { public string name; // Lower sort indexes are executed first. public int sortIndex {get; private set;} public UpdateCameraPropertiesDelegate updateCameraPropertiesDelegate {get; private set;} public ModifyCameraPropertiesDelegate setCameraPropertiesDelegate {get; private set;} public SetCameraPropertiesDelegateQueueItem (int sortIndex, UpdateCameraPropertiesDelegate updateCameraPropertiesDelegate, ModifyCameraPropertiesDelegate setCameraPropertiesDelegate) { this.sortIndex = sortIndex; this.updateCameraPropertiesDelegate = updateCameraPropertiesDelegate; this.setCameraPropertiesDelegate = setCameraPropertiesDelegate; } } public void Add (UpdateCameraPropertiesDelegate updateCameraPropertiesDelegate, ModifyCameraPropertiesDelegate setCameraPropertiesDelegate) { modifiers.Add(new SetCameraPropertiesDelegateQueueItem(modifiers.Count, updateCameraPropertiesDelegate, setCameraPropertiesDelegate)); } public void Add (UpdateCameraPropertiesDelegate updateCameraPropertiesDelegate, ModifyCameraPropertiesDelegate setCameraPropertiesDelegate, int sortIndex) { modifiers.Add(new SetCameraPropertiesDelegateQueueItem(sortIndex, updateCameraPropertiesDelegate, setCameraPropertiesDelegate)); modifiers.Sort((x, y) => x.sortIndex.CompareTo(y.sortIndex)); } public void Add (UpdateCameraPropertiesDelegate updateCameraPropertiesDelegate, ModifyCameraPropertiesDelegate setCameraPropertiesDelegate, int sortIndex, string name) { var queueItem = new SetCameraPropertiesDelegateQueueItem(sortIndex, updateCameraPropertiesDelegate, setCameraPropertiesDelegate); queueItem.name = name; modifiers.Add(queueItem); modifiers.Sort((x, y) => x.sortIndex.CompareTo(y.sortIndex)); } public bool Remove (ModifyCameraPropertiesDelegate setCameraPropertiesDelegate) { for (int i = modifiers.Count - 1; i >= 0; i--) { SetCameraPropertiesDelegateQueueItem queueItem = modifiers [i]; if (queueItem.setCameraPropertiesDelegate == setCameraPropertiesDelegate) { modifiers.RemoveAt(i); return true; } } return false; } public void Update (float deltaTime) { foreach(var modifier in modifiers) { modifier.updateCameraPropertiesDelegate(deltaTime); } } public void Generate (ref CameraProperties properties) { foreach(var modifier in modifiers) { modifier.setCameraPropertiesDelegate(ref properties); } } }
47.054795
186
0.811354
[ "MIT" ]
tomkail/UnityX
Assets/UnityX/Scripts/Extensions/Camera/Camera Properties/CameraPropertiesBuilderQueue.cs
3,435
C#
using System.Collections.Generic; namespace Halogen { public static class Constants { public const string KeyValueDelimiter = "│"; public const string KeyDelimiter = "║"; public static IReadOnlyList<string> SupportedExtensions = new List<string> { "mkv", "ogv", "avi", "mp4", "m4p", "m4v", "mpeg", "mpg", "mpe", "mpv", "mpg", "m2v", "mov" }.AsReadOnly(); } }
21.807692
82
0.435626
[ "MIT" ]
agc93/halogen
src/Halogen.Core/Constants.cs
571
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; namespace Sportradar.OddsFeed.SDK.Entities.REST { /// <summary> /// Defines a contract implemented by classes representing a match status /// </summary> /// <seealso cref="ICompetitionStatus" /> public interface IMatchStatus : ICompetitionStatus { /// <summary> /// Gets the <see cref="IEventClock"/> instance describing the timings in the current event /// </summary> /// <value>The <see cref="IEventClock"/> instance describing the timings in the current event</value> IEventClock EventClock { get; } /// <summary> /// Gets the list of <see cref="IPeriodScore"/> /// </summary> /// <value>The list of <see cref="IPeriodScore"/></value> IEnumerable<IPeriodScore> PeriodScores { get; } /// <summary> /// Gets the score of the home competitor competing on the associated sport event /// </summary> /// <value>The score of the home competitor competing on the associated sport event</value> decimal HomeScore { get; } /// <summary> /// Gets the score of the away competitor competing on the associated sport event /// </summary> /// <value>The score of the away competitor competing on the associated sport event</value> decimal AwayScore { get; } /// <summary> /// Asynchronously gets the match status /// </summary> /// <param name="culture">The culture used to get match status id and description</param> /// <returns>Returns the match status id and description in selected culture</returns> Task<ILocalizedNamedValue> GetMatchStatusAsync(CultureInfo culture); } }
39.291667
109
0.645281
[ "Apache-2.0" ]
Furti87/UnifiedOddsSdkNet
src/Sportradar.OddsFeed.SDK.Entities.REST/IMatchStatus.cs
1,888
C#
namespace P03_SalesDatabase.Data.Models { using System.Collections.Generic; public class Product { public Product() { this.Sales = new List<Sale>(); } public int ProductId { get; set; } public string Name { get; set; } public double Quantity { get; set; } public decimal Price { get; set; } public string Description { get; set; } public ICollection<Sale> Sales { get; set; } } }
19.56
53
0.558282
[ "MIT" ]
TihomirIvanovIvanov/SoftUni
C#DBFundamentals/DB-Advanced-Entity-Framework-Core/03DBCodeFirst/ExercisesCodeFirst/P03_SalesDatabase/Data/Models/Product.cs
491
C#
using Coldairarrow.Entity.PB; using Coldairarrow.Util; using System.Collections.Generic; using System.Threading.Tasks; namespace Coldairarrow.Business.PB { public interface IPB_TrayZoneBusiness { Task<PageResult<PB_TrayZone>> GetDataListAsync(PageInput<ConditionDTO> input); Task<List<PB_TrayZone>> GetDataListAsync(string typeId); Task<PB_TrayZone> GetTheDataAsync(string id); Task AddDataAsync(PB_TrayZone data); Task UpdateDataAsync(PB_TrayZone data); Task DeleteDataAsync(List<string> ids); } }
32.941176
86
0.741071
[ "MIT" ]
GerryGe/WMS
src/Coldairarrow.IBusiness/PB/IPB_TrayZoneBusiness.cs
562
C#
namespace Opal.Logging { public enum Importance { /// <summary> /// A high importance message. /// </summary> High = 0, /// <summary> /// A normal importance message /// </summary> Normal = 1, /// <summary> /// A low importance message /// </summary> Low = 2 } }
19.05
39
0.433071
[ "Apache-2.0" ]
mrfichtn/opal
oc/Logging/Importance.cs
383
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using WInterop.Errors; using WInterop.Memory.Native; namespace WInterop.Memory { public static partial class Memory { /// <summary> /// The handle for the process heap. /// </summary> public static IntPtr ProcessHeap = Imports.GetProcessHeap(); /// <summary> /// Allocate memory on the process heap. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if running in 32 bit and <paramref name="bytes"/> is greater than uint.MaxValue.</exception> public static IntPtr HeapAllocate(ulong bytes, bool zeroMemory = true) { return HeapAllocate(bytes, zeroMemory, IntPtr.Zero); } /// <summary> /// Allocate memory on the given heap. /// </summary> /// <param name="heap">If IntPtr.Zero will use the process heap.</param> /// <exception cref="OverflowException">Thrown if running in 32 bit and <paramref name="bytes"/> is greater than uint.MaxValue.</exception> public static IntPtr HeapAllocate(ulong bytes, bool zeroMemory, IntPtr heap) { return Imports.HeapAlloc( hHeap: heap == IntPtr.Zero ? ProcessHeap : heap, dwFlags: zeroMemory ? MemoryDefines.HEAP_ZERO_MEMORY : 0, dwBytes: (UIntPtr)bytes); } /// <summary> /// Reallocate memory on the process heap. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if running in 32 bit and <paramref name="bytes"/> is greater than uint.MaxValue.</exception> public static IntPtr HeapReallocate(IntPtr memory, ulong bytes, bool zeroMemory = true) { return HeapReallocate(memory, bytes, zeroMemory, IntPtr.Zero); } /// <summary> /// Reallocate memory on the given heap. /// </summary> /// <param name="heap">If IntPtr.Zero will use the process heap.</param> /// <exception cref="OverflowException">Thrown if running in 32 bit and <paramref name="bytes"/> is greater than uint.MaxValue.</exception> public static IntPtr HeapReallocate(IntPtr memory, ulong bytes, bool zeroMemory, IntPtr heap) { return Imports.HeapReAlloc( hHeap: heap == IntPtr.Zero ? ProcessHeap : heap, dwFlags: zeroMemory ? MemoryDefines.HEAP_ZERO_MEMORY : 0, lpMem: memory, dwBytes: (UIntPtr)bytes); } /// <summary> /// Free the specified memory on the process heap. /// </summary> public static bool HeapFree(IntPtr memory) { return HeapFree(memory, IntPtr.Zero); } /// <summary> /// Free the specified memory on the given heap. /// </summary> /// <param name="heap">If IntPtr.Zero will use the process heap.</param> public static bool HeapFree(IntPtr memory, IntPtr heap) { return Imports.HeapFree( hHeap: heap == IntPtr.Zero ? ProcessHeap : heap, dwFlags: 0, lpMem: memory); } public static void LocalFree(IntPtr memory) { if (Imports.LocalFree(memory) != IntPtr.Zero) Error.ThrowLastError(); } public static GlobalHandle GlobalAlloc(ulong bytes, GlobalMemoryFlags flags) { HGLOBAL handle = Imports.GlobalAlloc(flags, (UIntPtr)bytes); if (handle.Value == IntPtr.Zero) Error.ThrowLastError(); return new GlobalHandle(handle, bytes); } public static IntPtr GlobalLock(GlobalHandle handle) { IntPtr memory = Imports.GlobalLock(handle.HGLOBAL); if (memory == IntPtr.Zero) Error.ThrowLastError(); return memory; } public static void GlobalUnlock(GlobalHandle handle) { if (!Imports.GlobalUnlock(handle.HGLOBAL)) Error.ThrowIfLastErrorNot(WindowsError.NO_ERROR); } public static void GlobalFree(HGLOBAL handle) { if (Imports.GlobalFree(handle).Value != IntPtr.Zero) Error.ThrowLastError(); } } }
38.111111
157
0.592061
[ "MIT" ]
RussKie/WInterop
src/WInterop.Desktop/Memory/Memory.cs
4,461
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Glimpse.Core.Framework; using Ninject; namespace NuGetGallery.Diagnostics { public class NinjectGlimpseServiceLocator : IServiceLocator { public ICollection<T> GetAllInstances<T>() where T : class { var ninjectResources = Container.Kernel.GetAll<T>().ToList(); // Glimpse interprets an empty collection to mean: I'm overriding your defaults and telling you NOT to load anythig // However, we want an empty collection to indicate to Glimpse that it should use the default. Returning null does that. if (!ninjectResources.Any()) { return null; } return ninjectResources; } public T GetInstance<T>() where T : class { return Container.Kernel.TryGet<T>(); } } }
30.8
132
0.630952
[ "ECL-2.0", "Apache-2.0" ]
JetBrains/ReSharperGallery
src/NuGetGallery/Diagnostics/NinjectGlimpseServiceLocator.cs
926
C#
using System; using System.Collections.Generic; namespace PROProtocol { public class PokemonStats { public int Health; public int Attack; public int Defence; public int SpAttack; public int SpDefence; public int Speed; public PokemonStats() { } internal PokemonStats(string[] data, int index, int health = -1) { Attack = Convert.ToInt32(data[index++]); Defence = Convert.ToInt32(data[index++]); Speed = Convert.ToInt32(data[index++]); SpAttack = Convert.ToInt32(data[index++]); SpDefence = Convert.ToInt32(data[index++]); if (health == -1) { Health = Convert.ToInt32(data[index]); } else { Health = health; } } public int GetStat(StatType stat) { switch (stat) { case StatType.Health: return Health; case StatType.Attack: return Attack; case StatType.Defence: return Defence; case StatType.SpAttack: return SpAttack; case StatType.SpDefence: return SpDefence; case StatType.Speed: return Speed; } return 0; } public bool HasOnly(HashSet<StatType> types) { if ((!types.Contains(StatType.Health) && Health > 0) || (!types.Contains(StatType.Attack) && Attack > 0) || (!types.Contains(StatType.Defence) && Defence > 0) || (!types.Contains(StatType.SpAttack) && SpAttack > 0) || (!types.Contains(StatType.SpDefence) && SpDefence > 0) || (!types.Contains(StatType.Speed) && Speed > 0)) { return false; } return true; } public bool HasOnly(StatType type) { if ((type != StatType.Health && Health > 0) || (type != StatType.Attack && Attack > 0) || (type != StatType.Defence && Defence > 0) || (type != StatType.SpAttack && SpAttack > 0) || (type != StatType.SpDefence && SpDefence > 0) || (type != StatType.Speed && Speed > 0)) { return false; } return true; } } }
31.105882
74
0.442133
[ "MIT" ]
MeltWS/Proshine
PROProtocol/PokemonStats.cs
2,646
C#
using System; using System.Collections.Generic; using System.Text; namespace H6.WeJobTasks.Configuration { public class TaskDefinition { /// <summary> /// name of assembly where is task definition /// </summary> public string Assembly { get; set; } /// <summary> /// Namespace where is task definition /// </summary> public string Namespace { get; set; } /// <summary> /// Name of class /// </summary> public string Class { get; set; } //required /// <summary> /// Minutes after midnight for run task /// </summary> public int RunAfterMidnight { get; set; } //default 0 /// <summary> /// Period [s] - how often will task run /// </summary> public int Period { get; set; } = 300; /// <summary> /// Maximum [s] task runtime /// </summary> public int Timeout { get; set; } = 10 * 60; } }
22.35
57
0.583893
[ "Apache-2.0" ]
JOhugo6/H6
src/H6.WeJobTasks/Configuration/TaskDefinition.cs
896
C#
using System.Diagnostics; using System.Linq; namespace Gadgetry.Channels; /// <summary> /// Represents a hard-typed writer for a <see cref="GadgetRuntimeChannel{TModel}"/> during a <see cref="GadgetRuntime"/> execution. /// </summary> public class GadgetRuntimeChannelWriter<TModel> : IGadgetRuntimeChannelWriter { /// <summary> /// The template used to construct this <see cref="GadgetRuntimeChannelWriter{TModel}"/>. /// </summary> public GadgetChannelWriter<TModel> Template { get; } /// <summary> /// The <see cref="GadgetRuntimeChannel{TModel}"/> destination that this <see cref="GadgetRuntimeChannelWriter{TModel}"/> writes to. /// </summary> public GadgetRuntimeChannel<TModel> Destination { get; } /// <summary> /// A boolean value indicating whether this <see cref="GadgetRuntimeChannelWriter{TModel}"/> has completed writing. /// </summary> /// <returns><c>true</c> if this <see cref="GadgetRuntimeChannelWriter{TModel}"/> has completed writing; otherwise <c>false</c>.</returns> public bool HasCompletedWriting { get; private set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] IGadgetChannelWriter IGadgetRuntimeChannelWriter.Template => Template; [DebuggerBrowsable(DebuggerBrowsableState.Never)] IGadgetRuntimeChannel IGadgetRuntimeChannelWriter.Destination => Destination; internal GadgetRuntimeChannelWriter( GadgetChannelWriter<TModel> template, GadgetRuntimeChannel<TModel> destination) { Template = template; Destination = destination; } /// <inheritdoc/> public void CompleteWriting() { Destination.state.mutex.WaitOne(); try { HasCompletedWriting = true; if (Destination.Writers.All(writer => writer.HasCompletedWriting)) { Destination.InnerChannel.Writer.TryComplete(); } } finally { Destination.state.mutex.ReleaseMutex(); } } /// <inheritdoc/> public override string ToString() { return $"'write to '{Destination.Template.Identifier}'"; } }
30.936508
139
0.741919
[ "Apache-2.0" ]
Fydar/Gadgetry
src/Gadgetry.Channels/GadgetRuntimeChannelWriter.cs
1,951
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /* * * Base64Transform.cs * * Author: bal * */ // This file contains two ICryptoTransforms: ToBase64Transform and FromBase64Transform // they may be attached to a CryptoStream in either read or write mode namespace System.Security.Cryptography { using System; using System.IO; using System.Text; /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64TransformMode"]/*' /> [Serializable] public enum FromBase64TransformMode { /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64TransformMode.IgnoreWhiteSpaces"]/*' /> IgnoreWhiteSpaces = 0, /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64TransformMode.DoNotIgnoreWhiteSpaces"]/*' /> DoNotIgnoreWhiteSpaces = 1, } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform"]/*' /> public class ToBase64Transform : ICryptoTransform { private ASCIIEncoding asciiEncoding = new ASCIIEncoding(); // converting to Base64 takes 3 bytes input and generates 4 bytes output /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.InputBlockSize"]/*' /> public int InputBlockSize { get { return(3); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.OutputBlockSize"]/*' /> public int OutputBlockSize { get { return(4); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.CanTransformMultipleBlocks"]/*' /> public bool CanTransformMultipleBlocks { get { return(false); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.CanReuseTransform"]/*' /> public virtual bool CanReuseTransform { get { return(true); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.TransformBlock"]/*' /> public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (asciiEncoding == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1")); // Do some validation, we let InternalBlockCopy do the destination array validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); // for now, only convert 3 bytes to 4 char[] temp = new char[4]; Convert.ToBase64CharArray(inputBuffer, inputOffset, 3, temp, 0); byte[] tempBytes = asciiEncoding.GetBytes(temp); if (tempBytes.Length != 4) throw new CryptographicException(Environment.GetResourceString( "Cryptography_SSE_InvalidDataSize" )); Buffer.InternalBlockCopy(tempBytes, 0, outputBuffer, outputOffset, tempBytes.Length); return(tempBytes.Length); } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.TransformFinalBlock"]/*' /> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (asciiEncoding == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1")); // Do some validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); // Convert.ToBase64CharArray already does padding, so all we have to check is that // the inputCount wasn't 0 // again, for now only a block at a time if (inputCount == 0) { return(new byte[0]); } else { char[] temp = new char[4]; Convert.ToBase64CharArray(inputBuffer, inputOffset, inputCount, temp, 0); byte[] tempBytes = asciiEncoding.GetBytes(temp); return(tempBytes); } } // must implement IDisposable, but in this case there's nothing to do. /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.IDisposable.Dispose"]/*' /> /// <internalonly/> void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.Clear"]/*' /> public void Clear() { ((IDisposable) this).Dispose(); } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="ToBase64Transform.Dispose"]/*' /> protected virtual void Dispose(bool disposing) { if (disposing) { asciiEncoding = null; } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.Finalize"]/*' /> ~ToBase64Transform() { Dispose(false); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform"]/*' /> public class FromBase64Transform : ICryptoTransform { private byte[] _inputBuffer = new byte[4]; private int _inputIndex; private FromBase64TransformMode _whitespaces; // Constructors /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.FromBase64Transform"]/*' /> public FromBase64Transform() : this(FromBase64TransformMode.IgnoreWhiteSpaces) {} /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.FromBase64Transform1"]/*' /> public FromBase64Transform(FromBase64TransformMode whitespaces) { _whitespaces = whitespaces; _inputIndex = 0; } // converting from Base64 generates 3 bytes output from each 4 bytes input block /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.InputBlockSize"]/*' /> public int InputBlockSize { get { return(1); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.OutputBlockSize"]/*' /> public int OutputBlockSize { get { return(3); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.CanTransformMultipleBlocks"]/*' /> public bool CanTransformMultipleBlocks { get { return(false); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.CanReuseTransform"]/*' /> public virtual bool CanReuseTransform { get { return(true); } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.TransformBlock"]/*' /> public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { byte[] temp = new byte[inputCount]; char[] tempChar; int effectiveCount; // Do some validation, we let InternalBlockCopy do the destination array validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); if (_inputBuffer == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1")); if (_whitespaces == FromBase64TransformMode.IgnoreWhiteSpaces) { temp = DiscardWhiteSpaces(inputBuffer, inputOffset, inputCount); effectiveCount = temp.Length; } else { Buffer.InternalBlockCopy(inputBuffer, inputOffset, temp, 0, inputCount); effectiveCount = inputCount; } if (effectiveCount + _inputIndex < 4) { Buffer.InternalBlockCopy(temp, 0, _inputBuffer, _inputIndex, effectiveCount); _inputIndex += effectiveCount; return 0; } // Get the number of 4 bytes blocks to transform int numBlocks = (effectiveCount + _inputIndex) / 4; byte[] transformBuffer = new byte[_inputIndex + effectiveCount]; Buffer.InternalBlockCopy(_inputBuffer, 0, transformBuffer, 0, _inputIndex); Buffer.InternalBlockCopy(temp, 0, transformBuffer, _inputIndex, effectiveCount); _inputIndex = (effectiveCount + _inputIndex) % 4; Buffer.InternalBlockCopy(temp, effectiveCount - _inputIndex, _inputBuffer, 0, _inputIndex); tempChar = Encoding.ASCII.GetChars(transformBuffer, 0, 4*numBlocks); byte[] tempBytes = Convert.FromBase64CharArray(tempChar, 0, 4*numBlocks); Buffer.InternalBlockCopy(tempBytes, 0, outputBuffer, outputOffset, tempBytes.Length); return(tempBytes.Length); } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.TransformFinalBlock"]/*' /> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] temp = new byte[inputCount]; char[] tempChar; int effectiveCount; // Do some validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); if (_inputBuffer == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1")); if (_whitespaces == FromBase64TransformMode.IgnoreWhiteSpaces) { temp = DiscardWhiteSpaces(inputBuffer, inputOffset, inputCount); effectiveCount = temp.Length; } else { Buffer.InternalBlockCopy(inputBuffer, inputOffset, temp, 0, inputCount); effectiveCount = inputCount; } if (effectiveCount + _inputIndex < 4) { Reset(); return (new byte[0]); } // Get the number of 4 bytes blocks to transform int numBlocks = (effectiveCount + _inputIndex) / 4; byte[] transformBuffer = new byte[_inputIndex + effectiveCount]; Buffer.InternalBlockCopy(_inputBuffer, 0, transformBuffer, 0, _inputIndex); Buffer.InternalBlockCopy(temp, 0, transformBuffer, _inputIndex, effectiveCount); _inputIndex = (effectiveCount + _inputIndex) % 4; Buffer.InternalBlockCopy(temp, effectiveCount - _inputIndex, _inputBuffer, 0, _inputIndex); tempChar = Encoding.ASCII.GetChars(transformBuffer, 0, 4*numBlocks); byte[] tempBytes = Convert.FromBase64CharArray(tempChar, 0, 4*numBlocks); // reinitialize the transform Reset(); return(tempBytes); } private byte[] DiscardWhiteSpaces(byte[] inputBuffer, int inputOffset, int inputCount) { int i, iCount = 0; for (i=0; i<inputCount; i++) if (Char.IsWhiteSpace((char)inputBuffer[inputOffset + i])) iCount++; byte[] rgbOut = new byte[inputCount - iCount]; iCount = 0; for (i=0; i<inputCount; i++) if (!Char.IsWhiteSpace((char)inputBuffer[inputOffset + i])) { rgbOut[iCount++] = inputBuffer[inputOffset + i]; } return rgbOut; } // must implement IDisposable, which in this case means clearing the input buffer /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.IDisposable.Dispose"]/*' /> /// <internalonly/> void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Reset the state of the transform so it can be used again private void Reset() { _inputIndex = 0; } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.Clear"]/*' /> public void Clear() { ((IDisposable) this).Dispose(); } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.Dispose"]/*' /> protected virtual void Dispose(bool disposing) { // we always want to clear the input buffer if (disposing) { if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); _inputBuffer = null; _inputIndex = 0; } } /// <include file='doc\base64Transforms.uex' path='docs/doc[@for="FromBase64Transform.Finalize1"]/*' /> ~FromBase64Transform() { Dispose(false); } } }
50.07947
154
0.620206
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/clr/bcl/system/security/cryptography/base64transforms.cs
15,124
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BooksCatalogueAPI.Models { public class AzureStorageConfig { public string AccountName { get; set; } public string AccountKey { get; set; } public string QueueName { get; set; } public string ImageContainer { get; set; } public string ThumbnailContainer { get; set; } } }
25.470588
54
0.676674
[ "MIT" ]
IndraMahkota/BooksCatalogueAPI
Models/AzureStorageConfig.cs
435
C#
using System; using Master40.SimulationCore.Environment; using Master40.SimulationCore.Environment.Options; using MathNet.Numerics.Distributions; namespace Master40.SimulationCore.Helper.DistributionProvider { public class WorkTimeGenerator { public static WorkTimeGenerator Create(Configuration configuration, int salt = 0) { return new WorkTimeGenerator( seed: configuration.GetOption<Seed>().Value + salt , deviation: configuration.GetOption<WorkTimeDeviation>().Value , simNumber: configuration.GetOption<SimulationNumber>().Value); } public WorkTimeGenerator(int seed, double deviation, int simNumber) { var source = new Random(Seed: seed //TODO WARUM? //+ simNumber ); _distribution = new LogNormal(mu: 0, sigma: deviation, randomSource: source); } private readonly LogNormal _distribution; /// <summary> /// Returns LogNormal-distributed worktime. /// </summary> /// <param name="duration"></param> /// <returns></returns> public long GetRandomWorkTime(long duration) { long newDuration; while (true) { newDuration = (long)Math.Round(value: duration * _distribution.Sample(), mode: MidpointRounding.AwayFromZero); if (newDuration <= 3 * duration) break; } return newDuration > 1 ? newDuration : 1; } } }
36.666667
126
0.570909
[ "Apache-2.0" ]
s76527/ng-erp-4.0
Master40.SimulationCore/Helper/DistributionProvider/WorkTimeGenerator.cs
1,652
C#
/** * Copyright 2018 IBM Corp. 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. * 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 Newtonsoft.Json; namespace IBM.WatsonDeveloperCloud.SpeechToText.v1.Model { /// <summary> /// WordAlternativeResult. /// </summary> public class WordAlternativeResult : BaseModel { /// <summary> /// A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. /// </summary> [JsonProperty("confidence", NullValueHandling = NullValueHandling.Ignore)] public double? Confidence { get; set; } /// <summary> /// An alternative hypothesis for a word from the input audio. /// </summary> [JsonProperty("word", NullValueHandling = NullValueHandling.Ignore)] public string Word { get; set; } } }
33.175
94
0.68425
[ "Apache-2.0" ]
anlblci/dotnetwatson
src/IBM.WatsonDeveloperCloud.SpeechToText.v1/Model/WordAlternativeResult.cs
1,327
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.OpenGL.Legacy.Extensions.ARB { public static class ArbBindlessTextureOverloads { public static unsafe void GetVertexAttribL(this ArbBindlessTexture thisApi, [Flow(FlowDirection.In)] uint index, [Flow(FlowDirection.In)] ARB pname, [Flow(FlowDirection.Out)] Span<ulong> @params) { // SpanOverloader thisApi.GetVertexAttribL(index, pname, out @params.GetPinnableReference()); } public static unsafe void GetVertexAttribL(this ArbBindlessTexture thisApi, [Flow(FlowDirection.In)] uint index, [Flow(FlowDirection.In)] VertexAttribEnum pname, [Flow(FlowDirection.Out)] Span<ulong> @params) { // SpanOverloader thisApi.GetVertexAttribL(index, pname, out @params.GetPinnableReference()); } public static unsafe void ProgramUniformHandle(this ArbBindlessTexture thisApi, [Flow(FlowDirection.In)] uint program, [Flow(FlowDirection.In)] int location, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] ReadOnlySpan<ulong> values) { // SpanOverloader thisApi.ProgramUniformHandle(program, location, count, in values.GetPinnableReference()); } public static unsafe void UniformHandle(this ArbBindlessTexture thisApi, [Flow(FlowDirection.In)] int location, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] ReadOnlySpan<ulong> value) { // SpanOverloader thisApi.UniformHandle(location, count, in value.GetPinnableReference()); } public static unsafe void VertexAttribL1(this ArbBindlessTexture thisApi, [Flow(FlowDirection.In)] uint index, [Flow(FlowDirection.In)] ReadOnlySpan<ulong> v) { // SpanOverloader thisApi.VertexAttribL1(index, in v.GetPinnableReference()); } } }
43.5
283
0.706258
[ "MIT" ]
ThomasMiz/Silk.NET
src/OpenGL/Extensions/Silk.NET.OpenGL.Legacy.Extensions.ARB/ArbBindlessTextureOverloads.gen.cs
2,349
C#
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using MbUnit.Framework; using Subtext.Framework.Configuration; namespace UnitTests.Subtext.Framework.Components.EnclosureTests { [TestFixture] public class MimetypeDetectionTests { [Test] public void CanReadMimetypeMappings() { Assert.AreEqual(6, MimeTypesMapper.Mappings.Count); } //[Test] //public void CanGetListOfTypes() //{ // NameValueCollection list = MimeTypesMapper.Mappings.List; // Assert.AreEqual("audio/mpeg", list[0]); //} [RowTest] [Row(".mp3", "audio/mpeg")] [Row(".zip", "application/octetstream")] [Row(".pdf", "application/octetstream")] [Row(".mp4", "video/mp4")] [Row(".avi", null)] public void MimetypeAreMappedCorrectly(string ext, string expectedType) { Assert.AreEqual(expectedType, MimeTypesMapper.Mappings.GetMimeType(ext)); } [Test] public void GetMimeType_WithNullExtension_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => MimeTypesMapper.Mappings.GetMimeType(null)); } [RowTest] [Row("http://mywonderfulldomain.com/podcast/episode1.mp3", "audio/mpeg")] [Row("http://code.google.com/codeclimbercommons/items/download/linklift-src.1.0.zip", "application/octetstream") ] [Row("http://polimi.it/ingdelsoftware/Corso di primo livello/lezione1.pdf", "application/octetstream")] [Row("http://wekarod.com/mvcscreencasts/screencast3.mp4", "video/mp4")] [Row("http://wekarod.com/mvcscreencasts/screencast3", null)] [Row("http://wekarod.com/mvcscreencasts/screencast3.qt", null)] public void CanDetectCorrectMimeType(string url, string expectedType) { Assert.AreEqual(expectedType, MimeTypesMapper.Mappings.ParseUrl(url)); } [Test] public void ParseUrl_WithNullUrl_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => MimeTypesMapper.Mappings.ParseUrl(null)); } [Test] public void ParseUrl_WithInvalidUrl_ThrowsArgumentException() { UnitTestHelper.AssertThrows<ArgumentException>(() => MimeTypesMapper.Mappings.ParseUrl("not/a valid\\url")); } } }
37.268293
120
0.615183
[ "MIT", "BSD-3-Clause" ]
Dashboard-X/SubText-2.5.2.0.src
UnitTests.Subtext/Framework/Components/EnclosureTests/MimetypeDetectionTests.cs
3,056
C#
// <copyright file="DailyTimesheet.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // </copyright> namespace Microsoft.Teams.Apps.Timesheet.Models { using System; /// <summary> /// Represents user's efforts details for particular calendar date. /// </summary> public class DailyTimesheet { /// <summary> /// Gets or sets project id. /// </summary> public Guid ProjectId { get; set; } /// <summary> /// Gets or sets project title. /// </summary> public string ProjectTitle { get; set; } /// <summary> /// Gets or sets task id. /// </summary> public Guid TaskId { get; set; } /// <summary> /// Gets or sets task title. /// </summary> public string TaskTitle { get; set; } /// <summary> /// Gets or sets calendar date for which efforts invested. /// </summary> public DateTime TimesheetDate { get; set; } /// <summary> /// Gets or sets utilized efforts. /// </summary> public short Hours { get; set; } } }
25.978261
72
0.548954
[ "MIT" ]
Ampliosoft/microsoft-teams-apps-timesheet
Source/Microsoft.Teams.Apps.Timesheet/Models/DailyTimesheet.cs
1,197
C#
using Decider.Csp.BaseTypes; using Decider.Csp.Integer; using System; namespace ConstrainedObjectBuilder.UnitTests { class DataBuilder : ObjectBuilder<Data> { public override Data Build() { IState<int> state = new StateInteger(Variables.Values, Constraints); state.StartSearch(out StateOperationResult result); if (result == StateOperationResult.Unsatisfiable) { throw new InvalidOperationException(); } var data = new Data(); foreach (var variable in Variables) { if (variable.Key.PropertyType == typeof(DateTime)) { variable.Key.SetValue(data, DateHelper.ToDateTime(variable.Value.Value)); } else { variable.Key.SetValue(data, variable.Value.Value); } } return data; } } }
22.540541
83
0.631894
[ "MIT" ]
leonverschuren/ConstrainedObjectBuilder
ConstrainedObjectBuilder.UnitTests/DataBuilder.cs
834
C#
using Esquio.EntityFrameworkCore.Store; using Esquio.EntityFrameworkCore.Store.Entities; using Esquio.UI.Api.Diagnostics; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Esquio.UI.Api.Features.Users.Add { public class AddPermissionRequestHandler : IRequestHandler<AddPermissionRequest> { private readonly StoreDbContext _storeDbContext; private readonly ILogger<AddPermissionRequestHandler> _logger; public AddPermissionRequestHandler(StoreDbContext storeDbContext,ILogger<AddPermissionRequestHandler> logger) { _storeDbContext = storeDbContext ?? throw new ArgumentNullException(nameof(storeDbContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<Unit> Handle(AddPermissionRequest request, CancellationToken cancellationToken) { var currentPermission = await _storeDbContext .Permissions .Where(p => p.SubjectId == request.SubjectId) .SingleOrDefaultAsync(cancellationToken); if ( currentPermission == null ) { _storeDbContext .Permissions .Add(new PermissionEntity() { SubjectId = request.SubjectId, ReadPermission = request.Read, WritePermission = request.Write, ManagementPermission = request.Manage }); await _storeDbContext.SaveChangesAsync(cancellationToken); return Unit.Value; } Log.SubjectIdAlreadyExist(_logger, request.SubjectId); throw new InvalidOperationException("SubjectId already exits on the store."); } } }
38.150943
118
0.623145
[ "Apache-2.0" ]
evacrespob/Esquio
src/Esquio.UI.Api/Features/Users/Add/AddPermissionRequestHandler.cs
2,024
C#
// // System.Net.WebConnection // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2003 Ximian, Inc (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Collections; using System.Net.Sockets; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; #if SECURITY_DEP using Mono.Security.Protocol.Tls; #endif namespace System.Net { enum ReadState { None, Status, Headers, Content, Aborted } class WebConnection { ServicePoint sPoint; Stream nstream; Socket socket; object socketLock = new object (); WebExceptionStatus status; WaitCallback initConn; bool keepAlive; byte [] buffer; static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone); EventHandler abortHandler; AbortHelper abortHelper; internal WebConnectionData Data; bool chunkedRead; ChunkStream chunkStream; Queue queue; bool reused; int position; bool busy; HttpWebRequest priority_request; NetworkCredential ntlm_credentials; bool ntlm_authenticated; bool unsafe_sharing; enum NtlmAuthState { None, Challenge, Response } NtlmAuthState connect_ntlm_auth_state; HttpWebRequest connect_request; bool ssl; bool certsAvailable; Exception connect_exception; static object classLock = new object (); static Type sslStream; static PropertyInfo piClient; static PropertyInfo piServer; static PropertyInfo piTrustFailure; #if MONOTOUCH static MethodInfo start_wwan; static WebConnection () { Type type = Type.GetType ("MonoTouch.ObjCRuntime.Runtime, monotouch"); if (type != null) start_wwan = type.GetMethod ("StartWWAN", new Type [] { typeof (System.Uri) }); } #endif public WebConnection (WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte [4096]; Data = new WebConnectionData (); initConn = new WaitCallback (state => { try { InitConnection (state); } catch {} }); queue = group.Queue; abortHelper = new AbortHelper (); abortHelper.Connection = this; abortHandler = new EventHandler (abortHelper.Abort); } class AbortHelper { public WebConnection Connection; public void Abort (object sender, EventArgs args) { WebConnection other = ((HttpWebRequest) sender).WebConnection; if (other == null) other = Connection; other.Abort (sender, args); } } bool CanReuse () { // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0) // but if there's data pending to read (!) we won't reuse the socket. return (socket.Poll (0, SelectMode.SelectRead) == false); } void Connect (HttpWebRequest request) { lock (socketLock) { if (socket != null && socket.Connected && status == WebExceptionStatus.Success) { // Take the chunked stream to the expected state (State.None) if (CanReuse () && CompleteChunkedRead ()) { reused = true; return; } } reused = false; if (socket != null) { socket.Close(); socket = null; } chunkStream = null; IPHostEntry hostEntry = sPoint.HostEntry; if (hostEntry == null) { #if MONOTOUCH if (start_wwan != null) { start_wwan.Invoke (null, new object [1] { sPoint.Address }); hostEntry = sPoint.HostEntry; } if (hostEntry == null) { #endif status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure : WebExceptionStatus.NameResolutionFailure; return; #if MONOTOUCH } #endif } //WebConnectionData data = Data; foreach (IPAddress address in hostEntry.AddressList) { try { socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } catch (Exception se) { // The Socket ctor can throw if we run out of FD's if (!request.Aborted) status = WebExceptionStatus.ConnectFailure; connect_exception = se; return; } IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port); socket.NoDelay = !sPoint.UseNagleAlgorithm; try { sPoint.KeepAliveSetup (socket); } catch { // Ignore. Not supported in all platforms. } if (!sPoint.CallEndPointDelegate (socket, remote)) { socket.Close (); socket = null; status = WebExceptionStatus.ConnectFailure; } else { try { if (request.Aborted) return; socket.Connect (remote); status = WebExceptionStatus.Success; break; } catch (ThreadAbortException) { // program exiting... Socket s = socket; socket = null; if (s != null) s.Close (); return; } catch (ObjectDisposedException) { // socket closed from another thread return; } catch (Exception exc) { Socket s = socket; socket = null; if (s != null) s.Close (); if (!request.Aborted) status = WebExceptionStatus.ConnectFailure; connect_exception = exc; } } } } } static void EnsureSSLStreamAvailable () { lock (classLock) { if (sslStream != null) return; #if NET_2_1 && SECURITY_DEP sslStream = typeof (Mono.Security.Protocol.Tls.HttpsClientStream); #else // HttpsClientStream is an internal glue class in Mono.Security.dll sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " + Consts.AssemblyMono_Security, false); if (sslStream == null) { string msg = "Missing Mono.Security.dll assembly. " + "Support for SSL/TLS is unavailable."; throw new NotSupportedException (msg); } #endif piClient = sslStream.GetProperty ("SelectedClientCertificate"); piServer = sslStream.GetProperty ("ServerCertificate"); piTrustFailure = sslStream.GetProperty ("TrustFailure"); } } bool CreateTunnel (HttpWebRequest request, Uri connectUri, Stream stream, out byte[] buffer) { StringBuilder sb = new StringBuilder (); sb.Append ("CONNECT "); sb.Append (request.Address.Host); sb.Append (':'); sb.Append (request.Address.Port); sb.Append (" HTTP/"); if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11) sb.Append ("1.1"); else sb.Append ("1.0"); sb.Append ("\r\nHost: "); sb.Append (request.Address.Authority); bool ntlm = false; var challenge = Data.Challenge; Data.Challenge = null; var auth_header = request.Headers ["Proxy-Authorization"]; bool have_auth = auth_header != null; if (have_auth) { sb.Append ("\r\nProxy-Authorization: "); sb.Append (auth_header); ntlm = auth_header.ToUpper ().Contains ("NTLM"); } else if (challenge != null && Data.StatusCode == 407) { ICredentials creds = request.Proxy.Credentials; have_auth = true; if (connect_request == null) { // create a CONNECT request to use with Authenticate connect_request = (HttpWebRequest)WebRequest.Create ( connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/"); connect_request.Method = "CONNECT"; connect_request.Credentials = creds; } for (int i = 0; i < challenge.Length; i++) { var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds); if (auth == null) continue; ntlm = (auth.Module.AuthenticationType == "NTLM"); sb.Append ("\r\nProxy-Authorization: "); sb.Append (auth.Message); break; } } if (ntlm) { sb.Append ("\r\nProxy-Connection: keep-alive"); connect_ntlm_auth_state++; } sb.Append ("\r\n\r\n"); Data.StatusCode = 0; byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ()); stream.Write (connectBytes, 0, connectBytes.Length); int status; WebHeaderCollection result = ReadHeaders (stream, out buffer, out status); if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) && result != null && status == 407) { // Needs proxy auth var connectionHeader = result ["Connection"]; if (socket != null && !string.IsNullOrEmpty (connectionHeader) && connectionHeader.ToLower() == "close") { // The server is requesting that this connection be closed socket.Close(); socket = null; } Data.StatusCode = status; Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false); return false; } else if (status != 200) { string msg = String.Format ("The remote server returned a {0} status code.", status); HandleError (WebExceptionStatus.SecureChannelFailure, null, msg); return false; } return (result != null); } WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status) { retBuffer = null; status = 200; byte [] buffer = new byte [1024]; MemoryStream ms = new MemoryStream (); bool gotStatus = false; WebHeaderCollection headers = null; while (true) { int n = stream.Read (buffer, 0, 1024); if (n == 0) { HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders"); return null; } ms.Write (buffer, 0, n); int start = 0; string str = null; headers = new WebHeaderCollection (); while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) { if (str == null) { int contentLen = 0; try { contentLen = int.Parse(headers["Content-Length"]); } catch { contentLen = 0; } if (ms.Length - start - contentLen > 0) { // we've read more data than the response header and conents, // give back extra data to the caller retBuffer = new byte[ms.Length - start - contentLen]; Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length); } else { // haven't read in some or all of the contents for the response, do so now FlushContents(stream, contentLen - (int)(ms.Length - start)); } return headers; } if (gotStatus) { headers.Add (str); continue; } int spaceidx = str.IndexOf (' '); if (spaceidx == -1) { HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2"); return null; } status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3)); gotStatus = true; } } } void FlushContents(Stream stream, int contentLength) { while (contentLength > 0) { byte[] contentBuffer = new byte[contentLength]; int bytesRead = stream.Read(contentBuffer, 0, contentLength); if (bytesRead > 0) { contentLength -= bytesRead; } else { break; } } } bool CreateStream (HttpWebRequest request) { try { NetworkStream serverStream = new NetworkStream (socket, false); if (request.Address.Scheme == Uri.UriSchemeHttps) { ssl = true; EnsureSSLStreamAvailable (); if (!reused || nstream == null || nstream.GetType () != sslStream) { byte [] buffer = null; if (sPoint.UseConnect) { bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer); if (!ok) return false; } object[] args = new object [4] { serverStream, request.ClientCertificates, request, buffer}; nstream = (Stream) Activator.CreateInstance (sslStream, args); #if SECURITY_DEP SslClientStream scs = (SslClientStream) nstream; var helper = new ServicePointManager.ChainValidationHelper (request); scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain); #endif certsAvailable = false; } // we also need to set ServicePoint.Certificate // and ServicePoint.ClientCertificate but this can // only be done later (after handshake - which is // done only after a read operation). } else { ssl = false; nstream = serverStream; } } catch (Exception) { if (!request.Aborted) status = WebExceptionStatus.ConnectFailure; return false; } return true; } void HandleError (WebExceptionStatus st, Exception e, string where) { status = st; lock (this) { if (st == WebExceptionStatus.RequestCanceled) Data = new WebConnectionData (); } if (e == null) { // At least we now where it comes from try { #if TARGET_JVM throw new Exception (); #else throw new Exception (new System.Diagnostics.StackTrace ().ToString ()); #endif } catch (Exception e2) { e = e2; } } HttpWebRequest req = null; if (Data != null && Data.request != null) req = Data.request; Close (true); if (req != null) { req.FinishedReading = true; req.SetResponseError (st, e, where); } } static void ReadDone (IAsyncResult result) { WebConnection cnc = (WebConnection)result.AsyncState; WebConnectionData data = cnc.Data; Stream ns = cnc.nstream; if (ns == null) { cnc.Close (true); return; } int nread = -1; try { nread = ns.EndRead (result); } catch (ObjectDisposedException) { return; } catch (Exception e) { if (e.InnerException is ObjectDisposedException) return; cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1"); return; } if (nread == 0) { cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2"); return; } if (nread < 0) { cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3"); return; } int pos = -1; nread += cnc.position; if (data.ReadState == ReadState.None) { Exception exc = null; try { pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread); } catch (Exception e) { exc = e; } if (exc != null || pos == -1) { cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4"); return; } } if (data.ReadState == ReadState.Aborted) { cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone"); return; } if (data.ReadState != ReadState.Content) { int est = nread * 2; int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est; byte [] newBuffer = new byte [max]; Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread); cnc.buffer = newBuffer; cnc.position = nread; data.ReadState = ReadState.None; InitRead (cnc); return; } cnc.position = 0; WebConnectionStream stream = new WebConnectionStream (cnc); bool expect_content = ExpectContent (data.StatusCode, data.request.Method); string tencoding = null; if (expect_content) tencoding = data.Headers ["Transfer-Encoding"]; cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1); if (!cnc.chunkedRead) { stream.ReadBuffer = cnc.buffer; stream.ReadBufferOffset = pos; stream.ReadBufferSize = nread; try { stream.CheckResponseInBuffer (); } catch (Exception e) { cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7"); } } else if (cnc.chunkStream == null) { try { cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers); } catch (Exception e) { cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5"); return; } } else { cnc.chunkStream.ResetBuffer (); try { cnc.chunkStream.Write (cnc.buffer, pos, nread); } catch (Exception e) { cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6"); return; } } data.stream = stream; if (!expect_content) stream.ForceCompletion (); data.request.SetResponseData (data); } static bool ExpectContent (int statusCode, string method) { if (method == "HEAD") return false; return (statusCode >= 200 && statusCode != 204 && statusCode != 304); } internal void GetCertificates () { // here the SSL negotiation have been done X509Certificate client = (X509Certificate) piClient.GetValue (nstream, null); X509Certificate server = (X509Certificate) piServer.GetValue (nstream, null); sPoint.SetCertificates (client, server); certsAvailable = (server != null); } internal static void InitRead (object state) { WebConnection cnc = (WebConnection) state; Stream ns = cnc.nstream; try { int size = cnc.buffer.Length - cnc.position; ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc); } catch (Exception e) { cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead"); } } static int GetResponse (WebConnectionData data, ServicePoint sPoint, byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (data.ReadState == ReadState.Aborted) return -1; if (data.ReadState == ReadState.None) { lineok = ReadLine (buffer, ref pos, max, ref line); if (!lineok) return 0; if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; data.ReadState = ReadState.Status; string [] parts = line.Split (' '); if (parts.Length < 2) return -1; if (String.Compare (parts [0], "HTTP/1.1", true) == 0) { data.Version = HttpVersion.Version11; sPoint.SetVersion (HttpVersion.Version11); } else { data.Version = HttpVersion.Version10; sPoint.SetVersion (HttpVersion.Version10); } data.StatusCode = (int) UInt32.Parse (parts [1]); if (parts.Length >= 3) data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2); else data.StatusDescription = ""; if (pos >= max) return pos; } emptyFirstLine = false; if (data.ReadState == ReadState.Status) { data.ReadState = ReadState.Headers; data.Headers = new WebHeaderCollection (); ArrayList headers = new ArrayList (); bool finished = false; while (!finished) { if (ReadLine (buffer, ref pos, max, ref line) == false) break; if (line == null) { // Empty line: end of headers finished = true; continue; } if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) { int count = headers.Count - 1; if (count < 0) break; string prev = (string) headers [count] + line; headers [count] = prev; } else { headers.Add (line); } } if (!finished) return 0; foreach (string s in headers) data.Headers.SetInternal (s); if (data.StatusCode == (int) HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) return pos; if (data.request.ExpectContinue) { data.request.DoContinueDelegate (data.StatusCode, data.Headers); // Prevent double calls when getting the // headers in several packets. data.request.ExpectContinue = false; } data.ReadState = ReadState.None; isContinue = true; } else { data.ReadState = ReadState.Content; return pos; } } } while (emptyFirstLine || isContinue); return -1; } void InitConnection (object state) { HttpWebRequest request = (HttpWebRequest) state; request.WebConnection = this; if (request.Aborted) return; keepAlive = request.KeepAlive; Data = new WebConnectionData (request); retry: Connect (request); if (request.Aborted) return; if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError (status, connect_exception); Close (true); } return; } if (!CreateStream (request)) { if (request.Aborted) return; WebExceptionStatus st = status; if (Data.Challenge != null) goto retry; Exception cnc_exc = connect_exception; connect_exception = null; request.SetWriteStreamError (st, cnc_exc); Close (true); return; } request.SetWriteStream (new WebConnectionStream (this, request)); } #if MONOTOUCH static bool warned_about_queue = false; #endif internal EventHandler SendRequest (HttpWebRequest request) { if (request.Aborted) return null; lock (this) { if (!busy) { busy = true; status = WebExceptionStatus.Success; ThreadPool.QueueUserWorkItem (initConn, request); } else { lock (queue) { #if MONOTOUCH if (!warned_about_queue) { warned_about_queue = true; Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached."); } #endif queue.Enqueue (request); } } } return abortHandler; } void SendNext () { lock (queue) { if (queue.Count > 0) { SendRequest ((HttpWebRequest) queue.Dequeue ()); } } } internal void NextRead () { lock (this) { if (Data.request != null) Data.request.FinishedReading = true; string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection"; string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null; bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive); if (cncHeader != null) { cncHeader = cncHeader.ToLower (); keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1); } if ((socket != null && !socket.Connected) || (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) { Close (false); } busy = false; if (priority_request != null) { SendRequest (priority_request); priority_request = null; } else { SendNext (); } } } static bool ReadLine (byte [] buffer, ref int start, int max, ref string output) { bool foundCR = false; StringBuilder text = new StringBuilder (); int c = 0; while (start < max) { c = (int) buffer [start++]; if (c == '\n') { // newline if ((text.Length > 0) && (text [text.Length - 1] == '\r')) text.Length--; foundCR = false; break; } else if (foundCR) { text.Length--; break; } if (c == '\r') foundCR = true; text.Append ((char) c); } if (c != '\n' && c != '\r') return false; if (text.Length == 0) { output = null; return (c == '\n' || c == '\r'); } if (foundCR) text.Length--; output = text.ToString (); return true; } internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state) { Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) return null; s = nstream; } IAsyncResult result = null; if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) { try { result = s.BeginRead (buffer, offset, size, cb, state); cb = null; } catch (Exception) { HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead"); throw; } } if (chunkedRead) { WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size); wr.InnerAsyncResult = result; if (result == null) { // Will be completed from the data in ChunkStream wr.SetCompleted (true, (Exception) null); wr.DoCallback (); } return wr; } return result; } internal int EndRead (HttpWebRequest request, IAsyncResult result) { Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) throw new ObjectDisposedException (typeof (NetworkStream).FullName); s = nstream; } int nbytes = 0; WebAsyncResult wr = null; IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult; if (chunkedRead && (nsAsync is WebAsyncResult)) { wr = (WebAsyncResult) nsAsync; IAsyncResult inner = wr.InnerAsyncResult; if (inner != null && !(inner is WebAsyncResult)) nbytes = s.EndRead (inner); } else if (!(nsAsync is WebAsyncResult)) { nbytes = s.EndRead (nsAsync); wr = (WebAsyncResult) result; } if (chunkedRead) { bool done = (nbytes == 0); try { chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes); if (!done && nbytes == 0 && chunkStream.WantMore) nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size); } catch (Exception e) { if (e is WebException) throw e; throw new WebException ("Invalid chunked data.", e, WebExceptionStatus.ServerProtocolViolation, null); } if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) { HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead"); throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null); } } return (nbytes != 0) ? nbytes : -1; } // To be called on chunkedRead when we can read no data from the ChunkStream yet int EnsureRead (byte [] buffer, int offset, int size) { byte [] morebytes = null; int nbytes = 0; while (nbytes == 0 && chunkStream.WantMore) { int localsize = chunkStream.ChunkLeft; if (localsize <= 0) // not read chunk size yet localsize = 1024; else if (localsize > 16384) localsize = 16384; if (morebytes == null || morebytes.Length < localsize) morebytes = new byte [localsize]; int nread = nstream.Read (morebytes, 0, localsize); if (nread <= 0) return 0; // Error chunkStream.Write (morebytes, 0, nread); nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes); } return nbytes; } bool CompleteChunkedRead() { if (!chunkedRead || chunkStream == null) return true; while (chunkStream.WantMore) { int nbytes = nstream.Read (buffer, 0, buffer.Length); if (nbytes <= 0) return false; // Socket was disconnected chunkStream.Write (buffer, 0, nbytes); } return true; } internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state) { Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) return null; s = nstream; } IAsyncResult result = null; try { result = s.BeginWrite (buffer, offset, size, cb, state); } catch (Exception) { status = WebExceptionStatus.SendFailure; throw; } return result; } internal void EndWrite2 (HttpWebRequest request, IAsyncResult result) { if (request.FinishedReading) return; Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) throw new ObjectDisposedException (typeof (NetworkStream).FullName); s = nstream; } try { s.EndWrite (result); } catch (Exception exc) { status = WebExceptionStatus.SendFailure; if (exc.InnerException != null) throw exc.InnerException; throw; } } internal bool EndWrite (HttpWebRequest request, IAsyncResult result) { if (request.FinishedReading) return true; Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) throw new ObjectDisposedException (typeof (NetworkStream).FullName); s = nstream; } try { s.EndWrite (result); return true; } catch { status = WebExceptionStatus.SendFailure; return false; } } internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size) { Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) return 0; s = nstream; } int result = 0; try { bool done = false; if (!chunkedRead) { result = s.Read (buffer, offset, size); done = (result == 0); } if (chunkedRead) { try { chunkStream.WriteAndReadBack (buffer, offset, size, ref result); if (!done && result == 0 && chunkStream.WantMore) result = EnsureRead (buffer, offset, size); } catch (Exception e) { HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1"); throw; } if ((done || result == 0) && chunkStream.WantMore) { HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2"); throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null); } } } catch (Exception e) { HandleError (WebExceptionStatus.ReceiveFailure, e, "Read"); } return result; } internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg) { err_msg = null; Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); if (nstream == null) return false; s = nstream; } try { s.Write (buffer, offset, size); // here SSL handshake should have been done if (ssl && !certsAvailable) GetCertificates (); } catch (Exception e) { err_msg = e.Message; WebExceptionStatus wes = WebExceptionStatus.SendFailure; string msg = "Write: " + err_msg; if (e is WebException) { HandleError (wes, e, msg); return false; } // if SSL is in use then check for TrustFailure if (ssl && (bool) piTrustFailure.GetValue (nstream, null)) { wes = WebExceptionStatus.TrustFailure; msg = "Trust failure"; } HandleError (wes, e, msg); return false; } return true; } internal void Close (bool sendNext) { lock (this) { if (nstream != null) { try { nstream.Close (); } catch {} nstream = null; } if (socket != null) { try { socket.Close (); } catch {} socket = null; } if (ntlm_authenticated) ResetNtlm (); if (Data != null) { lock (Data) { Data.ReadState = ReadState.Aborted; } } busy = false; Data = new WebConnectionData (); if (sendNext) SendNext (); connect_request = null; connect_ntlm_auth_state = NtlmAuthState.None; } } void Abort (object sender, EventArgs args) { lock (this) { lock (queue) { HttpWebRequest req = (HttpWebRequest) sender; if (Data.request == req || Data.request == null) { if (!req.FinishedReading) { status = WebExceptionStatus.RequestCanceled; Close (false); if (queue.Count > 0) { Data.request = (HttpWebRequest) queue.Dequeue (); SendRequest (Data.request); } } return; } req.FinishedReading = true; req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted"); if (queue.Count > 0 && queue.Peek () == sender) { queue.Dequeue (); } else if (queue.Count > 0) { object [] old = queue.ToArray (); queue.Clear (); for (int i = old.Length - 1; i >= 0; i--) { if (old [i] != sender) queue.Enqueue (old [i]); } } } } } internal void ResetNtlm () { ntlm_authenticated = false; ntlm_credentials = null; unsafe_sharing = false; } internal bool Busy { get { lock (this) return busy; } } internal bool Connected { get { lock (this) { return (socket != null && socket.Connected); } } } // -Used for NTLM authentication internal HttpWebRequest PriorityRequest { set { priority_request = value; } } internal bool NtlmAuthenticated { get { return ntlm_authenticated; } set { ntlm_authenticated = value; } } internal NetworkCredential NtlmCredential { get { return ntlm_credentials; } set { ntlm_credentials = value; } } internal bool UnsafeAuthenticatedConnectionSharing { get { return unsafe_sharing; } set { unsafe_sharing = value; } } // - } }
26.494878
137
0.630331
[ "Apache-2.0" ]
Mailaender/mono
mcs/class/System/System.Net/WebConnection.cs
33,622
C#
using System.Threading.Tasks; using System.Web.Mvc; using Moq; using NUnit.Framework; using SFA.DAS.Authentication; using SFA.DAS.Authorization; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Models.AccountTeam; using SFA.DAS.EmployerAccounts.Web.Controllers; using SFA.DAS.EmployerAccounts.Web.Orchestrators; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.UnitTests.Controllers.InvitationControllerTests { public class WhenViewingInvitations : ControllerTestBase { private Mock<InvitationOrchestrator> _invitationOrchestrator; private InvitationController _controller; private Mock<IAuthenticationService> _owinWrapper; private Mock<IAuthorizationService> _featureToggle; private Mock<IMultiVariantTestingService> _userViewTestingService; private EmployerAccountsConfiguration _configuration; private Mock<ICookieStorageService<FlashMessageViewModel>> _flashMessage; [SetUp] public void Arrange() { base.Arrange(); _owinWrapper = new Mock<IAuthenticationService>(); _featureToggle = new Mock<IAuthorizationService>(); _userViewTestingService = new Mock<IMultiVariantTestingService>(); _flashMessage = new Mock<ICookieStorageService<FlashMessageViewModel>>(); _invitationOrchestrator = new Mock<InvitationOrchestrator>(); _configuration = new EmployerAccountsConfiguration(); _controller = new InvitationController( _invitationOrchestrator.Object, _owinWrapper.Object, _featureToggle.Object, _userViewTestingService.Object, _configuration, _flashMessage.Object); } [Test] public void ThenTheUserIsShownTheIndexWhenNotAuthenticated() { //Arrange _owinWrapper.Setup(x => x.GetClaimValue("sub")).Returns(""); //Act var actual = _controller.Invite(); //Assert Assert.IsNotNull(actual); } [Test] public void ThenTheUserIsRedirectedToTheServiceLandingPageWhenAuthenticated() { //Arrange _owinWrapper.Setup(x => x.GetClaimValue("sub")).Returns("my_user_id"); //Act var actual = _controller.Invite(); //Assert Assert.IsNotNull(actual); var actualRedirectResult = actual as RedirectToRouteResult; Assert.IsNotNull(actualRedirectResult); Assert.AreEqual("Index",actualRedirectResult.RouteValues["action"]); Assert.AreEqual("Home",actualRedirectResult.RouteValues["controller"]); } [Test] public async Task ThenTheCorrectInvitationIsRetrieved() { //Arrange _owinWrapper.Setup(x => x.GetClaimValue("sub")).Returns("TEST"); _invitationOrchestrator.Setup(x => x.GetInvitation(It.Is<string>(i => i == "123"))) .ReturnsAsync(new OrchestratorResponse<InvitationView> { Data = new InvitationView()}); //Act var actual = await _controller.Details("123"); //Assert _invitationOrchestrator.Verify(x => x.GetInvitation(It.Is<string>(i => i == "123"))); Assert.IsNotNull(actual); var viewResult = actual as ViewResult; Assert.IsNotNull(viewResult); } } }
36.864583
103
0.656965
[ "MIT" ]
SkillsFundingAgency/das-employeraccounts
src/SFA.DAS.EmployerAccounts.Web.UnitTests/Controllers/InvitationControllerTests/WhenViewingInvitations.cs
3,541
C#
using Newtonsoft.Json; using NHM.Common; using NHM.Common.Enums; using NHM.MinerPlugin; using NHM.MinerPluginToolkitV1; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using NHM.MinerPluginToolkitV1.Configs; using NHM.MinerPluginToolkitV1.ExtraLaunchParameters; namespace LolMiner { public class LolMiner : MinerBase { private string _devices; private int _apiPort; private double DevFee = 1d; private string _disableWatchdogParam = "--disablewatchdog 1"; // the order of intializing devices is the order how the API responds private Dictionary<int, string> _initOrderMirrorApiOrderUUIDs = new Dictionary<int, string>(); protected Dictionary<string, int> _mappedIDs; private readonly HttpClient _http = new HttpClient(); public LolMiner(string uuid, Dictionary<string, int> mappedIDs) : base(uuid) { _mappedIDs = mappedIDs; } protected virtual string AlgorithmName(AlgorithmType algorithmType) => PluginSupportedAlgorithms.AlgorithmName(algorithmType); public async override Task<ApiData> GetMinerStatsDataAsync() { var ad = new ApiData(); try { var summaryApiResult = await _http.GetStringAsync($"http://127.0.0.1:{_apiPort}/summary"); ad.ApiResponse = summaryApiResult; var summary = JsonConvert.DeserializeObject<ApiJsonResponse>(summaryApiResult); var perDeviceSpeedInfo = new Dictionary<string, IReadOnlyList<(AlgorithmType type, double speed)>>(); var speedUnit = summary.Session.Performance_Unit; var multiplier = 1; switch (speedUnit) { case "mh/s": multiplier = 1000000; //1M break; case "kh/s": multiplier = 1000; //1k break; default: break; } var totalSpeed = summary.Session.Performance_Summary * multiplier; var totalPowerUsage = 0; var perDevicePowerInfo = new Dictionary<string, int>(); var apiDevices = summary.GPUs; foreach (var pair in _miningPairs) { var gpuUUID = pair.Device.UUID; var gpuID = _mappedIDs[gpuUUID]; var currentStats = summary.GPUs.Where(devStats => devStats.Index == gpuID).FirstOrDefault(); if (currentStats == null) continue; perDeviceSpeedInfo.Add(gpuUUID, new List<(AlgorithmType type, double speed)>() { (_algorithmType, currentStats.Performance * multiplier * (1 - DevFee * 0.01)) }); } ad.AlgorithmSpeedsPerDevice = perDeviceSpeedInfo; ad.PowerUsageTotal = totalPowerUsage; ad.PowerUsagePerDevice = perDevicePowerInfo; } catch (Exception e) { Logger.Error(_logGroup, $"Error occured while getting API stats: {e.Message}"); } return ad; } protected override IEnumerable<MiningPair> GetSortedMiningPairs(IEnumerable<MiningPair> miningPairs) { var pairsList = miningPairs.ToList(); // sort by mapped ids pairsList.Sort((a, b) => _mappedIDs[a.Device.UUID].CompareTo(_mappedIDs[b.Device.UUID])); return pairsList; } protected override void Init() { _devices = string.Join(",", _miningPairs.Select(p => _mappedIDs[p.Device.UUID])); // ???????? GetSortedMiningPairs is now sorted so this thing probably makes no sense anymore var miningPairs = _miningPairs.ToList(); for (int i = 0; i < miningPairs.Count; i++) { _initOrderMirrorApiOrderUUIDs[i] = miningPairs[i].Device.UUID; } // if ELP contains watchdog remove default wd-param if (_extraLaunchParameters.Contains("--disablewatchdog")) { _disableWatchdogParam = ""; } } protected override string MiningCreateCommandLine() { // API port function might be blocking _apiPort = GetAvaliablePort(); // instant non blocking var urlWithPort = StratumServiceHelpers.GetLocationUrl(_algorithmType, _miningLocation, NhmConectionType.NONE); var algo = AlgorithmName(_algorithmType); var commandLine = $"--pool {urlWithPort} --user {_username} --tls 0 --apiport {_apiPort} {_disableWatchdogParam} --devices {_devices} {_extraLaunchParameters}"; if (_algorithmType == AlgorithmType.ZHash) commandLine += " --coin AUTO144_5"; else commandLine += $" --algo {algo}"; if (_algorithmType == AlgorithmType.DaggerHashimoto) commandLine += " --ethstratum ETHV1"; //--disablewatchdog 1 return commandLine; } public override void InitMiningPairs(IEnumerable<MiningPair> miningPairs) { // now should be ordered _miningPairs = GetSortedMiningPairs(miningPairs); //// update log group try { var devs = _miningPairs.Select(pair => $"{pair.Device.DeviceType}:{pair.Device.ID}"); var devsTag = $"devs({string.Join(",", devs)})"; var algo = _miningPairs.First().Algorithm.AlgorithmName; var algoTag = $"algo({algo})"; _logGroup = $"{_baseTag}-{algoTag}-{devsTag}"; } catch (Exception e) { Logger.Error(_logGroup, $"Error while setting _logGroup: {e.Message}"); } // init algo, ELP and finally miner specific init // init algo var singleType = MinerToolkit.GetAlgorithmSingleType(_miningPairs); _algorithmType = singleType.Item1; bool ok = singleType.Item2; if (!ok) { Logger.Info(_logGroup, "Initialization of miner failed. Algorithm not found!"); throw new InvalidOperationException("Invalid mining initialization"); } // init ELP, _miningPairs are ordered and ELP parsing keeps ordering if (MinerOptionsPackage != null) { var miningPairsList = _miningPairs.ToList(); var ignoreDefaults = MinerOptionsPackage.IgnoreDefaultValueOptions; var firstPair = miningPairsList.FirstOrDefault(); var optionsWithoutLHR = MinerOptionsPackage.GeneralOptions.Where(opt => !opt.ID.Contains("lolMiner_mode")).ToList(); var optionsWithLHR = MinerOptionsPackage.GeneralOptions.Where(opt => opt.ID.Contains("lolMiner_mode")).ToList(); var generalParamsWithoutLHR = ExtraLaunchParametersParser.Parse(miningPairsList, optionsWithoutLHR, ignoreDefaults); var isDagger = firstPair.Algorithm.FirstAlgorithmType == AlgorithmType.DaggerHashimoto; var generalParamsWithLHR = ExtraLaunchParametersParser.Parse(miningPairsList, optionsWithLHR, !isDagger); var modeOptions = ResolveDeviceMode(miningPairsList, generalParamsWithLHR); var generalParams = generalParamsWithoutLHR + (isDagger ? modeOptions : ""); var temperatureParams = ExtraLaunchParametersParser.Parse(miningPairsList, MinerOptionsPackage.TemperatureOptions, ignoreDefaults); _extraLaunchParameters = $"{generalParams} {temperatureParams}".Trim(); } // miner specific init Init(); } static string[] modeLHRV2 = { "RTX 3060 Ti", "RTX 3070" }; static string[] modeLHRV1 = { "RTX 3060" }; static string[] modeLHRLP = { "RTX 3080" }; static string[] modeA = { "RTX 3090" }; private static string ModeForName(string deviceName) { if (modeLHRV2.Any(dev => deviceName.Contains(dev))) return "LHR2"; if (modeLHRV1.Any(dev => deviceName.Contains(dev))) return "LHR1"; if (modeLHRLP.Any(dev => deviceName.Contains(dev))) return "LHRLP"; if (modeA.Any(dev => deviceName.Contains(dev))) return "a"; return "b"; } public static string ResolveDeviceMode(List<MiningPair> pairs, string lhrMode) { var existingOptions = lhrMode.Replace("--mode", "").Trim().Split(','); var newOptions = pairs.Select(pair => pair.Device.Name).Select(ModeForName).ToArray(); existingOptions = existingOptions.Select((opt, index) => opt == "missing" ? newOptions[index] : opt).ToArray(); return " --mode " + String.Join(",", existingOptions) + " "; } public override async Task<BenchmarkResult> StartBenchmark(CancellationToken stop, BenchmarkPerformanceType benchmarkType = BenchmarkPerformanceType.Standard) { var isDaggerNvidia = _miningPairs.Any(mp => mp.Algorithm.FirstAlgorithmType == AlgorithmType.DaggerHashimoto) && _miningPairs.Any(mp => mp.Device.DeviceType == DeviceType.NVIDIA); if (!isDaggerNvidia) return await base.StartBenchmark(stop, benchmarkType); using (var tickCancelSource = new CancellationTokenSource()) { // determine benchmark time // settup times int benchmarkTime = MinerBenchmarkTimeSettings.ParseBenchmarkTime(new List<int> { 180, 240, 300 }, MinerBenchmarkTimeSettings, _miningPairs, benchmarkType); ; var maxTicks = MinerBenchmarkTimeSettings.ParseBenchmarkTicks(new List<int> { 1, 3, 9 }, MinerBenchmarkTimeSettings, _miningPairs, benchmarkType); //// use demo user and disable the watchdog var commandLine = MiningCreateCommandLine(); var (binPath, binCwd) = GetBinAndCwdPaths(); Logger.Info(_logGroup, $"Benchmarking started with command: {commandLine}"); Logger.Info(_logGroup, $"Benchmarking settings: time={benchmarkTime} ticks={maxTicks}"); var bp = new BenchmarkProcess(binPath, binCwd, commandLine, GetEnvironmentVariables()); // disable line readings and read speeds from API bp.CheckData = null; var benchmarkTimeout = TimeSpan.FromSeconds(benchmarkTime + 5); var benchmarkWait = TimeSpan.FromMilliseconds(500); var t = MinerToolkit.WaitBenchmarkResult(bp, benchmarkTimeout, benchmarkWait, stop, tickCancelSource.Token); var stoppedAfterTicks = false; var validTicks = 0; var ticks = benchmarkTime / 10; // on each 10 seconds tick var result = new BenchmarkResult(); var benchmarkApiData = new List<ApiData>(); var delay = (benchmarkTime / maxTicks) * 1000; for (var tick = 0; tick < ticks; tick++) { if (t.IsCompleted || t.IsCanceled || stop.IsCancellationRequested) break; await Task.Delay(delay, stop); // 10 seconds delay if (t.IsCompleted || t.IsCanceled || stop.IsCancellationRequested) break; var ad = await GetMinerStatsDataAsync(); var adTotal = ad.AlgorithmSpeedsTotal(); var isTickValid = adTotal.Count > 0 && adTotal.All(pair => pair.speed > 0); benchmarkApiData.Add(ad); if (isTickValid) ++validTicks; if (validTicks >= maxTicks) { stoppedAfterTicks = true; break; } } // await benchmark task if (stoppedAfterTicks) { try { tickCancelSource.Cancel(); } catch { } } await t; if (stop.IsCancellationRequested) { return t.Result; } // calc speeds // TODO calc std deviaton to reduce invalid benches try { var nonZeroSpeeds = benchmarkApiData.Where(ad => ad.AlgorithmSpeedsTotal().Count > 0 && ad.AlgorithmSpeedsTotal().All(pair => pair.speed > 0)) .Select(ad => (ad, ad.AlgorithmSpeedsTotal().Count)).ToList(); var speedsFromTotals = new List<(AlgorithmType type, double speed)>(); if (nonZeroSpeeds.Count > 0) { var maxAlgoPiarsCount = nonZeroSpeeds.Select(adCount => adCount.Count).Max(); var sameCountApiDatas = nonZeroSpeeds.Where(adCount => adCount.Count == maxAlgoPiarsCount).Select(adCount => adCount.ad).ToList(); var firstPair = sameCountApiDatas.FirstOrDefault(); // sum var values = sameCountApiDatas.SelectMany(x => x.AlgorithmSpeedsTotal()).Select(pair => pair.speed).Reverse().Take(10).ToArray(); var value = values.Sum() / values.Length; result = new BenchmarkResult { AlgorithmTypeSpeeds = firstPair.AlgorithmSpeedsTotal().Select(pair => (pair.type, value)).ToList(), Success = true }; } } catch (Exception e) { Logger.Warn(_logGroup, $"benchmarking AlgorithmSpeedsTotal error {e.Message}"); } // return API result return result; } } } }
47.715719
191
0.569846
[ "MIT" ]
asaasasaasa/NiceHashMiner
src/Miners/LolMiner/LolMiner.cs
14,269
C#
using Microsoft.Extensions.DependencyInjection; using RealWorldDesignPatterns.Adapter.Contract; using RealWorldDesignPatterns.Adapter.Implementations.RickAndMorty; using RealWorldDesignPatterns.Adapter.Implementations.StarWars; using RealWorldDesignPatterns.Adapter.Implementations.StreetFighter; namespace RealWorldDesignPatterns.Adapter.DI { public static class Injector { public static IServiceCollection AddCharactersService(this IServiceCollection services) { services.AddHttpClient<GetRickAndMortyCharactersService>(); services.AddScoped<IGetCharactersService, GetRickAndMortyCharactersService>(); services.AddScoped<IGetCharactersService, GetStarWarsCharactersService>(); services.AddScoped<IGetCharactersService, GetStreetFighterCharactersService>(); return services; } } }
41.904762
95
0.782955
[ "Apache-2.0" ]
j-didi/RealWorldDesignPatterns
Patterns/Structural/RealWorldDesignPatterns.Adapter/DI/Injector.cs
882
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace SampleFormsApp.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.142857
91
0.635802
[ "MIT" ]
technoboom/xamarin-forms-sample
iOS/Main.cs
488
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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsAverageARequest. /// </summary> public partial interface IWorkbookFunctionsAverageARequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsAverageARequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken 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> IWorkbookFunctionsAverageARequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsAverageARequest Select(string value); } }
33.114754
153
0.579208
[ "MIT" ]
twsouthwick/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsAverageARequest.cs
2,020
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.GetSource8 { public partial class GetSource8YamlTests { [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class MissingDocumentWithCatch1Tests : YamlTestsBase { [Test] public void MissingDocumentWithCatch1Test() { //do get_source this.Do(()=> _client.GetSource("test_1", "test", "1"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class MissingDocumentWithIgnore2Tests : YamlTestsBase { [Test] public void MissingDocumentWithIgnore2Test() { //do get_source this.Do(()=> _client.GetSource("test_1", "test", "1", nv=>nv .AddQueryString("ignore", 404) )); } } } }
20.391304
84
0.715352
[ "Apache-2.0" ]
Entroper/elasticsearch-net
src/Tests/Elasticsearch.Net.Integration.Yaml/get_source/80_missing.yaml.cs
938
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; namespace Xam.HelpTools.Platform.Android.Helpers { public static class ImageSourceHelper { private static FileImageSourceHandler fileImageSourceHandler; private static ImageLoaderSourceHandler imageLoaderSourceHandler; private static StreamImagesourceHandler streamImagesourceHandler; static ImageSourceHelper() { fileImageSourceHandler = new FileImageSourceHandler(); imageLoaderSourceHandler = new ImageLoaderSourceHandler(); streamImagesourceHandler = new StreamImagesourceHandler(); } private static IImageSourceHandler GetHandler(ImageSource source) { IImageSourceHandler returnValue = null; if (source is UriImageSource) { returnValue = new ImageLoaderSourceHandler(); } else if (source is FileImageSource) { returnValue = new FileImageSourceHandler(); } else if (source is StreamImageSource) { returnValue = new StreamImagesourceHandler(); } return returnValue; } public static async Task<UIImage> ToUIImage(this ImageSource imageSource) { if (imageSource == null) return null; var handler = GetHandler(imageSource); var image = await handler.LoadImageAsync(imageSource); return image; } } }
31.283019
81
0.630881
[ "MIT" ]
angpysha/Xam.HelpTools
Xam.HelpTools/Platform/Android/Helpers/ImageSourceHelper.ios.cs
1,660
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Threading; using System.Diagnostics; using System.ComponentModel; namespace ShepMUDClient { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { bool menuVis = false; //whether or not the dropdown menu is visible. Default False. //Main main; public Window1() { InitializeComponent(); Title = "ShepMUD"; Width = 960; Height = 540; Show(); //main = new Main(); Main.Startup(this); } public void ChangeText(string text) { ConsoleBox.Text = text; ConsoleBox.ScrollToEnd(); //automatically scroll to the bottom } private void EnterClicked(object sender, KeyEventArgs e) { if (e.Key == Key.Return) { Main.sendMessage(); e.Handled = true; } } private void ConsoleBox_TextChanged(object sender, TextChangedEventArgs e) { } /** * Action Handler for Menu **/ private void MenuItem_Click(object sender, RoutedEventArgs e) { if (sender == M1) //Menu1 pressed { Trace.WriteLine("M1 Pressed"); //<---- debugging behaviour. Change before deployment. CommandControl.HandleCommand("~SetIP 192.168.0.244 2456"); CommandControl.HandleCommand("~Connect"); } else if (sender == M2) //Menu2 pressed { Trace.WriteLine("M2 Pressed"); } else if (sender == M3) //Menu3 pressed { Trace.WriteLine("M3 Pressed"); } } /** * Actionhandler which displays the menu items **/ private void menuDropDown_Click(object sender, RoutedEventArgs e) { if(menuVis == false) //if hidden { M1.Visibility = Visibility.Visible; //make not hidden M2.Visibility = Visibility.Visible; M3.Visibility = Visibility.Visible; } else //else { M1.Visibility = Visibility.Hidden; //make hidden M2.Visibility = Visibility.Hidden; M3.Visibility = Visibility.Hidden; } menuVis = !menuVis; } private void MainWindow_Closing(object sender, CancelEventArgs e) { } } }
28.311927
120
0.525924
[ "MIT" ]
Baradine/ShepMUD
ShepMUDClient/MainWindow.xaml.cs
3,088
C#
using System; using System.Linq; using System.Text.RegularExpressions; namespace SemVer { public class SemVerParser { private const string SemverRegexPattern = @"^(?<major>0|(?:[1-9][0-9]*))\.(?<minor>0|(?:[1-9][0-9]*))\.(?<patch>0|(?:[1-9][0-9]*))" + @"(?:\-(?<prerelease>0|[1-9][0-9]*|[0-9]*[a-zA-Z\-][0-9a-zA-\-]*(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z\-][0-9a-zA-Z\-]*))?))?" + @"(?:\+(?<build>[0-9a-zA-Z\-]+(?:\.[0-9a-zA-Z\-]+)*))?$"; private static readonly Regex SemverRegex = new Regex(SemverRegexPattern, RegexOptions.Compiled | RegexOptions.Singleline); public static Version Parse(string input) { var match = SemverRegex.Match(input); if (!match.Success) throw new ArgumentException($"{input} is not a valid Semantic Version!"); return new Version( match.ParseUint("major"), match.ParseUint("minor"), match.ParseUint("patch"), match.ParseIdentList("prerelease"), match.ParseIdentList("build"), input); } } public static class MatchExtensions { public static uint ParseUint(this Match match, string groupname) { return uint.Parse(match.Groups[groupname].Value); } public static Ident[] ParseIdentList(this Match match, string groupname) { var prereleaseGroup = match.Groups[groupname]; return !prereleaseGroup.Success ? new Ident[] { } : prereleaseGroup.Value.ParseIdentList(); } } public static class StringExtensions { public static Version ParseSemVer(this string input) { return SemVerParser.Parse(input); } public static Ident[] ParseIdentList(this string input) { if (string.IsNullOrWhiteSpace(input)) return new Ident[] { }; var elements = input.Split('.'); return elements.Select(ParseIdent).ToArray(); } public static Ident ParseIdent(this string input) { if (uint.TryParse(input, out var n)) return new Numeric(n); return new AlphaNumeric(input); } } }
33.731343
137
0.554425
[ "MIT" ]
putschoeglwe/SemVer
SemVer/SemVer/SemVerParser.cs
2,262
C#
/* Copyright 2017 Alexis Ryan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; using System.Reflection; namespace Ao3TrackReader.Models { [JsonConverter(typeof(StringEnumConverter))] public enum Ao3PageType { Unknown = 0, Tag, Search, Work, Bookmarks, Series, Collection, Other } [JsonConverter(typeof(StringEnumConverter))] public enum Ao3TagType { Unknown = 0, Warnings, Rating, Category, Complete, Fandoms, Relationships, Characters, Freeforms, Other } [JsonConverter(typeof(StringEnumConverter))] public enum Ao3RequiredTag { Rating, Warnings, Category, Complete } public class Ao3ChapterDetails { public Ao3ChapterDetails() { } public Ao3ChapterDetails(int available, int? total) { Available = available; Total = total; } public int Available { get; set; } public int? Total { get; set; } } public class Ao3SeriesLink { public Ao3SeriesLink() { } public Ao3SeriesLink(long seriesid, string url) { SeriesId = seriesid; Url = url; } public long SeriesId { get; set; } public string Url { get; set; } } public class Ao3WorkDetails { public Ao3WorkDetails() { } public long WorkId { get; set; } public Dictionary<string,string> Authors { get; set; } public Dictionary<string, string> Recipiants { get; set; } public Dictionary<string, Ao3SeriesLink> Series { get; set; } public DateTime? LastUpdated { get; set; } public int? Words { get; set; } public Ao3ChapterDetails Chapters { get; set; } public int? Collections { get; set; } public int? Comments { get; set; } public int? Kudos { get; set; } public int? Bookmarks { get; set; } public int? Hits { get; set; } public int? Works { get; set; } public Text.TextEx Summary { get; set; } [JsonIgnore] public bool? IsComplete { get { return Chapters != null ? Chapters.Available == Chapters.Total : (bool?)null; } } } public class Ao3RequredTagData { public Ao3RequredTagData() { } public Ao3RequredTagData(string tag, string label) { Tag = tag; Label = label; } private string tag; public string Tag { get => tag; set => tag = value.PoolString(); } private string label; public string Label { get => label; set => label = value.PoolString(); } } public class Ao3PageModel { public Ao3PageModel() { } public Uri Uri { set; get; } public Ao3PageType Type { set; get; } private string primaryTag; public string PrimaryTag { set => primaryTag = value.PoolString(); get => primaryTag; } public Ao3TagType PrimaryTagType { set; get; } public string Title; public SortedDictionary<Ao3TagType, List<string>> Tags { set; get; } public Dictionary<Ao3RequiredTag, Ao3RequredTagData> RequiredTags { get; set; } private static Dictionary<string, Uri> requiredTagUris = new Dictionary<string, Uri>(16); public Uri GetRequiredTagUri(Ao3RequiredTag tag) { Ao3RequredTagData rt = null; if (RequiredTags == null || RequiredTags.Count == 0) return null; if (!RequiredTags.TryGetValue(tag, out rt) || rt == null) { if (tag == Ao3RequiredTag.Category) rt = new Ao3RequredTagData("category-none", "None"); else if (tag == Ao3RequiredTag.Complete) rt = new Ao3RequredTagData("category-none", "None"); else if (tag == Ao3RequiredTag.Rating) rt = new Ao3RequredTagData("rating-notrated", "None"); else if (tag == Ao3RequiredTag.Warnings) rt = new Ao3RequredTagData("warning-none", "None"); } lock (requiredTagUris) { if (requiredTagUris.TryGetValue(rt.Tag, out var result)) return result; return requiredTagUris[rt.Tag] = new Uri("https://archiveofourown.org/images/skins/iconsets/default_large/" + rt.Tag + ".png"); } } public string GetRequiredTagText(Ao3RequiredTag tag) { Ao3RequredTagData rt; if (RequiredTags == null || !RequiredTags.TryGetValue(tag, out rt)) return null; return rt.Label; } public string Language { set; get; } public Ao3WorkDetails Details { get; set; } public string SearchQuery { get; set; } public string SortColumn { get; set; } public string SortDirection { get; set; } public IReadOnlyCollection<Ao3PageModel> SeriesWorks { get; set; } [JsonIgnore] public bool HasChapters => Type == Ao3PageType.Series || Type == Ao3PageType.Work || Type == Ao3PageType.Collection; private class SerializationBinder : Newtonsoft.Json.Serialization.DefaultSerializationBinder { public override Type BindToType(string assemblyName, string typeName) { if (assemblyName.StartsWith("Ao3TrackReader", StringComparison.OrdinalIgnoreCase)) assemblyName = GetType().GetTypeInfo().Assembly.FullName; return base.BindToType(assemblyName, typeName); } } static Newtonsoft.Json.JsonSerializerSettings JsonSettings { get; } = new Newtonsoft.Json.JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Auto, TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto, TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat, DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore, Culture = System.Globalization.CultureInfo.InvariantCulture, StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.Default, Formatting = Newtonsoft.Json.Formatting.None, SerializationBinder = new SerializationBinder(), }; string serialized = null; public static string Serialize(Ao3PageModel model) { if (model == null) return null; if (!string.IsNullOrWhiteSpace(model.serialized)) return model.serialized; return model.serialized = Newtonsoft.Json.JsonConvert.SerializeObject(model, JsonSettings); } public static Ao3PageModel Deserialize(string json) { if (string.IsNullOrWhiteSpace(json)) return null; var model = Newtonsoft.Json.JsonConvert.DeserializeObject<Ao3PageModel>(json, JsonSettings); model.serialized = json; return model; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { if (Tags != null) { foreach (var list in Tags.Values) { for (int i = 0; i < list.Count; i++) { list[i] = list[i].PoolString(); } } } } } }
35.310638
143
0.619426
[ "Apache-2.0" ]
Antyos/Ao3-Tracker
Ao3TrackReader/Ao3TrackReader/Models/Ao3PageModel.cs
8,300
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace P_Alarm.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.258065
151
0.580038
[ "MIT" ]
tomaskraus/P-Alarm
P-Alarm/Properties/Settings.Designer.cs
1,064
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01.AllocateArray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.AllocateArray")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ce3a49a3-4e32-42c4-8db3-a2f0b5203fba")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972973
84
0.745196
[ "MIT" ]
DimitarGaydardzhiev/TelerikAcademy
02. C# Part 2/01. Arrays/01.AllocateArray/Properties/AssemblyInfo.cs
1,408
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ExpressionVisitors; using Remotion.Linq.Clauses.StreamedData; using Remotion.Linq.Utilities; using Remotion.Utilities; namespace Remotion.Linq.Clauses.ResultOperators { /// <summary> /// Represents aggregating the items returned by a query into a single value. The first item is used as the seeding value for the aggregating /// function. /// This is a result operator, operating on the whole result set of a query. /// </summary> /// <example> /// In C#, the "Aggregate" call in the following example corresponds to an <see cref="AggregateResultOperator"/>. /// <code> /// var result = (from s in Students /// select s.Name).Aggregate((allNames, name) => allNames + " " + name); /// </code> /// </example> public sealed class AggregateResultOperator : ValueFromSequenceResultOperatorBase { private LambdaExpression _func; /// <summary> /// Initializes a new instance of the <see cref="AggregateResultOperator"/> class. /// </summary> /// <param name="func">The aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so /// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators /// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.</param> public AggregateResultOperator (LambdaExpression func) { ArgumentUtility.CheckNotNull ("func", func); if (func.Type.GetTypeInfo().IsGenericTypeDefinition) throw new ArgumentException ("Open generic delegates are not supported with AggregateResultOperator", "func"); Func = func; } /// <summary> /// Gets or sets the aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so /// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators /// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes. /// </summary> /// <value>The aggregating function.</value> public LambdaExpression Func { get { return _func; } set { ArgumentUtility.CheckNotNull ("value", value); if (value.Type.GetTypeInfo().IsGenericTypeDefinition) throw new ArgumentException ("Open generic delegates are not supported with AggregateResultOperator", "value"); if (!DescribesValidFuncType (value)) { var message = string.Format ( "The aggregating function must be a LambdaExpression that describes an instantiation of 'Func<T,T>', but it is '{0}'.", value.Type); throw new ArgumentException (message, "value"); } _func = value; } } /// <inheritdoc cref="ResultOperatorBase.ExecuteInMemory" /> public override StreamedValue ExecuteInMemory<T> (StreamedSequence input) { ArgumentUtility.CheckNotNull ("input", input); var sequence = input.GetTypedSequence<T>(); var funcLambda = ReverseResolvingExpressionVisitor.ReverseResolveLambda (input.DataInfo.ItemExpression, Func, 1); var func = (Func<T, T, T>) funcLambda.Compile (); var result = sequence.Aggregate (func); return new StreamedValue (result, GetOutputDataInfo (input.DataInfo)); } /// <inheritdoc /> public override ResultOperatorBase Clone (CloneContext cloneContext) { return new AggregateResultOperator (Func); } /// <inheritdoc /> public override IStreamedDataInfo GetOutputDataInfo (IStreamedDataInfo inputInfo) { var sequenceInfo = ArgumentUtility.CheckNotNullAndType<StreamedSequenceInfo> ("inputInfo", inputInfo); return GetOutputDataInfo (sequenceInfo); } private StreamedValueInfo GetOutputDataInfo ([NotNull] StreamedSequenceInfo sequenceInfo) { var expectedItemType = GetExpectedItemType(); CheckSequenceItemType (sequenceInfo, expectedItemType); return new StreamedScalarValueInfo (Func.Body.Type); } public override void TransformExpressions (Func<Expression, Expression> transformation) { ArgumentUtility.CheckNotNull ("transformation", transformation); Func = (LambdaExpression) transformation (Func); } /// <inheritdoc /> public override string ToString () { return "Aggregate(" + Func.BuildString() + ")"; } private bool DescribesValidFuncType (LambdaExpression value) { var funcType = value.Type; if (!funcType.GetTypeInfo().IsGenericType || funcType.GetGenericTypeDefinition () != typeof (Func<,>)) return false; Assertion.DebugAssert (funcType.GetTypeInfo().IsGenericTypeDefinition == false); var genericArguments = funcType.GetTypeInfo().GenericTypeArguments; return genericArguments[0].GetTypeInfo().IsAssignableFrom (genericArguments[1].GetTypeInfo()); } private Type GetExpectedItemType () { Assertion.DebugAssert (Func.Type.GetTypeInfo().IsGenericTypeDefinition == false); return Func.Type.GetTypeInfo().GenericTypeArguments[0]; } } }
40.97351
154
0.706966
[ "ECL-2.0", "Apache-2.0" ]
biohazard999/Relinq
Core/Clauses/ResultOperators/AggregateResultOperator.cs
6,187
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Microsoft.Practices.Unity.Properties; namespace Microsoft.Practices.ObjectBuilder2 { /// <summary> /// This class records the information about which constructor argument is currently /// being resolved, and is responsible for generating the error string required when /// an error has occurred. /// </summary> public class ConstructorArgumentResolveOperation : BuildOperation { private readonly string constructorSignature; private readonly string parameterName; /// <summary> /// Initializes a new instance of the <see cref="ConstructorArgumentResolveOperation"/> class. /// </summary> /// <param name="typeBeingConstructed">The type that is being constructed.</param> /// <param name="constructorSignature">A string representing the constructor being called.</param> /// <param name="parameterName">Parameter being resolved.</param> public ConstructorArgumentResolveOperation(Type typeBeingConstructed, string constructorSignature, string parameterName) : base(typeBeingConstructed) { this.constructorSignature = constructorSignature; this.parameterName = parameterName; } /// <summary> /// Generate the string describing what parameter was being resolved. /// </summary> /// <returns>The description string.</returns> public override string ToString() { return string.Format(CultureInfo.CurrentCulture, Resources.ConstructorArgumentResolveOperation, this.parameterName, this.constructorSignature); } /// <summary> /// String describing the constructor being set up. /// </summary> public string ConstructorSignature { get { return this.constructorSignature; } } /// <summary> /// Parameter that's being resolved. /// </summary> public string ParameterName { get { return this.parameterName; } } } }
37.241935
128
0.657427
[ "Apache-2.0", "MIT" ]
drcarver/unity
source/Unity/Src/ObjectBuilder/Strategies/BuildPlan/DynamicMethod/Creation/ConstructorArgumentResolveOperation.cs
2,311
C#
namespace Sledge.Common.Translations { /// <summary> /// A translation language /// </summary> public class Language { /// <summary> /// The language code /// </summary> public string Code { get; } /// <summary> /// A description of the language, ideally with both native and English text. /// </summary> public string Description { get; set; } /// <summary> /// The language code to inherit from, or null if language should not inherit. /// For non-English languages, this should be set to 'en' so untranslated strings are English instead of blank. /// </summary> public string Inherit { get; set; } /// <summary> /// The string collection for this language /// </summary> public TranslationStringsCollection Collection { get; } public Language(string code) { Code = code; Description = null; Inherit = null; Collection = new TranslationStringsCollection(); } } }
29.72973
119
0.56
[ "BSD-3-Clause" ]
LogicAndTrick/sledge
Sledge.Common/Translations/Language.cs
1,100
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.Description; namespace Microsoft.Azure.WebJobs { [Binding] public sealed class RabbitMQTriggerAttribute : Attribute { public RabbitMQTriggerAttribute(string queueName) { QueueName = queueName; } public RabbitMQTriggerAttribute(string exchangeName, string xMatch, string arguments) { ExchangeName = exchangeName; XMatch = xMatch; Arguments = arguments; } public RabbitMQTriggerAttribute(string hostName, string userNameSetting, string passwordSetting, int port, string queueName) { HostName = hostName; UserNameSetting = userNameSetting; PasswordSetting = passwordSetting; Port = port; QueueName = queueName; } [ConnectionString] public string ConnectionStringSetting { get; set; } public string HostName { get; set; } public string QueueName { get; } [AppSetting] public string UserNameSetting { get; set; } [AppSetting] public string PasswordSetting { get; set; } public int Port { get; set; } public string DeadLetterExchangeName { get; set; } public string ExchangeName { get; set; } public string XMatch { get; set; } public string Arguments { get; set; } } }
28.137931
133
0.604167
[ "MIT" ]
ianrathbone/azure-functions-rabbitmq-extension
src/Trigger/RabbitMQTriggerAttribute.cs
1,634
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using ImGuiNET; using SharpDX.Direct2D1; using SharpDX.Direct3D11; using Xacor.Game; using Xacor.Graphics.Api; using Buffer = System.Buffer; using CullMode = Xacor.Graphics.Api.CullMode; using FillMode = Xacor.Graphics.Api.FillMode; using Num = System.Numerics; namespace Xacor.Demo { /* public sealed class ImGuiRenderer : IDisposable { private readonly IGraphicsFactory _graphicsFactory; private readonly ITextureFactory _textureFactory; private readonly IGraphicsDevice _graphicsDevice; private IShader _effect; private readonly IRasterizerState _rasterizerState; private byte[] _vertexData; private IVertexBuffer _vertexBuffer; private int _vertexBufferSize; private byte[] _indexData; private IIndexBuffer _indexBuffer; private int _indexBufferSize; private readonly Dictionary<IntPtr, ITexture> _loadedTextures; private ITexture _fontAtlasTexture; private int _textureId; private IntPtr? _fontAtlasTextureId; private int _scrollWheelValue; private readonly List<int> _keys = new List<int>(); public ImGuiRenderer(GameBase game, IGraphicsFactory graphicsFactory, ITextureFactory textureFactory) { _graphicsFactory = graphicsFactory; _textureFactory = textureFactory; var context = ImGui.CreateContext(); ImGui.SetCurrentContext(context); _graphicsDevice = game.GraphicsDevice; _loadedTextures = new Dictionary<IntPtr, ITexture>(); _rasterizerState = _graphicsFactory.CreateRasterizerState( CullMode.None, FillMode.Solid, false, true, false, false); var io = ImGui.GetIO(); io.ConfigFlags = ImGuiConfigFlags.DockingEnable; SetupInput(io); //SetRedStyle(ImGui.GetStyle()); } public unsafe void RebuildFontAtlas() { var io = ImGui.GetIO(); io.Fonts.GetTexDataAsRGBA32(out byte* pixelData, out var width, out var height, out var bytesPerPixel); var pixels = new byte[width * height * bytesPerPixel]; Marshal.Copy(new IntPtr(pixelData), pixels, 0, pixels.Length); _fontAtlasTexture?.Dispose(); _fontAtlasTexture = _textureFactory.CreateTexture(width, height, Format.R8G8B8UNorm, false); _fontAtlasTexture.SetData(pixels); if (_fontAtlasTextureId.HasValue) { UnbindTexture(_fontAtlasTextureId.Value); } _fontAtlasTextureId = BindTexture(_fontAtlasTexture); io.Fonts.SetTexID(_fontAtlasTextureId.Value); io.Fonts.ClearTexData(); } public IntPtr BindTexture(ITexture texture) { var id = new IntPtr(_textureId++); _loadedTextures.Add(id, texture); return id; } public void Dispose() { _fontAtlasTexture?.Dispose(); } public void UnbindTexture(IntPtr textureId) { _loadedTextures.Remove(textureId); } public void BeginLayout(float gameTime) { ImGui.GetIO().DeltaTime = gameTime; UpdateInput(); ImGui.NewFrame(); } public void EndLayout() { ImGui.Render(); RenderDrawData(ImGui.GetDrawData()); } private void SetupInput(ImGuiIOPtr io) { _keys.Add(io.KeyMap[(int)ImGuiKey.Tab] = (int)Keys.Tab); _keys.Add(io.KeyMap[(int)ImGuiKey.LeftArrow] = (int)Keys.Left); _keys.Add(io.KeyMap[(int)ImGuiKey.RightArrow] = (int)Keys.Right); _keys.Add(io.KeyMap[(int)ImGuiKey.UpArrow] = (int)Keys.Up); _keys.Add(io.KeyMap[(int)ImGuiKey.DownArrow] = (int)Keys.Down); _keys.Add(io.KeyMap[(int)ImGuiKey.PageUp] = (int)Keys.PageUp); _keys.Add(io.KeyMap[(int)ImGuiKey.PageDown] = (int)Keys.PageDown); _keys.Add(io.KeyMap[(int)ImGuiKey.Home] = (int)Keys.Home); _keys.Add(io.KeyMap[(int)ImGuiKey.End] = (int)Keys.End); _keys.Add(io.KeyMap[(int)ImGuiKey.Delete] = (int)Keys.Delete); _keys.Add(io.KeyMap[(int)ImGuiKey.Backspace] = (int)Keys.Back); _keys.Add(io.KeyMap[(int)ImGuiKey.Enter] = (int)Keys.Enter); _keys.Add(io.KeyMap[(int)ImGuiKey.Escape] = (int)Keys.Escape); _keys.Add(io.KeyMap[(int)ImGuiKey.A] = (int)Keys.A); _keys.Add(io.KeyMap[(int)ImGuiKey.C] = (int)Keys.C); _keys.Add(io.KeyMap[(int)ImGuiKey.V] = (int)Keys.V); _keys.Add(io.KeyMap[(int)ImGuiKey.X] = (int)Keys.X); _keys.Add(io.KeyMap[(int)ImGuiKey.Y] = (int)Keys.Y); _keys.Add(io.KeyMap[(int)ImGuiKey.Z] = (int)Keys.Z); TextInputEXT.TextInput += c => { if (c == '\t') { return; } ImGui.GetIO().AddInputCharacter(c); }; ImGui.GetIO().Fonts.AddFontDefault(); } protected Effect UpdateEffect(Texture2D texture) { _effect ??= new BasicEffect(_graphicsDevice); var io = ImGui.GetIO(); var offset = 0f; _effect.World = Matrix.Identity; _effect.View = Matrix.Identity; _effect.Projection = Matrix.CreateOrthographicOffCenter( offset, io.DisplaySize.X + offset, io.DisplaySize.Y + offset, offset, -1f, 1f ); _effect.TextureEnabled = true; _effect.Texture = texture; _effect.VertexColorEnabled = true; return _effect; } public void UpdateInput() { var io = ImGui.GetIO(); var mouse = Mouse.GetState(); var keyboard = Keyboard.GetState(); for (var i = 0; i < _keys.Count; i++) { io.KeysDown[_keys[i]] = keyboard.IsKeyDown((Keys)_keys[i]); } io.KeyShift = keyboard.IsKeyDown(Keys.LeftShift) || keyboard.IsKeyDown(Keys.RightShift); io.KeyCtrl = keyboard.IsKeyDown(Keys.LeftControl) || keyboard.IsKeyDown(Keys.RightControl); io.KeyAlt = keyboard.IsKeyDown(Keys.LeftAlt) || keyboard.IsKeyDown(Keys.RightAlt); io.KeySuper = keyboard.IsKeyDown(Keys.LeftWindows) || keyboard.IsKeyDown(Keys.RightWindows); io.DisplaySize = new Num.Vector2( _graphicsDevice.PresentationParameters.BackBufferWidth, _graphicsDevice.PresentationParameters.BackBufferHeight ); io.DisplayFramebufferScale = new Num.Vector2(1f, 1f); io.MousePos = new Num.Vector2(mouse.X, mouse.Y); io.MouseDown[0] = mouse.LeftButton == ButtonState.Pressed; io.MouseDown[1] = mouse.RightButton == ButtonState.Pressed; io.MouseDown[2] = mouse.MiddleButton == ButtonState.Pressed; var scrollDelta = mouse.ScrollWheelValue - _scrollWheelValue; io.MouseWheel = scrollDelta > 0 ? 1 : scrollDelta < 0 ? -1 : 0; _scrollWheelValue = mouse.ScrollWheelValue; } private void RenderDrawData(ImDrawDataPtr drawData) { // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers var lastViewport = _graphicsDevice.Viewport; var lastScissorBox = _graphicsDevice.ScissorRectangle; _graphicsDevice.BlendFactor = Color.White; _graphicsDevice.BlendState = BlendState.NonPremultiplied; _graphicsDevice.RasterizerState = _rasterizerState; _graphicsDevice.DepthStencilState = DepthStencilState.DepthRead; // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) drawData.ScaleClipRects(ImGui.GetIO().DisplayFramebufferScale); // Setup projection _graphicsDevice.Viewport = new Viewport( 0, 0, _graphicsDevice.PresentationParameters.BackBufferWidth, _graphicsDevice.PresentationParameters.BackBufferHeight ); UpdateBuffers(drawData); RenderCommandLists(drawData); // Restore modified state _graphicsDevice.Viewport = lastViewport; _graphicsDevice.ScissorRectangle = lastScissorBox; } private unsafe void UpdateBuffers(ImDrawDataPtr drawData) { if (drawData.TotalVtxCount == 0) { return; } if (drawData.TotalVtxCount > _vertexBufferSize) { _vertexBuffer?.Dispose(); _vertexBufferSize = (int)(drawData.TotalVtxCount * 1.5f); _vertexBuffer = new VertexBuffer( _graphicsDevice, ImGuiDrawVertexDeclaration.Declaration, _vertexBufferSize, BufferUsage.None ); _vertexData = new byte[_vertexBufferSize * ImGuiDrawVertexDeclaration.Size]; } if (drawData.TotalIdxCount > _indexBufferSize) { _indexBuffer?.Dispose(); _indexBufferSize = (int)(drawData.TotalIdxCount * 1.5f); _indexBuffer = new IndexBuffer(_graphicsDevice, IndexElementSize.SixteenBits, _indexBufferSize, BufferUsage.None); _indexData = new byte[_indexBufferSize * sizeof(ushort)]; } // Copy ImGui's vertices and indices to a set of managed byte arrays var vtxOffset = 0; var idxOffset = 0; for (var n = 0; n < drawData.CmdListsCount; n++) { var cmdList = drawData.CmdListsRange[n]; fixed (void* vtxDstPtr = &_vertexData[vtxOffset * ImGuiDrawVertexDeclaration.Size]) { fixed (void* idxDstPtr = &_indexData[idxOffset * sizeof(ushort)]) { Buffer.MemoryCopy( (void*)cmdList.VtxBuffer.Data, vtxDstPtr, _vertexData.Length, cmdList.VtxBuffer.Size * ImGuiDrawVertexDeclaration.Size ); Buffer.MemoryCopy( (void*)cmdList.IdxBuffer.Data, idxDstPtr, _indexData.Length, cmdList.IdxBuffer.Size * sizeof(ushort) ); } } vtxOffset += cmdList.VtxBuffer.Size; idxOffset += cmdList.IdxBuffer.Size; } // Copy the managed byte arrays to the gpu vertex- and index buffers _vertexBuffer.SetData(_vertexData, 0, drawData.TotalVtxCount * ImGuiDrawVertexDeclaration.Size); _indexBuffer.SetData(_indexData, 0, drawData.TotalIdxCount * sizeof(ushort)); } private unsafe void RenderCommandLists(ImDrawDataPtr drawData) { _graphicsDevice.SetVertexBuffer(_vertexBuffer); _graphicsDevice.Indices = _indexBuffer; var vtxOffset = 0; var idxOffset = 0; for (var n = 0; n < drawData.CmdListsCount; n++) { var cmdList = drawData.CmdListsRange[n]; for (var cmdi = 0; cmdi < cmdList.CmdBuffer.Size; cmdi++) { var drawCmd = cmdList.CmdBuffer[cmdi]; if (!_loadedTextures.ContainsKey(drawCmd.TextureId)) { throw new InvalidOperationException( $"Could not find a texture with id '{drawCmd.TextureId}', please check your bindings" ); } _graphicsDevice.ScissorRectangle = new Rectangle( (int)drawCmd.ClipRect.X, (int)drawCmd.ClipRect.Y, (int)(drawCmd.ClipRect.Z - drawCmd.ClipRect.X), (int)(drawCmd.ClipRect.W - drawCmd.ClipRect.Y) ); var effect = UpdateEffect(_loadedTextures[drawCmd.TextureId]); foreach (var pass in effect.CurrentTechnique.Passes) { pass.Apply(); #pragma warning disable CS0618 // // FNA does not expose an alternative method. _graphicsDevice.DrawIndexedPrimitives( primitiveType: PrimitiveType.TriangleList, baseVertex: vtxOffset, minVertexIndex: 0, numVertices: cmdList.VtxBuffer.Size, startIndex: idxOffset, primitiveCount: (int)drawCmd.ElemCount / 3 ); #pragma warning restore CS0618 } idxOffset += (int)drawCmd.ElemCount; } vtxOffset += cmdList.VtxBuffer.Size; } } } */ }
36.399471
141
0.55629
[ "MIT" ]
deccer/Xacor
Demos/Xacor.Demo/ImGuiRenderer.cs
13,761
C#
using System.ComponentModel.DataAnnotations; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; using Ascend2018.Business.Rendering; using Ascend2018.Models.Properties; using EPiServer.Web; namespace Ascend2018.Models.Pages { /// <summary> /// Base class for all page types /// </summary> public abstract class SitePageData : PageData, ICustomCssInContentArea { [Display( GroupName = Global.GroupNames.MetaData, Order = 100)] [CultureSpecific] public virtual string MetaTitle { get { var metaTitle = this.GetPropertyValue(p => p.MetaTitle); // Use explicitly set meta title, otherwise fall back to page name return !string.IsNullOrWhiteSpace(metaTitle) ? metaTitle : PageName; } set { this.SetPropertyValue(p => p.MetaTitle, value); } } [Display( GroupName = Global.GroupNames.MetaData, Order = 200)] [CultureSpecific] [BackingType(typeof(PropertyStringList))] public virtual string[] MetaKeywords { get; set; } [Display( GroupName = Global.GroupNames.MetaData, Order = 300)] [CultureSpecific] [UIHint(UIHint.Textarea)] public virtual string MetaDescription { get; set; } [Display( GroupName = Global.GroupNames.MetaData, Order = 400)] [CultureSpecific] public virtual bool DisableIndexing { get; set; } [Display( GroupName = SystemTabNames.Content, Order = 100)] [UIHint(UIHint.Image)] public virtual ContentReference PageImage { get; set; } [Display( GroupName = SystemTabNames.Content, Order = 200)] [CultureSpecific] [UIHint(UIHint.Textarea)] public virtual string TeaserText { get { var teaserText = this.GetPropertyValue(p => p.TeaserText); // Use explicitly set teaser text, otherwise fall back to description return !string.IsNullOrWhiteSpace(teaserText) ? teaserText : MetaDescription; } set { this.SetPropertyValue(p => p.TeaserText, value); } } [Display( GroupName = SystemTabNames.Settings, Order = 200)] [CultureSpecific] public virtual bool HideSiteHeader { get; set; } [Display( GroupName = SystemTabNames.Settings, Order = 300)] [CultureSpecific] public virtual bool HideSiteFooter { get; set; } public string ContentAreaCssClass { get { return "teaserblock"; } //Page partials should be style like teasers } } }
30.525773
86
0.566025
[ "Apache-2.0" ]
episerver/ascend2018-lab-extend-ui
Alloy/Ascend2018/Models/Pages/SitePageData.cs
2,961
C#
// Copyright (c) Ryan Foster. All rights reserved. // Licensed under the Apache License, Version 2.0. using System; namespace SimpleIAM.PasswordlessLogin.Models { public class OneTimeCode { public string SentTo { get; set; } public string ClientNonceHash { get; set; } public string ShortCode { get; set; } public string LongCode { get; set; } public DateTime ExpiresUTC { get; set; } public int FailedAttemptCount { get; set; } public int SentCount { get; set; } public string RedirectUrl { get; set; } } }
22.037037
52
0.630252
[ "Apache-2.0" ]
SimpleIAM/PasswordlessLogin
PasswordlessLogin/Models/OneTimeCode.cs
597
C#
namespace ScintillaNET_Components { #region Using Directives using ScintillaNET; using ScintillaNET_Components.SearchTypes; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text.RegularExpressions; using System.Windows.Forms; #endregion Using Directives /// <summary> /// Class to enable programmatic and GUI-based finding and replacing of text in a <see cref="Scintilla"/> editor. /// </summary> public class FindReplace : ComponentManager { #region Fields private readonly int _historyMaxCount = 10; #endregion Fields #region Constructors /// <summary> /// Creates an instance of <see cref="FindReplace"/> with associated /// <see cref="FindReplaceDialog"/> and <see cref="IncrementalSearcher"/> instances. /// </summary> /// <param name="editor">The <see cref="Scintilla"/> editor to which the <see cref="FindReplace"/> is attached.</param> public FindReplace(Scintilla editor) : base() { Window = CreateWindowInstance(); Window.KeyPressed += FindReplace_KeyPressed; SearchBar = CreateIncrementalSearcherInstance(); SearchBar.KeyPressed += FindReplace_KeyPressed; SearchBar.Visible = false; FindHistory = new List<string> { Capacity = _historyMaxCount }; ReplaceHistory = new List<string> { Capacity = _historyMaxCount }; if (editor != null) { Editor = editor; } } /// <summary> /// Creates an instance of <see cref="FindReplace"/> with associated /// <see cref="FindReplaceDialog"/> and <see cref="IncrementalSearcher"/> instances. /// </summary> public FindReplace() : this(null) { } #endregion Constructors #region Events /// <summary> /// Triggered when a key is pressed on the <see cref="FindReplaceDialog"/>. /// </summary> public event KeyPressedHandler KeyPressed; /// <summary> /// Handler for the key press on the <see cref="FindReplaceDialog"/>. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The key info of the key(s) pressed.</param> public delegate void KeyPressedHandler(object sender, KeyEventArgs e); #endregion Events #region Properties /// <summary> /// Gets or sets the associated <see cref="Scintilla"/> control that <see cref="FindReplace"/> can act upon. /// </summary> public override Scintilla Editor { get { return base.Editor; } set { base.Editor = value; FoundMarker = new Marker(Editor, Constants.FoundMarkerIndex) { Symbol = MarkerSymbol.SmallRect, }; FoundMarker.SetForeColor(Color.DarkOrange); FoundMarker.SetBackColor(Color.DarkOrange); FoundIndicator = new Indicator(Editor, Constants.FoundIndicatorIndex) { ForeColor = Color.DarkOrange, Alpha = 100, Style = IndicatorStyle.RoundBox, Under = true }; Editor.Controls.Add(SearchBar); Editor.Resize += ResizeEditor; UpdateHighlights = true; } } /// <summary> /// Gets or sets the <see cref="IncrementalSearcher"/>. /// </summary> public IncrementalSearcher SearchBar { get; set; } /// <summary> /// Gets or sets the <see cref="FindReplaceDialog"/> instance. /// </summary> public FindReplaceDialog Window { get; set; } /// <summary> /// Gets or sets the <see cref="Indicator"/> used to mark found results in the document. /// </summary> public Indicator FoundIndicator { get; set; } /// <summary> /// Gets or sets the <see cref="Marker"/> used to mark found results in the margin. /// </summary> public Marker FoundMarker { get; set; } /// <summary> /// Gets the <see cref="Search"/> object that encapsualtes the last completed find/replace action. /// </summary> public Search CurrentQuery { get; internal set; } /// <summary> /// Gets the <see cref="List{CharacterRange}"/> that contains the last find/replace results. /// </summary> public List<CharacterRange> CurrentResults { get; private set; } /// <summary> /// Gets the list of terms that have been searched. /// </summary> public List<string> FindHistory { get; } /// <summary> /// Gets the list of terms used to replace search results. /// </summary> public List<string> ReplaceHistory { get; } internal bool UpdateHighlights { get; set; } #endregion Properties #region Methods #region Find /// <summary> /// Searches for the first or last instance of the given Regular Expression in the given range of the <see cref="Scintilla"/> text. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="searchUp">Search direction. Set to true to search from the bottom up.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Find(CharacterRange searchRange, Regex findExpression, bool searchUp) { RegexSearch query = new RegexSearch { SearchRange = searchRange, SearchExpression = findExpression, SearchUp = searchUp }; return query.Find(Editor); } /// <summary> /// Searches for the first or last instance of the given string in the given range of the <see cref="Scintilla"/> text, using the specified options. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="searchUp">Search direction. Set to true to search from the bottom up.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Find(CharacterRange searchRange, string searchString, SearchFlags searchFlags, bool searchUp) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags, SearchUp = searchUp }; return query.Find(Editor); } /// <summary> /// Searches for the first or last instance of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// <param name="searchUp">Search direction. Set to true to search from the bottom up.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Find(Search query, bool searchUp) { query.SearchUp = searchUp; return query.Find(Editor); } #endregion Find #region FindAll /// <summary> /// Searches for all instances of the given Regular Expression in the full body of the <see cref="Scintilla"/> text, and optionally and marks/highlights them. /// </summary> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> FindAll(Regex findExpression, bool mark, bool highlight) { return FindAll(new CharacterRange(0, Editor.TextLength), findExpression, mark, highlight); } /// <summary> /// Searches for all instances of the given Regular Expression in the given range of the <see cref="Scintilla"/> text, and optionally and marks/highlights them. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> FindAll(CharacterRange searchRange, Regex findExpression, bool mark, bool highlight) { RegexSearch query = new RegexSearch() { SearchRange = searchRange, SearchExpression = findExpression }; return FindAll(query, mark, highlight); } /// <summary> /// Searches for all instances of the given string in the full body of the <see cref="Scintilla"/> text, using the specified options, and optionally and marks/highlights them. /// </summary> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> FindAll(string searchString, SearchFlags searchFlags, bool mark, bool highlight) { return FindAll(new CharacterRange(0, Editor.TextLength), searchString, searchFlags, mark, highlight); } /// <summary> /// Searches for all instances of the given string in the given range of the <see cref="Scintilla"/> text, using the specified options, and optionally and marks/highlights them. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> FindAll(CharacterRange searchRange, string searchString, SearchFlags searchFlags, bool mark, bool highlight) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags }; return FindAll(query, mark, highlight); } /// <summary> /// Searches for all instances of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text, and optionally and marks/highlights them. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> FindAll(Search query, bool mark, bool highlight) { return UpdateResults(query, mark, highlight); } #endregion FindAll #region FindNext /// <summary> /// Searches for the next instance of the given Regular Expression in the full body of the <see cref="Scintilla"/> text based on the current caret position, optionally wrapping back to the beginning. /// </summary> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindNext(Regex findExpression, bool wrap) { return FindNext(new CharacterRange(0, Editor.TextLength), findExpression, wrap); } /// <summary> /// Searches for the next instance of the given Regular Expression in the given range of the <see cref="Scintilla"/> text based on the current caret position, optionally wrapping back to the beginning. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindNext(CharacterRange searchRange, Regex findExpression, bool wrap) { RegexSearch query = new RegexSearch() { SearchRange = searchRange, SearchExpression = findExpression }; UpdateResults(query); return query.FindNext(Editor, wrap); } /// <summary> /// Searches for the next instance of the given string in the full body of the <see cref="Scintilla"/> text based on the current caret position, using the specified options, and optionally wrapping back to the beginning. /// </summary> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindNext(string searchString, SearchFlags searchFlags, bool wrap) { return FindNext(new CharacterRange(0, Editor.TextLength), searchString, searchFlags, wrap); } /// <summary> /// Searches for the next instance of the given string in the given range of the <see cref="Scintilla"/> text based on the current caret position, using the specified options, and optionally wrapping back to the beginning. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindNext(CharacterRange searchRange, string searchString, SearchFlags searchFlags, bool wrap) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags }; return FindNext(query, wrap); } /// <summary> /// Searches for the next instance of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindNext(Search query, bool wrap) { UpdateResults(query); return query.FindNext(Editor, wrap); } #endregion FindNext #region FindPrevious /// <summary> /// Searches for the previous instance of the given Regular Expression in the full body of the <see cref="Scintilla"/> text based on the current caret position, optionally wrapping back to the end. /// </summary> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the end of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindPrevious(Regex findExpression, bool wrap) { return FindPrevious(new CharacterRange(0, Editor.TextLength), findExpression, wrap); } /// <summary> /// Searches for the previous instance of the given Regular Expression in the given range of the <see cref="Scintilla"/> text based on the current caret position, optionally wrapping back to the end. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the end of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindPrevious(CharacterRange searchRange, Regex findExpression, bool wrap) { RegexSearch query = new RegexSearch() { SearchRange = searchRange, SearchExpression = findExpression }; UpdateResults(query); return query.FindPrevious(Editor, wrap); } /// <summary> /// Searches for the previous instance of the given string in the full body of the <see cref="Scintilla"/> text based on the current caret position, using the specified options, and optionally wrapping back to the end. /// </summary> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the end of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindPrevious(string searchString, SearchFlags searchFlags, bool wrap) { return FindPrevious(new CharacterRange(0, Editor.TextLength), searchString, searchFlags, wrap); } /// <summary> /// Searches for the previous instance of the given string in the given range of the <see cref="Scintilla"/> text based on the current caret position, using the specified options, and optionally wrapping back to the end. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the end of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindPrevious(CharacterRange searchRange, string searchString, SearchFlags searchFlags, bool wrap) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags }; return FindPrevious(query, wrap); } /// <summary> /// Searches for the previous instance of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange FindPrevious(Search query, bool wrap) { UpdateResults(query); return query.FindPrevious(Editor, wrap); } #endregion FindPrevious #region Replace /// <summary> /// Replaces the next instance of the given Regular Expression in the full body of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Replace(Regex findExpression, string replaceString, bool wrap) { return Replace(new CharacterRange(0, Editor.TextLength), findExpression, replaceString, wrap); } /// <summary> /// Replaces the next instance of the given Regular Expression in the given range of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Replace(CharacterRange searchRange, Regex findExpression, string replaceString, bool wrap) { RegexSearch query = new RegexSearch() { SearchRange = searchRange, SearchExpression = findExpression }; UpdateResults(query); return query.Replace(Editor, replaceString, wrap); } /// <summary> /// Replaces the next instance of the given string in the full body of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchString">Text for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Replace(string searchString, string replaceString, SearchFlags searchFlags, bool wrap) { return Replace(new CharacterRange(0, Editor.TextLength), searchString, replaceString, searchFlags, wrap); } /// <summary> /// Replaces the next instance of the given string in the given range of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Replace(CharacterRange searchRange, string searchString, string replaceString, SearchFlags searchFlags, bool wrap) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags }; return Replace(query, replaceString, wrap); } /// <summary> /// Replaces the next instance of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="wrap">Set to true to allow the search to wrap back to the beginning of the text.</param> /// <returns><see cref="CharacterRange"/> where the result was found. /// <see cref="CharacterRange.cpMin"/> will be the same as <see cref="CharacterRange.cpMax"/> if no match was found.</returns> public CharacterRange Replace(Search query, string replaceString, bool wrap) { UpdateResults(query); return query.Replace(Editor, replaceString, wrap); } #endregion Replace #region ReplaceAll /// <summary> /// Replaces all instances of the given Regular Expression in the full body of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> ReplaceAll(Regex findExpression, string replaceString, bool mark, bool highlight) { return ReplaceAll(new CharacterRange(0, Editor.TextLength), findExpression, replaceString, mark, highlight); } /// <summary> /// Replaces all instances of the given Regular Expression in the given range of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="findExpression"><see cref="Regex"/> for which to search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> ReplaceAll(CharacterRange searchRange, Regex findExpression, string replaceString, bool mark, bool highlight) { RegexSearch query = new RegexSearch() { SearchRange = searchRange, SearchExpression = findExpression }; return ReplaceAll(query, replaceString, mark, highlight); } /// <summary> /// Replaces all instances of the given string in the full body of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchString">Text for which to search.</param> /// <param name="replaceString">String to replace any matches.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> ReplaceAll(string searchString, string replaceString, SearchFlags searchFlags, bool mark, bool highlight) { return ReplaceAll(new CharacterRange(0, Editor.TextLength), searchString, replaceString, searchFlags, mark, highlight); } /// <summary> /// Replaces all instances of the given string in the given range of the <see cref="Scintilla"/> text with the given string. /// </summary> /// <param name="searchRange"><see cref="CharacterRange"/> in which to search.</param> /// <param name="searchString">Text for which to search.</param> /// <param name="replaceString">String to replace any matches.</param> /// <param name="searchFlags"><see cref="SearchFlags"/> enumeration that sets the pattern matching options.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns><see cref="List{CharacterRange}"/> containing the locations of every match. Empty if none were found.</returns> public List<CharacterRange> ReplaceAll(CharacterRange searchRange, string searchString, string replaceString, SearchFlags searchFlags, bool mark, bool highlight) { StringSearch query = new StringSearch() { SearchRange = searchRange, SearchString = searchString, Flags = searchFlags }; return ReplaceAll(query, replaceString, mark, highlight); } /// <summary> /// Replaces all instances of the given <see cref="Search"/> query in the <see cref="Scintilla"/> text with the given string, and optionally and marks/highlights them. /// </summary> /// <param name="query"><see cref="Search"/> object to use to perform the search.</param> /// <param name="replaceString">String to replace any matches. Can be a regular expression pattern if <c>query</c> is a <see cref="RegexSearch"/> object.</param> /// <param name="mark">Set to true to use the configured margin marker to indicate the lines where matches were found.</param> /// <param name="highlight">Set to true to use the configured text indicator to highlight each match.</param> /// <returns></returns> public List<CharacterRange> ReplaceAll(Search query, string replaceString, bool mark, bool highlight) { return query.ReplaceAll(Editor, replaceString); } #endregion ReplaceAll #region Show /// <summary> /// Shows the <see cref="FindReplaceDialog"/> with the Find tab active. /// </summary> public void ShowFind() { ShowFindReplaceTab("tpgFind"); } /// <summary> /// Shows the <see cref="FindReplaceDialog"/> with the Replace tab active. /// </summary> public void ShowReplace() { ShowFindReplaceTab("tpgReplace"); } /// <summary> /// Hides the <see cref="FindReplaceDialog"/>. /// </summary> public void HideFindReplace() { if (Window.Visible) { Window.Hide(); } Editor.Focus(); } // Displays the FindReplaceDialog with the specified tab active, and sets the selection/text appropriately. private void ShowFindReplaceTab(string tabName) { HideIncrementalSearch(); if (!Window.Visible) { Window.Show(Editor.FindForm()); } Window.tabAll.SelectedTab = Window.tabAll.TabPages[tabName]; if (Editor.LineFromPosition(Editor.Selections[0].Start) != Editor.LineFromPosition(Editor.Selections[0].End)) { Window.chkSearchSelection.Checked = true; } if (CurrentQuery != null) { Window.txtFind.Text = CurrentQuery.ToString(); } else if (Editor.Selections[0].End > Editor.Selections[0].Start) { Window.txtFind.Text = Editor.SelectedText; } Window.txtFind.Select(); Window.txtFind.SelectAll(); } /// <summary> /// Shows the <see cref="IncrementalSearcher"/> control. /// </summary> public void ShowIncrementalSearch() { HideFindReplace(); SetIncrementalSearchPosition(); if (CurrentQuery != null) { SearchBar.txtFind.Text = CurrentQuery.ToString(); } else if (Editor.Selections[0].End > Editor.Selections[0].Start) { SearchBar.txtFind.Text = Editor.SelectedText; } SearchBar.Show(); SearchBar.txtFind.Focus(); SearchBar.txtFind.SelectAll(); } /// <summary> /// Hides the <see cref="IncrementalSearcher"/> control. /// </summary> public void HideIncrementalSearch() { if (SearchBar.Visible) { SearchBar.Hide(); } Editor.Focus(); } // Set the searchbar position along the bottom of the editor private void SetIncrementalSearchPosition() { SearchBar.Left = Editor.ClientRectangle.Left; SearchBar.Top = Editor.ClientRectangle.Bottom - SearchBar.Height; SearchBar.Width = Editor.ClientRectangle.Width; } // Update the searchbar position if the editor resizes private void ResizeEditor(object sender, EventArgs e) { SetIncrementalSearchPosition(); } #endregion Show #region Search UI /// <summary> /// Searches for the given <see cref="CharacterRange"/> in the current results and returns a string describing its index. /// </summary> /// <param name="r"><see cref="CharacterRange"/> of interest.</param> /// <returns>String in the format "i out of N matches".</returns> public string GetIndexString(CharacterRange r) { if ((CurrentResults != null) && (r.cpMax != r.cpMin)) { var index = CurrentResults.BinarySearch(r) + 1; return index + " out of " + CurrentResults.Count + " matches"; } else { return string.Empty; } } /// <summary> /// Clears highlights from the entire <see cref="Scintilla"/> text. /// </summary> public List<CharacterRange> ClearAllHighlights() { if (Editor != null) { int currentIndicator = Editor.IndicatorCurrent; Editor.IndicatorCurrent = FoundIndicator.Index; Editor.IndicatorClearRange(0, Editor.TextLength); Editor.IndicatorCurrent = currentIndicator; } return CurrentResults; } /// <summary> /// Clears find marks from the margins for the entire <see cref="Scintilla"/> text. /// </summary> public List<CharacterRange> ClearAllMarks() { if (Editor != null) { Editor.MarkerDeleteAll(FoundMarker.Index); } return CurrentResults; } /// <summary> /// Clears both marks and highlight. /// </summary> public List<CharacterRange> Clear() { if (Editor != null) { ClearAllMarks(); ClearAllHighlights(); CurrentQuery = null; CurrentResults = new List<CharacterRange>(); UpdateHighlights = true; } return CurrentResults; } /// <summary> /// Highlight ranges in the <see cref="Scintilla"/> text using the configured <see cref="Indicator"/>. /// </summary> /// <param name="ranges">List of ranges to which highlighting should be applied.</param> public void Highlight(List<CharacterRange> ranges) { if (Editor != null) { ClearAllHighlights(); Editor.IndicatorCurrent = FoundIndicator.Index; foreach (var r in ranges) { Editor.IndicatorFillRange(r.cpMin, r.cpMax - r.cpMin); } } } /// <summary> /// Mark lines in the <see cref="Scintilla"/> text using the configured <see cref="Marker"/>. /// </summary> /// <param name="ranges">List of ranges to which marks should be applied.</param> public void Mark(List<CharacterRange> ranges) { if (Editor != null) { ClearAllMarks(); var lastLine = -1; foreach (var r in ranges) { Line line = new Line(Editor, Editor.LineFromPosition(r.cpMin)); if (line.Position > lastLine) { line.MarkerAdd(FoundMarker.Index); } lastLine = line.Position; } } } // Update query/results and mark/highlight results as necessary. private List<CharacterRange> UpdateResults(Search query, bool mark = false, bool highlight = true) { if (query != null) { if (!query.Equals(CurrentQuery) || UpdateHighlights) { CurrentQuery = query; CurrentResults = query.FindAll(Editor); if (highlight) { Highlight(CurrentResults); } else { ClearAllHighlights(); } if (mark) { Mark(CurrentResults); } else { ClearAllMarks(); } } return CurrentResults; } else { return Clear(); } } #endregion Search UI #region Search Processing // Run find/replace next/previous: // - Update history // - Run search and navigate to first result // - Return status text internal string RunFindReplace(Func<bool, CharacterRange> findReplace, Action addMru, bool searchUp) { var statusText = string.Empty; addMru(); CharacterRange result; try { result = findReplace(searchUp); } catch (NullReferenceException) { // Expected: Search object could be null if constructor fails due to improper regex return null; } if (result.cpMin == result.cpMax) { statusText = "Match not found"; } else { statusText = GetIndexString(result); if (HasWrapped(result, searchUp)) { string boundary = searchUp ? "bottom" : "top"; string delimit = (statusText == string.Empty) ? "" : " | "; statusText += delimit + "Wrapped from " + boundary; } SetEditorSelection(result); } UpdateHighlights = false; return statusText; } // Run find/replace all: // - Update history // - Run search // - Return status text internal string RunFindReplaceAll(Func<List<CharacterRange>> findReplaceAll, Action addMru, bool replace) { var statusText = string.Empty; addMru(); List<CharacterRange> results; try { results = findReplaceAll(); } catch (NullReferenceException) { // Expected: Search object could be null if constructor fails due to improper regex return null; } if (results.Count == 0) { statusText = "Match could not be found"; } else { statusText = "Total " + (replace ? "replaced" : "found") + ": " + results.Count.ToString(); } UpdateHighlights = false; return statusText; } // Adds the given text to the find history internal void AddFindHistory(string findText) { AddHistory(findText, FindHistory); } // Adds the given text to the find & replace history internal void AddReplaceHistory(string findText, string replaceText) { AddHistory(findText, FindHistory); AddHistory(replaceText, ReplaceHistory); } // Adds the given text to the given list. If there is not enough room, the oldest entry is removed. private void AddHistory(string text, List<string> mru) { if (text != string.Empty) { mru.Remove(text); mru.Insert(0, text); if (mru.Count > _historyMaxCount) { mru.RemoveAt(mru.Count - 1); } } } // Raise the KeyPressed event. private void FindReplace_KeyPressed(object sender, KeyEventArgs e) { KeyPressed?.Invoke(this, e); } #endregion Search Processing #region Utility /// <summary> /// Creates and returns a new <see cref="IncrementalSearcher" /> object. /// </summary> /// <returns>A new <see cref="IncrementalSearcher" /> object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual IncrementalSearcher CreateIncrementalSearcherInstance() { return new IncrementalSearcher(this); } /// <summary> /// Creates and returns a new <see cref="FindReplaceDialog" /> object. /// </summary> /// <returns>A new <see cref="FindReplaceDialog" /> object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual FindReplaceDialog CreateWindowInstance() { return new FindReplaceDialog(this); } /// <summary> /// Checks if the given range has wrapped relative to the current selection in the editor. /// </summary> /// <param name="range"><see cref="CharacterRange"/> to check.</param> /// <param name="up">Direction to check.</param> /// <returns>True if the given range is below the current selection when the direction is up, or above the current selection when the direction is down.</returns> public bool HasWrapped(CharacterRange range, bool up) { return up ? (range.cpMin > Editor.CurrentPosition) : (range.cpMin < Editor.AnchorPosition); } /// <summary> /// Checks if the editor has any selected text. /// </summary> /// <returns>True if there are any selections.</returns> public bool EditorHasSelection() { return Editor.Selections.Count > 0; } /// <summary> /// Sets the editor selection to the given range. /// </summary> /// <param name="range">Target <see cref="CharacterRange"/> that will be the new editor selection.</param> public void SetEditorSelection(CharacterRange range) { Editor.SetSel(range.cpMin, range.cpMax); } /// <summary> /// Returns the <see cref="CharacterRange"/> currently selected in the editor. /// </summary> /// <returns><see cref="CharacterRange"/> between the anchor and current position.</returns> public CharacterRange GetEditorSelectedRange() { return new CharacterRange(Editor.SelectionStart, Editor.SelectionEnd); } /// <summary> /// Returns the <see cref="CharacterRange"/> of the whole document in the editor. /// </summary> /// <returns><see cref="CharacterRange"/> between zero and the text length.</returns> public CharacterRange GetEditorWholeRange() { return new CharacterRange(0, Editor.TextLength); } #endregion Utility #endregion Methods } }
52.771429
230
0.619258
[ "MIT" ]
jlj-ee/Code-Editor-Components
ScintillaNet Components/FindReplace/FindReplace.cs
48,022
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WeatherStation { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseUrls("http://*:5000"); }); } }
27.857143
71
0.608974
[ "CC0-1.0" ]
aaronperkins/weatherstation
Program.cs
780
C#
using System; using System.IO.Abstractions; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Party.Shared.Exceptions; using Party.Shared.Utils; namespace Party.Shared.Serializers { public class SceneSerializer : ISceneSerializer { private static readonly Regex _findScriptsFastRegex = new Regex( "\"plugin#(?>[0-9]+)\"(?> ?):(?> ?)\"(?<path>(?>[^\"]+))\"", RegexOptions.Compiled | RegexOptions.Multiline, TimeSpan.FromSeconds(5)); private readonly IFileSystem _fs; private readonly Throttler _throttler; public SceneSerializer(IFileSystem fs, Throttler throttler) { _fs = fs ?? throw new ArgumentNullException(nameof(fs)); _throttler = throttler ?? throw new ArgumentNullException(nameof(throttler)); } public async Task<ISceneJson> DeserializeAsync(string path) { try { JToken json; using (await _throttler.ThrottleIO().ConfigureAwait(false)) { using var file = _fs.File.OpenText(path); using var reader = new JsonTextReader(file); json = await JToken.ReadFromAsync(reader).ConfigureAwait(false); } return new SceneJson((JObject)json); } catch (JsonReaderException exc) { throw new SavesException(exc.Message, exc); } } public async Task SerializeAsync(ISceneJson scene, string path) { if (!(scene is SceneJson json)) throw new InvalidCastException("SceneSerializer expects a SceneJson"); using (await _throttler.ThrottleIO()) { using var file = _fs.File.CreateText(path); using var writer = new SceneJsonTextWriter(file); await json.Json.WriteToAsync(writer); } } public async Task<string[]> FindScriptsFastAsync(string path) { string content; using (await _throttler.ThrottleIO()) { content = _fs.File.ReadAllText(path); } var result = _findScriptsFastRegex.Matches(content); if (result == null) return new string[0]; return result.Cast<Match>().Select(m => m.Groups["path"].Value).ToArray(); } } public interface ISceneSerializer { Task<ISceneJson> DeserializeAsync(string path); Task SerializeAsync(ISceneJson scene, string path); Task<string[]> FindScriptsFastAsync(string path); } }
33.682927
89
0.583635
[ "MIT" ]
vam-community/vam-party
Party.Shared/Serializers/SceneSerializer.cs
2,762
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. // NOTE: This file is copied from src/Middleware/StaticFiles/src/IContentTypeProvider.cs // and made internal with a namespace change. // It can't be referenced directly from the StaticFiles package because that would cause this package to require // Microsoft.AspNetCore.App, thus preventing it from being used anywhere ASP.NET Core isn't supported (such as // various platforms that .NET MAUI runs on, such as Android and iOS). using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Microsoft.AspNetCore.Components.WebView { /// <summary> /// Provides a mapping between file extensions and MIME types. /// </summary> internal class FileExtensionContentTypeProvider : IContentTypeProvider { // Notes: // - This table was initially copied from IIS and has many legacy entries we will maintain for backwards compatibility. // - We only plan to add new entries where we expect them to be applicable to a majority of developers such as being // used in the project templates. #region Extension mapping table /// <summary> /// Creates a new provider with a set of default mappings. /// </summary> public FileExtensionContentTypeProvider() : this( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { ".323", "text/h323" }, { ".3g2", "video/3gpp2" }, { ".3gp2", "video/3gpp2" }, { ".3gp", "video/3gpp" }, { ".3gpp", "video/3gpp" }, { ".aac", "audio/aac" }, { ".aaf", "application/octet-stream" }, { ".aca", "application/octet-stream" }, { ".accdb", "application/msaccess" }, { ".accde", "application/msaccess" }, { ".accdt", "application/msaccess" }, { ".acx", "application/internet-property-stream" }, { ".adt", "audio/vnd.dlna.adts" }, { ".adts", "audio/vnd.dlna.adts" }, { ".afm", "application/octet-stream" }, { ".ai", "application/postscript" }, { ".aif", "audio/x-aiff" }, { ".aifc", "audio/aiff" }, { ".aiff", "audio/aiff" }, { ".appcache", "text/cache-manifest" }, { ".application", "application/x-ms-application" }, { ".art", "image/x-jg" }, { ".asd", "application/octet-stream" }, { ".asf", "video/x-ms-asf" }, { ".asi", "application/octet-stream" }, { ".asm", "text/plain" }, { ".asr", "video/x-ms-asf" }, { ".asx", "video/x-ms-asf" }, { ".atom", "application/atom+xml" }, { ".au", "audio/basic" }, { ".avi", "video/x-msvideo" }, { ".axs", "application/olescript" }, { ".bas", "text/plain" }, { ".bcpio", "application/x-bcpio" }, { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" }, { ".cab", "application/vnd.ms-cab-compressed" }, { ".calx", "application/vnd.ms-office.calx" }, { ".cat", "application/vnd.ms-pki.seccat" }, { ".cdf", "application/x-cdf" }, { ".chm", "application/octet-stream" }, { ".class", "application/x-java-applet" }, { ".clp", "application/x-msclip" }, { ".cmx", "image/x-cmx" }, { ".cnf", "text/plain" }, { ".cod", "image/cis-cod" }, { ".cpio", "application/x-cpio" }, { ".cpp", "text/plain" }, { ".crd", "application/x-mscardfile" }, { ".crl", "application/pkix-crl" }, { ".crt", "application/x-x509-ca-cert" }, { ".csh", "application/x-csh" }, { ".css", "text/css" }, { ".csv", "text/csv" }, // https://tools.ietf.org/html/rfc7111#section-5.1 { ".cur", "application/octet-stream" }, { ".dcr", "application/x-director" }, { ".deploy", "application/octet-stream" }, { ".der", "application/x-x509-ca-cert" }, { ".dib", "image/bmp" }, { ".dir", "application/x-director" }, { ".disco", "text/xml" }, { ".dlm", "text/dlm" }, { ".doc", "application/msword" }, { ".docm", "application/vnd.ms-word.document.macroEnabled.12" }, { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { ".dot", "application/msword" }, { ".dotm", "application/vnd.ms-word.template.macroEnabled.12" }, { ".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" }, { ".dsp", "application/octet-stream" }, { ".dtd", "text/xml" }, { ".dvi", "application/x-dvi" }, { ".dvr-ms", "video/x-ms-dvr" }, { ".dwf", "drawing/x-dwf" }, { ".dwp", "application/octet-stream" }, { ".dxr", "application/x-director" }, { ".eml", "message/rfc822" }, { ".emz", "application/octet-stream" }, { ".eot", "application/vnd.ms-fontobject" }, { ".eps", "application/postscript" }, { ".etx", "text/x-setext" }, { ".evy", "application/envoy" }, { ".exe", "application/vnd.microsoft.portable-executable" }, // https://www.iana.org/assignments/media-types/application/vnd.microsoft.portable-executable { ".fdf", "application/vnd.fdf" }, { ".fif", "application/fractals" }, { ".fla", "application/octet-stream" }, { ".flr", "x-world/x-vrml" }, { ".flv", "video/x-flv" }, { ".gif", "image/gif" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" }, { ".hdf", "application/x-hdf" }, { ".hdml", "text/x-hdml" }, { ".hhc", "application/x-oleobject" }, { ".hhk", "application/octet-stream" }, { ".hhp", "application/octet-stream" }, { ".hlp", "application/winhlp" }, { ".hqx", "application/mac-binhex40" }, { ".hta", "application/hta" }, { ".htc", "text/x-component" }, { ".htm", "text/html" }, { ".html", "text/html" }, { ".htt", "text/webviewhtml" }, { ".hxt", "text/html" }, { ".ical", "text/calendar" }, { ".icalendar", "text/calendar" }, { ".ico", "image/x-icon" }, { ".ics", "text/calendar" }, { ".ief", "image/ief" }, { ".ifb", "text/calendar" }, { ".iii", "application/x-iphone" }, { ".inf", "application/octet-stream" }, { ".ins", "application/x-internet-signup" }, { ".isp", "application/x-internet-signup" }, { ".IVF", "video/x-ivf" }, { ".jar", "application/java-archive" }, { ".java", "application/octet-stream" }, { ".jck", "application/liquidmotion" }, { ".jcz", "application/liquidmotion" }, { ".jfif", "image/pjpeg" }, { ".jpb", "application/octet-stream" }, { ".jpe", "image/jpeg" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/javascript" }, { ".json", "application/json" }, { ".jsx", "text/jscript" }, { ".latex", "application/x-latex" }, { ".lit", "application/x-ms-reader" }, { ".lpk", "application/octet-stream" }, { ".lsf", "video/x-la-asf" }, { ".lsx", "video/x-la-asf" }, { ".lzh", "application/octet-stream" }, { ".m13", "application/x-msmediaview" }, { ".m14", "application/x-msmediaview" }, { ".m1v", "video/mpeg" }, { ".m2ts", "video/vnd.dlna.mpeg-tts" }, { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4" }, { ".m4v", "video/mp4" }, { ".man", "application/x-troff-man" }, { ".manifest", "application/x-ms-manifest" }, { ".map", "text/plain" }, { ".markdown", "text/markdown" }, { ".md", "text/markdown" }, { ".mdb", "application/x-msaccess" }, { ".mdp", "application/octet-stream" }, { ".me", "application/x-troff-me" }, { ".mht", "message/rfc822" }, { ".mhtml", "message/rfc822" }, { ".mid", "audio/mid" }, { ".midi", "audio/mid" }, { ".mix", "application/octet-stream" }, { ".mmf", "application/x-smaf" }, { ".mno", "text/xml" }, { ".mny", "application/x-msmoney" }, { ".mov", "video/quicktime" }, { ".movie", "video/x-sgi-movie" }, { ".mp2", "video/mpeg" }, { ".mp3", "audio/mpeg" }, { ".mp4", "video/mp4" }, { ".mp4v", "video/mp4" }, { ".mpa", "video/mpeg" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpp", "application/vnd.ms-project" }, { ".mpv2", "video/mpeg" }, { ".ms", "application/x-troff-ms" }, { ".msi", "application/octet-stream" }, { ".mso", "application/octet-stream" }, { ".mvb", "application/x-msmediaview" }, { ".mvc", "application/x-miva-compiled" }, { ".nc", "application/x-netcdf" }, { ".nsc", "video/x-ms-asf" }, { ".nws", "message/rfc822" }, { ".ocx", "application/octet-stream" }, { ".oda", "application/oda" }, { ".odc", "text/x-ms-odc" }, { ".ods", "application/oleobject" }, { ".oga", "audio/ogg" }, { ".ogg", "video/ogg" }, { ".ogv", "video/ogg" }, { ".ogx", "application/ogg" }, { ".one", "application/onenote" }, { ".onea", "application/onenote" }, { ".onetoc", "application/onenote" }, { ".onetoc2", "application/onenote" }, { ".onetmp", "application/onenote" }, { ".onepkg", "application/onenote" }, { ".osdx", "application/opensearchdescription+xml" }, { ".otf", "font/otf" }, { ".p10", "application/pkcs10" }, { ".p12", "application/x-pkcs12" }, { ".p7b", "application/x-pkcs7-certificates" }, { ".p7c", "application/pkcs7-mime" }, { ".p7m", "application/pkcs7-mime" }, { ".p7r", "application/x-pkcs7-certreqresp" }, { ".p7s", "application/pkcs7-signature" }, { ".pbm", "image/x-portable-bitmap" }, { ".pcx", "application/octet-stream" }, { ".pcz", "application/octet-stream" }, { ".pdf", "application/pdf" }, { ".pfb", "application/octet-stream" }, { ".pfm", "application/octet-stream" }, { ".pfx", "application/x-pkcs12" }, { ".pgm", "image/x-portable-graymap" }, { ".pko", "application/vnd.ms-pki.pko" }, { ".pma", "application/x-perfmon" }, { ".pmc", "application/x-perfmon" }, { ".pml", "application/x-perfmon" }, { ".pmr", "application/x-perfmon" }, { ".pmw", "application/x-perfmon" }, { ".png", "image/png" }, { ".pnm", "image/x-portable-anymap" }, { ".pnz", "image/png" }, { ".pot", "application/vnd.ms-powerpoint" }, { ".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12" }, { ".potx", "application/vnd.openxmlformats-officedocument.presentationml.template" }, { ".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12" }, { ".ppm", "image/x-portable-pixmap" }, { ".pps", "application/vnd.ms-powerpoint" }, { ".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" }, { ".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" }, { ".ppt", "application/vnd.ms-powerpoint" }, { ".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12" }, { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".prf", "application/pics-rules" }, { ".prm", "application/octet-stream" }, { ".prx", "application/octet-stream" }, { ".ps", "application/postscript" }, { ".psd", "application/octet-stream" }, { ".psm", "application/octet-stream" }, { ".psp", "application/octet-stream" }, { ".pub", "application/x-mspublisher" }, { ".qt", "video/quicktime" }, { ".qtl", "application/x-quicktimeplayer" }, { ".qxd", "application/octet-stream" }, { ".ra", "audio/x-pn-realaudio" }, { ".ram", "audio/x-pn-realaudio" }, { ".rar", "application/octet-stream" }, { ".ras", "image/x-cmu-raster" }, { ".rf", "image/vnd.rn-realflash" }, { ".rgb", "image/x-rgb" }, { ".rm", "application/vnd.rn-realmedia" }, { ".rmi", "audio/mid" }, { ".roff", "application/x-troff" }, { ".rpm", "audio/x-pn-realaudio-plugin" }, { ".rtf", "application/rtf" }, { ".rtx", "text/richtext" }, { ".scd", "application/x-msschedule" }, { ".sct", "text/scriptlet" }, { ".sea", "application/octet-stream" }, { ".setpay", "application/set-payment-initiation" }, { ".setreg", "application/set-registration-initiation" }, { ".sgml", "text/sgml" }, { ".sh", "application/x-sh" }, { ".shar", "application/x-shar" }, { ".sit", "application/x-stuffit" }, { ".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12" }, { ".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" }, { ".smd", "audio/x-smd" }, { ".smi", "application/octet-stream" }, { ".smx", "audio/x-smd" }, { ".smz", "audio/x-smd" }, { ".snd", "audio/basic" }, { ".snp", "application/octet-stream" }, { ".spc", "application/x-pkcs7-certificates" }, { ".spl", "application/futuresplash" }, { ".spx", "audio/ogg" }, { ".src", "application/x-wais-source" }, { ".ssm", "application/streamingmedia" }, { ".sst", "application/vnd.ms-pki.certstore" }, { ".stl", "application/vnd.ms-pki.stl" }, { ".sv4cpio", "application/x-sv4cpio" }, { ".sv4crc", "application/x-sv4crc" }, { ".svg", "image/svg+xml" }, { ".svgz", "image/svg+xml" }, { ".swf", "application/x-shockwave-flash" }, { ".t", "application/x-troff" }, { ".tar", "application/x-tar" }, { ".tcl", "application/x-tcl" }, { ".tex", "application/x-tex" }, { ".texi", "application/x-texinfo" }, { ".texinfo", "application/x-texinfo" }, { ".tgz", "application/x-compressed" }, { ".thmx", "application/vnd.ms-officetheme" }, { ".thn", "application/octet-stream" }, { ".tif", "image/tiff" }, { ".tiff", "image/tiff" }, { ".toc", "application/octet-stream" }, { ".tr", "application/x-troff" }, { ".trm", "application/x-msterminal" }, { ".ts", "video/vnd.dlna.mpeg-tts" }, { ".tsv", "text/tab-separated-values" }, { ".ttc", "application/x-font-ttf" }, { ".ttf", "application/x-font-ttf" }, { ".tts", "video/vnd.dlna.mpeg-tts" }, { ".txt", "text/plain" }, { ".u32", "application/octet-stream" }, { ".uls", "text/iuls" }, { ".ustar", "application/x-ustar" }, { ".vbs", "text/vbscript" }, { ".vcf", "text/x-vcard" }, { ".vcs", "text/plain" }, { ".vdx", "application/vnd.ms-visio.viewer" }, { ".vml", "text/xml" }, { ".vsd", "application/vnd.visio" }, { ".vss", "application/vnd.visio" }, { ".vst", "application/vnd.visio" }, { ".vsto", "application/x-ms-vsto" }, { ".vsw", "application/vnd.visio" }, { ".vsx", "application/vnd.visio" }, { ".vtx", "application/vnd.visio" }, { ".wasm", "application/wasm" }, { ".wav", "audio/wav" }, { ".wax", "audio/x-ms-wax" }, { ".wbmp", "image/vnd.wap.wbmp" }, { ".wcm", "application/vnd.ms-works" }, { ".wdb", "application/vnd.ms-works" }, { ".webm", "video/webm" }, { ".webmanifest", "application/manifest+json" }, // https://w3c.github.io/manifest/#media-type-registration { ".webp", "image/webp" }, { ".wks", "application/vnd.ms-works" }, { ".wm", "video/x-ms-wm" }, { ".wma", "audio/x-ms-wma" }, { ".wmd", "application/x-ms-wmd" }, { ".wmf", "application/x-msmetafile" }, { ".wml", "text/vnd.wap.wml" }, { ".wmlc", "application/vnd.wap.wmlc" }, { ".wmls", "text/vnd.wap.wmlscript" }, { ".wmlsc", "application/vnd.wap.wmlscriptc" }, { ".wmp", "video/x-ms-wmp" }, { ".wmv", "video/x-ms-wmv" }, { ".wmx", "video/x-ms-wmx" }, { ".wmz", "application/x-ms-wmz" }, { ".woff", "application/font-woff" }, // https://www.w3.org/TR/WOFF/#appendix-b { ".woff2", "font/woff2" }, // https://www.w3.org/TR/WOFF2/#IMT { ".wps", "application/vnd.ms-works" }, { ".wri", "application/x-mswrite" }, { ".wrl", "x-world/x-vrml" }, { ".wrz", "x-world/x-vrml" }, { ".wsdl", "text/xml" }, { ".wtv", "video/x-ms-wtv" }, { ".wvx", "video/x-ms-wvx" }, { ".x", "application/directx" }, { ".xaf", "x-world/x-vrml" }, { ".xaml", "application/xaml+xml" }, { ".xap", "application/x-silverlight-app" }, { ".xbap", "application/x-ms-xbap" }, { ".xbm", "image/x-xbitmap" }, { ".xdr", "text/plain" }, { ".xht", "application/xhtml+xml" }, { ".xhtml", "application/xhtml+xml" }, { ".xla", "application/vnd.ms-excel" }, { ".xlam", "application/vnd.ms-excel.addin.macroEnabled.12" }, { ".xlc", "application/vnd.ms-excel" }, { ".xlm", "application/vnd.ms-excel" }, { ".xls", "application/vnd.ms-excel" }, { ".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12" }, { ".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { ".xlt", "application/vnd.ms-excel" }, { ".xltm", "application/vnd.ms-excel.template.macroEnabled.12" }, { ".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" }, { ".xlw", "application/vnd.ms-excel" }, { ".xml", "text/xml" }, { ".xof", "x-world/x-vrml" }, { ".xpm", "image/x-xpixmap" }, { ".xps", "application/vnd.ms-xpsdocument" }, { ".xsd", "text/xml" }, { ".xsf", "text/xml" }, { ".xsl", "text/xml" }, { ".xslt", "text/xml" }, { ".xsn", "application/octet-stream" }, { ".xtp", "application/octet-stream" }, { ".xwd", "image/x-xwindowdump" }, { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, } ) { } #endregion /// <summary> /// Creates a lookup engine using the provided mapping. /// It is recommended that the IDictionary instance use StringComparer.OrdinalIgnoreCase. /// </summary> /// <param name="mapping"></param> public FileExtensionContentTypeProvider(IDictionary<string, string> mapping) { if (mapping == null) { throw new ArgumentNullException(nameof(mapping)); } Mappings = mapping; } /// <summary> /// The cross reference table of file extensions and content-types. /// </summary> public IDictionary<string, string> Mappings { get; private set; } /// <summary> /// Given a file path, determine the MIME type /// </summary> /// <param name="subpath">A file path</param> /// <param name="contentType">The resulting MIME type</param> /// <returns>True if MIME type could be determined</returns> public bool TryGetContentType(string subpath, [MaybeNullWhen(false)] out string contentType) { var extension = GetExtension(subpath); if (extension == null) { contentType = null; return false; } return Mappings.TryGetValue(extension, out contentType); } private static string? GetExtension(string path) { // Don't use Path.GetExtension as that may throw an exception if there are // invalid characters in the path. Invalid characters should be handled // by the FileProviders if (string.IsNullOrWhiteSpace(path)) { return null; } int index = path.LastIndexOf('.'); if (index < 0) { return null; } return path.Substring(index); } } }
52.220884
174
0.409444
[ "Apache-2.0" ]
belav/aspnetcore
src/Components/WebView/WebView/src/FileExtensionContentTypeProvider.cs
26,006
C#
//Released under the MIT License. // //Copyright (c) 2018 Ntreev Soft co., Ltd. // //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 Caliburn.Micro; using Ntreev.Crema.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ntreev.Crema.Designer.ViewModels { class TypeItemViewModel : PropertyChangedBase { private readonly CremaDataType type; public TypeItemViewModel(CremaDataType type) { this.type = type; } public CremaDataType Source { get { return this.type; } } public string Name { get { return this.type.Name; } } public override string ToString() { return this.type.Name; } } }
34.811321
121
0.705691
[ "MIT" ]
NtreevSoft/Crema
tools/Ntreev.Crema.Designer/ViewModels/TypeItemViewModel.cs
1,847
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { /// <summary> /// The amount of power in a volume. /// </summary> // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. public sealed partial class PowerDensity : IQuantity { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly double _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly PowerDensityUnit? _unit; static PowerDensity() { BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); } /// <summary> /// Creates the quantity with a value of 0 in the base unit WattPerCubicMeter. /// </summary> /// <remarks> /// Windows Runtime Component requires a default constructor. /// </remarks> public PowerDensity() { _value = 0; _unit = BaseUnit; } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="numericValue">The numeric value to contruct this quantity with.</param> /// <param name="unit">The unit representation to contruct this quantity with.</param> /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> private PowerDensity(double numericValue, PowerDensityUnit unit) { if(unit == PowerDensityUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); _unit = unit; } #region Static Properties /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. /// </summary> public static PowerDensityUnit BaseUnit { get; } = PowerDensityUnit.WattPerCubicMeter; /// <summary> /// Represents the largest possible value of PowerDensity /// </summary> public static PowerDensity MaxValue { get; } = new PowerDensity(double.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of PowerDensity /// </summary> public static PowerDensity MinValue { get; } = new PowerDensity(double.MinValue, BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public static QuantityType QuantityType { get; } = QuantityType.PowerDensity; /// <summary> /// All units of measurement for the PowerDensity quantity. /// </summary> public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast<PowerDensityUnit>().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. /// </summary> public static PowerDensity Zero { get; } = new PowerDensity(0, BaseUnit); #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => Convert.ToDouble(_value); /// <summary> /// The unit this quantity was constructed with -or- <see cref="BaseUnit" /> if default ctor was used. /// </summary> public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public QuantityType Type => PowerDensity.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => PowerDensity.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Get PowerDensity in DecawattsPerCubicFoot. /// </summary> public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); /// <summary> /// Get PowerDensity in DecawattsPerCubicInch. /// </summary> public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); /// <summary> /// Get PowerDensity in DecawattsPerCubicMeter. /// </summary> public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); /// <summary> /// Get PowerDensity in DecawattsPerLiter. /// </summary> public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); /// <summary> /// Get PowerDensity in DeciwattsPerCubicFoot. /// </summary> public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); /// <summary> /// Get PowerDensity in DeciwattsPerCubicInch. /// </summary> public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); /// <summary> /// Get PowerDensity in DeciwattsPerCubicMeter. /// </summary> public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); /// <summary> /// Get PowerDensity in DeciwattsPerLiter. /// </summary> public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); /// <summary> /// Get PowerDensity in GigawattsPerCubicFoot. /// </summary> public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); /// <summary> /// Get PowerDensity in GigawattsPerCubicInch. /// </summary> public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); /// <summary> /// Get PowerDensity in GigawattsPerCubicMeter. /// </summary> public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); /// <summary> /// Get PowerDensity in GigawattsPerLiter. /// </summary> public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); /// <summary> /// Get PowerDensity in KilowattsPerCubicFoot. /// </summary> public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); /// <summary> /// Get PowerDensity in KilowattsPerCubicInch. /// </summary> public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); /// <summary> /// Get PowerDensity in KilowattsPerCubicMeter. /// </summary> public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); /// <summary> /// Get PowerDensity in KilowattsPerLiter. /// </summary> public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); /// <summary> /// Get PowerDensity in MegawattsPerCubicFoot. /// </summary> public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); /// <summary> /// Get PowerDensity in MegawattsPerCubicInch. /// </summary> public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); /// <summary> /// Get PowerDensity in MegawattsPerCubicMeter. /// </summary> public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); /// <summary> /// Get PowerDensity in MegawattsPerLiter. /// </summary> public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); /// <summary> /// Get PowerDensity in MicrowattsPerCubicFoot. /// </summary> public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); /// <summary> /// Get PowerDensity in MicrowattsPerCubicInch. /// </summary> public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); /// <summary> /// Get PowerDensity in MicrowattsPerCubicMeter. /// </summary> public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); /// <summary> /// Get PowerDensity in MicrowattsPerLiter. /// </summary> public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); /// <summary> /// Get PowerDensity in MilliwattsPerCubicFoot. /// </summary> public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); /// <summary> /// Get PowerDensity in MilliwattsPerCubicInch. /// </summary> public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); /// <summary> /// Get PowerDensity in MilliwattsPerCubicMeter. /// </summary> public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); /// <summary> /// Get PowerDensity in MilliwattsPerLiter. /// </summary> public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); /// <summary> /// Get PowerDensity in NanowattsPerCubicFoot. /// </summary> public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); /// <summary> /// Get PowerDensity in NanowattsPerCubicInch. /// </summary> public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); /// <summary> /// Get PowerDensity in NanowattsPerCubicMeter. /// </summary> public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); /// <summary> /// Get PowerDensity in NanowattsPerLiter. /// </summary> public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); /// <summary> /// Get PowerDensity in PicowattsPerCubicFoot. /// </summary> public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); /// <summary> /// Get PowerDensity in PicowattsPerCubicInch. /// </summary> public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); /// <summary> /// Get PowerDensity in PicowattsPerCubicMeter. /// </summary> public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); /// <summary> /// Get PowerDensity in PicowattsPerLiter. /// </summary> public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); /// <summary> /// Get PowerDensity in TerawattsPerCubicFoot. /// </summary> public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); /// <summary> /// Get PowerDensity in TerawattsPerCubicInch. /// </summary> public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); /// <summary> /// Get PowerDensity in TerawattsPerCubicMeter. /// </summary> public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); /// <summary> /// Get PowerDensity in TerawattsPerLiter. /// </summary> public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); /// <summary> /// Get PowerDensity in WattsPerCubicFoot. /// </summary> public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); /// <summary> /// Get PowerDensity in WattsPerCubicInch. /// </summary> public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); /// <summary> /// Get PowerDensity in WattsPerCubicMeter. /// </summary> public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); /// <summary> /// Get PowerDensity in WattsPerLiter. /// </summary> public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); #endregion #region Static Methods /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(PowerDensityUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Get PowerDensity from DecawattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) { double value = (double) decawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); } /// <summary> /// Get PowerDensity from DecawattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) { double value = (double) decawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); } /// <summary> /// Get PowerDensity from DecawattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) { double value = (double) decawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); } /// <summary> /// Get PowerDensity from DecawattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) { double value = (double) decawattsperliter; return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); } /// <summary> /// Get PowerDensity from DeciwattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) { double value = (double) deciwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); } /// <summary> /// Get PowerDensity from DeciwattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) { double value = (double) deciwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); } /// <summary> /// Get PowerDensity from DeciwattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) { double value = (double) deciwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); } /// <summary> /// Get PowerDensity from DeciwattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) { double value = (double) deciwattsperliter; return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); } /// <summary> /// Get PowerDensity from GigawattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) { double value = (double) gigawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); } /// <summary> /// Get PowerDensity from GigawattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) { double value = (double) gigawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); } /// <summary> /// Get PowerDensity from GigawattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) { double value = (double) gigawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); } /// <summary> /// Get PowerDensity from GigawattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) { double value = (double) gigawattsperliter; return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); } /// <summary> /// Get PowerDensity from KilowattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) { double value = (double) kilowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); } /// <summary> /// Get PowerDensity from KilowattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) { double value = (double) kilowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); } /// <summary> /// Get PowerDensity from KilowattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) { double value = (double) kilowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); } /// <summary> /// Get PowerDensity from KilowattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) { double value = (double) kilowattsperliter; return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); } /// <summary> /// Get PowerDensity from MegawattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) { double value = (double) megawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); } /// <summary> /// Get PowerDensity from MegawattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) { double value = (double) megawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); } /// <summary> /// Get PowerDensity from MegawattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) { double value = (double) megawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); } /// <summary> /// Get PowerDensity from MegawattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) { double value = (double) megawattsperliter; return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); } /// <summary> /// Get PowerDensity from MicrowattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) { double value = (double) microwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); } /// <summary> /// Get PowerDensity from MicrowattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) { double value = (double) microwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); } /// <summary> /// Get PowerDensity from MicrowattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) { double value = (double) microwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); } /// <summary> /// Get PowerDensity from MicrowattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) { double value = (double) microwattsperliter; return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); } /// <summary> /// Get PowerDensity from MilliwattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) { double value = (double) milliwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); } /// <summary> /// Get PowerDensity from MilliwattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) { double value = (double) milliwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); } /// <summary> /// Get PowerDensity from MilliwattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) { double value = (double) milliwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); } /// <summary> /// Get PowerDensity from MilliwattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) { double value = (double) milliwattsperliter; return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); } /// <summary> /// Get PowerDensity from NanowattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) { double value = (double) nanowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); } /// <summary> /// Get PowerDensity from NanowattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) { double value = (double) nanowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); } /// <summary> /// Get PowerDensity from NanowattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) { double value = (double) nanowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); } /// <summary> /// Get PowerDensity from NanowattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) { double value = (double) nanowattsperliter; return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); } /// <summary> /// Get PowerDensity from PicowattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) { double value = (double) picowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); } /// <summary> /// Get PowerDensity from PicowattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) { double value = (double) picowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); } /// <summary> /// Get PowerDensity from PicowattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) { double value = (double) picowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); } /// <summary> /// Get PowerDensity from PicowattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) { double value = (double) picowattsperliter; return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); } /// <summary> /// Get PowerDensity from TerawattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) { double value = (double) terawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); } /// <summary> /// Get PowerDensity from TerawattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) { double value = (double) terawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); } /// <summary> /// Get PowerDensity from TerawattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) { double value = (double) terawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); } /// <summary> /// Get PowerDensity from TerawattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) { double value = (double) terawattsperliter; return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); } /// <summary> /// Get PowerDensity from WattsPerCubicFoot. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) { double value = (double) wattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); } /// <summary> /// Get PowerDensity from WattsPerCubicInch. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) { double value = (double) wattspercubicinch; return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); } /// <summary> /// Get PowerDensity from WattsPerCubicMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) { double value = (double) wattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); } /// <summary> /// Get PowerDensity from WattsPerLiter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static PowerDensity FromWattsPerLiter(double wattsperliter) { double value = (double) wattsperliter; return new PowerDensity(value, PowerDensityUnit.WattPerLiter); } /// <summary> /// Dynamically convert from value and unit enum <see cref="PowerDensityUnit" /> to <see cref="PowerDensity" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>PowerDensity unit value.</returns> // Fix name conflict with parameter "value" [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] public static PowerDensity From(double value, PowerDensityUnit fromUnit) { return new PowerDensity((double)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static PowerDensity Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static PowerDensity Parse(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.Parse<PowerDensity, PowerDensityUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse([CanBeNull] string str, out PowerDensity result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out PowerDensity result) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.TryParse<PowerDensity, PowerDensityUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static PowerDensityUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static PowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.Parse<PowerDensityUnit>(str, provider); } public static bool TryParseUnit(string str, out PowerDensityUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PowerDensityUnit unit) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.TryParse<PowerDensityUnit>(str, provider, out unit); } #endregion #region Equality / IComparable public int CompareTo(object obj) { if(obj is null) throw new ArgumentNullException(nameof(obj)); if(!(obj is PowerDensity objPowerDensity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); return CompareTo(objPowerDensity); } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods internal int CompareTo(PowerDensity other) { return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } [Windows.Foundation.Metadata.DefaultOverload] public override bool Equals(object obj) { if(obj is null || !(obj is PowerDensity objPowerDensity)) return false; return Equals(objPowerDensity); } public bool Equals(PowerDensity other) { return _value.Equals(other.AsBaseNumericType(this.Unit)); } /// <summary> /// <para> /// Compare equality to another PowerDensity within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) { if(tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); double thisValue = (double)this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current PowerDensity.</returns> public override int GetHashCode() { return new { QuantityType, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(PowerDensityUnit unit) { if(Unit == unit) return Convert.ToDouble(Value); var converted = AsBaseNumericType(unit); return Convert.ToDouble(converted); } /// <summary> /// Converts this PowerDensity to another PowerDensity with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A PowerDensity with the specified unit.</returns> public PowerDensity ToUnit(PowerDensityUnit unit) { var convertedValue = AsBaseNumericType(unit); return new PowerDensity(convertedValue, unit); } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private double AsBaseUnit() { switch(Unit) { case PowerDensityUnit.DecawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e1d; case PowerDensityUnit.DecawattPerCubicInch: return (_value*6.102374409473228e4) * 1e1d; case PowerDensityUnit.DecawattPerCubicMeter: return (_value) * 1e1d; case PowerDensityUnit.DecawattPerLiter: return (_value*1.0e3) * 1e1d; case PowerDensityUnit.DeciwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-1d; case PowerDensityUnit.DeciwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-1d; case PowerDensityUnit.DeciwattPerCubicMeter: return (_value) * 1e-1d; case PowerDensityUnit.DeciwattPerLiter: return (_value*1.0e3) * 1e-1d; case PowerDensityUnit.GigawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e9d; case PowerDensityUnit.GigawattPerCubicInch: return (_value*6.102374409473228e4) * 1e9d; case PowerDensityUnit.GigawattPerCubicMeter: return (_value) * 1e9d; case PowerDensityUnit.GigawattPerLiter: return (_value*1.0e3) * 1e9d; case PowerDensityUnit.KilowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e3d; case PowerDensityUnit.KilowattPerCubicInch: return (_value*6.102374409473228e4) * 1e3d; case PowerDensityUnit.KilowattPerCubicMeter: return (_value) * 1e3d; case PowerDensityUnit.KilowattPerLiter: return (_value*1.0e3) * 1e3d; case PowerDensityUnit.MegawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e6d; case PowerDensityUnit.MegawattPerCubicInch: return (_value*6.102374409473228e4) * 1e6d; case PowerDensityUnit.MegawattPerCubicMeter: return (_value) * 1e6d; case PowerDensityUnit.MegawattPerLiter: return (_value*1.0e3) * 1e6d; case PowerDensityUnit.MicrowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-6d; case PowerDensityUnit.MicrowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-6d; case PowerDensityUnit.MicrowattPerCubicMeter: return (_value) * 1e-6d; case PowerDensityUnit.MicrowattPerLiter: return (_value*1.0e3) * 1e-6d; case PowerDensityUnit.MilliwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-3d; case PowerDensityUnit.MilliwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-3d; case PowerDensityUnit.MilliwattPerCubicMeter: return (_value) * 1e-3d; case PowerDensityUnit.MilliwattPerLiter: return (_value*1.0e3) * 1e-3d; case PowerDensityUnit.NanowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-9d; case PowerDensityUnit.NanowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-9d; case PowerDensityUnit.NanowattPerCubicMeter: return (_value) * 1e-9d; case PowerDensityUnit.NanowattPerLiter: return (_value*1.0e3) * 1e-9d; case PowerDensityUnit.PicowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-12d; case PowerDensityUnit.PicowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-12d; case PowerDensityUnit.PicowattPerCubicMeter: return (_value) * 1e-12d; case PowerDensityUnit.PicowattPerLiter: return (_value*1.0e3) * 1e-12d; case PowerDensityUnit.TerawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e12d; case PowerDensityUnit.TerawattPerCubicInch: return (_value*6.102374409473228e4) * 1e12d; case PowerDensityUnit.TerawattPerCubicMeter: return (_value) * 1e12d; case PowerDensityUnit.TerawattPerLiter: return (_value*1.0e3) * 1e12d; case PowerDensityUnit.WattPerCubicFoot: return _value*3.531466672148859e1; case PowerDensityUnit.WattPerCubicInch: return _value*6.102374409473228e4; case PowerDensityUnit.WattPerCubicMeter: return _value; case PowerDensityUnit.WattPerLiter: return _value*1.0e3; default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } private double AsBaseNumericType(PowerDensityUnit unit) { if(Unit == unit) return _value; var baseUnitValue = AsBaseUnit(); switch(unit) { case PowerDensityUnit.DecawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e1d; case PowerDensityUnit.DecawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e1d; case PowerDensityUnit.DecawattPerCubicMeter: return (baseUnitValue) / 1e1d; case PowerDensityUnit.DecawattPerLiter: return (baseUnitValue/1.0e3) / 1e1d; case PowerDensityUnit.DeciwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-1d; case PowerDensityUnit.DeciwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-1d; case PowerDensityUnit.DeciwattPerCubicMeter: return (baseUnitValue) / 1e-1d; case PowerDensityUnit.DeciwattPerLiter: return (baseUnitValue/1.0e3) / 1e-1d; case PowerDensityUnit.GigawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e9d; case PowerDensityUnit.GigawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e9d; case PowerDensityUnit.GigawattPerCubicMeter: return (baseUnitValue) / 1e9d; case PowerDensityUnit.GigawattPerLiter: return (baseUnitValue/1.0e3) / 1e9d; case PowerDensityUnit.KilowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e3d; case PowerDensityUnit.KilowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e3d; case PowerDensityUnit.KilowattPerCubicMeter: return (baseUnitValue) / 1e3d; case PowerDensityUnit.KilowattPerLiter: return (baseUnitValue/1.0e3) / 1e3d; case PowerDensityUnit.MegawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e6d; case PowerDensityUnit.MegawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e6d; case PowerDensityUnit.MegawattPerCubicMeter: return (baseUnitValue) / 1e6d; case PowerDensityUnit.MegawattPerLiter: return (baseUnitValue/1.0e3) / 1e6d; case PowerDensityUnit.MicrowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-6d; case PowerDensityUnit.MicrowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-6d; case PowerDensityUnit.MicrowattPerCubicMeter: return (baseUnitValue) / 1e-6d; case PowerDensityUnit.MicrowattPerLiter: return (baseUnitValue/1.0e3) / 1e-6d; case PowerDensityUnit.MilliwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-3d; case PowerDensityUnit.MilliwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-3d; case PowerDensityUnit.MilliwattPerCubicMeter: return (baseUnitValue) / 1e-3d; case PowerDensityUnit.MilliwattPerLiter: return (baseUnitValue/1.0e3) / 1e-3d; case PowerDensityUnit.NanowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-9d; case PowerDensityUnit.NanowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-9d; case PowerDensityUnit.NanowattPerCubicMeter: return (baseUnitValue) / 1e-9d; case PowerDensityUnit.NanowattPerLiter: return (baseUnitValue/1.0e3) / 1e-9d; case PowerDensityUnit.PicowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-12d; case PowerDensityUnit.PicowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-12d; case PowerDensityUnit.PicowattPerCubicMeter: return (baseUnitValue) / 1e-12d; case PowerDensityUnit.PicowattPerLiter: return (baseUnitValue/1.0e3) / 1e-12d; case PowerDensityUnit.TerawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e12d; case PowerDensityUnit.TerawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e12d; case PowerDensityUnit.TerawattPerCubicMeter: return (baseUnitValue) / 1e12d; case PowerDensityUnit.TerawattPerLiter: return (baseUnitValue/1.0e3) / 1e12d; case PowerDensityUnit.WattPerCubicFoot: return baseUnitValue/3.531466672148859e1; case PowerDensityUnit.WattPerCubicInch: return baseUnitValue/6.102374409473228e4; case PowerDensityUnit.WattPerCubicMeter: return baseUnitValue; case PowerDensityUnit.WattPerLiter: return baseUnitValue/1.0e3; default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Get default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName) { var provider = cultureName; return ToString(provider, 2); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString(string cultureName, int significantDigitsAfterRadix) { var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implictly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? GlobalConfiguration.DefaultCulture; var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) { return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; } } }
49.404255
223
0.639627
[ "MIT" ]
tongbong/UnitsNet
UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs
65,018
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace StudentsSystem.Data.Migrations { public partial class Changing : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "UserId", table: "Exercises", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "UserId", table: "Events", nullable: false, defaultValue: ""); migrationBuilder.CreateIndex( name: "IX_Exercises_UserId", table: "Exercises", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Events_UserId", table: "Events", column: "UserId"); migrationBuilder.AddForeignKey( name: "FK_Events_AspNetUsers_UserId", table: "Events", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Exercises_AspNetUsers_UserId", table: "Exercises", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Events_AspNetUsers_UserId", table: "Events"); migrationBuilder.DropForeignKey( name: "FK_Exercises_AspNetUsers_UserId", table: "Exercises"); migrationBuilder.DropIndex( name: "IX_Exercises_UserId", table: "Exercises"); migrationBuilder.DropIndex( name: "IX_Events_UserId", table: "Events"); migrationBuilder.DropColumn( name: "UserId", table: "Exercises"); migrationBuilder.DropColumn( name: "UserId", table: "Events"); } } }
31.131579
71
0.516061
[ "MIT" ]
antoniovelev/Softuni
C#/Web Project/Data/StudentsSystem.Data/Migrations/20200412110306_Changing.cs
2,368
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("BurningMan")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("BurningMan")] [assembly: System.Reflection.AssemblyTitleAttribute("BurningMan")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.833333
80
0.646939
[ "MIT" ]
JAZZKIT/Burning-Man-Course-Project
BurningMan/BurningMan/obj/Debug/netcoreapp3.1/BurningMan.AssemblyInfo.cs
980
C#
using System; using System.Reflection; [assembly: AssemblyProduct("Exceptionless")] [assembly: AssemblyCompany("Exceptionless")] [assembly: AssemblyTrademark("Exceptionless")] [assembly: AssemblyCopyright("Copyright (c) 2016 Exceptionless. All rights reserved.")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("3.4.0")] [assembly: AssemblyFileVersion("3.4.0")] [assembly: AssemblyInformationalVersion("3.4.0")]
28.166667
88
0.773176
[ "Apache-2.0" ]
ToddZhao/Exceptionless
Source/GlobalAssemblyInfo.cs
507
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ChatChannel.Account { public partial class RegisterExternalLogin { /// <summary> /// userName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox userName; } }
31.08
84
0.474903
[ "MIT" ]
niki-funky/Telerik_Academy
Web Development/ASP.NET Web Forms/08. Identity/08. Indentity/ChatChannel/Account/RegisterExternalLogin.aspx.designer.cs
779
C#
namespace fairTeams.Core { /// <summary> /// Request object for RequestGame /// </summary> public class GameRequest { /// <summary> /// UNKNOWN /// </summary> public uint Token { get; set; } /// <summary> /// ID of match /// </summary> public ulong MatchId { get; set; } /// <summary> /// ID of outcome of match /// </summary> public ulong OutcomeId { get; set; } } }
23.238095
44
0.47541
[ "MIT" ]
diveflo/fair-teams-ai
backend/fairTeams.Core/GameRequest.cs
490
C#
using System; using UnityEngine; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; //[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. //[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. //[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); //PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } //private void PlayLandingSound() //{ // m_AudioSource.clip = m_LandSound; // m_AudioSource.Play(); // m_NextStep = m_StepCycle + .5f; //} private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; //PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } //private void PlayJumpSound() //{ // m_AudioSource.clip = m_JumpSound; // m_AudioSource.Play(); //} private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; //PlayFootStepAudio(); } //private void PlayFootStepAudio() //{ // if (!m_CharacterController.isGrounded) // { // return; // } // // pick & play a random footstep sound from the array, // // excluding sound at index 0 // int n = Random.Range(1, m_FootstepSounds.Length); // m_AudioSource.clip = m_FootstepSounds[n]; // m_AudioSource.PlayOneShot(m_AudioSource.clip); // // move picked sound to index 0 so it's not picked next time // m_FootstepSounds[n] = m_FootstepSounds[0]; // m_FootstepSounds[0] = m_AudioSource.clip; //} private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Enemy")) { Scene currentScene = SceneManager.GetActiveScene(); SceneManager.LoadScene(currentScene.name); } } } }
36.642066
135
0.589023
[ "MIT" ]
IUS-CS/s20-project-jakob-drew-bryce-a-dog
src/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs
9,930
C#
using System; namespace Gimela.Rukbat.GUI.Modules.UIMessage { public partial class UIMessageType { public static readonly string DeviceConfiguration_SelectServiceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_ServiceSelectedEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CreateCameraEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateCameraEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CancelCameraEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_NavigateVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CancelNavigateVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectLocalCameraVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectLocalAVIFileVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectLocalDesktopVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectNetworkJPEGVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectNetworkMJPEGVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_SelectVLCPluginVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CancelUpdateVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateLocalCameraVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateLocalAVIFileVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateLocalDesktopVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateNetworkJPEGVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_UpdateNetworkMJPEGVideoSourceEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_VideoSourceCreateSelectedEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_VideoSourceUpdateSelectedEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CameraCreatedEvent = Guid.NewGuid().ToString(); public static readonly string DeviceConfiguration_CameraUpdatedEvent = Guid.NewGuid().ToString(); } }
69.75
117
0.823656
[ "MIT" ]
J-W-Chan/Gimela
src/Rukbat/GUI/Modules/Gimela.Rukbat.GUI.Modules.UIMessage/UIMessageType.DeviceConfiguration.cs
2,792
C#
// <auto-generated /> using System; using AspNetWebApp2.DotNetCore.v2.MVC.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace AspNetWebApp2.DotNetCore.v2.MVC.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-preview1") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.191489
125
0.487062
[ "MIT" ]
iwhp/AspNetIdentitySideBySide
AspNetWebApp2.DotNetCore.v2.MVC/Data/Migrations/ApplicationDbContextModelSnapshot.cs
8,270
C#
//----------------------------------------------------------------------- // <copyright file="D:\PROJEKTE\restcountries\src\RestCountries.API\Program.cs" company="AXA Partners"> // Author: Jörg H Primke // Copyright (c) 2021 - AXA Partners. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RestCountries.Data; var builder = WebApplication.CreateBuilder(args); IConfiguration configuration = builder.Configuration; // Add services to the container. builder.Services.AddControllers(); builder.Services.AddHealthChecks(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1.0", new() { Title = "RestCountries.API", Version = "v1.0" }); }); bool useJsonFile = configuration.GetValue<bool>("UseJsonFile"); if (useJsonFile) { builder.Services .Configure<CountryFileOptions>(config => { var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; config.Directory = Path.Combine(rootPath, configuration.GetValue<string>("ResourceDirectory")); config.FileName = "allCountries.json"; }); builder.Services.AddSingleton<ICountryContext, CountryFileContext>(); } else { builder.Services .AddScoped<DbContextOptions<CountryCosmosContext>>(sp => { var cs = configuration.GetValue<string>("CosmosDb:ConnectionString"); var dn = configuration.GetValue<string>("CosmosDb:DatabaseName"); var dbcob = new DbContextOptionsBuilder<CountryCosmosContext>(); return dbcob.UseCosmos(cs, dn).Options; }); builder.Services.AddDbContext<ICountryContext, CountryCosmosContext>(); } builder.Services.AddScoped<CountryRepository>(); builder.Services.AddCors(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "RestCountries.API v1.0")); } app.UseCors(p => { p.AllowAnyOrigin(); p.WithMethods("GET"); p.AllowAnyHeader(); }); app.UseHsts(); app.UseHttpsRedirection(); app.MapGet("countries/all", (CountryRepository repository) => Results.Ok(repository.GetAll())); app.MapGet("countries/alpha/{alphaCode:alpha:length(2,3)}", (CountryRepository repository, string alphaCode) => Results.Ok(repository.GetCountriesByAlphaCode(alphaCode))); app.MapGet("countries/alpha", (CountryRepository repository, [FromQuery] string codes) => { var splitCodes = codes.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); return Results.Ok(repository.GetCountriesByAlphaCodes(splitCodes)); }); app.MapGet("countries/name/{name}", (CountryRepository repository, string name, [FromQuery] bool? fullText) => Results.Ok(repository.GetCountriesByName(name, fullText))); app.MapGet("countries/region/{region:alpha}", (CountryRepository repository, string region) => Results.Ok(repository.GetCountriesByRegion(region))); app.MapGet("countries/currency/{currency:alpha}", (CountryRepository repository, string currency) => Results.Ok(repository.GetCountriesByCurrency(currency))); app.MapGet("countries/lang/{lang:alpha}", (CountryRepository repository, string lang) => Results.Ok(repository.GetCountriesByLanguage(lang))); app.MapGet("countries/callingcode/{callingcode}", (CountryRepository repository, string callingcode) => Results.Ok(repository.GetCountriesByCallingCode(callingcode))); app.MapGet("countries/subregion/{subregion}", (CountryRepository repository, string subregion) => Results.Ok(repository.GetCountriesBySubRegion(subregion))); app.MapGet("countries/capital/{capital:alpha}", (CountryRepository repository, string capital) => Results.Ok(repository.GetCountriesByCapital(capital))); app.MapGet("countries/regionalBloc/{bloc:alpha}", (CountryRepository repository, string bloc) => Results.Ok(repository.GetCountriesByRegionalBloc(bloc))); app.MapGet("countries/topleveldomain/{topleveldomain}", (CountryRepository repository, string topleveldomain) => Results.Ok(repository.GetCountriesByTopLevelDomain(topleveldomain))); app.MapGet("countries/cioc/{cioc:alpha}", (CountryRepository repository, string cioc) => Results.Ok(repository.GetCountriesByCioc(cioc))); app.MapHealthChecks("/health"); app.Run(); internal partial class Program { }
42.379032
141
0.624167
[ "MPL-2.0" ]
jprimke/restcountries
src/RestCountries.API/Program.cs
5,256
C#
// Originally submitted to OSEHRA 2/21/2017 by DSS, Inc. // Authored by DSS, Inc. 2014-2017 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VA.Gov.Artemis.Commands.Dsio.Tracking; using VA.Gov.Artemis.Vista.Broker; using VA.Gov.Artemis.Vista.Utility; namespace VA.Gov.Artemis.Commands.Dsio.Patient { /// <summary> /// Command to retrieve basic patient information /// </summary> public class DsioGetPatientInformationCommand : DsioCommand { /// <summary> /// The patient details /// </summary> public DsioPatientInformation Patient { get; set; } /// <summary> /// Creates the command /// </summary> /// <param name="newBroker">An object which allows communication with VistA and implements IRpcBroker</param> public DsioGetPatientInformationCommand(IRpcBroker newBroker) : base(newBroker) { } /// <summary> /// Add command arguments to the RPC call /// </summary> /// <param name="patientDfn"></param> public void AddCommandArguments(string patientDfn) { this.CommandArgs = new object[] { patientDfn}; } /// <summary> /// The name of the RPC /// </summary> public override string RpcName { get { return "WEBM GET PATIENT INFORMATION"; } } protected override void ProcessResponse() { if (this.ProcessQueryResponse()) { this.Patient = new DsioPatientInformation(); this.Patient.Dfn = this.CommandArgs[0] as string; string[] lines = this.Response.Lines; foreach (string line in lines) { string id = Util.Piece(line, Caret, 1); string val = Util.Piece(line, Caret, 2); switch (id) { case DsioPatientInformationFields.PatientKey: // Name //this.Patient.LastName = Util.Piece(val, ",", 1); //this.Patient.FirstName = Util.Piece(val, ",", 2); this.Patient.PatientName = val; break; case DsioPatientInformationFields.TrackingKey: // Tracking Status this.Patient.TrackingStatus = val; break; case DsioPatientInformationFields.NextContactDueKey: // Next Contact Date this.Patient.NextContactDue = val; break; case DsioPatientInformationFields.SSNKey: // SSN this.Patient.SSN = val; break; case DsioPatientInformationFields.DOBKey: // DOB this.Patient.DOB = val; break; case DsioPatientInformationFields.ResidencePhoneKey: // Home Phone this.Patient.HomePhone = val; break; case DsioPatientInformationFields.WorkPhoneKey: // Work Phone this.Patient.WorkPhone = val; break; case DsioPatientInformationFields.CellPhoneKey: // Cell Phone this.Patient.MobilePhone = val; break; case DsioPatientInformationFields.PregnantKey: // Pregnant this.Patient.Pregnant = val; break; case DsioPatientInformationFields.EddKey: // EDD this.Patient.EDD = val; break; case DsioPatientInformationFields.GravidaParaSummaryKey: // Gravida & Para this.Patient.GravidaPara = val; break; case DsioPatientInformationFields.LastDeliveryKey: this.Patient.LastLiveBirth = val; break; case DsioPatientInformationFields.LactatingKey: this.Patient.Lactating = val; break; case DsioPatientInformationFields.LastContactDateKey: this.Patient.LastContactDate = val; break; case DsioPatientInformationFields.NextChecklistDueKey: this.Patient.NextChecklistDue = val; break; case DsioPatientInformationFields.LmpKey: this.Patient.Lmp = val; break; case DsioPatientInformationFields.CurrentPregHighRiskKey: this.Patient.CurrentPregnancyHighRisk = val; string detail = Util.Piece(line, Caret, 3); if (!string.IsNullOrWhiteSpace(detail)) this.Patient.HighRiskDetails = detail; break; case DsioPatientInformationFields.ZipCodeKey: this.Patient.ZipCode = val; break; case DsioPatientInformationFields.EmailKey: this.Patient.Email = val; break; case DsioPatientInformationFields.T4BStatusKey: this.Patient.Text4BabyStatus = val; break; case DsioPatientInformationFields.T4BDateKey: this.Patient.Text4BabyDate = val; break; case DsioPatientInformationFields.T4BIdKey: this.Patient.Text4BabyId = val; break; } this.Response.Status = RpcResponseStatus.Success; } } } } }
41.48366
117
0.482118
[ "Apache-2.0" ]
Veratics/Maternity-Tracker
Dashboard/va.gov.artemis.commands/Dsio/Patient/DsioGetPatientInformationCommand.cs
6,349
C#
// Copyright 2020 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. using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; public class Program { // [START eventarc_audit_storage_server] public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { var port = Environment.GetEnvironmentVariable("PORT") ?? "8080"; var url = $"http://0.0.0.0:{port}"; return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>().UseUrls(url); }); } // [END eventarc_audit_storage_server] }
33.717949
76
0.66692
[ "Apache-2.0" ]
BearerPipelineTest/dotnet-docs-samples
eventarc/audit-storage/Program.cs
1,315
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TokanPages.Backend.Database; namespace TokanPages.Backend.Database.Migrations { [DbContext(typeof(DatabaseContext))] [Migration("20210327224914_AddAlbumTables")] partial class AddAlbumTables { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.10") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Albums", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("PhotoId") .HasColumnType("uniqueidentifier"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("PhotoId"); b.HasIndex("UserId"); b.ToTable("Albums"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Articles", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<bool>("IsPublished") .HasColumnType("bit"); b.Property<int>("ReadCount") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Articles"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Likes", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<Guid>("ArticleId") .HasColumnType("uniqueidentifier"); b.Property<string>("IpAddress") .IsRequired() .HasColumnType("nvarchar(15)") .HasMaxLength(15); b.Property<int>("LikeCount") .HasColumnType("int"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("ArticleId"); b.HasIndex("UserId"); b.ToTable("Likes"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.PhotoCategories", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("CategoryName") .IsRequired() .HasColumnType("nvarchar(60)") .HasMaxLength(60); b.HasKey("Id"); b.ToTable("PhotoCategories"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.PhotoGears", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<decimal>("Aperture") .HasColumnType("decimal(18,2)"); b.Property<string>("BodyModel") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<string>("BodyVendor") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<int>("FilmIso") .HasColumnType("int"); b.Property<int>("FocalLength") .HasColumnType("int"); b.Property<string>("LensName") .HasColumnType("nvarchar(60)") .HasMaxLength(60); b.Property<string>("LensVendor") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<string>("ShutterSpeed") .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.HasKey("Id"); b.ToTable("PhotoGears"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Photos", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("DateTaken") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Keywords") .HasColumnType("nvarchar(500)") .HasMaxLength(500); b.Property<Guid>("PhotoCategoryId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("PhotoGearId") .HasColumnType("uniqueidentifier"); b.Property<string>("PhotoUrl") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("PhotoCategoryId"); b.HasIndex("PhotoGearId"); b.HasIndex("UserId"); b.ToTable("Photos"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Subscribers", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<int>("Count") .HasColumnType("int"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<bool>("IsActivated") .HasColumnType("bit"); b.Property<DateTime?>("LastUpdated") .HasColumnType("datetime2"); b.Property<DateTime>("Registered") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Subscribers"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Users", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("AvatarName") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("FirstName") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<bool>("IsActivated") .HasColumnType("bit"); b.Property<DateTime?>("LastLogged") .HasColumnType("datetime2"); b.Property<string>("LastName") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<DateTime?>("LastUpdated") .HasColumnType("datetime2"); b.Property<DateTime>("Registered") .HasColumnType("datetime2"); b.Property<string>("ShortBio") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("UserAlias") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Albums", b => { b.HasOne("TokanPages.Backend.Domain.Entities.Photos", "Photo") .WithMany("Albums") .HasForeignKey("PhotoId") .HasConstraintName("FK_Albums_Photos") .IsRequired(); b.HasOne("TokanPages.Backend.Domain.Entities.Users", "User") .WithMany("Albums") .HasForeignKey("UserId") .HasConstraintName("FK_Albums_Users") .IsRequired(); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Articles", b => { b.HasOne("TokanPages.Backend.Domain.Entities.Users", "User") .WithMany("Articles") .HasForeignKey("UserId") .HasConstraintName("FK_Articles_Users") .IsRequired(); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Likes", b => { b.HasOne("TokanPages.Backend.Domain.Entities.Articles", "Article") .WithMany("Likes") .HasForeignKey("ArticleId") .HasConstraintName("FK_Likes_Articles") .IsRequired(); b.HasOne("TokanPages.Backend.Domain.Entities.Users", "User") .WithMany("Likes") .HasForeignKey("UserId") .HasConstraintName("FK_Likes_Users"); }); modelBuilder.Entity("TokanPages.Backend.Domain.Entities.Photos", b => { b.HasOne("TokanPages.Backend.Domain.Entities.PhotoCategories", "PhotoCategory") .WithMany("Photos") .HasForeignKey("PhotoCategoryId") .HasConstraintName("FK_Photos_PhotoCategories") .IsRequired(); b.HasOne("TokanPages.Backend.Domain.Entities.PhotoGears", "PhotoGear") .WithMany("Photos") .HasForeignKey("PhotoGearId") .HasConstraintName("FK_Photos_PhotoGears") .IsRequired(); b.HasOne("TokanPages.Backend.Domain.Entities.Users", "User") .WithMany("Photos") .HasForeignKey("UserId") .HasConstraintName("FK_Photos_Users") .IsRequired(); }); #pragma warning restore 612, 618 } } }
36.323034
117
0.4449
[ "MIT" ]
TomaszKandula/TokanPages
TokanPages.Backend/TokanPages.Backend.Database/Migrations/20210327224914_AddAlbumTables.Designer.cs
12,933
C#