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 Foundation.SceneManage.ScriptableObjects; using UnityEngine; using UnityTemplateProjects.Foundation.Event; namespace Foundation.SceneManage { public class StartGame : MonoBehaviour { [SerializeField] private GameSceneSO _loadLevelScene; // 开始游戏要加载的关卡 [Header("Broadcasting on")] [SerializeField] private LoadEventChannelSO _loadLevelChannel; // 发送event [Header("Listening to")] [SerializeField] private VoidEventChannelSO _onNewGameButton = default; private void Start() { _onNewGameButton.OnEventRaised += StartNewGame; } private void OnDestroy() { _onNewGameButton.OnEventRaised -= StartNewGame; } void StartNewGame() { if (_loadLevelChannel && _loadLevelScene) { _loadLevelChannel.RaiseEvent(_loadLevelScene); } else { Debug.LogWarningFormat("未绑定要启动的level,不能开始游戏"); } } } }
26.897436
79
0.605338
[ "MIT" ]
xiaoran301/unity_agile
Assets/Scripts/Foundation/SceneManage/StartGame.cs
1,103
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Reflection; using Xunit; namespace Microsoft.Build.UnitTests { sealed internal class StreamHelpers { /// <summary> /// Take a string and convert it to a StreamReader. /// </summary> /// <param name="value"></param> /// <returns></returns> static internal StreamReader StringToStreamReader(string value) { MemoryStream m = new MemoryStream(); TextWriter w = new StreamWriter(m, System.Text.Encoding.Default); w.Write(value); w.Flush(); m.Seek(0, SeekOrigin.Begin); return new StreamReader(m); } } }
28.258065
102
0.591324
[ "MIT" ]
HydAu/MsBuild
src/Shared/UnitTests/StreamHelpers.cs
848
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsvToClass.Utility { /// <summary> /// Gets values from the app.config file /// </summary> public static class Config { /// <summary> /// Gets the default csv file from the config appSettings /// </summary> /// <returns>string - the file path</returns> public static string GetDefaultInputFile() { string defaultOutputDirectory = null; NameValueCollection appSettings = ConfigurationManager.AppSettings; for (int i = 0; i < appSettings.Count; i++) { if (appSettings.GetKey(i) == "defaultCsvFile") { defaultOutputDirectory = appSettings[i]; } } return defaultOutputDirectory; } /// <summary> /// Gets the default download directory from the config appSettings /// </summary> /// <returns>string - the directory path</returns> public static string GetDefaultOutputFile() { string defaultOutputDirectory = null; NameValueCollection appSettings = ConfigurationManager.AppSettings; for (int i = 0; i < appSettings.Count; i++) { if (appSettings.GetKey(i) == "defaultOutputFile") { defaultOutputDirectory = appSettings[i]; } } return defaultOutputDirectory; } public static string GetDefaultNamespace() { string defaultNameSpace = null; NameValueCollection appSettings = ConfigurationManager.AppSettings; for (int i = 0; i < appSettings.Count; i++) { if (appSettings.GetKey(i) == "defaultNamespace") { defaultNameSpace = appSettings[i]; } } return defaultNameSpace; } } }
32.014925
79
0.551981
[ "MIT" ]
bizcad/CsvToClass
CsvToClass/Utility/Config.cs
2,147
C#
using System.Collections.Generic; using System.Linq; namespace PSImaging { public abstract class ImageProcesser { public abstract PixelsData Process(PixelsData sourcePixels); } public class GrayScaleConverter : ImageProcesser { public override PixelsData Process(PixelsData source) { var ret = new PixelsData(source.width, source.height); for (var i = 0; i < ret.pixels.Length; i += 4) { var grayValue = (byte)((source.pixels[i + 0] + source.pixels[i + 1] + source.pixels[i + 2]) / 3); ret.pixels[i + 0] = grayValue; ret.pixels[i + 1] = grayValue; ret.pixels[i + 2] = grayValue; ret.pixels[i + 3] = source.pixels[i + 3]; // keep the alpha value as-is } return ret; } } public class FrameAdder : ImageProcesser { public int borderSize = 1; public override PixelsData Process(PixelsData source) { var newWidth = source.width + borderSize * 2; var newHeight = source.height + borderSize * 2; var ret = new PixelsData(newWidth, newHeight); var sourceIndex = 0; for (var drawingIndex = 0; drawingIndex < ret.pixels.Length; drawingIndex += 4) { // when drawing pixel is in border, set the value to black if (IsInBorder(drawingIndex, newWidth, source.width, source.height)) { ret.pixels[drawingIndex + 0] = 0; ret.pixels[drawingIndex + 1] = 0; ret.pixels[drawingIndex + 2] = 0; ret.pixels[drawingIndex + 3] = 0xFF; } else { ret.pixels[drawingIndex + 0] = source.pixels[sourceIndex + 0]; ret.pixels[drawingIndex + 1] = source.pixels[sourceIndex + 1]; ret.pixels[drawingIndex + 2] = source.pixels[sourceIndex + 2]; ret.pixels[drawingIndex + 3] = source.pixels[sourceIndex + 3]; sourceIndex += 4; } } return ret; } private bool IsInBorder(int drawingIndex, int newWidth, int originalWidth, int originalHeight) { return PixelUtil.GetXPosition(drawingIndex, newWidth) < borderSize || PixelUtil.GetXPosition(drawingIndex, newWidth) >= (originalWidth + borderSize) || PixelUtil.GetYPosition(drawingIndex, newWidth) < borderSize || PixelUtil.GetYPosition(drawingIndex, newWidth) >= (originalHeight + borderSize); } } public class MedianFilter : ImageProcesser { public int distance = 1; public override PixelsData Process(PixelsData source) { var ret = new PixelsData(source.width, source.height); for (var yi = 0; yi < ret.height; yi++) { for (var xi = 0; xi < ret.width; xi++) { var neighborPixels = source.GetNeighborPixels(xi, yi, distance); var medianPixel = neighborPixels.OrderBy(pixel => pixel.A + pixel.G + pixel.B) .ElementAt(neighborPixels.Count / 2); ret.pixels[ret.GetIndex(xi, yi) + 0] = medianPixel.B; ret.pixels[ret.GetIndex(xi, yi) + 1] = medianPixel.G; ret.pixels[ret.GetIndex(xi, yi) + 2] = medianPixel.R; ret.pixels[ret.GetIndex(xi, yi) + 3] = 0xFF; // ignore alpha channel for this filter } } return ret; } } public class EdgeDrawer : ImageProcesser { private const bool X = true; private const bool _ = false; private bool[][][] masks = new bool[][][] { // level 0 new bool[][] { new bool[] {_, X, _}, new bool[] {X, X, X}, new bool[] {_, X, _} }, // level 1 new bool[][] { new bool[] {X, X, X}, new bool[] {X, X, X}, new bool[] {X, X, X} }, // level 2 new bool[][] { new bool[] {_, _, X, _, _}, new bool[] {_, X, X, X, _}, new bool[] {X, X, X, X, X}, new bool[] {_, X, X, X, _}, new bool[] {_, _, X, _, _} }, // level 3 new bool[][] { new bool[] {_, X, X, X, _}, new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X}, new bool[] {_, X, X, X, _} }, // level 4 new bool[][] { new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X}, new bool[] {X, X, X, X, X} }, }; private int level = 0; private Pixel drawingColor = new Pixel("000000"); private Pixel backGroundColor = new Pixel("FFFFFF"); public override PixelsData Process(PixelsData source) { var ret = source.Copy(); for (var yi = 0; yi < ret.height; yi++) { for (var xi = 0; xi < ret.width; xi++) { if (source.GetPixel(xi, yi).Equals(backGroundColor)) { continue; } for (var vi = 0; vi < masks[level].Length; vi++) { for (var ui = 0; ui < masks[level][0].Length; ui++) { if (!masks[level][vi][ui]) { continue; } var cursorX = getCursorPositionX(xi, ui); var cursorY = getCursorPositionY(yi, vi); if (!source.IsInBounds(cursorX, cursorY) || source.GetPixel(cursorX, cursorY).NotEquals(backGroundColor)) { continue; } ret.pixels[ret.GetIndex(cursorX, cursorY) + 0] = drawingColor.B; ret.pixels[ret.GetIndex(cursorX, cursorY) + 1] = drawingColor.G; ret.pixels[ret.GetIndex(cursorX, cursorY) + 2] = drawingColor.R; ret.pixels[ret.GetIndex(cursorX, cursorY) + 3] = 0xFF; // ignore alpha channel for this filter } } } } return ret; } public void SetLevel(int level) { this.level = level; } public void SetDrawingColor(string drawingColor) { this.drawingColor = new Pixel(drawingColor); } public void SetBackGroundColor(string backGroundColor) { this.backGroundColor = new Pixel(backGroundColor); } private int getCursorPositionX(int xi, int ui) { return xi + ui - masks[level][0].Length / 2; } private int getCursorPositionY(int yi, int vi) { return yi + vi - masks[level].Length / 2; } } public class FrameDrawer : ImageProcesser { private Pixel horizontalColor = new Pixel("FF0000"); private Pixel verticalColor = new Pixel("0000FF"); private Pixel borderColor = new Pixel("000000"); private Pixel frameColor = new Pixel("FFFF00"); private Pixel backGroundColor = new Pixel("FFFFFF"); public override PixelsData Process(PixelsData source) { var ret = new PixelsData(source.width, source.height); // Initialize for (var yi = 0; yi < ret.height; yi++) { for (var xi = 0; xi < ret.width; xi++) { ret.pixels[ret.GetIndex(xi, yi) + 0] = backGroundColor.B; ret.pixels[ret.GetIndex(xi, yi) + 1] = backGroundColor.G; ret.pixels[ret.GetIndex(xi, yi) + 2] = backGroundColor.R; ret.pixels[ret.GetIndex(xi, yi) + 3] = 0xFF; // ignore alpha channel for this filter } } for (var yi = 0; yi < ret.height; yi++) { for (var xi = 0; xi < ret.width; xi++) { if (source.GetPixel(xi, yi).Equals(horizontalColor)) { // upper border for (var vi = -10; vi <= -8; vi++) { var cursorY = yi + vi; if (cursorY < 0 || ret.GetPixel(xi, cursorY).Equals(frameColor)) { continue; } ret.pixels[ret.GetIndex(xi, cursorY) + 0] = borderColor.B; ret.pixels[ret.GetIndex(xi, cursorY) + 1] = borderColor.G; ret.pixels[ret.GetIndex(xi, cursorY) + 2] = borderColor.R; ret.pixels[ret.GetIndex(xi, cursorY) + 3] = 0xFF; } // within the border for (var vi = -7; vi <= 7; vi++) { var cursorY = yi + vi; if (cursorY < 0 || cursorY >= source.height) { continue; } ret.pixels[ret.GetIndex(xi, cursorY) + 0] = frameColor.B; ret.pixels[ret.GetIndex(xi, cursorY) + 1] = frameColor.G; ret.pixels[ret.GetIndex(xi, cursorY) + 2] = frameColor.R; ret.pixels[ret.GetIndex(xi, cursorY) + 3] = 0xFF; } // lower border for (var vi = 8; vi <= 10; vi++) { var cursorY = yi + vi; if (cursorY >= source.height || ret.GetPixel(xi, cursorY).Equals(frameColor)) { continue; } ret.pixels[ret.GetIndex(xi, cursorY) + 0] = borderColor.B; ret.pixels[ret.GetIndex(xi, cursorY) + 1] = borderColor.G; ret.pixels[ret.GetIndex(xi, cursorY) + 2] = borderColor.R; ret.pixels[ret.GetIndex(xi, cursorY) + 3] = 0xFF; } } if (source.GetPixel(xi, yi).Equals(verticalColor)) { // left border for (var ui = -3; ui <= -1; ui++) { var cursorX = xi + ui; if (cursorX < 0 || ret.GetPixel(cursorX, yi).Equals(frameColor)) { continue; } ret.pixels[ret.GetIndex(cursorX, yi) + 0] = borderColor.B; ret.pixels[ret.GetIndex(cursorX, yi) + 1] = borderColor.G; ret.pixels[ret.GetIndex(cursorX, yi) + 2] = borderColor.R; ret.pixels[ret.GetIndex(cursorX, yi) + 3] = 0xFF; } // within the border for (var ui = 0; ui <= 1; ui++) { var cursorX = xi + ui; if (cursorX < 0 || cursorX >= source.width) { continue; } ret.pixels[ret.GetIndex(cursorX, yi) + 0] = frameColor.B; ret.pixels[ret.GetIndex(cursorX, yi) + 1] = frameColor.G; ret.pixels[ret.GetIndex(cursorX, yi) + 2] = frameColor.R; ret.pixels[ret.GetIndex(cursorX, yi) + 3] = 0xFF; } // lower border for (var ui = 2; ui <= 4; ui++) { var cursorX = xi + ui; if (cursorX >= source.width || ret.GetPixel(cursorX, yi).Equals(frameColor)) { continue; } ret.pixels[ret.GetIndex(cursorX, yi) + 0] = borderColor.B; ret.pixels[ret.GetIndex(cursorX, yi) + 1] = borderColor.G; ret.pixels[ret.GetIndex(cursorX, yi) + 2] = borderColor.R; ret.pixels[ret.GetIndex(cursorX, yi) + 3] = 0xFF; } } } } return ret; } public void SetHorizontalColor(string color) { this.horizontalColor = new Pixel(color); } public void SetVerticalColor(string color) { this.verticalColor = new Pixel(color); } public void SetBorderColor(string color) { this.borderColor = new Pixel(color); } public void SetFrameColor(string color) { this.frameColor = new Pixel(color); } public void SetBackGroundColor(string color) { this.backGroundColor = new Pixel(color); } } public class ColorReplacer : ImageProcesser { private Pixel pixelFrom; private Pixel pixelTo; public override PixelsData Process(PixelsData source) { var ret = source.Copy(); for (var i = 0; i < ret.pixels.Length; i += 4) { var drawingPixel = new Pixel(source.pixels[i + 0], source.pixels[i + 1], source.pixels[i + 2], source.pixels[i + 3]); if (drawingPixel.Equals(pixelFrom)) { ret.pixels[i + 0] = pixelTo.B; ret.pixels[i + 1] = pixelTo.G; ret.pixels[i + 2] = pixelTo.R; ret.pixels[i + 3] = drawingPixel.A; // keep the alpha value as-is } } return ret; } public void SetColorsToReplace(string from, string to) { this.pixelFrom = new Pixel(from); this.pixelTo = new Pixel(to); } } public class ColorCleaner : ImageProcesser { private Pixel allowedColor; private Pixel resultColor; public override PixelsData Process(PixelsData source) { var ret = source.Copy(); for (var i = 0; i < ret.pixels.Length; i += 4) { var drawingPixel = new Pixel(source.pixels[i + 0], source.pixels[i + 1], source.pixels[i + 2], source.pixels[i + 3]); if (!drawingPixel.Equals(allowedColor)) { ret.pixels[i + 0] = resultColor.B; ret.pixels[i + 1] = resultColor.G; ret.pixels[i + 2] = resultColor.R; ret.pixels[i + 3] = drawingPixel.A; // keep the alpha value as-is } } return ret; } public void SetAllowedColor(string allowedColor) { this.allowedColor = new Pixel(allowedColor); } public void SetResultColor(string resultColor) { this.resultColor = new Pixel(resultColor); } } }
37.411236
122
0.421132
[ "MIT" ]
saggie/psimaging
scripts/ImageProcesser.cs
16,648
C#
namespace KpiLex.Api.Models.Response { public class UserResponseModel { } }
13.857143
37
0.618557
[ "MIT" ]
SemenchenkoVitaliy/GDC-CP
kpi-lex/KpiLex.Api/Models/Response/UserResponseModel.cs
99
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.462/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using System; using System.Reflection; namespace UpdateFileMaker.UI.Wizard { public class MainWindow : KryptonForm { #region Designer Code private ExtendedControls.ExtendedToolkit.Wizard.Controls.KryptonWizard kwUpdate; private void InitializeComponent() { this.kwUpdate = new ExtendedControls.ExtendedToolkit.Wizard.Controls.KryptonWizard(); this.wizardPage2 = new ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage(); this.kryptonLabel3 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.wizardPage1 = new ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage(); this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.wizardPage4 = new ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage(); this.wizardPage3 = new ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage(); this.kwUpdate.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage2)).BeginInit(); this.wizardPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage1)).BeginInit(); this.wizardPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage3)).BeginInit(); this.SuspendLayout(); // // kwUpdate // this.kwUpdate.Controls.Add(this.wizardPage2); this.kwUpdate.Controls.Add(this.wizardPage1); this.kwUpdate.Controls.Add(this.wizardPage4); this.kwUpdate.Controls.Add(this.wizardPage3); this.kwUpdate.Dock = System.Windows.Forms.DockStyle.Fill; this.kwUpdate.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kwUpdate.Location = new System.Drawing.Point(0, 0); this.kwUpdate.Name = "kwUpdate"; this.kwUpdate.Pages.AddRange(new ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage[] { this.wizardPage1, this.wizardPage2, this.wizardPage3, this.wizardPage4}); this.kwUpdate.Size = new System.Drawing.Size(1004, 628); this.kwUpdate.TabIndex = 0; // // wizardPage2 // this.wizardPage2.Controls.Add(this.kryptonLabel3); this.wizardPage2.Dock = System.Windows.Forms.DockStyle.Fill; this.wizardPage2.IsFinishPage = false; this.wizardPage2.Location = new System.Drawing.Point(0, 0); this.wizardPage2.Name = "wizardPage2"; this.wizardPage2.Size = new System.Drawing.Size(1004, 580); this.wizardPage2.TabIndex = 3; // // kryptonLabel3 // this.kryptonLabel3.Location = new System.Drawing.Point(117, 124); this.kryptonLabel3.Name = "kryptonLabel3"; this.kryptonLabel3.Size = new System.Drawing.Size(151, 26); this.kryptonLabel3.StateCommon.LongText.Font = new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel3.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel3.TabIndex = 0; this.kryptonLabel3.Values.Text = "Application Name:"; // // wizardPage1 // this.wizardPage1.Controls.Add(this.kryptonLabel2); this.wizardPage1.Controls.Add(this.kryptonLabel1); this.wizardPage1.Dock = System.Windows.Forms.DockStyle.Fill; this.wizardPage1.IsFinishPage = false; this.wizardPage1.Location = new System.Drawing.Point(0, 0); this.wizardPage1.Name = "wizardPage1"; this.wizardPage1.Size = new System.Drawing.Size(1004, 580); this.wizardPage1.TabIndex = 2; // // kryptonLabel2 // this.kryptonLabel2.Location = new System.Drawing.Point(80, 178); this.kryptonLabel2.Name = "kryptonLabel2"; this.kryptonLabel2.Size = new System.Drawing.Size(228, 33); this.kryptonLabel2.StateCommon.LongText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel2.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel2.TabIndex = 1; this.kryptonLabel2.Values.Text = "To begin, click \'Next\'"; // // kryptonLabel1 // this.kryptonLabel1.Location = new System.Drawing.Point(46, 127); this.kryptonLabel1.Name = "kryptonLabel1"; this.kryptonLabel1.Size = new System.Drawing.Size(596, 33); this.kryptonLabel1.StateCommon.LongText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel1.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel1.TabIndex = 0; this.kryptonLabel1.Values.Text = "Welcome to the aplication file update file maker wizard..."; // // wizardPage4 // this.wizardPage4.Dock = System.Windows.Forms.DockStyle.Fill; this.wizardPage4.IsFinishPage = false; this.wizardPage4.Location = new System.Drawing.Point(0, 0); this.wizardPage4.Name = "wizardPage4"; this.wizardPage4.Size = new System.Drawing.Size(1215, 772); this.wizardPage4.TabIndex = 5; // // wizardPage3 // this.wizardPage3.Dock = System.Windows.Forms.DockStyle.Fill; this.wizardPage3.IsFinishPage = false; this.wizardPage3.Location = new System.Drawing.Point(0, 0); this.wizardPage3.Name = "wizardPage3"; this.wizardPage3.Size = new System.Drawing.Size(1215, 772); this.wizardPage3.TabIndex = 4; // // MainWindow // this.ClientSize = new System.Drawing.Size(1004, 628); this.Controls.Add(this.kwUpdate); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.Name = "MainWindow"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Update File Maker"; this.kwUpdate.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.wizardPage2)).EndInit(); this.wizardPage2.ResumeLayout(false); this.wizardPage2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage1)).EndInit(); this.wizardPage1.ResumeLayout(false); this.wizardPage1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.wizardPage3)).EndInit(); this.ResumeLayout(false); } private ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage wizardPage1; private KryptonLabel kryptonLabel2; private KryptonLabel kryptonLabel1; private ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage wizardPage2; private ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage wizardPage3; private ExtendedControls.ExtendedToolkit.Wizard.Classes.WizardPage wizardPage4; private KryptonLabel kryptonLabel3; #endregion #region Variables private Version _applicationVersion = Assembly.GetExecutingAssembly().GetName().Version; #endregion #region Constructor public MainWindow() { InitializeComponent(); TextExtra = $"(Alpha - Version: { _applicationVersion.ToString() })"; } #endregion } }
52.174419
189
0.643303
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.462
Source/Krypton Toolkit Suite Extended/Applications/Update File Maker/UI/Wizard/MainWindow.cs
8,976
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // 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.Security.AccessControl; using NUnit.Framework; using System.Collections.Generic; namespace DiscUtils.Ntfs { [TestFixture] public class NtfsFileSystemTest { [Test] public void AclInheritance() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); RawSecurityDescriptor sd = new RawSecurityDescriptor("O:BAG:BAD:(A;OICINP;GA;;;BA)"); ntfs.CreateDirectory("dir"); ntfs.SetSecurity("dir", sd); ntfs.CreateDirectory(@"dir\subdir"); RawSecurityDescriptor inheritedSd = ntfs.GetSecurity(@"dir\subdir"); Assert.NotNull(inheritedSd); Assert.AreEqual("O:BAG:BAD:(A;ID;GA;;;BA)", inheritedSd.GetSddlForm(AccessControlSections.All)); using (ntfs.OpenFile(@"dir\subdir\file", FileMode.Create, FileAccess.ReadWrite)) { } inheritedSd = ntfs.GetSecurity(@"dir\subdir\file"); Assert.NotNull(inheritedSd); Assert.AreEqual("O:BAG:BAD:", inheritedSd.GetSddlForm(AccessControlSections.All)); } [Test] public void ReparsePoints_Empty() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.CreateDirectory("dir"); ntfs.SetReparsePoint("dir", new ReparsePoint(12345, new byte[0])); ReparsePoint rp = ntfs.GetReparsePoint("dir"); Assert.AreEqual(12345, rp.Tag); Assert.IsNotNull(rp.Content); Assert.AreEqual(0, rp.Content.Length); } [Test] public void ReparsePoints_NonEmpty() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.CreateDirectory("dir"); ntfs.SetReparsePoint("dir", new ReparsePoint(123, new byte[] { 4, 5, 6 })); ReparsePoint rp = ntfs.GetReparsePoint("dir"); Assert.AreEqual(123, rp.Tag); Assert.IsNotNull(rp.Content); Assert.AreEqual(3, rp.Content.Length); } [Test] public void Format_SmallDisk() { long size = 8 * 1024 * 1024; SparseMemoryStream partStream = new SparseMemoryStream(); //VirtualDisk disk = Vhd.Disk.InitializeDynamic(partStream, Ownership.Dispose, size); NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512); NtfsFileSystem ntfs = new NtfsFileSystem(partStream); ntfs.Dump(TextWriter.Null, ""); } [Test] public void Format_LargeDisk() { long size = 1024L * 1024 * 1024L * 1024; // 1 TB SparseMemoryStream partStream = new SparseMemoryStream(); NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512); NtfsFileSystem ntfs = new NtfsFileSystem(partStream); ntfs.Dump(TextWriter.Null, ""); } [Test] public void ClusterInfo() { // 'Big' files have clusters NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); using (Stream s = ntfs.OpenFile(@"file", FileMode.Create, FileAccess.ReadWrite)) { s.Write(new byte[(int)ntfs.ClusterSize], 0, (int)ntfs.ClusterSize); } var ranges = ntfs.PathToClusters("file"); Assert.AreEqual(1, ranges.Length); Assert.AreEqual(1, ranges[0].Count); // Short files have no clusters (stored in MFT) using (Stream s = ntfs.OpenFile(@"file2", FileMode.Create, FileAccess.ReadWrite)) { s.WriteByte(1); } ranges = ntfs.PathToClusters("file2"); Assert.AreEqual(0, ranges.Length); } [Test] public void ExtentInfo() { using (SparseMemoryStream ms = new SparseMemoryStream()) { Geometry diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024); NtfsFileSystem ntfs = NtfsFileSystem.Format(ms, "", diskGeometry, 0, diskGeometry.TotalSectorsLong); // Check non-resident attribute using (Stream s = ntfs.OpenFile(@"file", FileMode.Create, FileAccess.ReadWrite)) { byte[] data = new byte[(int)ntfs.ClusterSize]; data[0] = 0xAE; data[1] = 0x3F; data[2] = 0x8D; s.Write(data, 0, (int)ntfs.ClusterSize); } var extents = ntfs.PathToExtents("file"); Assert.AreEqual(1, extents.Length); Assert.AreEqual(ntfs.ClusterSize, extents[0].Length); ms.Position = extents[0].Start; Assert.AreEqual(0xAE, ms.ReadByte()); Assert.AreEqual(0x3F, ms.ReadByte()); Assert.AreEqual(0x8D, ms.ReadByte()); // Check resident attribute using (Stream s = ntfs.OpenFile(@"file2", FileMode.Create, FileAccess.ReadWrite)) { s.WriteByte(0xBA); s.WriteByte(0x82); s.WriteByte(0x2C); } extents = ntfs.PathToExtents("file2"); Assert.AreEqual(1, extents.Length); Assert.AreEqual(3, extents[0].Length); byte[] read = new byte[100]; ms.Position = extents[0].Start; ms.Read(read, 0, 100); Assert.AreEqual(0xBA, read[0]); Assert.AreEqual(0x82, read[1]); Assert.AreEqual(0x2C, read[2]); } } [Test] public void ManyAttributes() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); using (Stream s = ntfs.OpenFile(@"file", FileMode.Create, FileAccess.ReadWrite)) { s.WriteByte(32); } for (int i = 0; i < 50; ++i) { ntfs.CreateHardLink("file", "hl" + i); } using (Stream s = ntfs.OpenFile("hl35", FileMode.Open, FileAccess.ReadWrite)) { Assert.AreEqual(32, s.ReadByte()); s.Position = 0; s.WriteByte(12); } using (Stream s = ntfs.OpenFile("hl5", FileMode.Open, FileAccess.ReadWrite)) { Assert.AreEqual(12, s.ReadByte()); } for (int i = 0; i < 50; ++i) { ntfs.DeleteFile("hl" + i); } Assert.AreEqual(1, ntfs.GetFiles(@"\").Length); ntfs.DeleteFile("file"); Assert.AreEqual(0, ntfs.GetFiles(@"\").Length); } [Test] public void ShortNames() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); // Check we can find a short name in the same directory using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) {} ntfs.SetShortName("ALongFileName.txt", "ALONG~01.TXT"); Assert.AreEqual("ALONG~01.TXT", ntfs.GetShortName("ALongFileName.txt")); Assert.IsTrue(ntfs.FileExists("ALONG~01.TXT")); // Check path handling ntfs.CreateDirectory("DIR"); using (Stream s = ntfs.OpenFile(@"DIR\ALongFileName2.txt", FileMode.CreateNew)) { } ntfs.SetShortName(@"DIR\ALongFileName2.txt", "ALONG~02.TXT"); Assert.AreEqual("ALONG~02.TXT", ntfs.GetShortName(@"DIR\ALongFileName2.txt")); Assert.IsTrue(ntfs.FileExists(@"DIR\ALONG~02.TXT")); // Check we can open a file by the short name using (Stream s = ntfs.OpenFile("ALONG~01.TXT", FileMode.Open)) { } // Delete the long name, and make sure the file is gone ntfs.DeleteFile("ALONG~01.TXT"); Assert.IsFalse(ntfs.FileExists("ALONG~01.TXT")); // Delete the short name, and make sure the file is gone ntfs.DeleteFile(@"DIR\ALONG~02.TXT"); Assert.IsFalse(ntfs.FileExists(@"DIR\ALongFileName2.txt")); } [Test] public void HardLinkCount() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { } Assert.AreEqual(1, ntfs.GetHardLinkCount("ALongFileName.txt")); ntfs.CreateHardLink("ALongFileName.txt", "AHardLink.TXT"); Assert.AreEqual(2, ntfs.GetHardLinkCount("ALongFileName.txt")); ntfs.CreateDirectory("DIR"); ntfs.CreateHardLink(@"ALongFileName.txt", @"DIR\SHORTLNK.TXT"); Assert.AreEqual(3, ntfs.GetHardLinkCount("ALongFileName.txt")); // If we enumerate short names, then the initial long name results in two 'hardlinks' ntfs.NtfsOptions.HideDosFileNames = false; Assert.AreEqual(4, ntfs.GetHardLinkCount("ALongFileName.txt")); } [Test] public void HasHardLink() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { } Assert.IsFalse(ntfs.HasHardLinks("ALongFileName.txt")); ntfs.CreateHardLink("ALongFileName.txt", "AHardLink.TXT"); Assert.IsTrue(ntfs.HasHardLinks("ALongFileName.txt")); using (Stream s = ntfs.OpenFile("ALongFileName2.txt", FileMode.CreateNew)) { } // If we enumerate short names, then the initial long name results in two 'hardlinks' ntfs.NtfsOptions.HideDosFileNames = false; Assert.IsTrue(ntfs.HasHardLinks("ALongFileName2.txt")); } [Test] public void MoveLongName() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { } Assert.IsTrue(ntfs.FileExists("ALONGF~1.TXT")); ntfs.MoveFile("ALongFileName.txt", "ADifferentLongFileName.txt"); Assert.IsFalse(ntfs.FileExists("ALONGF~1.TXT")); Assert.IsTrue(ntfs.FileExists("ADIFFE~1.TXT")); ntfs.CreateDirectory("ALongDirectoryName"); Assert.IsTrue(ntfs.DirectoryExists("ALONGD~1")); ntfs.MoveDirectory("ALongDirectoryName", "ADifferentLongDirectoryName"); Assert.IsFalse(ntfs.DirectoryExists("ALONGD~1")); Assert.IsTrue(ntfs.DirectoryExists("ADIFFE~1")); } [Test] public void OpenRawStream() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); #pragma warning disable 618 Assert.Null(ntfs.OpenRawStream(@"$Extend\$ObjId", AttributeType.Data, null, FileAccess.Read)); #pragma warning restore 618 } [Test] public void GetAlternateDataStreams() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.OpenFile("AFILE.TXT", FileMode.Create).Close(); Assert.AreEqual(0, ntfs.GetAlternateDataStreams("AFILE.TXT").Length); ntfs.OpenFile("AFILE.TXT:ALTSTREAM", FileMode.Create).Close(); Assert.AreEqual(1, ntfs.GetAlternateDataStreams("AFILE.TXT").Length); Assert.AreEqual("ALTSTREAM", ntfs.GetAlternateDataStreams("AFILE.TXT")[0]); } [Test] public void DeleteAlternateDataStreams() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.OpenFile("AFILE.TXT", FileMode.Create).Close(); ntfs.OpenFile("AFILE.TXT:ALTSTREAM", FileMode.Create).Close(); Assert.AreEqual(1, ntfs.GetAlternateDataStreams("AFILE.TXT").Length); ntfs.DeleteFile("AFILE.TXT:ALTSTREAM"); Assert.AreEqual(1, ntfs.GetFileSystemEntries("").Length); Assert.AreEqual(0, ntfs.GetAlternateDataStreams("AFILE.TXT").Length); } [Test] public void DeleteShortNameDir() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.CreateDirectory(@"\TestLongName1\TestLongName2"); ntfs.SetShortName(@"\TestLongName1\TestLongName2", "TESTLO~1"); Assert.IsTrue(ntfs.DirectoryExists(@"\TestLongName1\TESTLO~1")); Assert.IsTrue(ntfs.DirectoryExists(@"\TestLongName1\TestLongName2")); ntfs.DeleteDirectory(@"\TestLongName1", true); Assert.IsFalse(ntfs.DirectoryExists(@"\TestLongName1")); } [Test] public void GetFileLength() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.OpenFile(@"AFILE.TXT", FileMode.Create).Close(); Assert.AreEqual(0, ntfs.GetFileLength("AFILE.TXT")); using (var stream = ntfs.OpenFile(@"AFILE.TXT", FileMode.Open)) { stream.Write(new byte[14325], 0, 14325); } Assert.AreEqual(14325, ntfs.GetFileLength("AFILE.TXT")); using (var attrStream = ntfs.OpenFile(@"AFILE.TXT:altstream", FileMode.Create)) { attrStream.Write(new byte[122], 0, 122); } Assert.AreEqual(122, ntfs.GetFileLength("AFILE.TXT:altstream")); // Test NTFS options for hardlink behaviour ntfs.CreateDirectory("Dir"); ntfs.CreateHardLink("AFILE.TXT", @"Dir\OtherLink.txt"); using (var stream = ntfs.OpenFile("AFILE.TXT", FileMode.Open, FileAccess.ReadWrite)) { stream.SetLength(50); } Assert.AreEqual(50, ntfs.GetFileLength("AFILE.TXT")); Assert.AreEqual(14325, ntfs.GetFileLength(@"Dir\OtherLink.txt")); ntfs.NtfsOptions.FileLengthFromDirectoryEntries = false; Assert.AreEqual(50, ntfs.GetFileLength(@"Dir\OtherLink.txt")); } [Test] public void Fragmented() { NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); ntfs.CreateDirectory(@"DIR"); byte[] buffer = new byte[4096]; for(int i = 0; i < 2500; ++i) { using(var stream = ntfs.OpenFile(@"DIR\file" + i + ".bin", FileMode.Create, FileAccess.ReadWrite)) { stream.Write(buffer, 0,buffer.Length); } using(var stream = ntfs.OpenFile(@"DIR\" + i + ".bin", FileMode.Create, FileAccess.ReadWrite)) { stream.Write(buffer, 0,buffer.Length); } } for (int i = 0; i < 2500; ++i) { ntfs.DeleteFile(@"DIR\file" + i + ".bin"); } // Create fragmented file (lots of small writes) using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.Create, FileAccess.ReadWrite)) { for (int i = 0; i < 2500; ++i) { stream.Write(buffer, 0, buffer.Length); } } // Try a large write byte[] largeWriteBuffer = new byte[200 * 1024]; for (int i = 0; i < largeWriteBuffer.Length / 4096; ++i) { largeWriteBuffer[i * 4096] = (byte)i; } using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { stream.Position = stream.Length - largeWriteBuffer.Length; stream.Write(largeWriteBuffer, 0, largeWriteBuffer.Length); } // And a large read byte[] largeReadBuffer = new byte[largeWriteBuffer.Length]; using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { stream.Position = stream.Length - largeReadBuffer.Length; stream.Read(largeReadBuffer, 0, largeReadBuffer.Length); } Assert.AreEqual(largeWriteBuffer, largeReadBuffer); } [Test] public void Sparse() { int fileSize = 1 * 1024 * 1024; NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem(); byte[] data = new byte[fileSize]; for (int i = 0; i < fileSize; i++) { data[i] = (byte)i; } using (SparseStream s = ntfs.OpenFile("file.bin", FileMode.CreateNew)) { s.Write(data, 0, fileSize); ntfs.SetAttributes("file.bin", ntfs.GetAttributes("file.bin") | FileAttributes.SparseFile); s.Position = 64 * 1024; s.Clear(128 * 1024); s.Position = fileSize - 64 * 1024; s.Clear(128 * 1024); } using (SparseStream s = ntfs.OpenFile("file.bin", FileMode.Open)) { Assert.AreEqual(fileSize + 64 * 1024, s.Length); List<StreamExtent> extents = new List<StreamExtent>(s.Extents); Assert.AreEqual(2, extents.Count); Assert.AreEqual(0, extents[0].Start); Assert.AreEqual(64 * 1024, extents[0].Length); Assert.AreEqual((64 + 128) * 1024, extents[1].Start); Assert.AreEqual(fileSize - (64 * 1024) - ((64 + 128) * 1024), extents[1].Length); s.Position = 72 * 1024; s.WriteByte(99); byte[] readBuffer = new byte[fileSize]; s.Position = 0; s.Read(readBuffer, 0, fileSize); for (int i = 64 * 1024; i < (128 + 64) * 1024; ++i) { data[i] = 0; } for (int i = fileSize - (64 * 1024); i < fileSize; ++i) { data[i] = 0; } data[72 * 1024] = 99; Assert.AreEqual(data, readBuffer); } } } }
38.605416
117
0.548023
[ "MIT" ]
ChaplinMarchais/DiscUtils
unittests/LibraryTests/Ntfs/NtfsFileSystemTest.cs
19,959
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PredicateParty { class Program { private static List<string> names = new List<string>(); private static Dictionary<string, Func<string, string, bool>> predicates = new Dictionary<string, Func<string, string, bool>> { { "StartsWith", (name, condition) => name.StartsWith(condition) }, { "EndsWith", (name, condition) => name.EndsWith(condition)}, { "Length", (name, condition) => name.Length.ToString().Equals(condition)} }; static void Main(string[] args) { names = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); var outputNames = new List<string>(); var input = Console.ReadLine(); while(input.ToLower() != "party!") { var splitted = input.Split(); var command = splitted[0]; var condition = splitted[1]; var criteria = splitted[2]; if(command == "Remove") { names.RemoveAll(x => predicates[condition](x, criteria)); }else { var matches = names.FindAll(x => predicates[condition](x, criteria)); foreach (var m in matches) { var index = names.FindIndex(x => x == m); names.Insert(index, m); } } input = Console.ReadLine(); } if(names.Count > 0) { var outputNamesString = string.Join(", ", names); Console.WriteLine($"{outputNamesString} are going to the party!"); } else { Console.WriteLine("Nobody is going to the party!"); } } } }
33.419355
133
0.479247
[ "MIT" ]
AleksandrinaGeorgieva/SoftUni
03 - C# Advanced/05 - Functional Programming/PredicateParty/PredicateParty/Program.cs
2,074
C#
using ITfoxtec.Identity.Saml2; using ITfoxtec.Identity.Saml2.MvcCore; using ITfoxtec.Identity.Saml2.Schemas; using ITfoxtec.Identity.Saml2.Schemas.Metadata; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using TestWebAppCoreNemLogin3Sp.Identity; namespace TestWebApp.Controllers { [AllowAnonymous] [Route("Metadata")] public class MetadataController : Controller { private readonly Saml2Configuration config; public MetadataController(IOptions<Saml2Configuration> configAccessor) { config = configAccessor.Value; } public IActionResult Index() { var defaultSite = new Uri($"{Request.Scheme}://{Request.Host.ToUriComponent()}/"); var entityDescriptor = new EntityDescriptor(config, signMetadata: false); entityDescriptor.ValidUntil = 365; entityDescriptor.SPSsoDescriptor = new SPSsoDescriptor { SigningCertificates = new X509Certificate2[] { config.SigningCertificate }, EncryptionCertificates = new X509Certificate2[] { config.DecryptionCertificate }, SingleLogoutServices = new SingleLogoutService[] { new SingleLogoutService { Binding = ProtocolBindings.HttpPost, Location = new Uri(defaultSite, "Auth/SingleLogout"), ResponseLocation = new Uri(defaultSite, "Auth/LoggedOut") } }, NameIDFormats = new Uri[] { NameIdentifierFormats.Persistent }, AssertionConsumerServices = new AssertionConsumerService[] { new AssertionConsumerService { Binding = ProtocolBindings.HttpPost, Location = new Uri(defaultSite, "Auth/AssertionConsumerService") } }, AttributeConsumingServices = new AttributeConsumingService[] { new AttributeConsumingService { ServiceName = new ServiceName("ITfoxtecIdentitySaml2-dev", "en"), RequestedAttributes = CreateRequestedAttributes() } }, }; entityDescriptor.SPSsoDescriptor.SetDefaultEncryptionMethods(); entityDescriptor.ContactPersons = new[] { new ContactPerson(ContactTypes.Administrative) { Company = "Some Company", GivenName = "Some Given Name", SurName = "Some Surname", EmailAddress = "some@some-domain.com", TelephoneNumber = "11111111", }, new ContactPerson(ContactTypes.Technical) { Company = "Some Company", GivenName = "Some tech Given Name", SurName = "Some tech Surname", EmailAddress = "sometech@some-domain.com", TelephoneNumber = "22222222", } }; return new Saml2Metadata(entityDescriptor).CreateMetadata().ToActionResult(); } private IEnumerable<RequestedAttribute> CreateRequestedAttributes() { yield return new RequestedAttribute(OioSaml3ClaimTypes.SpecVersion, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.BootstrapToken, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); //yield return new RequestedAttribute(OioSaml3ClaimTypes.PrivilegesIntermediate, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.NsisLoa, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.NsisIal, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.NsisAal, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.FullName, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.FirstName, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.LastName, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.Email, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); //yield return new RequestedAttribute(OioSaml3ClaimTypes.CprNumber, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.Age, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.CprUuid, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.DateOfBirth, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.PersonPid, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalUuidPersistent, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalRid, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalCvr, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalOrgName, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalProductionUnit, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); yield return new RequestedAttribute(OioSaml3ClaimTypes.ProfessionalSeNumber, isRequired: false, nameFormat: Saml2MetadataConstants.AttributeNameFormatUri); } } }
62.607477
196
0.705478
[ "BSD-3-Clause" ]
YaronSpawn/ITfoxtec.Identity.Saml2
test/TestWebAppCoreNemLogin3Sp/Controllers/MetadataController.cs
6,701
C#
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Linq; using System.Text.RegularExpressions; using Boo.Lang.Runtime; namespace Boo.Lang.Compiler.TypeSystem { public static class Types { public static readonly Type RuntimeServices = typeof(RuntimeServices); public static readonly Type Builtins = typeof(Builtins); public static readonly Type List = typeof(List); public static readonly Type Hash = typeof(Hash); public static readonly Type ICallable = typeof(ICallable); public static readonly Type ICollection = typeof(ICollection); public static readonly Type IEnumerable = typeof(IEnumerable); public static readonly Type IEnumerableGeneric = typeof(System.Collections.Generic.IEnumerable<>); public static readonly Type Object = typeof(object); public static readonly Type Regex = typeof(Regex); public static readonly Type ValueType = typeof(ValueType); public static readonly Type Array = typeof(Array); public static readonly Type ObjectArray = typeof(object[]); public static readonly Type Void = typeof(void); public static readonly Type String = typeof(string); public static readonly Type Byte = typeof(byte); public static readonly Type SByte = typeof(sbyte); public static readonly Type Char = typeof(char); public static readonly Type Short = typeof(short); public static readonly Type Int = typeof(int); public static readonly Type Long = typeof(long); public static readonly Type UShort = typeof(ushort); public static readonly Type UInt = typeof(uint); public static readonly Type ULong = typeof(ulong); public static readonly Type TimeSpan = typeof(TimeSpan); public static readonly Type DateTime = typeof(DateTime); public static readonly Type Single = typeof(float); public static readonly Type Double = typeof(double); public static readonly Type Decimal = typeof(decimal); public static readonly Type Bool = typeof(bool); public static readonly Type IntPtr = typeof(IntPtr); public static readonly Type UIntPtr = typeof(UIntPtr); public static readonly Type Type = typeof(Type); public static readonly Type MulticastDelegate = typeof(MulticastDelegate); public static readonly Type Delegate = typeof(Delegate); public static readonly Type DuckTypedAttribute = typeof(DuckTypedAttribute); public static readonly Type ClrExtensionAttribute; public static readonly Type DllImportAttribute = typeof(System.Runtime.InteropServices.DllImportAttribute); public static readonly Type ModuleAttribute = typeof(System.Runtime.CompilerServices.CompilerGlobalScopeAttribute); public static readonly Type ParamArrayAttribute = typeof(ParamArrayAttribute); public static readonly Type DefaultMemberAttribute = typeof(System.Reflection.DefaultMemberAttribute); public static readonly Type Nullable = typeof(Nullable<>); public static readonly Type CompilerGeneratedAttribute = typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute); static Type FindType(string fullTypeName, string[] possibleAssemblyNames) { return AppDomain.CurrentDomain.GetAssemblies() .Where(a => possibleAssemblyNames.Any(name => a.FullName.StartsWith(name))) .Select(assembly => assembly.GetType(fullTypeName, false)) .FirstOrDefault(type => type != null); } static Types() { // ExtensionAttribute is in System.Core for .NET 4.0 and in mscorlib for .NET 4.5. // We use reflection to get the type to avoid a hardcoded reference to mscorlib that // will crash the boo compiler if it was built with .NET 4.5 and then run on .NET 4.0. // Windows XP only supports .NET 4.0. ClrExtensionAttribute = FindType("System.Runtime.CompilerServices.ExtensionAttribute", new[] { "mscorlib", "System.Core" }); } } }
37.5625
127
0.764467
[ "BSD-3-Clause" ]
LaudateCorpus1/boo
src/Boo.Lang.Compiler/TypeSystem/Types.cs
5,409
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.Insights.V20150501 { /// <summary> /// An Application Insights workbook definition. /// </summary> [AzureNextGenResourceType("azure-nextgen:insights/v20150501:Workbook")] public partial class Workbook : Pulumi.CustomResource { /// <summary> /// Workbook category, as defined by the user at creation time. /// </summary> [Output("category")] public Output<string> Category { get; private set; } = null!; /// <summary> /// The kind of workbook. Choices are user and shared. /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// Resource location /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Azure resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Configuration of this particular workbook. Configuration data is a string containing valid JSON /// </summary> [Output("serializedData")] public Output<string> SerializedData { get; private set; } = null!; /// <summary> /// Enum indicating if this workbook definition is owned by a specific user or is shared between all users with access to the Application Insights component. /// </summary> [Output("sharedTypeKind")] public Output<string> SharedTypeKind { get; private set; } = null!; /// <summary> /// Optional resourceId for a source resource. /// </summary> [Output("sourceResourceId")] public Output<string?> SourceResourceId { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Date and time in UTC of the last modification that was made to this workbook definition. /// </summary> [Output("timeModified")] public Output<string> TimeModified { get; private set; } = null!; /// <summary> /// Azure resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Unique user id of the specific user that owns this workbook. /// </summary> [Output("userId")] public Output<string> UserId { get; private set; } = null!; /// <summary> /// This instance's version of the data model. This can change as new features are added that can be marked workbook. /// </summary> [Output("version")] public Output<string?> Version { get; private set; } = null!; /// <summary> /// Internally assigned unique id of the workbook definition. /// </summary> [Output("workbookId")] public Output<string> WorkbookId { get; private set; } = null!; /// <summary> /// Create a Workbook resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Workbook(string name, WorkbookArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:insights/v20150501:Workbook", name, args ?? new WorkbookArgs(), MakeResourceOptions(options, "")) { } private Workbook(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:insights/v20150501:Workbook", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:insights:Workbook"}, new Pulumi.Alias { Type = "azure-nextgen:insights/latest:Workbook"}, new Pulumi.Alias { Type = "azure-nextgen:insights/v20180617preview:Workbook"}, new Pulumi.Alias { Type = "azure-nextgen:insights/v20201020:Workbook"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Workbook resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Workbook Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Workbook(name, id, options); } } public sealed class WorkbookArgs : Pulumi.ResourceArgs { /// <summary> /// Workbook category, as defined by the user at creation time. /// </summary> [Input("category", required: true)] public Input<string> Category { get; set; } = null!; /// <summary> /// The kind of workbook. Choices are user and shared. /// </summary> [Input("kind")] public InputUnion<string, Pulumi.AzureNextGen.Insights.V20150501.SharedTypeKind>? Kind { get; set; } /// <summary> /// Resource location /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The user-defined name of the workbook. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the Application Insights component resource. /// </summary> [Input("resourceName")] public Input<string>? ResourceName { get; set; } /// <summary> /// Configuration of this particular workbook. Configuration data is a string containing valid JSON /// </summary> [Input("serializedData", required: true)] public Input<string> SerializedData { get; set; } = null!; /// <summary> /// Enum indicating if this workbook definition is owned by a specific user or is shared between all users with access to the Application Insights component. /// </summary> [Input("sharedTypeKind", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Insights.V20150501.SharedTypeKind> SharedTypeKind { get; set; } = null!; /// <summary> /// Optional resourceId for a source resource. /// </summary> [Input("sourceResourceId")] public Input<string>? SourceResourceId { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Unique user id of the specific user that owns this workbook. /// </summary> [Input("userId", required: true)] public Input<string> UserId { get; set; } = null!; /// <summary> /// This instance's version of the data model. This can change as new features are added that can be marked workbook. /// </summary> [Input("version")] public Input<string>? Version { get; set; } /// <summary> /// Internally assigned unique id of the workbook definition. /// </summary> [Input("workbookId", required: true)] public Input<string> WorkbookId { get; set; } = null!; public WorkbookArgs() { SharedTypeKind = "shared"; } } }
38.722689
165
0.58431
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Insights/V20150501/Workbook.cs
9,216
C#
using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using TodoListWebApp; namespace Microsoft.AspNetCore.Authentication { public static class AzureAdAuthenticationBuilderExtensions { public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder) => builder.AddAzureAd(_ => { }); public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions) { builder.Services.Configure(configureOptions); builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>(); builder.AddOpenIdConnect(); return builder; } private class ConfigureAzureOptions : IConfigureNamedOptions<OpenIdConnectOptions> { private readonly AzureAdOptions _azureOptions; public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions) { _azureOptions = azureOptions.Value; } public void Configure(string name, OpenIdConnectOptions options) { options.ClientId = _azureOptions.ClientId; options.Authority = _azureOptions.Authority; options.UseTokenLifetime = true; options.CallbackPath = _azureOptions.CallbackPath; options.RequireHttpsMetadata = false; options.ClientSecret = _azureOptions.ClientSecret; options.Resource = "https://graph.microsoft.com"; // AAD graph // Without overriding the response type (which by default is id_token), the OnAuthorizationCodeReceived event is not called. // but instead OnTokenValidated event is called. Here we request both so that OnTokenValidated is called first which // ensures that context.Principal has a non-null value when OnAuthorizeationCodeReceived is called options.ResponseType = "id_token code"; // Subscribing to the OIDC events options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived; options.Events.OnAuthenticationFailed = OnAuthenticationFailed; } public void Configure(OpenIdConnectOptions options) { Configure(Options.DefaultName, options); } /// <summary> /// Redeems the authorization code by calling AcquireTokenByAuthorizationCodeAsync in order to ensure /// that the cache has a token for the signed-in user, which will then enable the controllers (like the /// TodoController, to call AcquireTokenSilentAsync successfully. /// </summary> private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context) { // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API string userObjectId = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; //Adding role to the claims //Add claim if they are #region Adding role to the claims var claims = new List<Claim> { new Claim(ClaimTypes.Role, "admin") }; var appIdentity = new ClaimsIdentity(claims); context.Principal.AddIdentity(appIdentity); #endregion var authContext = new AuthenticationContext(context.Options.Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session)); var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret); var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource); // Notify the OIDC middleware that we already took care of code redemption. context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken); } /// <summary> /// this method is invoked if exceptions are thrown during request processing /// </summary> private Task OnAuthenticationFailed(AuthenticationFailedContext context) { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Exception.Message); return Task.FromResult(0); } } } }
47.345794
165
0.656929
[ "MIT" ]
rammi44/asp_net_core_azure_active_directory
TodoListWebApp/Extensions/AzureAdAuthenticationBuilderExtensions.cs
5,068
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; namespace Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Runtime.Json { internal class ParserException : Exception { internal ParserException(string message) : base(message) { } internal ParserException(string message, SourceLocation location) : base(message) { Location = location; } internal SourceLocation Location { get; } } }
34.125
97
0.484737
[ "MIT" ]
3quanfeng/azure-powershell
src/Blockchain/generated/runtime/Parser/Exceptions/ParseException.cs
798
C#
/**************************************************************************** Functions for interpreting c# code for blocks. Copyright 2016 dtknowlove@qq.com Copyright 2016 sophieml1989@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace UBlockly { [CodeInterpreter(BlockType = "lists_create_empty")] public class Lists_Create_Empty_Cmdtor : ValueCmdtor { protected override DataStruct Execute(Block block) { return new DataStruct(new ArrayList()); } } [CodeInterpreter(BlockType = "lists_create_with")] public class Lists_Create_With_Cmdtor : ValueCmdtor { protected override DataStruct Execute(Block block) { ItemListMutator mutator = block.Mutator as ItemListMutator; if (mutator == null) throw new Exception("Block \"lists_create_with\" must have a mutator \"lists_create_with_item_mutator\""); ArrayList resultList=new ArrayList(); for (int i = 0; i < mutator.ItemCount; i++) { resultList.Add(CSharp.Interpreter.ValueReturn(block, "ADD" + i, new DataStruct(0))); } return new DataStruct(resultList); } } [CodeInterpreter(BlockType = "lists_repeat")] public class Lists_Repeat_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "ITEM", new DataStruct()); yield return ctor; DataStruct arg0 = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block,"NUM",new DataStruct(0)); yield return ctor; DataStruct arg1 = ctor.Data; ArrayList list=new ArrayList(); int repeatCount = (int) arg1.NumberValue.Value; for (int i = 0; i < repeatCount; i++) { list.Add(arg0); } ReturnData(new DataStruct(list)); } } [CodeInterpreter(BlockType = "lists_reverse")] public class Lists_Reverse_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block,"LIST",new DataStruct(new ArrayList())); yield return ctor; DataStruct arg0 = ctor.Data; arg0.ListValue.Reverse(); ReturnData(new DataStruct(arg0.ListValue)); } } [CodeInterpreter(BlockType = "lists_isEmpty")] public class Lists_IsEmpty_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block,"VALUE",new DataStruct(new ArrayList())); yield return ctor; DataStruct arg0 = ctor.Data; ReturnData(arg0.IsList ? new DataStruct(arg0.ListValue.Count <= 0) : new DataStruct(arg0.StringValue.Length <= 0)); } } [CodeInterpreter(BlockType = "lists_length")] public class Lists_Length_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "VALUE", new DataStruct(new ArrayList())); yield return ctor; DataStruct arg0 = ctor.Data; ReturnData(arg0.IsList ? new DataStruct(arg0.ListValue.Count) : new DataStruct(arg0.StringValue.Length)); } } [CodeInterpreter(BlockType = "lists_indexOf")] public class Lists_IndexOf_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "VALUE", new DataStruct("")); yield return ctor; DataStruct arg0 = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "FIND", new DataStruct("")); yield return ctor; DataStruct arg1 = ctor.Data; string end = block.GetFieldValue("END"); int index = -1; switch (end) { case "FIRST": { if (arg0.IsString) { index = arg0.StringValue.IndexOf(arg1.StringValue); } else { for (int i = 0; i < arg0.ListValue.Count; i++) { if (arg1.Equals(arg0.ListValue[i])) { index = i; break; } } } break; } case "LAST": { if (arg0.IsString) { index = arg0.StringValue.LastIndexOf(arg1.StringValue); } else { for (int i = arg0.ListValue.Count - 1; i >= 0; i--) { if (arg1.Equals(arg0.ListValue[i])) { index = i; break; } } } break; } } ReturnData(new DataStruct(index)); } } [CodeInterpreter(BlockType = "lists_getIndex")] public class Lists_GetIndex_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "VALUE", new DataStruct("")); yield return ctor; DataStruct argList = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "AT", new DataStruct(1)); yield return ctor; DataStruct argAt = ctor.Data; string mode = block.GetFieldValue("MODE"); string where = block.GetFieldValue("WHERE"); ArrayList array = argList.ListValue; int index = (int)argAt.NumberValue.Value; int length = array.Count; if (mode.Equals("GET")) { switch (where) { case "FROM_START": ReturnData((DataStruct)array[index]); break; case "FROM_END": ReturnData((DataStruct)array[length-index]); break; case "FIRST": ReturnData((DataStruct)array[0]); break; case "LAST": ReturnData((DataStruct)array[length-1]); break; case "RANDOM": ReturnData((DataStruct)array[new Random().Next(0,length)]); break; } } else { //GET_REMOVE DataStruct res=new DataStruct(); int tmp = 0; switch (where) { case "FROM_START": tmp = index; break; case "FROM_END": tmp = length-index; break; case "FIRST": tmp = 0; break; case "LAST": tmp = length-1; break; case "RANDOM": tmp = new Random().Next(0,length); break; } res = (DataStruct)array[tmp]; array.RemoveAt(length-1); ReturnData(res); } } } [CodeInterpreter(BlockType = "lists_removeIndex")] public class Lists_RemoveIndex_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "VALUE", new DataStruct("")); yield return ctor; DataStruct argList = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "AT", new DataStruct(1)); yield return ctor; DataStruct argAt = ctor.Data; string where = block.GetFieldValue("WHERE"); ArrayList array = argList.ListValue; int index = (int)argAt.NumberValue.Value; int length = array.Count; int tmp = 0; switch (where) { case "FROM_START": tmp = index; break; case "FROM_END": tmp = length-index; break; case "FIRST": tmp = 0; break; case "LAST": tmp = length-1; break; case "RANDOM": tmp = new Random().Next(0,length); break; } argList.ListValue.RemoveAt(tmp); CSharp.VariableDatas.SetData("VALUE", argList); } } [CodeInterpreter(BlockType = "lists_setIndex")] public class Lists_SetIndex_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "LIST", new DataStruct("")); yield return ctor; DataStruct argList = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "AT", new DataStruct(1)); yield return ctor; DataStruct argAt = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "TO", new DataStruct(1)); yield return ctor; DataStruct changeValue = ctor.Data; string mode = block.GetFieldValue("MODE"); string where = block.GetFieldValue("WHERE"); ArrayList array = argList.ListValue; int index = (int)argAt.NumberValue.Value; int length = array.Count; if(index>=length) yield break; int tmp = 0; switch (where) { case "FROM_START": tmp = index; break; case "FROM_END": tmp = length-index; break; case "FIRST": tmp = 0; break; case "LAST": tmp = length-1; break; case "RANDOM": tmp = new Random().Next(0,length); break; } if(tmp>=length) yield break; if (mode.Equals("SET")) { argList.ListValue[tmp] = changeValue; } else { //INSERT argList.ListValue.Insert(tmp,changeValue); } CSharp.VariableDatas.SetData("LIST", argList); } } [CodeInterpreter(BlockType = "lists_getSublist")] public class Lists_GetSublist_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "LIST", new DataStruct("")); yield return ctor; DataStruct argList = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "AT1", new DataStruct(1)); yield return ctor; DataStruct argAt1 = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "AT2", new DataStruct(1)); yield return ctor; DataStruct argAt2 = ctor.Data; string where1 = block.GetFieldValue("WHERE1"); string where2 = block.GetFieldValue("WHERE2"); int index1=(int)argAt1.NumberValue.Value; int index2=(int)argAt2.NumberValue.Value; int lengh = argList.ListValue.Count; ArrayList result=new ArrayList(); if (index1 < lengh && index2 < lengh) { switch (where1) { case "FROM_START": break; case "FROM_END": index1 = lengh - index1; break; case "FIRST": index1 = 0; break; } switch (where2) { case "FROM_START": break; case "FROM_END": index2 = lengh - index2; break; case "LAST": index2 = lengh - 1; break; } if (index1 < 0 || index2 < 0) { ReturnData(new DataStruct(result)); yield break; } if (index1 < index2) for (int i = index1; i < (index2 - index1) + 1; i++) { result.Add(i); } } ReturnData(new DataStruct(result)); } } [CodeInterpreter(BlockType = "lists_sort")] public class Lists_Sort_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "LIST", new DataStruct("")); yield return ctor; DataStruct arg0 = ctor.Data; string type = block.GetFieldValue("TYPE"); string direction = block.GetFieldValue("DIRECTION"); switch (type) { case "NUMERIC": arg0.ListValue.ArraySort(CompareNumeric, direction == "-1"); ReturnData(new DataStruct(arg0.ListValue)); break; case "TEXT": arg0.ListValue.ArraySort(CompareText, direction == "-1"); ReturnData(new DataStruct(arg0.ListValue)); break; case "IGNORE_CASE": arg0.ListValue.ArraySort(CompareImgoreCase, direction == "-1"); ReturnData(new DataStruct(arg0.ListValue)); break; } } private bool CompareNumeric(object a, object b) { return new Number(a.ToString()) > new Number(b.ToString()); } private bool CompareText(object a, object b) { return string.Compare(a.ToString(), b.ToString()) > 0; } private bool CompareImgoreCase(object a, object b) { return string.Compare(a.ToString().ToLower(), b.ToString().ToLower()) > 0; } } [CodeInterpreter(BlockType = "lists_split_from_text")] public class Lists_SplitFromText_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "INPUT", new DataStruct("")); yield return ctor; DataStruct arg0 = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "DELIM", new DataStruct("")); yield return ctor; DataStruct arg1 = ctor.Data; ReturnData(new DataStruct(new ArrayList(arg0.StringValue.Split(new string[]{arg1.StringValue},StringSplitOptions.None)))); } } [CodeInterpreter(BlockType = "lists_join_text")] public class Lists_JoinText_Cmdtor : EnumeratorCmdtor { protected override IEnumerator Execute(Block block) { CmdEnumerator ctor = CSharp.Interpreter.ValueReturn(block, "INPUT", new DataStruct("")); yield return ctor; DataStruct arg0 = ctor.Data; ctor = CSharp.Interpreter.ValueReturn(block, "DELIM", new DataStruct("")); yield return ctor; DataStruct arg1 = ctor.Data; ReturnData(new DataStruct(string.Join(arg1.StringValue,(string[])arg0.ListValue.ToArray()))); } } #region ToolClass public static class ArrayListExtension { public static ArrayList ArraySort(this ArrayList list,Func<object,object,bool> compareFunc,bool reverse) { if (compareFunc != null) { list.Sort(new ArrayListCompare(compareFunc,reverse)); } return list; } public static bool HasString(this ArrayList list) { bool hasString = false; for (int i = 0; i < list.Count; i++) { DataStruct ds = (DataStruct) list[i]; if (ds.IsString) { hasString = true; } } return hasString; } public static bool HasList(this ArrayList list) { bool hasList = false; for (int i = 0; i < list.Count; i++) { DataStruct ds = (DataStruct) list[i]; if (ds.IsList) { hasList = true; } } return hasList; } public static ArrayList ConvertString(this ArrayList list) { bool hasString = false; int index = 0; for (int i = 0; i < list.Count; i++) { DataStruct ds = (DataStruct) list[i]; if (!hasString) { if (ds.IsString) { hasString = true; index = i; } } else { if (!ds.IsString) list[i] = new DataStruct(ds.ToString()); } } if (!hasString) { return list; } else { for (int i = 0; i < index; i++) { list[i] = new DataStruct(((DataStruct) list[i]).ToString()); } return list; } } public static ArrayList ConvertBoolean(this ArrayList list) { for (int i = 0; i < list.Count; i++) { DataStruct ds = (DataStruct) list[i]; if (ds.IsBoolean) { list[i] = new DataStruct(ds.BooleanValue ? new Number(1): new Number(0)); } } return list; } public static DataStruct Sum(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); StringBuilder sumStr = new StringBuilder(); for (int i = 0; i < list.Count; i++) { sumStr.Append(((DataStruct) list[i]).StringValue); } return new DataStruct(sumStr.ToString()); } list = list.ConvertBoolean(); Number sum = new Number(0); for (int i = 0; i < list.Count; i++) { sum += ((DataStruct) list[i]).NumberValue; } return new DataStruct(sum); } public static DataStruct Min(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); string minStr=String.Empty; for (int i = 0; i < list.Count; i++) { string tmp = ((DataStruct) list[i]).StringValue; if (string.Compare(minStr,tmp)>0) minStr = tmp; } return new DataStruct(minStr); } list = list.ConvertBoolean(); Number min = new Number(0); if (list.Count > 0) { min.Value = float.PositiveInfinity; for (int i = 0; i < list.Count; i++) { Number tmp=((DataStruct) list[i]).NumberValue; if (min > tmp) min = tmp; } } return new DataStruct(min); } public static DataStruct Max(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); string maxStr=String.Empty; for (int i = 0; i < list.Count; i++) { string tmp = ((DataStruct) list[i]).StringValue; if (string.Compare(maxStr,tmp)<0) maxStr = tmp; } return new DataStruct(maxStr); } list = list.ConvertBoolean(); Number max = new Number(0); if (list.Count > 0) { max.Value = float.NegativeInfinity; for (int i = 0; i < list.Count; i++) { Number tmp=((DataStruct) list[i]).NumberValue; if (max < tmp) max = tmp; } } return new DataStruct(max); } public static DataStruct Average(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); Number strAverage = new Number(list.Sum().StringValue.ToCharArray().SumCharArray()/list.Count); return new DataStruct(strAverage); } list = list.ConvertBoolean(); Number average = new Number(0); if (list.Count > 0) { average = list.Sum().NumberValue / new Number(list.Count); } return new DataStruct(average); } public static DataStruct Median(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); Number strMedian = new Number(0); char[] tmpCharArray = list.Sum().StringValue.ToCharArray(); Array.Sort(tmpCharArray); int length = tmpCharArray.Length; if (length > 0) { if (length % 2 == 0) strMedian = new Number(((int)tmpCharArray[length / 2] + (int)tmpCharArray[length / 2 + 1]) / 2); else strMedian = new Number((int)tmpCharArray[length / 2 + 1]); } return new DataStruct(strMedian); } list = list.ConvertBoolean(); Number median = new Number(0); int count = list.Count; if (count > 0) { list.Sort(); if (count % 2 == 0) median = (((DataStruct) list[count / 2]).NumberValue + ((DataStruct) list[count / 2+1]).NumberValue) / new Number(2); else median = ((DataStruct) list[count / 2+1]).NumberValue; } return new DataStruct(median); } public static DataStruct Mode(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); ArrayList resultStrList=new ArrayList(); Dictionary<string, int> strDict = new Dictionary<string, int>(); int length = list.Count; for (int i = 0; i < length; i++) { string tmp = ((DataStruct) list[i]).StringValue; if (strDict.ContainsKey(tmp)) { strDict[tmp]++; } else { strDict.Add(tmp, 1); } } int biggerCount = 0; foreach (int dictValue in strDict.Values) { if (biggerCount < dictValue) biggerCount = dictValue; } foreach (string s in strDict.Keys) { if (biggerCount == strDict[s]) resultStrList.Add(new DataStruct(s)); } return new DataStruct(resultStrList); } list = list.ConvertBoolean(); int count = list.Count; ArrayList resultNumList=new ArrayList(); if (count > 0) { Dictionary<Number, int> numDict = new Dictionary<Number, int>(); for (int i = 0; i < count; i++) { Number tmp = ((DataStruct) list[i]).NumberValue; if (numDict.ContainsKey(tmp)) { numDict[tmp]++; } else { numDict.Add(tmp, 1); } } int biggerCount = 0; foreach (int dictValue in numDict.Values) { if (biggerCount < dictValue) biggerCount = dictValue; } foreach (Number n in numDict.Keys) { if (biggerCount == numDict[n]) resultNumList.Add(new DataStruct(n)); } } return new DataStruct(resultNumList); } public static DataStruct StdDev(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { return new DataStruct(new Number(0)); } list = list.ConvertBoolean(); Number resultNum = new Number(0); int count = list.Count; if (count > 0) { float totalSquare = 0; float average = list.Average().NumberValue.Value; for (int i = 0; i < count; i++) { Number tmpNum = ((DataStruct) list[i]).NumberValue; float differ = tmpNum.Value - average; totalSquare += differ * differ; } resultNum=new Number(Math.Sqrt(totalSquare/count)); } return new DataStruct(resultNum); } public static DataStruct Random(this ArrayList list) { if (list.HasList()) { UnityEngine.Debug.LogError("There is not permit a list!"); return new DataStruct(-1); } if (list.HasString()) { list = list.ConvertString(); int length = list.Count; int index = new Random().Next(0, length-1); string resultStr = String.Empty; resultStr = ((DataStruct) list[index]).StringValue; return new DataStruct(resultStr); } list = list.ConvertBoolean(); Number resultNum = new Number(0); int count = list.Count; if (count > 0) { int index = new Random().Next(0, count-1); resultNum = ((DataStruct) list[index]).NumberValue; } return new DataStruct(resultNum); } } public static class CharArraytExtension { public static int SumCharArray(this char[] charArray) { int sum = 0; for (int i = 0; i < charArray.Length; i++) { sum += (int)charArray[i]; } return sum; } } public class ArrayListCompare : IComparer { private Func<object, object, bool> m_Func; private bool m_Reverse; public ArrayListCompare(Func<object,object,bool> f,bool reverse=false) { m_Func = f; m_Reverse = reverse; } public int Compare(object x, object y) { if (m_Func == null) return 0; if (m_Reverse) { if (m_Func(y, x)) return 1; else return 0; } else { if (m_Func(x, y)) return 1; else return 0; } } } #endregion }
34.219804
137
0.452875
[ "Apache-2.0" ]
imagicbell/ublockly
Source/Script/CodeDB/CSharp/Interpreters/List_CSharp.cs
31,450
C#
using UnityEngine; using UnityEngine.UIElements; public class DmxOutputBoolUI : DmxOutputUI<DmxOutputBool> { public DmxOutputBoolUI(DmxOutputBool dmxOutput) : base(dmxOutput) { } protected override void BuildControlUI() { base.BuildControlUI(); area = controlUI.Q("input-area"); var toggle = controlUI.Q("toggle-switch"); var trigger = controlUI.Q("trigger"); textField = controlUI.Q<TextField>(); toggle.RegisterCallback<PointerUpEvent>(evt => { var shift = evt.shiftKey; var val = !targetDmxOutput.Value; SetValue(val); if (shift) multiEditUIs.ForEach(ui => (ui as DmxOutputBoolUI).SetValue(val)); }); trigger.RegisterCallback<PointerDownEvent>(evt => { var shift = evt.shiftKey; trigger.CapturePointer(evt.pointerId); SetValue(true); if (shift) multiEditUIs.ForEach(ui => (ui as DmxOutputBoolUI).SetValue(true)); }); trigger.RegisterCallback<PointerUpEvent>(evt => { var shift = evt.shiftKey; trigger.ReleasePointer(evt.pointerId); SetValue(false); if (shift) multiEditUIs.ForEach(ui => (ui as DmxOutputBoolUI).SetValue(false)); }); textField.isDelayed = true; textField.SetEnabled(false); SetValue(targetDmxOutput.Value); } VisualElement area; TextField textField; void SetValue(bool val) { if (val) { area.RemoveFromClassList("switch-off"); area.AddToClassList("switch-on"); } else { area.RemoveFromClassList("switch-on"); area.AddToClassList("switch-off"); } targetDmxOutput.Value = val; textField.value = (val ? 255 : 0).ToString(); } }
29.19697
84
0.569798
[ "MIT" ]
sugi-cho/ArtNetController
Assets/ArtNetController/Scripts/UI/DmxOutputUI/DmxOutputBoolUI.cs
1,927
C#
// // ColorPickerBackend.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.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 AppKit; using Xwt.Backends; namespace Xwt.Mac { public class ColorPickerBackend: ViewBackend<NSColorWell,IColorPickerEventSink>, IColorPickerBackend { public override void Initialize () { ViewObject = new MacColorWell (EventSink, ApplicationContext); } public Xwt.Drawing.Color Color { get { return Widget.Color.ToXwtColor (); } set { Widget.Color = value.ToNSColor (); } } public bool SupportsAlpha { get; set; } public string Title { get; set; } public void SetButtonStyle (ButtonStyle style) { // The Borderless property can't be used because when set the NSColorPanel popup // is not shown when the picker is clicked. } public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { return new Size (35, 20); } } class MacColorWell: NSColorWell, IViewObject { IColorPickerEventSink eventSink; ApplicationContext context; public MacColorWell (IColorPickerEventSink eventSink, ApplicationContext context) { this.eventSink = eventSink; this.context = context; } static string defaultTitle; public override void Activate (bool exclusive) { NSColorPanel.SharedColorPanel.ShowsAlpha = ((ColorPickerBackend)Backend).SupportsAlpha; if (defaultTitle == null) defaultTitle = NSColorPanel.SharedColorPanel.Title; NSColorPanel.SharedColorPanel.Title = ((ColorPickerBackend)Backend).Title ?? defaultTitle; base.Activate (exclusive); } public bool SupportsAlpha { get; set; } public ViewBackend Backend { get; set; } public NSView View { get { return this; } } public override NSColor Color { get { return base.Color; } set { base.Color = value; if (context != null) context.InvokeUserCode (eventSink.OnColorChanged); } } } }
29.833333
105
0.733158
[ "MIT" ]
Bert1974/xwt
Xwt.XamMac/Xwt.Mac/ColorPickerBackend.cs
3,045
C#
using System; namespace HerosLib { /// <summary> /// Subscriber 2 /// </summary> public class TextMessageService { public static void SendText(){ Console.WriteLine("----------Text Sent-------"); } } }
19.461538
60
0.513834
[ "MIT" ]
201019-UiPath/ZhengHong-Code
1-CSharp/HerosApp/HerosLib/TextMessageService.cs
253
C#
namespace MyShop.Sales.Messages { using System; using NServiceBus; public class CancelOrder : ICommand { public Guid OrderId { get; set; } } }
15.727273
41
0.624277
[ "MIT" ]
vchircu/LongRunningProcesses
MyShop/MyShop.Sales.Messages/CancelOrder.cs
175
C#
using System; using System.Diagnostics; using Armature.Core.Annotations; using Armature.Core.Sdk; namespace Armature.Core; /// <summary> /// Couples an entity with a weight /// </summary> public readonly struct Weighted<T> : IComparable<Weighted<T>> { public readonly T Entity; public readonly int Weight; [DebuggerStepThrough] public Weighted(T entity, int weight) { Entity = entity; Weight = weight; } [WithoutTest] [DebuggerStepThrough] public int CompareTo(Weighted<T> other) => Weight.CompareTo(other.Weight); [DebuggerStepThrough] public override string ToString() => string.Format("{0}, Weight={1}", Entity.ToHoconString(), Weight.ToHoconString()); } public static class WeightedExtension { [DebuggerStepThrough] public static Weighted<T> WithWeight<T>(this T entity, int weight) => new(entity, weight); }
24.428571
120
0.726316
[ "Apache-2.0" ]
Ed-ward/Armature
src/Armature.Core/src/Weighted.cs
857
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace Clarity.Common.Infra.ActiveModel.ClassEmitting { public class AmListBindingDescription : AmBindingDescriptionBase { private Type ChildType { get; } public AmListBindingDescription(PropertyInfo property) : base(property) { Debug.Assert(property.PropertyType.IsGenericType, "property.PropertyType.IsGenericType"); Debug.Assert(property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>), "property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)"); ChildType = property.PropertyType.GetGenericArguments().Single(); } public override Type MakeBindingType(Type selfType) => typeof(AmListBinding<,>).MakeGenericType(selfType, ChildType); public override MethodInfo MakePropertyGetMethod(Type selfType) => MakeBindingType(selfType).GetMethod("get_" + nameof(IAmListBinding<object>.Items)); public override MethodInfo MakePropertySetMethod(Type selfType) { throw new InvalidOperationException("Trying to get a setter property method for a list binding."); } public override string BuildGetterString(string bindingRef) => $"return {bindingRef}.Items;"; public override string BuildSetterString(string bindingRef) => null; } }
45.0625
165
0.716366
[ "MIT" ]
Zulkir/ClarityWorlds
Source/Clarity.Common/Infra/ActiveModel/ClassEmitting/AmListBindingDescription.cs
1,444
C#
// // IFontBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Drawing; using System.Collections.Generic; namespace Xwt.Backends { public abstract class FontBackendHandler: BackendHandler { Font systemFont; Font systemMonospaceFont; Font systemSerifFont; Font systemSansSerifFont; internal Font SystemFont { get { if (systemFont == null) systemFont = new Font (GetSystemDefaultFont (), ApplicationContext.Toolkit); return systemFont; } } internal Font SystemMonospaceFont { get { if (systemMonospaceFont == null) { var f = GetSystemDefaultMonospaceFont (); if (f != null) systemMonospaceFont = new Font (f, ApplicationContext.Toolkit); else systemMonospaceFont = SystemFont.WithFamily ("Courier New, Courier, monospace"); } return systemMonospaceFont; } } internal Font SystemSerifFont { get { if (systemSerifFont == null) { var f = GetSystemDefaultSerifFont (); if (f != null) systemSerifFont = new Font (f, ApplicationContext.Toolkit); else systemSerifFont = SystemFont.WithFamily ("Times New Roman, Times, serif"); } return systemSerifFont; } } internal Font SystemSansSerifFont { get { if (systemSansSerifFont == null) { var f = GetSystemDefaultSansSerifFont (); if (f != null) systemSansSerifFont = new Font (f, ApplicationContext.Toolkit); else systemSansSerifFont = SystemFont.WithFamily ("Lucida Sans Unicode, Lucida Grande, Arial, Helvetica, sans-serif"); } return systemSansSerifFont; } } public abstract object GetSystemDefaultFont (); /// <summary> /// Gets the system default serif font, or null if there is no default for such font /// </summary> public virtual object GetSystemDefaultSerifFont () { return null; } /// <summary> /// Gets the system default sans-serif font, or null if there is no default for such font /// </summary> public virtual object GetSystemDefaultSansSerifFont () { return null; } /// <summary> /// Gets the system default monospace font, or null if there is no default for such font /// </summary> public virtual object GetSystemDefaultMonospaceFont () { return null; } public abstract IEnumerable<string> GetInstalledFonts (); /// <summary> /// Creates a new font. Returns null if the font family is not available in the system /// </summary> /// <param name="fontName">Font family name</param> /// <param name="size">Size in points</param> /// <param name="style">Style</param> /// <param name="weight">Weight</param> /// <param name="stretch">Stretch</param> public abstract object Create (string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch); public abstract object Copy (object handle); public abstract object SetSize (object handle, double size); public abstract object SetFamily (object handle, string family); public abstract object SetStyle (object handle, FontStyle style); public abstract object SetWeight (object handle, FontWeight weight); public abstract object SetStretch (object handle, FontStretch stretch); public abstract double GetSize (object handle); public abstract string GetFamily (object handle); public abstract FontStyle GetStyle (object handle); public abstract FontWeight GetWeight (object handle); public abstract FontStretch GetStretch (object handle); } }
32.549296
120
0.715707
[ "MIT" ]
DavidKarlas/xwt
Xwt/Xwt.Backends/FontBackendHandler.cs
4,622
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CarServiceProject { using System; using System.Collections.Generic; public partial class Auto { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Auto() { this.Comenzi = new HashSet<Comanda>(); } public int Id { get; private set; } public string NumarAuto { get; private set; } public string SerieSasiu { get; private set; } public int SasiuId { get; set; } public int ClientId { get; set; } public virtual Sasiu Sasiu { get; set; } public virtual Client Client { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Comanda> Comenzi { get; set; } } }
37.628571
128
0.577069
[ "Apache-2.0" ]
ioanabirsan/advanced-topics-net
project-2/CarServiceProject/CarServiceProject/Auto.cs
1,317
C#
using Aurora.Devices; using Aurora.Settings; using Aurora.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Aurora.Profiles.Dota_2.Layers { /// <summary> /// Interaction logic for Control_Dota2AbilityLayer.xaml /// </summary> public partial class Control_Dota2AbilityLayer : UserControl { private bool settingsset = false; public Control_Dota2AbilityLayer() { InitializeComponent(); } public Control_Dota2AbilityLayer(Dota2AbilityLayerHandler datacontext) { InitializeComponent(); this.DataContext = datacontext; } public void SetSettings() { if (this.DataContext is Dota2AbilityLayerHandler && !settingsset) { this.ColorPicker_CanCastAbility.SelectedColor = Utils.ColorUtils.DrawingColorToMediaColor((this.DataContext as Dota2AbilityLayerHandler).Properties._CanCastAbilityColor ?? System.Drawing.Color.Empty); this.ColorPicker_CanNotCastAbility.SelectedColor = Utils.ColorUtils.DrawingColorToMediaColor((this.DataContext as Dota2AbilityLayerHandler).Properties._CanNotCastAbilityColor ?? System.Drawing.Color.Empty); UIUtils.SetSingleKey(this.ability_key1_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 0); UIUtils.SetSingleKey(this.ability_key2_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 1); UIUtils.SetSingleKey(this.ability_key3_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 2); UIUtils.SetSingleKey(this.ability_key4_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 3); UIUtils.SetSingleKey(this.ability_key5_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 4); UIUtils.SetSingleKey(this.ability_key6_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 5); settingsset = true; } } internal void SetProfile(Application profile) { } private void UserControl_Loaded(object sender, RoutedEventArgs e) { SetSettings(); this.Loaded -= UserControl_Loaded; } private void abilities_canuse_colorpicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e) { if (IsLoaded && settingsset && this.DataContext is Dota2AbilityLayerHandler && sender is Xceed.Wpf.Toolkit.ColorPicker && (sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.HasValue) (this.DataContext as Dota2AbilityLayerHandler).Properties._CanCastAbilityColor = Utils.ColorUtils.MediaColorToDrawingColor((sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.Value); } private void abilities_cannotuse_colorpicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e) { if (IsLoaded && settingsset && this.DataContext is Dota2AbilityLayerHandler && sender is Xceed.Wpf.Toolkit.ColorPicker && (sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.HasValue) (this.DataContext as Dota2AbilityLayerHandler).Properties._CanNotCastAbilityColor = Utils.ColorUtils.MediaColorToDrawingColor((sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.Value); } private void ability_key1_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ability 1 Key", sender as TextBlock, ability1_keys_callback); } private void ability1_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability1_keys_callback; Dispatcher.Invoke(() => { ability_key1_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[0] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key1_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 0); } }); Global.key_recorder.Reset(); } private void ability_key2_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ability 2 Key", sender as TextBlock, ability2_keys_callback); } private void ability2_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability2_keys_callback; Dispatcher.Invoke(() => { ability_key2_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[1] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key2_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 1); } }); Global.key_recorder.Reset(); } private void ability_key3_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ability 3 Key", sender as TextBlock, ability3_keys_callback); } private void ability3_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability3_keys_callback; Dispatcher.Invoke(() => { ability_key3_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[2] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key3_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 2); } }); Global.key_recorder.Reset(); } private void ability_key4_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ability 4 Key", sender as TextBlock, ability4_keys_callback); } private void ability4_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability4_keys_callback; Dispatcher.Invoke(() => { ability_key4_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[3] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key4_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 3); } }); Global.key_recorder.Reset(); } private void ability_key5_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ability 5 Key", sender as TextBlock, ability5_keys_callback); } private void ability5_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability5_keys_callback; Dispatcher.Invoke(() => { ability_key5_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[4] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key5_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 4); } }); Global.key_recorder.Reset(); } private void ability_key6_textblock_MouseDown(object sender, MouseButtonEventArgs e) { RecordSingleKey("Dota 2 - Ultimate Ability Key", sender as TextBlock, ability6_keys_callback); } private void ability6_keys_callback(DeviceKeys[] resulting_keys) { Global.key_recorder.FinishedRecording -= ability6_keys_callback; Dispatcher.Invoke(() => { ability_key6_textblock.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); if (resulting_keys.Length > 0) { if (IsLoaded) (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys[5] = resulting_keys[0]; UIUtils.SetSingleKey(this.ability_key6_textblock, (this.DataContext as Dota2AbilityLayerHandler).Properties._AbilityKeys, 5); } }); Global.key_recorder.Reset(); } private void RecordSingleKey(string whoisrecording, TextBlock textblock, KeyRecorder.RecordingFinishedHandler callback) { if (Global.key_recorder.IsRecording()) { if (Global.key_recorder.GetRecordingType().Equals(whoisrecording)) { Global.key_recorder.StopRecording(); Global.key_recorder.Reset(); } else { MessageBox.Show("You are already recording a key sequence for " + Global.key_recorder.GetRecordingType()); } } else { Global.key_recorder.FinishedRecording += callback; Global.key_recorder.StartRecording(whoisrecording, true); textblock.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)); } } } }
43.537255
223
0.613853
[ "MIT" ]
ADoesGit/Aurora
Project-Aurora/Project-Aurora/Profiles/Dota 2/Layers/Control_Dota2AbilityLayer.xaml.cs
10,850
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace MultasTransito.Areas.Identity.Pages.Account { [AllowAnonymous] public class ResetPasswordModel : PageModel { private readonly UserManager<IdentityUser> _userManager; public ResetPasswordModel(UserManager<IdentityUser> userManager) { _userManager = userManager; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public IActionResult OnGet(string code = null) { if (code == null) { return BadRequest("A code must be supplied for password reset."); } else { Input = new InputModel { Code = code }; return Page(); } } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToPage("./ResetPasswordConfirmation"); } var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return RedirectToPage("./ResetPasswordConfirmation"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } }
29.719101
129
0.555388
[ "Apache-2.0" ]
johnsvill/MultasBot
Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
2,647
C#
 namespace AuthorizationGenerator { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBoxMac = new System.Windows.Forms.TextBox(); this.buttonEn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Anchor = System.Windows.Forms.AnchorStyles.None; this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.label1.Location = new System.Drawing.Point(78, 124); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(139, 41); this.label1.TabIndex = 0; this.label1.Text = "CODE:"; // // textBoxMac // this.textBoxMac.Anchor = System.Windows.Forms.AnchorStyles.None; this.textBoxMac.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.textBoxMac.Location = new System.Drawing.Point(241, 121); this.textBoxMac.Name = "textBoxMac"; this.textBoxMac.Size = new System.Drawing.Size(482, 48); this.textBoxMac.TabIndex = 3; // // buttonEn // this.buttonEn.Anchor = System.Windows.Forms.AnchorStyles.None; this.buttonEn.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.buttonEn.Location = new System.Drawing.Point(293, 229); this.buttonEn.Name = "buttonEn"; this.buttonEn.Size = new System.Drawing.Size(196, 96); this.buttonEn.TabIndex = 6; this.buttonEn.Text = "生成"; this.buttonEn.UseVisualStyleBackColor = true; this.buttonEn.Click += new System.EventHandler(this.buttonEn_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(14F, 31F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 528); this.Controls.Add(this.buttonEn); this.Controls.Add(this.textBoxMac); this.Controls.Add(this.label1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Gen"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBoxMac; private System.Windows.Forms.Button buttonEn; } }
40.602151
155
0.585011
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
nmgzzy/HotelSystem
AuthorizationGenerator/Form1.Designer.cs
3,784
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Incidents. /// </summary> public static partial class IncidentsExtensions { /// <summary> /// Get entities from incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static GetOKResponseModelModelModelModelModelModelModelModelModelModelModelModelModelModelModel Get(this IIncidents operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entities from incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GetOKResponseModelModelModelModelModelModelModelModelModelModelModelModelModelModelModel> GetAsync(this IIncidents operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add new entity to incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMincident Create(this IIncidents operations, MicrosoftDynamicsCRMincident body, string prefer = "return=representation") { return operations.CreateAsync(body, prefer).GetAwaiter().GetResult(); } /// <summary> /// Add new entity to incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMincident> CreateAsync(this IIncidents operations, MicrosoftDynamicsCRMincident body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get entity from incidents by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMincident GetByKey(this IIncidents operations, string incidentid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetByKeyAsync(incidentid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entity from incidents by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMincident> GetByKeyAsync(this IIncidents operations, string incidentid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByKeyWithHttpMessagesAsync(incidentid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete entity from incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='ifMatch'> /// ETag /// </param> public static void Delete(this IIncidents operations, string incidentid, string ifMatch = default(string)) { operations.DeleteAsync(incidentid, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Delete entity from incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='ifMatch'> /// ETag /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIncidents operations, string incidentid, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(incidentid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Update entity in incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IIncidents operations, string incidentid, MicrosoftDynamicsCRMincident body) { operations.UpdateAsync(incidentid, body).GetAwaiter().GetResult(); } /// <summary> /// Update entity in incidents /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='incidentid'> /// key: incidentid /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IIncidents operations, string incidentid, MicrosoftDynamicsCRMincident body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(incidentid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
43.416
520
0.532338
[ "Apache-2.0" ]
devinleighsmith/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/IncidentsExtensions.cs
10,854
C#
using System; using System.Collections.Generic; using System.Globalization; using CG.Commons.Extensions; using CG.Commons.Util; using Xunit; namespace CG.Commons.Test.Util { public class GenericParserTests { [Fact] public void TestCanary() { Assert.True(true); } #region Test Data Emitters public static IEnumerable<object[]> CreateBooleanCases() { yield return new object[] {"true", true}; yield return new object[] {"false", false}; yield return new object[] {"True", true}; yield return new object[] {"False", false}; } public static IEnumerable<object[]> CreateIntegerCases() { yield return new object[] { "1", 1 }; yield return new object[] { "2", 2 }; yield return new object[] { "2147483647", 2147483647 }; yield return new object[] { "0", 0 }; yield return new object[] { "-1", -1 }; yield return new object[] { "-2", -2 }; yield return new object[] { "-2147483648", -2147483648 }; } public static IEnumerable<object[]> CreateLongCases() { yield return new object[] { "1", 1L }; yield return new object[] { "2", 2L }; yield return new object[] { "9223372036854775807", 9223372036854775807L }; yield return new object[] { "0", 0L }; yield return new object[] { "-1", -1L }; yield return new object[] { "-2", -2L }; yield return new object[] { "-9223372036854775808", -9223372036854775808L }; } public static IEnumerable<object[]> CreateDoubleCases() { yield return new object[] { "1.123", 1.123D }; yield return new object[] { "2.321", 2.321D }; yield return new object[] { "1.7976931348623157E+308", 1.7976931348623157E+308D }; yield return new object[] { "0.0", 0.0D }; yield return new object[] { "-1.123", -1.123D }; yield return new object[] { "-2.321", -2.321D }; yield return new object[] { "-1.7976931348623157E+308", -1.7976931348623157E+308D }; } public static IEnumerable<object[]> CreateDecimalCases() { yield return new object[] { "1.123", 1.123M }; yield return new object[] { "2.321", 2.321M }; yield return new object[] { "79228162514264337593543950335", 79228162514264337593543950335M }; yield return new object[] { "0.0", 0.0M }; yield return new object[] { "-1.123", -1.123M }; yield return new object[] { "-2.321", -2.321M }; yield return new object[] { "-79228162514264337593543950335", -79228162514264337593543950335M }; } public static IEnumerable<object[]> CreateFloatCases() { yield return new object[] { "1.123", 1.123F }; yield return new object[] { "2.321", 2.321F }; yield return new object[] { "3.40282347E+38", 3.40282347E+38F }; yield return new object[] { "0", 0F }; yield return new object[] { "-1.123", -1.123F }; yield return new object[] { "-2.321", -2.321F }; yield return new object[] { "-3.40282347E+38", -3.40282347E+38F }; } public static IEnumerable<object[]> CreateShortCases() { yield return new object[] { "1", (short)1 }; yield return new object[] { "2", (short)2 }; yield return new object[] { "32767", (short)32767 }; yield return new object[] { "0", (short)0 }; yield return new object[] { "-1", (short)-1 }; yield return new object[] { "-2", (short)-2 }; yield return new object[] { "-32768", (short)-32768 }; } public static IEnumerable<object[]> CreateByteCases() { yield return new object[] { "1", (byte)1 }; yield return new object[] { "2", (byte)2 }; yield return new object[] { "255", (byte)255 }; yield return new object[] { "0", (byte)0 }; } public static IEnumerable<object[]> CreateSignedByteCases() { yield return new object[] { "1", (sbyte)1 }; yield return new object[] { "2", (sbyte)2 }; yield return new object[] { "127", (sbyte)127 }; yield return new object[] { "0", (sbyte)0 }; yield return new object[] { "-1", (sbyte)-1 }; yield return new object[] { "-2", (sbyte)-2 }; yield return new object[] { "-128", (sbyte)-128 }; } public static IEnumerable<object[]> CreateUnsignedIntCases() { yield return new object[] { "1", 1U }; yield return new object[] { "2", 2U }; yield return new object[] { "4294967295", 4294967295U }; yield return new object[] { "0", 0U }; } public static IEnumerable<object[]> CreateUnsignedLongCases() { yield return new object[] { "1", 1UL }; yield return new object[] { "2", 2UL }; yield return new object[] { "18446744073709551615", 18446744073709551615UL }; yield return new object[] { "0", 0UL }; } public static IEnumerable<object[]> CreateUnsignedShortCases() { yield return new object[] { "1", (ushort)1U }; yield return new object[] { "2", (ushort)2U }; yield return new object[] { "65535", (ushort)65535U }; yield return new object[] { "0", (ushort)0U }; } public static IEnumerable<object[]> CreateCharacterCases() { yield return new object[] { "1", '1' }; yield return new object[] { " ", ' ' }; yield return new object[] { "a", 'a' }; yield return new object[] { "B", 'B' }; } public static IEnumerable<object[]> CreateDateTimeCases() { yield return new object[] { DateTime.MinValue.ToString(CultureInfo.InvariantCulture), DateTime.MinValue }; yield return new object[] { DateTime.MaxValue.ToString(CultureInfo.InvariantCulture), DateTime.MaxValue.TruncateMilliseconds() }; var now = DateTime.UtcNow; yield return new object[] { now.ToString(CultureInfo.InvariantCulture), now.TruncateMilliseconds() }; } public static IEnumerable<object[]> CreateDateTimeOffsetCases() { yield return new object[] { DateTimeOffset.MinValue.ToString(CultureInfo.InvariantCulture), DateTimeOffset.MinValue }; yield return new object[] { DateTimeOffset.MaxValue.ToString(CultureInfo.InvariantCulture), DateTimeOffset.MaxValue.TruncateMilliseconds() }; var now = DateTimeOffset.UtcNow; yield return new object[] { now.ToString(CultureInfo.InvariantCulture), now.TruncateMilliseconds() }; } public static IEnumerable<object[]> CreateTimespanCases() { yield return new object[] { TimeSpan.MinValue.ToString(), TimeSpan.MinValue }; yield return new object[] { TimeSpan.MaxValue.ToString(), TimeSpan.MaxValue }; var endOfAllThings = DateTime.MaxValue - DateTime.UtcNow; yield return new object[] { endOfAllThings.ToString(), endOfAllThings }; } public static IEnumerable<object[]> CreateGuidCases() { for (var i = 0; i < 10; i++) { var guid = Guid.NewGuid(); yield return i.IsEven() ? new object[] {guid.ToString().ToUpper(), guid} : new object[] {guid.ToString().ToLower(), guid}; } } public static IEnumerable<object[]> CreateNullableCases() { yield return new object[] { null, null }; yield return new object[] { "", null }; yield return new object[] { " ", null }; } #endregion #region Test Methods private class MockClass { } [Fact] public void TestParse_Unknown() { Assert.Throws<ArgumentException>(() => { GenericParser.Parse<MockClass>("foo"); }); Assert.Throws<ArgumentException>(() => { GenericParser.Parse("foo", typeof(MockClass)); }); } [Fact] public void Test_TryParseFail() { var res1 = GenericParser.TryParse("foo", out int _); Assert.False(res1); var res2 = GenericParser.TryParse("bar", out object _, typeof(int)); Assert.False(res2); } [Fact] public void Test_RegisterParser() { GenericParser.RegisterParser(typeof(object), s => s); var res1 = GenericParser.TryParse("foo", out object o1); Assert.True(res1); Assert.Equal("foo", o1.ToString()); var res2 = GenericParser.TryParse("bar", out object o2, typeof(object)); Assert.True(res2); Assert.Equal("bar", o2.ToString()); } [Theory] [InlineData("", "")] [InlineData("test", "test")] public void TestParse_string(string stringValue, string expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateBooleanCases))] public void TestParse_bool(string stringValue, bool expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateIntegerCases))] public void TestParse_int(string stringValue, int expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateLongCases))] public void TestParse_long(string stringValue, long expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDoubleCases))] public void TestParse_double(string stringValue, double expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateFloatCases))] public void TestParse_float(string stringValue, float expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDecimalCases))] public void TestParse_decimal(string stringValue, decimal expectedValue) { //Decimals while a basic type are not a primitive type and hence cannot be represented in metadata which prevents it from being an attribute parameter. TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateShortCases))] public void TestParse_short(string stringValue, short expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateByteCases))] public void TestParse_byte(string stringValue, byte expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateSignedByteCases))] public void TestParse_sbyte(string stringValue, sbyte expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedIntCases))] public void TestParse_uint(string stringValue, uint expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedLongCases))] public void TestParse_ulong(string stringValue, ulong expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedShortCases))] public void TestParse_ushort(string stringValue, ushort expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateCharacterCases))] public void TestParse_char(string stringValue, char expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateBooleanCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullablebool(string stringValue, bool? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateIntegerCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullableint(string stringValue, int? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateLongCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullablelong(string stringValue, long? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDoubleCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullabledouble(string stringValue, double? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateFloatCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullablefloat(string stringValue, float? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDecimalCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullabledecimal(string stringValue, decimal? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateShortCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullableshort(string stringValue, short? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateByteCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullablebyte(string stringValue, byte? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateSignedByteCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullablesbyte(string stringValue, sbyte? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedIntCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullableuint(string stringValue, uint? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedLongCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullableulong(string stringValue, ulong? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateUnsignedShortCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_Nullableushort(string stringValue, ushort? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateCharacterCases))] [InlineData(null, null)] [InlineData("", null)] public void TestParse_Nullablechar(string stringValue, char? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDateTimeCases))] public void TestParse_DateTime(string stringValue, DateTime expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDateTimeOffsetCases))] public void TestParse_DateTimeOffset(string stringValue, DateTimeOffset expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateTimespanCases))] public void TestParse_TimeSpan(string stringValue, TimeSpan expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateGuidCases))] public void TestParse_Guid(string stringValue, Guid expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDateTimeCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_NullableDateTime(string stringValue, DateTime? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateDateTimeOffsetCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_NullableDateTimeOffset(string stringValue, DateTimeOffset? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateTimespanCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_NullableTimeSpan(string stringValue, TimeSpan? expectedValue) { TestParse(stringValue, expectedValue); } [Theory] [MemberData(nameof(CreateGuidCases))] [MemberData(nameof(CreateNullableCases))] public void TestParse_NullableGuid(string stringValue, Guid? expectedValue) { TestParse(stringValue, expectedValue); } #endregion #region Utility Methods private static void TestParse<T>(string stringValue, T expectedValue) { var result1 = GenericParser.Parse<T>(stringValue); Assert.Equal(expectedValue, result1); var result2 = GenericParser.Parse(stringValue, typeof(T)); Assert.Equal(expectedValue, result2); var result3 = GenericParser.TryParse(stringValue, out T out1); Assert.True(result3); Assert.Equal(expectedValue, out1); var result4 = GenericParser.TryParse(stringValue, out object out2, typeof(T)); Assert.True(result4); Assert.Equal(expectedValue, out2); var result5 = stringValue.Parse<T>(); Assert.Equal(expectedValue, result5); var result6 = stringValue.Parse(typeof(T)); Assert.Equal(expectedValue, result6); } #endregion } }
36.034286
163
0.590126
[ "MIT" ]
chrisg32/Commons
Commons.Test/Util/GenericParserTests.cs
18,920
C#
using System.Collections.Generic; using NUnit.Framework; namespace Cnp.Sdk.Test.Functional { [TestFixture] internal class TestFastAccessFunding { private CnpOnline _cnp; [OneTimeSetUp] public void SetUpCnp() { _cnp = new CnpOnline(); } [Test] public void TestFastAccessFunding_token() { fastAccessFunding fastAccessFunding = new fastAccessFunding(); fastAccessFunding.id = "A123456"; fastAccessFunding.reportGroup = "FastPayment"; fastAccessFunding.fundingSubmerchantId = "SomeSubMerchant"; fastAccessFunding.submerchantName = "Some Merchant Inc."; fastAccessFunding.fundsTransferId = "123e4567e89b12d3"; fastAccessFunding.amount = 3000; fastAccessFunding.token = new cardTokenType { cnpToken = "1111000101039449", expDate = "1112", cardValidationNum = "987", type = methodOfPaymentTypeEnum.VI, }; var response = _cnp.FastAccessFunding(fastAccessFunding); Assert.AreEqual("000", response.response); Assert.AreEqual("sandbox", response.location); StringAssert.AreEqualIgnoringCase("Approved", response.message); } [Test] public void TestFastAccessFunding_tokenWithCardHolderAddress() { fastAccessFunding fastAccessFunding = new fastAccessFunding(); fastAccessFunding.id = "A123456"; fastAccessFunding.reportGroup = "FastPayment"; fastAccessFunding.fundingSubmerchantId = "SomeSubMerchant"; fastAccessFunding.submerchantName = "Some Merchant Inc."; fastAccessFunding.fundsTransferId = "123e4567e89b12d3"; fastAccessFunding.amount = 3000; fastAccessFunding.token = new cardTokenType { cnpToken = "1111000101039449", expDate = "1112", cardValidationNum = "987", type = methodOfPaymentTypeEnum.VI, }; addressType cardHolderAddressType = new addressType(); cardHolderAddressType.addressLine1 = "37 Main Street"; cardHolderAddressType.addressLine2 = ""; cardHolderAddressType.addressLine3 = ""; cardHolderAddressType.city = "Augusta"; cardHolderAddressType.state = "Wisconsin"; cardHolderAddressType.zip = "28209"; cardHolderAddressType.country = countryTypeEnum.USA; fastAccessFunding.cardholderAddress = cardHolderAddressType; var response = _cnp.FastAccessFunding(fastAccessFunding); Assert.AreEqual("000", response.response); Assert.AreEqual("sandbox", response.location); StringAssert.AreEqualIgnoringCase("Approved", response.message); } [Test] [Ignore("Sandbox does not check for mismatch. Production does check.")] public void TestFastAccessFunding_mixedNames() { fastAccessFunding fastAccessFunding = new fastAccessFunding(); fastAccessFunding.id = "A123456"; fastAccessFunding.reportGroup = "FastPayment"; fastAccessFunding.fundingSubmerchantId = "SomeSubMerchant"; fastAccessFunding.customerName = "Some Customer"; fastAccessFunding.fundsTransferId = "123e4567e89b12d3"; fastAccessFunding.amount = 3000; fastAccessFunding.token = new cardTokenType { cnpToken = "1111000101039449", expDate = "1112", cardValidationNum = "987", type = methodOfPaymentTypeEnum.VI, }; Assert.Throws<CnpOnlineException>(() => { _cnp.FastAccessFunding(fastAccessFunding); }); } } }
39.63
100
0.605854
[ "MIT" ]
Vantiv/cnp_sdk-for-dotnet
CnpSdkForNet/CnpSdkForNetTest/Functional/TestFastAccessFunding.cs
3,965
C#
using System.Collections.Generic; using Cafe.Waiter.Commands; using Cafe.Waiter.Contracts.Commands; using Cafe.Waiter.Events; using NUnit.Framework; namespace Cafe.Waiter.Domain.Tests { [TestFixture] public class PlaceOrderTests : EventTestsBase<Tab, PlaceOrderCommand> { private readonly int _tableNumber = 123; private readonly string _waiter = "John Smith"; private const decimal FoodPrice = 12m; private const int FoodMenuNumber = 101; private const string FoodDescription = "Tikka Masala"; private const decimal DrinkPrice = 2m; private const int DrinkMenuNumber = 13; private const string DrinkDescription = "Coca Cola"; [Test] public void CanOrderFoodWhenTabHasAlreadyBeenOpened() { var foodOrderedItem = GetFoodOrderedItem(); var orderedItems = new List<OrderedItem> { foodOrderedItem }; Given(new TabOpened { AggregateId = AggregateId, TableNumber = _tableNumber, Waiter = _waiter }); When(new PlaceOrderCommand { Id = CommandId, AggregateId = AggregateId, Items = orderedItems }); Then(new FoodOrdered { AggregateId = AggregateId, CommandId = CommandId, Items = orderedItems }); } [Test] public void CanOrderDrinksWhenTabHasAlreadyBeenOpened() { var drinksOrderedItem = GetDrinkOrderedItem(); var orderedItems = new List<OrderedItem> { drinksOrderedItem }; Given(new TabOpened { AggregateId = AggregateId, TableNumber = _tableNumber, Waiter = _waiter }); When(new PlaceOrderCommand { Id = CommandId, AggregateId = AggregateId, Items = orderedItems } ); Then(new DrinksOrdered { AggregateId = AggregateId, CommandId = CommandId, Items = orderedItems }); } [Test] public void CanOrderFoodAndDrinksWhenTabHasAlreadyBeenOpened() { var foodOrderedItem = GetFoodOrderedItem(); var drinksOrderedItem = GetDrinkOrderedItem(); var orderedItems = new List<OrderedItem> { foodOrderedItem, drinksOrderedItem }; Given(new TabOpened { AggregateId = AggregateId, TableNumber = _tableNumber, Waiter = _waiter }); When(new PlaceOrderCommand { Id = CommandId, AggregateId = AggregateId, Items = orderedItems } ); Then( new DrinksOrdered { AggregateId = AggregateId, CommandId = CommandId, Items = new List<OrderedItem> { drinksOrderedItem } }, new FoodOrdered { AggregateId = AggregateId, CommandId = CommandId, Items = new List<OrderedItem> { foodOrderedItem } } ); } private OrderedItem GetFoodOrderedItem() { return new OrderedItem { Description = FoodDescription, IsDrink = false, MenuNumber = FoodMenuNumber, Price = FoodPrice }; } private OrderedItem GetDrinkOrderedItem() { return new OrderedItem { Description = DrinkDescription, IsDrink = true, MenuNumber = DrinkMenuNumber, Price = DrinkPrice }; } } }
29.528986
92
0.502577
[ "MIT" ]
ronanmoriarty/CQSplit
src/Cafe/Cafe.Waiter.Domain.Tests/PlaceOrderTests.cs
4,077
C#
using System.Collections.Generic; using System.Linq; using X4_ComplexCalculator.DB.X4DB.Interfaces; namespace X4_ComplexCalculator.DB.X4DB.Entity { /// <summary> /// ウェア単位のウェア生産時の追加効果情報用クラス /// </summary> public class WareEffects : IWareEffects { #region メンバ /// <summary> /// ウェア生産時の追加効果情報一覧 /// </summary> private readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, IWareEffect>> _Effects; #endregion /// <summary> /// コンストラクタ /// </summary> /// <param name="effects">ウェア単位の追加効果情報一覧</param> public WareEffects(IEnumerable<IWareEffect> effects) { _Effects = effects .GroupBy(x => x.Method) .ToDictionary( x => x.Key, x => x.ToDictionary(y => y.EffectID) as IReadOnlyDictionary<string, IWareEffect> ); } /// <inheritdoc/> public IReadOnlyDictionary<string, IWareEffect>? TryGet(string method) { // 生産方式で絞り込み if (!_Effects.TryGetValue(method, out var effects)) { // デフォルトの生産方式で取得 if (!_Effects.TryGetValue("default", out effects)) { // 生産方式取得失敗 return null; } } return effects; } /// <inheritdoc/> public IWareEffect? TryGet(string method, string effectID) { var effects = TryGet(method); if (effects is not null) { return effects.TryGetValue(effectID, out var effect) ? effect : null; } return null; } } }
26.681818
104
0.512777
[ "Apache-2.0" ]
Ocelot1210/X4_ComplexCalculator
X4_ComplexCalculator/DB/X4DB/Entity/WareEffects.cs
1,947
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Xml; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters.Xml { #pragma warning disable CS0618 // Type or member is obsolete public class ValidationProblemDetails21WrapperTest { [Fact] public void ReadXml_ReadsValidationProblemDetailsXml() { // Arrange var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ValidationProblemDetails>" + "<Title>Some title</Title>" + "<Status>400</Status>" + "<Instance>Some instance</Instance>" + "<key1>Test Value 1</key1>" + "<_x005B_key2_x005D_>Test Value 2</_x005B_key2_x005D_>" + "<MVC-Errors>" + "<error1>Test error 1 Test error 2</error1>" + "<_x005B_error2_x005D_>Test error 3</_x005B_error2_x005D_>" + "<MVC-Empty>Test error 4</MVC-Empty>" + "</MVC-Errors>" + "</ValidationProblemDetails>"; var serializer = new DataContractSerializer(typeof(ValidationProblemDetails21Wrapper)); // Act var value = serializer.ReadObject( new MemoryStream(Encoding.UTF8.GetBytes(xml))); // Assert var problemDetails = Assert.IsType<ValidationProblemDetails21Wrapper>(value).ProblemDetails; Assert.Equal("Some title", problemDetails.Title); Assert.Equal("Some instance", problemDetails.Instance); Assert.Equal(400, problemDetails.Status); Assert.Collection( problemDetails.Extensions.OrderBy(kvp => kvp.Key), kvp => { Assert.Equal("[key2]", kvp.Key); Assert.Equal("Test Value 2", kvp.Value); }, kvp => { Assert.Equal("key1", kvp.Key); Assert.Equal("Test Value 1", kvp.Value); }); Assert.Collection( problemDetails.Errors.OrderBy(kvp => kvp.Key), kvp => { Assert.Empty(kvp.Key); Assert.Equal(new[] { "Test error 4" }, kvp.Value); }, kvp => { Assert.Equal("[error2]", kvp.Key); Assert.Equal(new[] { "Test error 3" }, kvp.Value); }, kvp => { Assert.Equal("error1", kvp.Key); Assert.Equal(new[] { "Test error 1 Test error 2" }, kvp.Value); }); } [Fact] public void ReadXml_ReadsValidationProblemDetailsXml_WithNoErrors() { // Arrange var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ValidationProblemDetails>" + "<Title>Some title</Title>" + "<Status>400</Status>" + "<Instance>Some instance</Instance>" + "<key1>Test Value 1</key1>" + "<_x005B_key2_x005D_>Test Value 2</_x005B_key2_x005D_>" + "</ValidationProblemDetails>"; var serializer = new DataContractSerializer(typeof(ValidationProblemDetails21Wrapper)); // Act var value = serializer.ReadObject( new MemoryStream(Encoding.UTF8.GetBytes(xml))); // Assert var problemDetails = Assert.IsType<ValidationProblemDetails21Wrapper>(value).ProblemDetails; Assert.Equal("Some title", problemDetails.Title); Assert.Equal("Some instance", problemDetails.Instance); Assert.Equal(400, problemDetails.Status); Assert.Collection( problemDetails.Extensions, kvp => { Assert.Equal("key1", kvp.Key); Assert.Equal("Test Value 1", kvp.Value); }, kvp => { Assert.Equal("[key2]", kvp.Key); Assert.Equal("Test Value 2", kvp.Value); }); Assert.Empty(problemDetails.Errors); } [Fact] public void ReadXml_ReadsValidationProblemDetailsXml_WithEmptyErrorsElement() { // Arrange var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ValidationProblemDetails>" + "<Title>Some title</Title>" + "<Status>400</Status>" + "<MVC-Errors />" + "</ValidationProblemDetails>"; var serializer = new DataContractSerializer(typeof(ValidationProblemDetails21Wrapper)); // Act var value = serializer.ReadObject( new MemoryStream(Encoding.UTF8.GetBytes(xml))); // Assert var problemDetails = Assert.IsType<ValidationProblemDetails21Wrapper>(value).ProblemDetails; Assert.Equal("Some title", problemDetails.Title); Assert.Equal(400, problemDetails.Status); Assert.Empty(problemDetails.Errors); } [Fact] public void WriteXml_WritesValidXml() { // Arrange var problemDetails = new ValidationProblemDetails { Title = "Some title", Detail = "Some detail", Extensions = { ["key1"] = "Test Value 1", ["[Key2]"] = "Test Value 2" }, Errors = { { "error1", new[] {"Test error 1", "Test error 2" } }, { "[error2]", new[] {"Test error 3" } }, { "", new[] { "Test error 4" } }, } }; var wrapper = new ValidationProblemDetails21Wrapper(problemDetails); var outputStream = new MemoryStream(); var expectedContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ValidationProblemDetails>" + "<Detail>Some detail</Detail>" + "<Title>Some title</Title>" + "<key1>Test Value 1</key1>" + "<_x005B_Key2_x005D_>Test Value 2</_x005B_Key2_x005D_>" + "<MVC-Errors>" + "<error1>Test error 1 Test error 2</error1>" + "<_x005B_error2_x005D_>Test error 3</_x005B_error2_x005D_>" + "<MVC-Empty>Test error 4</MVC-Empty>" + "</MVC-Errors>" + "</ValidationProblemDetails>"; // Act using (var xmlWriter = XmlWriter.Create(outputStream)) { var dataContractSerializer = new DataContractSerializer(wrapper.GetType()); dataContractSerializer.WriteObject(xmlWriter, wrapper); } outputStream.Position = 0; var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd(); // Assert Assert.Equal(expectedContent, res); } [Fact] public void WriteXml_WithNoValidationErrors() { // Arrange var problemDetails = new ValidationProblemDetails { Title = "Some title", Detail = "Some detail", Extensions = { ["key1"] = "Test Value 1", ["[Key2]"] = "Test Value 2" }, }; var wrapper = new ValidationProblemDetails21Wrapper(problemDetails); var outputStream = new MemoryStream(); var expectedContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ValidationProblemDetails>" + "<Detail>Some detail</Detail>" + "<Title>Some title</Title>" + "<key1>Test Value 1</key1>" + "<_x005B_Key2_x005D_>Test Value 2</_x005B_Key2_x005D_>" + "</ValidationProblemDetails>"; // Act using (var xmlWriter = XmlWriter.Create(outputStream)) { var dataContractSerializer = new DataContractSerializer(wrapper.GetType()); dataContractSerializer.WriteObject(xmlWriter, wrapper); } outputStream.Position = 0; var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd(); // Assert Assert.Equal(expectedContent, res); } } #pragma warning restore CS0618 // Type or member is obsolete }
38.842795
111
0.508038
[ "Apache-2.0" ]
0xced/AspNetCore
src/Mvc/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/ValidationProblemDetails21WrapperTest.cs
8,897
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.450) // Version 5.450.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Manage the items that can be added to the top level of a ribbon group instance. /// </summary> public class KryptonRibbonGroupContainerCollection : TypedRestrictCollection<KryptonRibbonGroupContainer> { #region Static Fields private static readonly Type[] _types = { typeof(KryptonRibbonGroupLines), typeof(KryptonRibbonGroupTriple), typeof(KryptonRibbonGroupSeparator), typeof(KryptonRibbonGroupGallery)}; #endregion #region Restrict /// <summary> /// Gets an array of types that the collection is restricted to contain. /// </summary> public override Type[] RestrictTypes => _types; #endregion } }
46.289474
157
0.58158
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-NET-5.450
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Group Contents/KryptonRibbonGroupContainerCollection.cs
1,762
C#
// ----------------------------------------------------------------------- // <copyright file="SeekQuery.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.Models.Query { /// <summary> /// Represents a seek query. The seek query can be used to seek through sets of results using the given seek operation. /// </summary> internal class SeekQuery : IndexedQuery { /// <summary> /// Gets the query type. /// </summary> public override QueryType Type => QueryType.Seek; /// <summary> /// Gets or sets the seek operation. /// </summary> public override SeekOperation SeekOperation { get; set; } } }
35.583333
123
0.515222
[ "MIT" ]
vijayraavi/Partner-Center-PowerShell
src/PartnerCenter/Models/Query/SeekQuery.cs
856
C#
namespace dw_service.Areas.HelpPage.ModelDescriptions { public class SimpleTypeModelDescription : ModelDescription { } }
22
62
0.772727
[ "MIT" ]
dataventure-io/dw
src/dw-service/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs
132
C#
namespace SqlStreamStore { using System; using System.Collections.Generic; using System.Threading.Tasks; using Shouldly; using SqlStreamStore.Streams; using Xunit; public partial class AcceptanceTests { [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_different_message_then_should_throw() { const string streamId = "stream-1"; await Store.AppendToStream( streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var exception = await Record.ExceptionAsync(() => Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(2, 3, 4))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, ExpectedVersion.NoStream)); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_same_messages_then_should_then_should_be_idempotent() { // Idempotency const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var exception = await Record.ExceptionAsync(() => Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2))); exception.ShouldBeNull(); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_same_messages_then_should_then_should_have_expected_result() { // Idempotency const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); result2.CurrentVersion.ShouldBe(1); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_additional_messages_then_should_throw() { // Idempotency const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, ExpectedVersion.NoStream)); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_same_inital_message_then_should_be_idempotent() { // Idempotency const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1))); exception.ShouldBeNull(); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_same_inital_message_then_should_have_expected_result() { // Idempotency const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var result2 = await Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1)); result2.CurrentVersion.ShouldBe(1); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_no_stream_expected_and_different_inital_messages_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(2))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, ExpectedVersion.NoStream)); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_with_wrong_expected_version_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 1, CreateNewStreamMessages(4, 5, 6))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, 1)); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_multiple_messages_to_stream_with_correct_expected_version() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result2 = await Store.AppendToStream(streamId, result1.CurrentVersion, CreateNewStreamMessages(4, 5, 6)); result2.CurrentVersion.ShouldBe(5); result2.CurrentPosition.ShouldBeGreaterThan(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_single_message_to_stream_with_correct_expected_version() { const string streamId = "stream-1"; var result1 = await Store.AppendToStream( streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result2 = await Store.AppendToStream( streamId, result1.CurrentVersion, CreateNewStreamMessages(4)[0]); result2.CurrentVersion.ShouldBe(3); result2.CurrentPosition.ShouldBeGreaterThan(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_correct_expected_version_second_time_with_same_messages_then_should_not_throw() { const string streamId = "stream-1"; await Store.AppendToStream( streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); await Store.AppendToStream( streamId, 2, CreateNewStreamMessages(4, 5, 6)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5, 6))); exception.ShouldBeNull(); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_multiple_messages_to_stream_with_correct_expected_version_second_time_with_same_messages_then_should_have_expected_result() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result1 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5, 6)); var result2 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5, 6)); result2.CurrentVersion.ShouldBe(5); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_single_message_to_stream_with_correct_expected_version_second_time_with_same_messages_then_should_have_expected_result() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result1 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4)[0]); var result2 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4)[0]); result2.CurrentVersion.ShouldBe(3); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_correct_expected_version_second_time_with_same_initial_messages_then_should_not_throw() { const string streamId = "stream-1"; await Store.AppendToStream( streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); await Store.AppendToStream( streamId, 2, CreateNewStreamMessages(4, 5, 6)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5))); exception.ShouldBeNull(); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_multiple_messages_to_stream_with_correct_expected_version_second_time_with_same_initial_messages_then_should_have_expected_result() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result1 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5, 6)); var result2 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5)); result2.CurrentVersion.ShouldBe(5); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_single_message_to_stream_with_correct_expected_version_second_time_with_same_initial_messages_then_should_have_expected_result() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result1 = await Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4)[0]); var result2 = await Store.AppendToStream(streamId, 1, CreateNewStreamMessages(3)[0]); result2.CurrentVersion.ShouldBe(3); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_correct_expected_version_second_time_with_additional_messages_then_should_throw() { const string streamId = "stream-1"; await Store.AppendToStream( streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); await Store.AppendToStream( streamId, 2, CreateNewStreamMessages(4, 5, 6)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 2, CreateNewStreamMessages(4, 5, 6, 7))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, 2)); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_multiple_messages_to_non_existing_stream_with_expected_version_any() { const string streamId = "stream-1"; var result = await Store.AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result.CurrentVersion.ShouldBe(2); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 4); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_single_message_to_non_existing_stream_with_expected_version_any() { const string streamId = "stream-1"; var result = await Store.AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)[0]); result.CurrentVersion.ShouldBe(0); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 2); page.Messages.Length.ShouldBe(1); } [Fact, Trait("Category", "AppendStream")] public async Task Can_create_empty_stream() { const string streamId = "stream-1"; await Store.AppendToStream(streamId, ExpectedVersion.NoStream, new NewStreamMessage[0]); var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2); page.Messages.Length.ShouldBe(0); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_to_empty_stream() { const string streamId = "stream-1"; await Store.AppendToStream(streamId, ExpectedVersion.NoStream, new NewStreamMessage[0]); var result = await Store.AppendToStream(streamId, ExpectedVersion.EmptyStream, CreateNewStreamMessages(1, 2, 3)); result.CurrentVersion.ShouldBe(2); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_expected_version_any_and_all_messages_committed_then_should_be_idempotent_first_message() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_any_and_all_messages_committed_then_should_be_idempotent_subsequent_message() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(2)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(2)); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(2); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_second_time_with_expected_version_any_single_message_and_all_messages_committed_then_should_be_idempotent() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(1); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_multiple_messages_to_stream_second_time_with_expected_version_any_and_all_messages_committed_then_should_have_expected_result() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result2.CurrentVersion.ShouldBe(2); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_single_message_to_stream_second_time_with_expected_version_any_and_all_messages_committed_then_should_have_expected_result() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)[0]); result1.CurrentVersion.ShouldBe(0); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)[0]); result2.CurrentVersion.ShouldBe(0); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 3); page.Messages.Length.ShouldBe(1); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_any_and_some_of_the_messages_previously_committed_then_should_be_idempotent() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2)); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_any_and_some_of_the_messages_previously_committed_but_out_of_order_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); Func<Task> act = () => Store.AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(2, 1)); await act.ShouldThrowAsync<WrongExpectedVersionException>(); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_multiple_messages_to_stream_with_expected_version_any_and_some_of_the_messages_previously_committed_then_should_have_expected_result() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2)); result2.CurrentVersion.ShouldBe(2); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_single_message_to_stream_with_expected_version_any_and_some_of_the_messages_previously_committed_then_should_have_expected_result() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1)[0]); result2.CurrentVersion.ShouldBe(2); result2.CurrentPosition.ShouldBe(result1.CurrentPosition); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 4); page.Messages.Length.ShouldBe(3); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_stream_with_expected_version_any_and_none_of_the_messages_previously_committed() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(4, 5, 6)); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(6); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_multiple_messages_to_stream_with_expected_version_any_and_none_of_the_messages_previously_committed_should_have_expected_results() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(4, 5, 6)); result2.CurrentVersion.ShouldBe(5); result2.CurrentPosition.ShouldBeGreaterThanOrEqualTo(result1.CurrentPosition + 3L); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 10); page.Messages.Length.ShouldBe(6); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_single_message_to_stream_with_expected_version_any_and_none_of_the_messages_previously_committed_should_have_expected_results() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(4)[0]); result2.CurrentVersion.ShouldBe(3); result2.CurrentPosition.ShouldBeGreaterThanOrEqualTo(result1.CurrentPosition + 1L); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 5); page.Messages.Length.ShouldBe(4); } [Fact, Trait("Category", "AppendStream")] public async Task Can_append_message_to_stream_with_expected_version_any_and_none_of_the_messages_previously_committed_should_have_expected_results() { const string streamId = "stream-1"; var result1 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(4)[0]); result2.CurrentVersion.ShouldBe(3); result2.CurrentPosition.ShouldBeGreaterThanOrEqualTo(result1.CurrentPosition + 1L); var page = await Store .ReadStreamForwards(streamId, StreamVersion.Start, 5); page.Messages.Length.ShouldBe(4); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_any_and_some_of_the_messages_previously_committed_and_with_additional_messages_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(2, 3, 4))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, ExpectedVersion.Any)); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_and_no_messages_then_should_have_expected_result() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var result = await Store.AppendToStream(streamId, 2, new NewStreamMessage[0]); result.CurrentVersion.ShouldBe(2); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_no_stream_and_no_messages_then_should_have_expected_result() { const string streamId = "stream-1"; var result = await Store .AppendToStream(streamId, ExpectedVersion.NoStream, new NewStreamMessage[0]); result.CurrentVersion.ShouldBe(-1); result.CurrentPosition.ShouldBeLessThan(Fixture.MinPosition); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_expected_version_and_duplicate_message_Id_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 2, CreateNewStreamMessages(1))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, 2)); } [Theory, Trait("Category", "AppendStream")] [InlineData(ExpectedVersion.NoStream)] [InlineData(ExpectedVersion.Any)] public async Task When_append_to_non_existent_stream_with_empty_collection_of_messages_then_should_create_empty_stream(int expectedVersion) { const string streamId = "stream-1"; await Store.AppendToStream(streamId, expectedVersion, new NewStreamMessage[0]); var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 1); page.Status.ShouldBe(PageReadStatus.Success); page.FromStreamVersion.ShouldBe(0); page.LastStreamVersion.ShouldBe(-1); page.LastStreamPosition.ShouldBe(-1); page.NextStreamVersion.ShouldBe(0); page.IsEnd.ShouldBe(true); } [Theory, Trait("Category", "AppendStream")] [InlineData(ExpectedVersion.Any)] [InlineData(ExpectedVersion.NoStream)] public async Task When_append_to_many_streams_returns_expected_position(int expectedVersion) { const string streamId1 = "stream-1"; const string streamId2 = "stream-2"; var result1 = await Store.AppendToStream(streamId1, expectedVersion, CreateNewStreamMessages(1, 2, 3)); result1.CurrentVersion.ShouldBe(2); result1.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); var result2 = await Store.AppendToStream(streamId2, expectedVersion, CreateNewStreamMessages(1, 2, 3)); result2.CurrentVersion.ShouldBe(2); result2.CurrentPosition.ShouldBeGreaterThanOrEqualTo(result1.CurrentPosition + 2L); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_with_higher_wrong_expected_version_then_should_throw() { const string streamId = "stream-1"; await Store .AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); var exception = await Record.ExceptionAsync(() => Store.AppendToStream(streamId, 10, CreateNewStreamMessages(4))); exception.ShouldBeOfType<WrongExpectedVersionException>( ErrorMessages.AppendFailedWrongExpectedVersion(streamId, 10)); } [Theory, Trait("Category", "AppendStream")] [InlineData("stream/id")] [InlineData("stream%id")] public async Task When_append_to_stream_with_url_encodable_characters_and_expected_version_no_stream_then_should_have_expected_result(string streamId) { var result = await Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3)); result.CurrentVersion.ShouldBe(2); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); } [Theory, Trait("Category", "AppendStream")] [InlineData("stream/id")] [InlineData("stream%id")] public async Task When_append_to_stream_with_url_encodable_characters_and_expected_version_any_then_should_have_expected_result(string streamId) { var result = await Store.AppendToStream(streamId, ExpectedVersion.Any, CreateNewStreamMessages(1, 2, 3)); result.CurrentVersion.ShouldBe(2); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); } [Theory, Trait("Category", "AppendStream")] [InlineData("stream/id")] [InlineData("stream%id")] public async Task When_append_to_stream_with_url_encodable_characters_and_expected_version_empty_stream_then_should_have_expected_result(string streamId) { await Store.AppendToStream(streamId, ExpectedVersion.NoStream, Array.Empty<NewStreamMessage>()); var result = await Store.AppendToStream(streamId, ExpectedVersion.EmptyStream, CreateNewStreamMessages(1, 2, 3)); result.CurrentVersion.ShouldBe(2); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); } [Theory, Trait("Category", "AppendStream")] [InlineData("stream/id")] [InlineData("stream%id")] public async Task When_append_to_stream_with_url_encodable_characters_and_expected_version_then_should_have_expected_result(string streamId) { await Store.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamMessages(1)); var result = await Store.AppendToStream(streamId, 0, CreateNewStreamMessages(2, 3)); result.CurrentVersion.ShouldBe(2); result.CurrentPosition.ShouldBeGreaterThanOrEqualTo(Fixture.MinPosition + 2L); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_stream_concurrently_with_no_stream_expected_and_same_messages_then_should_then_should_have_expected_result() { // Idempotency const string streamId = "stream-1"; var messages = CreateNewStreamMessages(1, 2); var tasks = new List<Task<AppendResult>>(); for(var index = 0; index < 10; index++) { tasks.Add(Store.AppendToStream(streamId, ExpectedVersion.NoStream, messages)); } var results = await Task.WhenAll(tasks); Assert.All(results, result => result.CurrentVersion.ShouldBe(1)); Assert.All(results, result => result.CurrentPosition.ShouldBe(results[0].CurrentPosition)); } [Fact, Trait("Category", "AppendStream")] public async Task When_append_to_different_streams_concurrently_with_no_stream_expected_and_same_messages_then_should_then_should_have_expected_result() { // Idempotency const string streamPrefix = "stream-"; var messages = CreateNewStreamMessages(1, 2); var tasks = new List<Task<AppendResult>>(); for(var index = 0; index < 10; index++) { tasks.Add(Store.AppendToStream(streamPrefix + index, ExpectedVersion.NoStream, messages)); } var results = await Task.WhenAll(tasks); Assert.All(results, result => result.CurrentVersion.ShouldBe(1)); } } }
45.212483
172
0.661536
[ "MIT" ]
ArneSchoonvliet/SQLStreamStore
tests/SqlStreamStore.AcceptanceTests/AcceptanceTests.AppendStream.cs
34,047
C#
using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Windows.Data; namespace Xceed.Wpf.Toolkit.PropertyGrid.Converters { public class SelectedObjectConverter : IValueConverter { private const string ValidParameterMessage = "parameter must be one of the following strings: 'Type', 'TypeName', 'SelectedObjectName'"; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter == null) { throw new ArgumentNullException("parameter"); } if (!(parameter is string)) { throw new ArgumentException("parameter must be one of the following strings: 'Type', 'TypeName', 'SelectedObjectName'"); } if (CompareParam(parameter, "Type")) { return ConvertToType(value, culture); } if (CompareParam(parameter, "TypeName")) { return ConvertToTypeName(value, culture); } if (CompareParam(parameter, "SelectedObjectName")) { return ConvertToSelectedObjectName(value, culture); } throw new ArgumentException("parameter must be one of the following strings: 'Type', 'TypeName', 'SelectedObjectName'"); } private bool CompareParam(object parameter, string parameterValue) { return string.Compare((string)parameter, parameterValue, true) == 0; } private object ConvertToType(object value, CultureInfo culture) { if (value == null) { return null; } return value.GetType(); } private object ConvertToTypeName(object value, CultureInfo culture) { if (value == null) { return string.Empty; } Type type = value.GetType(); if (type.GetInterface("ICustomTypeProvider", true) != null) { MethodInfo method = type.GetMethod("GetCustomType"); type = (method.Invoke(value, null) as Type); } DisplayNameAttribute displayNameAttribute = type.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault(); if (displayNameAttribute != null) { return displayNameAttribute.DisplayName; } return type.Name; } private object ConvertToSelectedObjectName(object value, CultureInfo culture) { if (value == null) { return string.Empty; } Type type = value.GetType(); PropertyInfo[] properties = type.GetProperties(); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { if (propertyInfo.Name == "Name") { return propertyInfo.GetValue(value, null); } } return string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
27.295918
138
0.706542
[ "MIT" ]
ay2015/AYUI8
Ay/ay/SDK/CONTROLLIB/Large/PropertyGrid/Converters/SelectedObjectConverter.cs
2,675
C#
// <copyright file="ITestCaseLogger.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace AutomationTestSetFramework { /// <summary> /// Interface that represents the test case logger. It writes information about the test case. /// </summary> public interface ITestCaseLogger { /// <summary> /// Writes to log information anout the test case. /// </summary> /// <param name="testCase">The test case to log.</param> public void Log(ITestCase testCase); } }
34.352941
98
0.655822
[ "MIT" ]
zzzrst/AutomationTestSetFramework
AutomationFramework/TestInterfaces/ITestCaseLogger.cs
586
C#
#region Statements using System; using System.Collections.Generic; using System.Net; using Cysharp.Threading.Tasks; using ENet; using UnityEngine; using Event = ENet.Event; using EventType = ENet.EventType; #endregion namespace Mirage.ENet { public class IgnoranceServer { #region Fields private readonly Configuration _config; private readonly Transport _transport; private Host _enetHost; private Address _enetAddress; public bool ServerStarted; private readonly Dictionary<uint, ENetClientConnection> _connectedClients = new Dictionary<uint, ENetClientConnection>(); #endregion /// <summary> /// Initialize constructor. /// </summary> /// <param name="config"></param> public IgnoranceServer(Configuration config, Transport transport) { _config = config; _transport = transport; _enetHost = new Host(); } /// <summary> /// Processes and accepts new incoming connections. /// </summary> /// <returns></returns> private async UniTaskVoid AcceptConnections() { while (ServerStarted) { bool serverWasPolled = false; while (!serverWasPolled) { if (_enetHost.CheckEvents(out Event networkEvent) <= 0) { if (_enetHost.Service(_config.EnetPollTimeout, out networkEvent) <= 0) break; serverWasPolled = true; } _connectedClients.TryGetValue(networkEvent.Peer.ID, out ENetClientConnection client); switch (networkEvent.Type) { case EventType.Connect: // A client connected to the server. Assign a new ID to them. if (_config.DebugEnabled) { Debug.Log( $"Ignorance: New connection from {networkEvent.Peer.IP}:{networkEvent.Peer.Port}"); Debug.Log( $"Ignorance: Map {networkEvent.Peer.IP}:{networkEvent.Peer.Port} (ENET Peer {networkEvent.Peer.ID})"); } if (_config.CustomTimeoutLimit) networkEvent.Peer.Timeout(Library.throttleScale, _config.CustomTimeoutBaseTicks, _config.CustomTimeoutBaseTicks * _config.CustomTimeoutMultiplier); var connection = new ENetClientConnection(networkEvent.Peer, _enetHost, _config, true); _connectedClients.Add(networkEvent.Peer.ID, connection); _transport.Connected.Invoke(connection); break; case EventType.Timeout: case EventType.Disconnect: if(!(client is null)) { if (_config.DebugEnabled) Debug.Log($"Ignorance: Dead Peer. {networkEvent.Peer.ID}."); client.Disconnect(); _connectedClients.Remove(networkEvent.Peer.ID); } else { if (_config.DebugEnabled) Debug.LogWarning( "Ignorance: Peer is already dead, received another disconnect message."); } networkEvent.Packet.Dispose(); break; case EventType.Receive: // Client recieving some data. if (client?.Client.ID != networkEvent.Peer.ID) { // Emit a warning and clean the packet. We don't want it in memory. if (_config.DebugEnabled) Debug.LogWarning( $"Ignorance: Unknown packet from Peer {networkEvent.Peer.ID}. Be cautious - if you get this error too many times, you're likely being attacked."); networkEvent.Packet.Dispose(); break; } if (!networkEvent.Packet.IsSet) { if (_config.DebugEnabled) Debug.LogWarning("Ignorance WARNING: A incoming packet is not set correctly."); break; } if (networkEvent.Packet.Length > _config.PacketCache.Length) { if (_config.DebugEnabled) Debug.LogWarning( $"Ignorance: Packet too big to fit in buffer. {networkEvent.Packet.Length} packet bytes vs {_config.PacketCache.Length} cache bytes {networkEvent.Peer.ID}."); networkEvent.Packet.Dispose(); } else { // invoke on the client. try { var incomingIgnoranceMessage = new IgnoranceIncomingMessage { ChannelId = networkEvent.ChannelID, Data = new byte[networkEvent.Packet.Length] }; networkEvent.Packet.CopyTo(incomingIgnoranceMessage.Data); client.IncomingQueuedData.Enqueue(incomingIgnoranceMessage); if (_config.DebugEnabled) Debug.Log( $"Ignorance: Queuing up incoming data packet: {BitConverter.ToString(incomingIgnoranceMessage.Data)}"); } catch (Exception e) { Debug.LogError( $"Ignorance caught an exception while trying to copy data from the unmanaged (ENET) world to managed (Mono/IL2CPP) world. Please consider reporting this to the Ignorance developer on GitHub.\n" + $"Exception returned was: {e.Message}\n" + $"Debug details: {(_config.PacketCache == null ? "packet buffer was NULL" : $"{_config.PacketCache.Length} byte work buffer")}, {networkEvent.Packet.Length} byte(s) network packet length\n" + $"Stack Trace: {e.StackTrace}"); } } networkEvent.Packet.Dispose(); break; default: networkEvent.Packet.Dispose(); break; } await UniTask.Delay(10); } foreach (KeyValuePair<uint, ENetClientConnection> connectedClient in _connectedClients) { while (connectedClient.Value.OutgoingQueuedData.TryDequeue(out IgnoranceOutgoingMessage message)) { int returnCode = connectedClient.Value.Client.Send(message.ChannelId, ref message.Payload); if (returnCode == 0) { if (_config.DebugEnabled) Debug.Log( $"[DEBUGGING MODE] Ignorance: Outgoing packet on channel {message.ChannelId} OK"); continue; } if (_config.DebugEnabled) Debug.Log( $"[DEBUGGING MODE] Ignorance: Outgoing packet on channel {message.ChannelId} FAIL, code {returnCode}"); } } await UniTask.Delay(10); } } /// <summary> /// Shutdown the server and cleanup. /// </summary> public void Shutdown() { if (_config.DebugEnabled) { Debug.Log("[DEBUGGING MODE] Ignorance: ServerStop()"); Debug.Log("[DEBUGGING MODE] Ignorance: Cleaning the packet cache..."); } ServerStarted = false; _enetHost.Flush(); _enetHost.Dispose(); } /// <summary> /// Start up the server and initialize things /// </summary> /// <returns></returns> public void Start() { if (!_config.ServerBindAll) { if (_config.DebugEnabled) Debug.Log( "Ignorance: Not binding to all interfaces, checking if supplied info is actually an IP address"); if (IPAddress.TryParse(_config.ServerBindAddress, out _)) { // Looks good to us. Let's use it. if (_config.DebugEnabled) Debug.Log($"Ignorance: Valid IP Address {_config.ServerBindAddress}"); _enetAddress.SetIP(_config.ServerBindAddress); } else { // Might be a hostname. if (_config.DebugEnabled) Debug.Log("Ignorance: Doesn't look like a valid IP address, assuming it's a hostname?"); _enetAddress.SetHost(_config.ServerBindAddress); } } else { if (_config.DebugEnabled) Debug.Log($"Ignorance: Setting address to all interfaces, port {_config.CommunicationPort}"); #if UNITY_IOS // Coburn: temporary fix until I figure out if this is similar to the MacOS bug again... ENETAddress.SetIP("::0"); #endif } _enetAddress.Port = (ushort) _config.CommunicationPort; if (_enetHost == null || !_enetHost.IsSet) _enetHost = new Host(); // Go go go! Clear those corners! _enetHost.Create(_enetAddress, _config.CustomMaxPeerLimit ? _config.CustomMaxPeers : (int) Library.maxPeers, _config.Channels.Length, 0, 0); if (_config.DebugEnabled) Debug.Log( "[DEBUGGING MODE] Ignorance: Server should be created now... If Ignorance immediately crashes after this line, please file a bug report on the GitHub."); ServerStarted = true; UniTask.Run(AcceptConnections).Forget(); // Transport has finish starting. _transport.Started.Invoke(); } } }
41.821818
235
0.459873
[ "MIT" ]
MirageNet/IgnoranceNG
Assets/Mirage/Runtime/Transport/Ignorance/IgnoranceServer.cs
11,501
C#
namespace UI { partial class inHospital_zhiban { /// <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.lvwzhuyuan = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader9 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button6 = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.button5 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // lvwzhuyuan // this.lvwzhuyuan.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.lvwzhuyuan.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader9, this.columnHeader2, this.columnHeader3, this.columnHeader4, this.columnHeader5, this.columnHeader6, this.columnHeader7, this.columnHeader8}); this.lvwzhuyuan.FullRowSelect = true; this.lvwzhuyuan.Location = new System.Drawing.Point(12, 137); this.lvwzhuyuan.Name = "lvwzhuyuan"; this.lvwzhuyuan.Size = new System.Drawing.Size(859, 264); this.lvwzhuyuan.TabIndex = 0; this.lvwzhuyuan.UseCompatibleStateImageBehavior = false; this.lvwzhuyuan.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "病人卡号"; this.columnHeader1.Width = 67; // // columnHeader9 // this.columnHeader9.Text = "姓名"; // // columnHeader2 // this.columnHeader2.Text = "科室"; this.columnHeader2.Width = 61; // // columnHeader3 // this.columnHeader3.Text = "病房号"; this.columnHeader3.Width = 61; // // columnHeader4 // this.columnHeader4.Text = "床位"; this.columnHeader4.Width = 93; // // columnHeader5 // this.columnHeader5.Text = "预交费"; this.columnHeader5.Width = 106; // // columnHeader6 // this.columnHeader6.Text = "病情描述"; this.columnHeader6.Width = 149; // // columnHeader7 // this.columnHeader7.Text = "药物禁忌"; this.columnHeader7.Width = 142; // // columnHeader8 // this.columnHeader8.Text = "登记时间"; this.columnHeader8.Width = 193; // // button1 // this.button1.Location = new System.Drawing.Point(171, 16); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(58, 23); this.button1.TabIndex = 1; this.button1.Text = "查看"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(80, 16); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(85, 21); this.textBox1.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(15, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(59, 12); this.label2.TabIndex = 3; this.label2.Text = "病人卡号:"; // // groupBox1 // this.groupBox1.Controls.Add(this.button6); this.groupBox1.Controls.Add(this.comboBox1); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.textBox5); this.groupBox1.Controls.Add(this.textBox4); this.groupBox1.Controls.Add(this.textBox3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textBox1); this.groupBox1.Controls.Add(this.button5); this.groupBox1.Controls.Add(this.button4); this.groupBox1.Controls.Add(this.button3); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.button1); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(865, 90); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "筛选:"; // // button6 // this.button6.Location = new System.Drawing.Point(688, 50); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(90, 27); this.button6.TabIndex = 5; this.button6.Text = "查看所有"; this.button6.UseVisualStyleBackColor = true; this.button6.Click += new System.EventHandler(this.button6_Click); // // comboBox1 // this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(80, 48); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(85, 20); this.comboBox1.TabIndex = 4; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(564, 17); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(65, 12); this.label5.TabIndex = 3; this.label5.Text = "楼 层:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(296, 53); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(65, 12); this.label4.TabIndex = 3; this.label4.Text = "病 房 号:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(297, 19); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(59, 12); this.label3.TabIndex = 3; this.label3.Text = "病人姓名:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(15, 53); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 12); this.label1.TabIndex = 3; this.label1.Text = "科 室:"; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(629, 14); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(85, 21); this.textBox5.TabIndex = 2; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(368, 50); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(85, 21); this.textBox4.TabIndex = 2; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(368, 16); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(85, 21); this.textBox3.TabIndex = 2; // // button5 // this.button5.Location = new System.Drawing.Point(720, 14); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(58, 23); this.button5.TabIndex = 1; this.button5.Text = "查看"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // button4 // this.button4.Location = new System.Drawing.Point(459, 14); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(58, 23); this.button4.TabIndex = 1; this.button4.Text = "查看"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // button3 // this.button3.Location = new System.Drawing.Point(459, 50); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(58, 23); this.button3.TabIndex = 1; this.button3.Text = "查看"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button2 // this.button2.Location = new System.Drawing.Point(171, 48); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(58, 23); this.button2.TabIndex = 1; this.button2.Text = "查看"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(14, 119); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(53, 12); this.label6.TabIndex = 5; this.label6.Text = "查看结果"; // // groupBox2 // this.groupBox2.Location = new System.Drawing.Point(12, 93); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(865, 324); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; // // inHospital_zhiban // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(921, 427); this.Controls.Add(this.label6); this.Controls.Add(this.lvwzhuyuan); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "inHospital_zhiban"; this.Text = "inHospital_zhiban"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.inHospital_zhiban_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView lvwzhuyuan; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.ColumnHeader columnHeader7; private System.Windows.Forms.ColumnHeader columnHeader8; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.ColumnHeader columnHeader9; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button2; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.Button button5; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label6; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button button6; } }
44.138965
158
0.568739
[ "MIT" ]
zhangzelei520/dewei
UI/inHospital-zhiban.Designer.cs
16,333
C#
using System; namespace GDAXSharp.Shared.Utilities.Clock { public class Clock : IClock { public DateTime GetTime() { return DateTime.UtcNow; } } }
15.153846
42
0.568528
[ "MIT" ]
Sotam/gdax-csharp
GDAXSharp/Shared/Utilities/Clock/Clock.cs
199
C#
using AbhsChinese.Domain.Enum; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AbhsChinese.Domain.JsonEntity.UnitStep { /// <summary> /// 快速阅读 /// </summary> public class StudyFastRead : StepAction { public StudyFastRead() : base(LessonActionTypeEnum.StudyFastRead) { } /// <summary> /// 文本id /// </summary> public string TextId { get; set; } /// <summary> /// 开场白 /// </summary> public string KcbId { get; set; } /// <summary> /// 切换速度 /// </summary> public int Speed { get; set; } /// <summary> /// 显示文字数 /// </summary> public int ShowNum { get; set; } /// <summary> /// 显示类型 /// </summary> public string ShowModel { get; set; } /// <summary> /// 金币数量 /// </summary> public int Golds { get; set; } } }
23.285714
77
0.502045
[ "Apache-2.0" ]
GuoQqizz/SmartChinese
AbhsChinese.Domain/JsonEntity/UnitStep/StudyFastRead.cs
1,032
C#
 using BeUtl.Graphics; namespace BeUtl.Media; /// <summary> /// A brush that draws with a linear gradient. /// </summary> public interface ILinearGradientBrush : IGradientBrush { /// <summary> /// Gets or sets the start point for the gradient. /// </summary> RelativePoint StartPoint { get; } /// <summary> /// Gets or sets the end point for the gradient. /// </summary> RelativePoint EndPoint { get; } }
21
54
0.643991
[ "MIT" ]
YiB-PC/BeUtl
src/BeUtl.Graphics/Media/ILinearGradientBrush.cs
443
C#
namespace Pidgin { public static partial class Parser<TToken, TUser> { /// <summary> /// A parser which returns the number of input tokens which have been consumed. /// </summary> /// <returns>A parser which returns the number of input tokens which have been consumed</returns> public static Parser<TToken, TUser, int> CurrentOffset { get; } = new CurrentOffsetParser<TToken, TUser>(); } internal sealed class CurrentOffsetParser<TToken, TUser> : Parser<TToken, TUser, int> { public sealed override bool TryParse(ref ParseState<TToken, TUser> state, ref PooledList<Expected<TToken>> expecteds, out int result) { result = state.Location; return true; } } }
37.142857
141
0.635897
[ "MIT" ]
Artentus/Pidgin
Pidgin/Parser.CurrentOffset.cs
780
C#
using Machine.Specifications; using Moq; using It = Machine.Specifications.It; namespace Chronicle.Specs { public class LogManagerSpecs { [Subject("Logger")] public class when_creating_a_logger_without_setting_the_provider { static ILogger _logger; Because of = () => _logger = LogManager.GetLogger<LogManagerSpecs>(); It should_create_a_null_logger = () => _logger.GetType().Name.ShouldEqual("NullLogger"); } [Subject("Logger")] public class when_logging_with_a_created_logger { const string Id = "D828E6F6-7536-4375-B84E-ECB566D0686F"; static ILogger _logger; static LogEntry _logEntry; Establish context = () => { var loggerStub = new Mock<ILogger>(); loggerStub.Setup(x => x.Write(Moq.It.IsAny<LogEntry>())).Callback<LogEntry>(e => _logEntry = e); LogManager.SetLoggerProvider(t => loggerStub.Object); _logger = LogManager.GetLogger<LogManagerSpecs>(); }; Because of = () => _logger.Write(new LogEntry(Id)); It should_log = () => _logEntry.Message.ShouldEqual(Id); } [Subject("Logger")] public class when_logging_with_a_created_logger_non_generic { const string Id = "D828E6F6-7536-4375-B84E-ECB566D0686F"; static ILogger _logger; static LogEntry _logEntry; Establish context = () => { var loggerStub = new Mock<ILogger>(); loggerStub.Setup(x => x.Write(Moq.It.IsAny<LogEntry>())).Callback<LogEntry>(e => _logEntry = e); LogManager.SetLoggerProvider(t => loggerStub.Object); _logger = LogManager.GetLogger(typeof(LogManagerSpecs)); }; Because of = () => _logger.Write(new LogEntry(Id)); It should_log = () => _logEntry.Message.ShouldEqual(Id); } } }
34.389831
112
0.579596
[ "MIT" ]
JTOne123/chronicle
src/Chronicle.Specs/LogManagerSpecs.cs
2,031
C#
// <copyright file="CallControlSendDTMFServiceTest.cs" company="Telnyx"> // Copyright (c) Telnyx. All rights reserved. // </copyright> namespace TelnyxTests.Services.Calls.CallCommands { using System.Net.Http; using System.Threading.Tasks; using Telnyx; using Xunit; public class CallControlSendDTMFServiceTest : BaseTelnyxTest { private const string CallControllId = "call_123"; private readonly CallControlSendDTMFService service; private readonly CallControlSendDTMFCreateOptions createOptions; public CallControlSendDTMFServiceTest(MockHttpClientFixture mockHttpClientFixture) : base(mockHttpClientFixture) { this.service = new CallControlSendDTMFService(); this.createOptions = new CallControlSendDTMFCreateOptions() { ClientState = "aGF2ZSBhIG5pY2UgZGF5ID1d", CommandId = new System.Guid("891510ac-f3e4-11e8-af5b-de00688a4901"), Digits = "1www2WABCDw9", DurationMillis = 250 }; } [Fact] public void Create() { var message = this.service.Create(CallControllId, this.createOptions); //this.AssertRequest(HttpMethod.Post, $"/v2/calls/{CallControllId}/actions/send_dtmf"); Assert.NotNull(message); Assert.Equal("Telnyx.CallAnswerResponse", message.GetType().ToString()); } [Fact] public async Task CreateAsync() { var message = await this.service.CreateAsync(CallControllId, this.createOptions); //this.AssertRequest(HttpMethod.Post, $"/v2/calls/{CallControllId}/actions/send_dtmf"); Assert.NotNull(message); Assert.Equal("Telnyx.CallAnswerResponse", message.GetType().ToString()); } } }
35.730769
99
0.644241
[ "MIT" ]
thedonmon/telnyx-dotnet
src/TelnyxTests/Services/Calls/CallCommands/SendDTMF/CallControlSendDTMFServiceTest.cs
1,860
C#
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using System; using Xunit; using Xunit.Abstractions; namespace Microsoft.PSharp.TestingServices.Tests { public class GotoStateExitFailTest : BaseTest { public GotoStateExitFailTest(ITestOutputHelper output) : base(output) { } private class M : Machine { [Start] [OnEntry(nameof(InitOnEntry))] [OnExit(nameof(ExitInit))] private class Init : MachineState { } private void InitOnEntry() { this.Goto<Done>(); } private void ExitInit() { // This assertion is reachable. this.Assert(false, "Bug found."); } private class Done : MachineState { } } [Fact(Timeout=5000)] public void TestGotoStateExitFail() { this.TestWithError(r => { r.CreateMachine(typeof(M)); }, expectedError: "Bug found.", replay: true); } } }
26.5
100
0.438679
[ "MIT" ]
alexsyeo/PSharp
Tests/TestingServices.Tests/Machines/Transitions/GotoStateExitFailTest.cs
1,486
C#
using System.Diagnostics; using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { /// <summary> /// A field that can index numbers so that they can later be used /// to boost documents in queries with a rank_feature query. /// </summary> [InterfaceDataContract] public interface IRankFeatureProperty : IProperty { /// <summary> /// Rank features that correlate negatively with the score should set <see cref="PositiveScoreImpact"/> /// to false (defaults to true). This will be used by the rank_feature query to modify the scoring /// formula in such a way that the score decreases with the value of the feature instead of /// increasing. For instance in web search, the url length is a commonly used feature /// which correlates negatively with scores. /// </summary> [DataMember(Name = "positive_score_impact")] bool? PositiveScoreImpact { get; set; } } /// <inheritdoc cref="IRankFeatureProperty" /> public class RankFeatureProperty : PropertyBase, IRankFeatureProperty { public RankFeatureProperty() : base(FieldType.RankFeature) { } /// <inheritdoc /> public bool? PositiveScoreImpact { get; set; } } /// <inheritdoc cref="IRankFeatureProperty" /> [DebuggerDisplay("{DebugDisplay}")] public class RankFeaturePropertyDescriptor<T> : PropertyDescriptorBase<RankFeaturePropertyDescriptor<T>, IRankFeatureProperty, T>, IRankFeatureProperty where T : class { public RankFeaturePropertyDescriptor() : base(FieldType.RankFeature) { } bool? IRankFeatureProperty.PositiveScoreImpact { get; set; } /// <inheritdoc cref="IRankFeatureProperty.PositiveScoreImpact" /> public RankFeaturePropertyDescriptor<T> PositiveScoreImpact(bool? positiveScoreImpact = true) => Assign(positiveScoreImpact, (a, v) => a.PositiveScoreImpact = v); } }
37.142857
107
0.749451
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Nest/Mapping/Types/Core/RankFeature/RankFeatureProperty.cs
1,820
C#
/******************************************************************************** Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ***********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MixERP.Net.FrontEnd.Sales.Entry { public partial class Quotation : MixERP.Net.BusinessLayer.BasePageClass { protected void Page_Init(object sender, EventArgs e) { this.OverridePath = "/Sales/Quotation.aspx"; } protected void Page_Load(object sender, EventArgs e) { } protected void SalesQuotation_SaveButtonClick(object sender, EventArgs e) { DateTime valueDate = MixERP.Net.Common.Conversion.TryCastDate(SalesQuotation.GetForm.DateTextBox.Text); string partyCode = SalesQuotation.GetForm.PartyDropDownList.SelectedItem.Value; int priceTypeId = MixERP.Net.Common.Conversion.TryCastInteger(SalesQuotation.GetForm.PriceTypeDropDownList.SelectedItem.Value); GridView grid = SalesQuotation.GetForm.Grid; string referenceNumber = SalesQuotation.GetForm.ReferenceNumberTextBox.Text; string statementReference = SalesQuotation.GetForm.StatementReferenceTextBox.Text; long nonGlStockMasterId = MixERP.Net.BusinessLayer.Transactions.NonGLStockTransaction.Add("Sales.Quotation", valueDate, partyCode, priceTypeId, grid, referenceNumber, statementReference); if(nonGlStockMasterId > 0) { Response.Redirect("~/Sales/Quotation.aspx?TranId=" + nonGlStockMasterId, true); } } } }
43.108696
199
0.647504
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
gj86/mixerp2
MixERP.Net.FrontEnd/Sales/Entry/Quotation.aspx.cs
1,985
C#
using System.Collections.Generic; namespace SimpleExpressions.Core.Converters { public abstract class BaseConverter: IConverter { /// <summary> /// The functions the converter can support /// </summary> public abstract IList<string> SupportedFunctionNames { get; } /// <summary> /// The function the converter will handle /// </summary> public Function Function { get; set; } /// <summary> /// Used to know if this converter can parse the given function /// </summary> /// <param name="functionName">The name of the function to be converted</param> public bool CanParse(string functionName) { return this.SupportedFunctionNames.Contains(functionName); } } }
28.857143
87
0.611386
[ "MIT" ]
Timothep/SimpleExpressions
SimpleExpression/SimpleExpression.Core/Converters/BaseConverter.cs
810
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="GraphicsQualityOptionsData.cs"> // Copyright (c) 2020 Aspose.Words for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Words.Cloud.Sdk.Model { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// Allows to specify additional System.Drawing.Graphics quality options. /// </summary> public class GraphicsQualityOptionsData { /// <summary> /// Gets or sets the value, that specifies how composited images are drawn to this Graphics. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum CompositingModeEnum { /// <summary> /// Enum value "SourceOver" /// </summary> SourceOver, /// <summary> /// Enum value "SourceCopy" /// </summary> SourceCopy } /// <summary> /// Gets or sets the rendering quality of composited images drawn to this Graphics. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum CompositingQualityEnum { /// <summary> /// Enum value "Default" /// </summary> Default, /// <summary> /// Enum value "HighSpeed" /// </summary> HighSpeed, /// <summary> /// Enum value "HighQuality" /// </summary> HighQuality, /// <summary> /// Enum value "GammaCorrected" /// </summary> GammaCorrected, /// <summary> /// Enum value "AssumeLinear" /// </summary> AssumeLinear, /// <summary> /// Enum value "Invalid" /// </summary> Invalid } /// <summary> /// Gets or sets the interpolation mode associated with this Graphics. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum InterpolationModeEnum { /// <summary> /// Enum value "Default" /// </summary> Default, /// <summary> /// Enum value "Low" /// </summary> Low, /// <summary> /// Enum value "High" /// </summary> High, /// <summary> /// Enum value "Bilinear" /// </summary> Bilinear, /// <summary> /// Enum value "Bicubic" /// </summary> Bicubic, /// <summary> /// Enum value "NearestNeighbor" /// </summary> NearestNeighbor, /// <summary> /// Enum value "HighQualityBilinear" /// </summary> HighQualityBilinear, /// <summary> /// Enum value "HighQualityBicubic" /// </summary> HighQualityBicubic, /// <summary> /// Enum value "Invalid" /// </summary> Invalid } /// <summary> /// Gets or sets the rendering quality for this Graphics. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum SmoothingModeEnum { /// <summary> /// Enum value "Default" /// </summary> Default, /// <summary> /// Enum value "HighSpeed" /// </summary> HighSpeed, /// <summary> /// Enum value "HighQuality" /// </summary> HighQuality, /// <summary> /// Enum value "None" /// </summary> None, /// <summary> /// Enum value "AntiAlias" /// </summary> AntiAlias, /// <summary> /// Enum value "Invalid" /// </summary> Invalid } /// <summary> /// Gets or sets the rendering mode for text associated with this Graphics. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum TextRenderingHintEnum { /// <summary> /// Enum value "SystemDefault" /// </summary> SystemDefault, /// <summary> /// Enum value "SingleBitPerPixelGridFit" /// </summary> SingleBitPerPixelGridFit, /// <summary> /// Enum value "SingleBitPerPixel" /// </summary> SingleBitPerPixel, /// <summary> /// Enum value "AntiAliasGridFit" /// </summary> AntiAliasGridFit, /// <summary> /// Enum value "AntiAlias" /// </summary> AntiAlias, /// <summary> /// Enum value "ClearTypeGridFit" /// </summary> ClearTypeGridFit } /// <summary> /// Gets or sets the value, that specifies how composited images are drawn to this Graphics. /// </summary> public CompositingModeEnum? CompositingMode { get; set; } /// <summary> /// Gets or sets the rendering quality of composited images drawn to this Graphics. /// </summary> public CompositingQualityEnum? CompositingQuality { get; set; } /// <summary> /// Gets or sets the interpolation mode associated with this Graphics. /// </summary> public InterpolationModeEnum? InterpolationMode { get; set; } /// <summary> /// Gets or sets the rendering quality for this Graphics. /// </summary> public SmoothingModeEnum? SmoothingMode { get; set; } /// <summary> /// Gets or sets text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features. /// </summary> public StringFormatData StringFormat { get; set; } /// <summary> /// Gets or sets the rendering mode for text associated with this Graphics. /// </summary> public TextRenderingHintEnum? TextRenderingHint { get; set; } /// <summary> /// Get the string presentation of the object. /// </summary> /// <returns>String presentation of the object.</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class GraphicsQualityOptionsData {\n"); sb.Append(" CompositingMode: ").Append(this.CompositingMode).Append("\n"); sb.Append(" CompositingQuality: ").Append(this.CompositingQuality).Append("\n"); sb.Append(" InterpolationMode: ").Append(this.InterpolationMode).Append("\n"); sb.Append(" SmoothingMode: ").Append(this.SmoothingMode).Append("\n"); sb.Append(" StringFormat: ").Append(this.StringFormat).Append("\n"); sb.Append(" TextRenderingHint: ").Append(this.TextRenderingHint).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
33.744444
202
0.503677
[ "MIT" ]
rizwanniazigroupdocs/aspose-words-cloud-dotnet
Aspose.Words.Cloud.Sdk/Model/GraphicsQualityOptionsData.cs
8,842
C#
#region Copyright Syncfusion Inc. 2001 - 2016 // Copyright Syncfusion Inc. 2001 - 2016. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.AspNet.SignalR; namespace MVCSampleBrowser { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { RouteTable.Routes.MapHubs(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //AuthConfig.RegisterAuth(); AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true); } } }
35.368421
92
0.72247
[ "MIT" ]
ds112/hbase-on-windowns
Samples/CSharp/C# Analytics Samples/MVC/Global.asax.cs
1,344
C#
using System; using System.Collections.Generic; using Grasshopper.Kernel; using Rhino.Geometry; using T_RexEngine; namespace T_Rex { public class CustomSpacingGH : GH_Component { public CustomSpacingGH() : base("Custom Spacing", "Custom Spacing", "Creates the Rebar Group without any additional spacing - you have to set the spaces by creating Rebar Shapes that have already have spaces between them." + " Add 1 or more Rebar Shapes to create that Rebar Group.", "T-Rex", "Rebar Spacing") { } protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddIntegerParameter("Id", "Id", "Id as an integer for Rebar Group", GH_ParamAccess.item); pManager.AddGenericParameter("Rebar Shapes", "Rebar Shapes", "Rebar Shapes to create the Rebar Group", GH_ParamAccess.list); } protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddGenericParameter("Rebar Group", "Rebar Group", "Group of the reinforcement bars", GH_ParamAccess.item); pManager.AddMeshParameter("Mesh", "Mesh", "Mesh group representation", GH_ParamAccess.list); pManager.AddCurveParameter("Curve", "Curve", "Curves that represents reinforcement", GH_ParamAccess.list); } protected override void SolveInstance(IGH_DataAccess DA) { int id = 0; List<RebarShape> rebarShapes = new List<RebarShape>(); DA.GetData(0, ref id); DA.GetDataList(1, rebarShapes); RebarGroup rebarGroup = new RebarGroup(id, rebarShapes); DA.SetData(0, rebarGroup); DA.SetDataList(1, rebarGroup.RebarGroupMesh); DA.SetDataList(2, rebarGroup.RebarGroupCurves); } protected override System.Drawing.Bitmap Icon { get { return Properties.Resources.WithoutSpacing; } } public override Guid ComponentGuid { get { return new Guid("ceb38659-6e1c-48c5-b12c-7046343226cc"); } } } }
38.87931
170
0.626608
[ "MIT" ]
paireks/T-Rex
T-Rex/CustomSpacingGH.cs
2,257
C#
using NSubstitute; using NUnit.Framework; using StackExchange.NET.Clients; namespace Tests.Client { public class BaseClient { internal StackExchangeClient Client; [SetUp] public void Setup() { Client = Substitute.For<StackExchangeClient>("someKey"); } } }
16.117647
59
0.737226
[ "MIT" ]
gethari/FluentExchange
StackExchange.NET/Tests/Client/BaseClient.cs
276
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Liuliu.Blogs.Blogs; using Liuliu.Blogs.Blogs.Dtos; using Liuliu.Blogs.Blogs.Entities; using Microsoft.AspNetCore.Mvc; using OSharp.AspNetCore.Mvc.Filters; using OSharp.AspNetCore.UI; using OSharp.Core.Modules; using OSharp.Data; using OSharp.Entity; using OSharp.Filter; namespace Liuliu.Blogs.Web.Areas.Admin.Controllers.Blogs { [ModuleInfo(Position = "Blogs", PositionName = "博客模块")] [Description("管理-文章信息")] public class PostController : AdminApiController { /// <summary> /// 初始化一个<see cref="PostController"/>类型的新实例 /// </summary> public PostController(IBlogsContract blogsContract, IFilterService filterService) { BlogsContract = blogsContract; FilterService = filterService; } /// <summary> /// 获取或设置 数据过滤服务对象 /// </summary> protected IFilterService FilterService { get; } /// <summary> /// 获取或设置 博客模块业务契约对象 /// </summary> protected IBlogsContract BlogsContract { get; } /// <summary> /// 读取文章列表信息 /// </summary> /// <param name="request">页请求信息</param> /// <returns>文章列表分页信息</returns> [HttpPost] [ModuleInfo] [Description("读取")] public virtual PageData<PostOutputDto> Read(PageRequest request) { Check.NotNull(request, nameof(request)); Expression<Func<Post, bool>> predicate = FilterService.GetExpression<Post>(request.FilterGroup); var page = BlogsContract.Posts.ToPage<Post, PostOutputDto>(predicate, request.PageCondition); return page.ToPageData(); } /// <summary> /// 新增文章信息 /// </summary> /// <param name="dtos">文章信息输入DTO</param> /// <returns>JSON操作结果</returns> [HttpPost] [ModuleInfo] [DependOnFunction("Read")] [ServiceFilter(typeof(UnitOfWorkAttribute))] [Description("新增")] public virtual async Task<AjaxResult> Create(PostInputDto[] dtos) { Check.NotNull(dtos, nameof(dtos)); OperationResult result = await BlogsContract.CreatePosts(dtos); return result.ToAjaxResult(); } /// <summary> /// 更新文章信息 /// </summary> /// <param name="dtos">文章信息输入DTO</param> /// <returns>JSON操作结果</returns> [HttpPost] [ModuleInfo] [DependOnFunction("Read")] [ServiceFilter(typeof(UnitOfWorkAttribute))] [Description("更新")] public virtual async Task<AjaxResult> Update(PostInputDto[] dtos) { Check.NotNull(dtos, nameof(dtos)); OperationResult result = await BlogsContract.UpdatePosts(dtos); return result.ToAjaxResult(); } /// <summary> /// 删除文章信息 /// </summary> /// <param name="ids">文章信息编号</param> /// <returns>JSON操作结果</returns> [HttpPost] [ModuleInfo] [DependOnFunction("Read")] [ServiceFilter(typeof(UnitOfWorkAttribute))] [Description("删除")] public virtual async Task<AjaxResult> Delete(int[] ids) { Check.NotNull(ids, nameof(ids)); OperationResult result = await BlogsContract.DeletePosts(ids); return result.ToAjaxResult(); } } }
30.964912
108
0.597167
[ "Apache-2.0" ]
gmf520/osharp-docs-samples
samples/Liuliu.Blogs/src/Liuliu.Blogs.Web/Areas/Admin/Controllers/Blogs/PostController.cs
3,784
C#
using ESTAPAR.Core.Application; using ESTAPAR.Core.Domain.Interfaces.Infrastructures.Contexts; using ESTAPAR.Core.Domain.Interfaces.Infrastructures.Repositories; using ESTAPAR.Core.Domain.Interfaces.Services; using ESTAPAR.Core.Domain.Services; using ESTAPAR.Infrastructures.Data; using ESTAPAR.Infrastructures.Data.Repositories; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace ESTAPAR.Middleware { public static class Configurations { public static IServiceCollection AddMiddleware(this IServiceCollection services, IConfiguration configuration, Assembly presentationAssembly) { services.AddDbContext<IEstaparDbContext, EstaparDbContext>(options => options.UseSqlServer( configuration.GetConnectionString("DefaultConnection"), sql => sql.MigrationsAssembly(presentationAssembly.GetName().Name))); services.AddTransient<ICarroRepository, CarroRepository>(); services.AddTransient<IManobraRepository, ManobraRepository>(); services.AddTransient<IManobristaRepository, ManobristaRepository>(); services.AddTransient<ICarroDomainService, CarroDomainService>(); services.AddTransient<IManobraDomainService, ManobraDomainService>(); services.AddTransient<IManobristaDomainService, ManobristaDomainService>(); services.AddTransient<CarroApplicationService>(); services.AddTransient<ManobraApplicationService>(); services.AddTransient<ManobristaApplicationService>(); // YOUR CODE GOES HERE return services; } public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app) { // YOUR CODE GOES HERE return app; } } }
40.9375
149
0.728244
[ "MIT" ]
isilveira/challenge-project-estapar
src/ESTAPAR.Middleware/Configurations.cs
1,967
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("Dictionary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Dictionary")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34d678b8-7be2-445a-8144-887408f72619")] // 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.513514
84
0.747118
[ "MIT" ]
jem-green/Dictionary
Properties/AssemblyInfo.cs
1,391
C#
// Modified by SignalFx using System.Threading.Tasks; namespace SignalFx.Tracing.Agent { internal interface IApi { Task SendTracesAsync(Span[][] traces); } }
16.272727
46
0.681564
[ "Apache-2.0" ]
AJJLVizio/signalfx-dotnet-tracing
src/Datadog.Trace/Agent/IApi.cs
179
C#
#pragma checksum "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Movies_Create), @"mvc.1.0.view", @"/Views/Movies/Create.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\_ViewImports.cshtml" using WebApplication1; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\_ViewImports.cshtml" using WebApplication1.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d", @"/Views/Movies/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"729efaa87342638aecfe1a972ce9f9f8dff55b4c", @"/Views/_ViewImports.cshtml")] public class Views_Movies_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<WebApplication1.Models.Movie> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" ViewData["Title"] = "Create"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Create</h1>\r\n\r\n<h4>Movie</h4>\r\n<hr />\r\n<div class=\"row\">\r\n <div class=\"col-md-4\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d6147", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d6417", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #nullable restore #line 14 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d8189", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 16 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d9829", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 17 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d11463", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 18 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d13238", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 21 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ReleaseDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d14885", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 22 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ReleaseDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d16526", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 23 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ReleaseDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d18307", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 26 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d19948", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 27 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d21583", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 28 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d23358", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 31 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d24999", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 32 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d26634", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 33 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Create\" class=\"btn btn-primary\" />\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n</div>\r\n\r\n<div>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7ff3e87db3b9b246d9f26278ba4ec0c5c0ed8a7d29725", async() => { WriteLiteral("Back to List"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>\r\n\r\n"); DefineSection("Scripts", async() => { WriteLiteral("\r\n"); #nullable restore #line 47 "C:\Users\kotik\Desktop\proga\dotnet\tut10\tutorial-10-lacrit-a1mond\WebApplication1\WebApplication1\Views\Movies\Create.cshtml" await Html.RenderPartialAsync("_ValidationScriptsPartial"); #line default #line hidden #nullable disable } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<WebApplication1.Models.Movie> Html { get; private set; } } } #pragma warning restore 1591
75.089623
351
0.740405
[ "MIT" ]
a1mond/APBD
Tutorial10/WebApplication1/WebApplication1/obj/Debug/net5.0/Razor/Views/Movies/Create.cshtml.g.cs
31,838
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Marketplace.Models { /// <summary> /// Defines values for IdentityType. /// </summary> public static class IdentityType { public const string User = "User"; public const string Application = "Application"; public const string ManagedIdentity = "ManagedIdentity"; public const string Key = "Key"; } }
29.88
74
0.692102
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/marketplace/Microsoft.Azure.Management.Marketplace/src/Generated/Models/IdentityType.cs
747
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Linq; using System.Management.Automation; using static Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.PowerShell.PsHelpOutputExtensions; namespace Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.PowerShell { internal class HelpMetadataOutput { public MarkdownHelpInfo HelpInfo { get; } public HelpMetadataOutput(MarkdownHelpInfo helpInfo) { HelpInfo = helpInfo; } public override string ToString() => $@"--- external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} Module Name: {HelpInfo.ModuleName} online version: {HelpInfo.OnlineVersion} schema: {HelpInfo.Schema.ToString(3)} --- "; } internal class HelpSyntaxOutput { public MarkdownSyntaxHelpInfo SyntaxInfo { get; } public bool HasMultipleParameterSets { get; } public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) { SyntaxInfo = syntaxInfo; HasMultipleParameterSets = hasMultipleParameterSets; } public override string ToString() { var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; return $@"{psnText}``` {SyntaxInfo.SyntaxText} ``` "; } } internal class HelpExampleOutput { public MarkdownExampleHelpInfo ExampleInfo { get; } public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) { ExampleInfo = exampleInfo; } public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} {ExampleCodeHeader} {ExampleInfo.Code} {ExampleCodeFooter} {ExampleInfo.Description.ToDescriptionFormat()} "; } internal class HelpParameterOutput { public MarkdownParameterHelpInfo ParameterInfo { get; } public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) { ParameterInfo = parameterInfo; } public override string ToString() { var pipelineInputTypes = new[] { ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty }.JoinIgnoreEmpty(", "); var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName ? $@"{true} ({pipelineInputTypes})" : false.ToString(); return $@"### -{ParameterInfo.Name} {ParameterInfo.Description.ToDescriptionFormat()} ```yaml Type: {ParameterInfo.Type.FullName} Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} Required: {ParameterInfo.IsRequired} Position: {ParameterInfo.Position} Default value: {ParameterInfo.DefaultValue} Accept pipeline input: {pipelineInput} Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} ``` "; } } internal class ModulePageMetadataOutput { public PsModuleHelpInfo ModuleInfo { get; } private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/powershell/module/"; public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) { ModuleInfo = moduleInfo; } public override string ToString() => $@"--- Module Name: {ModuleInfo.Name} Module Guid: {ModuleInfo.Guid} Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} Help Version: 1.0.0.0 Locale: en-US --- "; } internal class ModulePageCmdletOutput { public MarkdownHelpInfo HelpInfo { get; } public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) { HelpInfo = helpInfo; } public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) {HelpInfo.Synopsis.ToDescriptionFormat()} "; } internal static class PsHelpOutputExtensions { public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); public static string ReplaceBrWithNewline(this string text) => text?.Replace("<br>", $"{Environment.NewLine}"); public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) { var description = text?.ReplaceBrWithNewline(); description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; return description?.ReplaceSentenceEndWithNewline().Trim(); } public const string ExampleNameHeader = "### "; public const string ExampleCodeHeader = "```powershell"; public const string ExampleCodeFooter = "```"; public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); } }
37.561798
192
0.659438
[ "MIT" ]
Agazoth/azure-powershell
src/DataBox/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs
6,509
C#
using AutoMapper; namespace DefaultTemplate.Application.Common.Mappings { public interface IMapFrom<T> { void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); } }
20.8
81
0.6875
[ "MIT" ]
Magicianred/ASP.NET-Server-Architectures
3. Clean Architecture Template/src/Application/Common/Mappings/IMapFrom.cs
210
C#
namespace FredrikScript.Core.Expressions { public abstract class UnaryExpression : Expression { public UnaryExpression(Context context, SourceInformation sourceInformation, Expression value) : base(context, sourceInformation) { Value = value; } public Expression Value { get; } } }
26.153846
137
0.667647
[ "MIT" ]
FredrikAleksander/FredrikScript
FredrikScript.Core/Expressions/UnaryExpression.cs
342
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions; /// <summary>Creates a new firewall rule or updates an existing firewall rule.</summary> /// <remarks> /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMySQL/servers/{serverName}/firewallRules/{firewallRuleName}" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMySqlFirewallRule_CreateExpanded", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule))] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Description(@"Creates a new firewall rule or updates an existing firewall rule.")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Generated] public partial class NewAzMySqlFirewallRule_CreateExpanded : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.MySql.MySql Client => Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>The end IP address of the server firewall rule. Must be IPv4 format.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The end IP address of the server firewall rule. Must be IPv4 format.")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The end IP address of the server firewall rule. Must be IPv4 format.", SerializedName = @"endIpAddress", PossibleTypes = new [] { typeof(string) })] public string EndIPAddress { get => ParametersBody.EndIPAddress ?? null; set => ParametersBody.EndIPAddress = value; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary>Backing field for <see cref="Name" /> property.</summary> private string _name; /// <summary>The name of the server firewall rule.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server firewall rule.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the server firewall rule.", SerializedName = @"firewallRuleName", PossibleTypes = new [] { typeof(string) })] [global::System.Management.Automation.Alias("FirewallRuleName")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string Name { get => this._name; set => this._name = value; } /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary>Backing field for <see cref="ParametersBody" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.FirewallRule(); /// <summary>Represents a server firewall rule.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary> private string _resourceGroupName; /// <summary>The name of the resource group. The name is case insensitive.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the resource group. The name is case insensitive.", SerializedName = @"resourceGroupName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } /// <summary>Backing field for <see cref="ServerName" /> property.</summary> private string _serverName; /// <summary>The name of the server.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the server.", SerializedName = @"serverName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string ServerName { get => this._serverName; set => this._serverName = value; } /// <summary>The start IP address of the server firewall rule. Must be IPv4 format.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The start IP address of the server firewall rule. Must be IPv4 format.")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The start IP address of the server firewall rule. Must be IPv4 format.", SerializedName = @"startIpAddress", PossibleTypes = new [] { typeof(string) })] public string StartIPAddress { get => ParametersBody.StartIPAddress ?? null; set => ParametersBody.StartIPAddress = value; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of NewAzMySqlFirewallRule_CreateExpanded</returns> public Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets.NewAzMySqlFirewallRule_CreateExpanded Clone() { var clone = new NewAzMySqlFirewallRule_CreateExpanded(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.ParametersBody = this.ParametersBody; clone.SubscriptionId = this.SubscriptionId; clone.ResourceGroupName = this.ResourceGroupName; clone.ServerName = this.ServerName; clone.Name = this.Name; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary> /// Intializes a new instance of the <see cref="NewAzMySqlFirewallRule_CreateExpanded" /> cmdlet class. /// </summary> public NewAzMySqlFirewallRule_CreateExpanded() { } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'FirewallRulesCreateOrUpdate' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.FirewallRulesCreateOrUpdate(SubscriptionId, ResourceGroupName, ServerName, Name, ParametersBody, onOk, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ServerName=ServerName,Name=Name,body=ParametersBody}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule WriteObject((await response)); } } } }
71.122807
451
0.662926
[ "MIT" ]
3quanfeng/azure-powershell
src/MySql/generated/cmdlets/NewAzMySqlFirewallRule_CreateExpanded.cs
31,977
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using TicketCore.Common; using TicketCore.Models.MenuCategorys; using TicketCore.ViewModels.MenuCategorys; using TicketCore.ViewModels.Ordering; namespace TicketCore.Data.MenuCategorys.Queries { public class MenuCategoryQueries : IMenuCategoryQueries { private readonly VueTicketDbContext _vueTicketDbContext; private readonly IMemoryCache _cache; public MenuCategoryQueries(VueTicketDbContext vueTicketDbContext, IMemoryCache cache) { _vueTicketDbContext = vueTicketDbContext; _cache = cache; } public EditMenuCategoriesViewModel GetCategoryByMenuCategoryIdForEdit(int? menuCategoryId) { try { var result = (from category in _vueTicketDbContext.MenuCategorys.AsNoTracking() where category.MenuCategoryId == menuCategoryId select new EditMenuCategoriesViewModel() { RoleId = category.RoleId, Status = category.Status, MenuCategoryId = category.MenuCategoryId, MenuCategoryName = category.MenuCategoryName }).SingleOrDefault(); return result; } catch (Exception) { throw; } } public MenuCategory GetCategoryByMenuCategoryId(int? menuCategoryId) { var result = (from category in _vueTicketDbContext.MenuCategorys.AsNoTracking() where category.MenuCategoryId == menuCategoryId select category).SingleOrDefault(); return result; } public List<SelectListItem> GetCategorybyRoleId(int? roleId) { var categoryList = (from cat in _vueTicketDbContext.MenuCategorys where cat.Status == true && cat.RoleId == roleId select new SelectListItem() { Text = cat.MenuCategoryName, Value = cat.MenuCategoryId.ToString() }).ToList(); categoryList.Insert(0, new SelectListItem() { Value = "", Text = "-----Select-----" }); return categoryList; } public IQueryable<MenuCategoryGridViewModel> ShowAllMenusCategory(string sortColumn, string sortColumnDir, string search) { try { var queryableMenuMaster = (from menuCategory in _vueTicketDbContext.MenuCategorys join roleMaster in _vueTicketDbContext.RoleMasters on menuCategory.RoleId equals roleMaster.RoleId select new MenuCategoryGridViewModel() { Status = menuCategory.Status == true ? "Active" : "InActive", MenuCategoryId = menuCategory.MenuCategoryId, MenuCategoryName = menuCategory.MenuCategoryName, RoleName = roleMaster.RoleName } ); if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir))) { queryableMenuMaster = queryableMenuMaster.OrderBy(sortColumn + " " + sortColumnDir); } if (!string.IsNullOrEmpty(search)) { queryableMenuMaster = queryableMenuMaster.Where(m => m.MenuCategoryName.Contains(search) || m.MenuCategoryName.Contains(search)); } return queryableMenuMaster; } catch (Exception) { throw; } } public bool CheckCategoryNameExists(string menuCategoryName, int roleId) { try { var result = (from category in _vueTicketDbContext.MenuCategorys.AsNoTracking() where category.MenuCategoryName == menuCategoryName && category.RoleId == roleId select category).Any(); return result; } catch (Exception) { throw; } } public List<MenuCategory> GetCategoryByRoleId(int? roleId) { var key = $"{AllMemoryCacheKeys.MenuCategoryKey}_{roleId}"; List<MenuCategory> menuCategory; if (_cache.Get(key) == null) { var result = (from category in _vueTicketDbContext.MenuCategorys.AsNoTracking() orderby category.SortingOrder ascending where category.RoleId == roleId && category.Status == true select category).ToList(); MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddDays(7), Priority = CacheItemPriority.Normal }; menuCategory = _cache.Set<List<MenuCategory>>(key, result, cacheExpirationOptions); } else { menuCategory = _cache.Get(key) as List<MenuCategory>; } return menuCategory; } public List<MenuCategoryOrderingVm> ListofMenubyRoleCategoryId(int roleId) { var listofmenucategories = (from tempmenu in _vueTicketDbContext.MenuCategorys where tempmenu.Status == true && tempmenu.RoleId == roleId orderby tempmenu.SortingOrder ascending select new MenuCategoryOrderingVm { MenuCategoryId = tempmenu.MenuCategoryId, MenuCategoryName = tempmenu.MenuCategoryName }).ToList(); return listofmenucategories; } } }
40.071429
149
0.513666
[ "MIT" ]
pankajkadam333/VueTicket
VueTicketCore/TicketCore.Data/MenuCategorys/Queries/MenuCategoryQueries.cs
6,734
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ActiveSubmenuTracker : MonoBehaviour { void Start() { m_Animator = GetComponent<Animator>(); } void Update() { if (Game.game && Game.game.clientFrontend) { m_Animator.SetInteger("Menu_Number", Game.game.clientFrontend.ActiveMainMenuNumber); } else m_Animator.SetInteger("Menu_Number", -1); } Animator m_Animator; }
20.958333
96
0.634195
[ "MIT" ]
The-ULTIMATE-MULTIPLAYER-EXPERIENCE/Ultimate-Archery-Multiplayer-Unity-Game
DOTSSample-master/Assets/Scripts/Game/Frontend/ActiveSubmenuTracker.cs
505
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcThrottleImproved; namespace MvcThrottle.Demo.Controllers { public class HomeController : BaseController { public ActionResult Index() { return View(); } [EnableThrottling(PerSecond = 2, PerMinute = 5)] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } [EnableThrottling(PerSecond = 2, SuspendTime = 30)] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
22.151515
67
0.592339
[ "MIT" ]
weslleyramos/MvcThrottleImproved
MvcThrottle.Demo/Controllers/HomeController.cs
733
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Oci.DataScience.Outputs { [OutputType] public sealed class GetModelDeploymentsModelDeploymentModelDeploymentConfigurationDetailsResult { /// <summary> /// The type of the model deployment. /// </summary> public readonly string DeploymentType; /// <summary> /// The model configuration details. /// </summary> public readonly Outputs.GetModelDeploymentsModelDeploymentModelDeploymentConfigurationDetailsModelConfigurationDetailsResult ModelConfigurationDetails; [OutputConstructor] private GetModelDeploymentsModelDeploymentModelDeploymentConfigurationDetailsResult( string deploymentType, Outputs.GetModelDeploymentsModelDeploymentModelDeploymentConfigurationDetailsModelConfigurationDetailsResult modelConfigurationDetails) { DeploymentType = deploymentType; ModelConfigurationDetails = modelConfigurationDetails; } } }
36.555556
159
0.734802
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/DataScience/Outputs/GetModelDeploymentsModelDeploymentModelDeploymentConfigurationDetailsResult.cs
1,316
C#
using Command.Core.Commands; using Command.Core.Contract; using Command.Core.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace Command.Test { [TestClass] public class SimpleRemoteControlTest { [TestMethod] public void Quando_eu_pressionar_o_botao_de_ligar() { //arrange var simpleRemoteControl = new SimpleRemoteControl(new List<ICommand>(7) { new LightOnCommand(new Light()), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand() }, new List<ICommand>(7) { new LightOffCommand(new Light()), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand(), new NoCommand() }, new NoCommand()); //action simpleRemoteControl.SetCommand(0, new LightOnCommand(new Light()), new LightOffCommand(new Light())); simpleRemoteControl.OnButtonWasPressed(0); simpleRemoteControl.OffButtonWasPressed(0); } } }
29.6
113
0.538288
[ "MIT" ]
adrianomota/design-patterns
test/Command.Test/SimpleRemoteControlTest.cs
1,334
C#
using System; using System.Collections; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Serialization.Formatters; using System.Threading; using System.Windows.Forms; using System.Xml; using System.Xml.Linq; using Cim.Eap.Properties; using Cim.Management; using Cim.Services; using log4net; using log4net.Core; using log4net.Layout; using log4net.ObjectRenderer; using log4net.Repository.Hierarchy; using Secs4Net; using Secs4Net.Sml; namespace Cim.Eap { static class Program { sealed class SecsMessageRenderer : IObjectRenderer { public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) { var msgInfo = obj as SecsMessageLogInfo; if (msgInfo != null) { writer.WriteLine($"EAP {(msgInfo.In ? "<<" : ">>")} EQP : [id=0x{msgInfo.SystemByte:X8}]"); msgInfo.Message.WriteTo(writer); } } } [STAThread]//Postman COM interop need STA appartment [LoaderOptimization(LoaderOptimization.MultiDomainHost)] static void Main() { Application.ThreadException += (sender, e) => { EapLogger.Error(e.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => { EapLogger.Error(e.ExceptionObject as Exception); if (e.IsTerminating) MessageBox.Show(e.ExceptionObject.ToString(), "程式發生嚴重錯誤而終止"); }; var fileAppender = new RollingLogFileAppender { Layout = new PatternLayout("%date{HH:mm:ss,fff} %-6level [%4thread] %message%newline") }; fileAppender.ActivateOptions(); var l = (Logger)LogManager.GetLogger("EAP").Logger; l.Level = Level.All; l.Repository.RendererMap.Put(typeof(SecsMessageLogInfo), new SecsMessageRenderer()); l.Repository.Threshold = Level.All; l.Repository.Configured = true; l.AddAppender(fileAppender); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; ChannelServices.RegisterChannel( new TcpChannel( new Hashtable { ["port"] = 0, ["bindTo"] = Settings.Default.TcpBindTo }, null, new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full }), false); bool newMutexCreated; using (new Mutex(true, "EAP" + EAPConfig.Instance.ToolId, out newMutexCreated)) { if (!newMutexCreated) { MessageBox.Show($"系統中已經執行了EAP:{EAPConfig.Instance.ToolId}啟動錯誤"); return; } EapLogger.Info("__________________ EAP Started __________________"); var form = new HostMainForm(); RemotingServices.Marshal(form, EAPConfig.Instance.ToolId, typeof(ISecsDevice)); PublishZService(); Application.Run(form); EapLogger.Info("___________________ EAP Stop ____________________"); } } internal static void PublishZService() { var channels = ChannelServices.RegisteredChannels.OfType<IChannelReceiver>(); var url = channels.First().GetUrlsForUri(EAPConfig.Instance.ToolId)[0]; var serviceManager = (IServiceManager<ISecsDevice>)RemotingServices.Connect(typeof(IServiceManager<ISecsDevice>), Settings.Default.ZUrl); serviceManager.Publish(EAPConfig.Instance.ToolId, url); } private static readonly XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Indent = true }; public static string ToFormatedXml(this XDocument xmlDoc) { using (var swr = new StringWriter()) { using (var xwr = XmlWriter.Create(swr, xmlWriterSettings)) xmlDoc.WriteTo(xwr); return swr.ToString(); } } public static Action<T> AddHandler<T, TKey>(this ConcurrentDictionary<TKey, Action<T>> handlers, TKey key, Action<T> handler) => handlers.AddOrUpdate(key, handler, (_, old) => old += handler); public static Action<T> RemoveHandler<T, TKey>(this ConcurrentDictionary<TKey, Action<T>> handlers, TKey key, Action<T> handler) => handlers.AddOrUpdate(key, (Action<T>)null, (_, old) => old -= handler); public static int GetKey(this SecsEventSubscription subscription) => subscription.Filter.S << 8 | subscription.Filter.F; public static int GetKey(this SecsMessage msg) => msg.S << 8 | msg.F; } sealed class SecsMessageLogInfo { public bool In; public int SystemByte; public SecsMessage Message; } }
39.53125
149
0.614822
[ "MIT" ]
FanYuchi/secs4net
secs4net/Core/EAPHost/Program.cs
5,108
C#
/* Copyright 2019 Esri 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. */ namespace RSSWeatherLayer { partial class PropertySheet { /// <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 Component 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.SuspendLayout(); // // PropertySheet // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Name = "PropertySheet"; this.Size = new System.Drawing.Size(541, 398); this.ResumeLayout(false); } #endregion } }
27.546875
103
0.663642
[ "Apache-2.0" ]
Esri/arcobjects-sdk-community-samples
Net/GraphicsPipeline/RSSWeatherLayer/CSharp/PropertySheet.Designer.cs
1,763
C#
using System; using System.Threading.Tasks; using DomainModel; using IdeaBlade.EntityModel; namespace DomainServices.Services { public class DuplicateAccoService { public static async Task ExecuteAsync(int fromaccoid, int toaccoid, string language) { EntityManager mgr = new AccoBookingEntities(); var result = await mgr.InvokeServerMethodAsync(Library.Acco, Method.DuplicateAcco, fromaccoid, toaccoid, language); var message = (string) result; if (!String.IsNullOrEmpty(message)) throw (new Exception(message)); } } }
21.407407
121
0.723183
[ "MIT" ]
jkattestaart/AccoBooking
DomainServices.SL/Services/DuplicateAccoService.cs
580
C#
// --------------------------------------------------------------------------------------- // <copyright file="NativeCallException.cs" company="SharpBlade"> // Copyright © 2013-2014 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: SharpBlade is in no way affiliated with Razer and/or any of // its employees and/or licensors. Adam Hellberg and/or Brandon Scott do not // take responsibility for any harm caused, direct or indirect, to any Razer // peripherals via the use of SharpBlade. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace SharpBlade.Razer { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; using SharpBlade.Annotations; using SharpBlade.Native; /// <summary> /// Exception for failures in native code provided by Razer. /// </summary> [Serializable] [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This is a special exception type.")] public class NativeCallException : SwitchbladeException { /// <summary> /// The name of the native function that failed. /// </summary> private readonly string _function; /// <summary> /// <see cref="HRESULT" /> obtained from calling the native function. /// </summary> private readonly HRESULT _hresult; /// <summary> /// Initializes a new instance of the <see cref="NativeCallException" /> class. /// </summary> /// <param name="function">The name of the function that failed.</param> /// <param name="hresult"><see cref="HRESULT" /> returned from the native function.</param> internal NativeCallException(string function, HRESULT hresult) : base( string.Format( CultureInfo.InvariantCulture, "Call to native RazerAPI function {0} failed with error message: {1}", function, HelperMethods.GetErrorMessage(hresult)), HelperMethods.GetWin32Exception(hresult)) { _function = function; _hresult = hresult; } /// <summary> /// Initializes a new instance of the <see cref="NativeCallException" /> class /// from serialization data. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> protected NativeCallException(SerializationInfo info, StreamingContext context) : base(info, context) { _function = info.GetString("Function"); _hresult = info.GetInt32("Hresult"); } /// <summary> /// Gets the name of the native function that failed. /// </summary> [PublicAPI] public string Function { get { return _function; } } /// <summary> /// Gets the <see cref="HRESULT" /> obtained from calling the native function. /// </summary> [CLSCompliant(false)] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hresult", Justification = "This name is derived from native code, so there's not much to do about it.")] public new HRESULT HResult { get { return _hresult; } } /// <summary> /// Adds object data to serialization object. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Function", _function); info.AddValue("HResult", (int)HResult); } } }
41.090909
113
0.606379
[ "MIT" ]
SharpBlade/SharpBlade
SharpBlade/Razer/NativeCallException.cs
5,427
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Module_9.Filters; namespace Module_9.Pages { [SimplePage] public class CustomModel : PageModel { public void OnGet() { } } }
18.105263
42
0.703488
[ "MIT" ]
daniil-lukashevich/core-lab
Lab/Module 9/Module 9/Pages/Custom.cshtml.cs
344
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace OpenIdMvc { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //将认证服务添加到依赖注入容器中 services.AddAuthentication(options => { //使用cookie作为验证用户的主要方法 options.DefaultScheme = "Cookies"; //用户登录时使用odic方案 options.DefaultChallengeScheme = "oidc"; }) //添加cookie的处理程序 .AddCookie() //配置执行openid connection协议的处理程序 //.AddOpenIdConnect("oidc", options => //{ // //用于在OpenID Connect协议完成后使用cookie处理程序发出cookie // options.SignInScheme = "Cookies"; // //identity server 4 的服务地址 // options.Authority = "http://localhost:5000"; // options.RequireHttpsMetadata = false; // //通过clientid识别客户端 // options.ClientId = "mvc"; // //用于在Cookie中保存IdentityServer中的令牌 // options.SaveTokens = true; //}) // 使用Hybrid Flow并添加API访问控制 .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; options.ClientId = "mvc"; options.ClientSecret = "secret"; options.ResponseType = "code id_token"; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.Scope.Add("api1"); options.Scope.Add("offline_access"); }); //1. services.AddHttpClient(); //2. 指定HttpClient名字 services.AddHttpClient("github", client => { client.BaseAddress = new Uri("https://api.github.com/"); client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); // ... }); //3.使用自定义的HttpClient类 services.AddHttpClient<IGitHubClient,GitHubClient>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); //添加authentication中间件 app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
34.834711
119
0.541637
[ "Apache-2.0" ]
leili-ncut/IdentityServer4.Samples.Test
QuickStarts/1_ClientCredentials/OpenIdMvc/Startup.cs
4,453
C#
using UnityEngine; /// <summary> /// Be aware this will not prevent a non singleton constructor /// such as `T myT = new T();` /// To prevent that, add `protected T () {}` to your singleton class. /// /// As a note, this is made as MonoBehaviour because we need Coroutines. /// </summary> public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { private static T _instance; private static object _lock = new object(); public static T Instance { get { if (applicationIsQuitting) { Debug.LogWarning("[Singleton] Instance '" + typeof(T) + "' already destroyed on application quit." + " Won't create again - returning null."); return null; } lock (_lock) { if (_instance == null) { _instance = (T)FindObjectOfType(typeof(T)); if (FindObjectsOfType(typeof(T)).Length > 1) { Debug.LogError("[Singleton] Something went really wrong " + " - there should never be more than 1 singleton!" + " Reopening the scene might fix it."); return _instance; } if (_instance == null) { GameObject singleton = new GameObject(); _instance = singleton.AddComponent<T>(); singleton.name = "(singleton) " + typeof(T).ToString(); //DontDestroyOnLoad(singleton); Debug.Log("[Singleton] An instance of " + typeof(T) + " is needed in the scene, so '" + singleton + "' was created with DontDestroyOnLoad."); } else { Debug.Log("[Singleton] Using instance already created: " + _instance.gameObject.name); } } return _instance; } } } private static bool applicationIsQuitting = false; /// <summary> /// When Unity quits, it destroys objects in a random order. /// In principle, a Singleton is only destroyed when application quits. /// If any script calls Instance after it have been destroyed, /// it will create a buggy ghost object that will stay on the Editor scene /// even after stopping playing the Application. Really bad! /// So, this was made to be sure we're not creating that buggy ghost object. /// </summary> public void OnDestroy() { //applicationIsQuitting = true; } }
30.492958
77
0.649885
[ "MIT" ]
carlsc2/BigQuestionRepo
OldPeopleInSpace/Assets/Scripts/Singleton.cs
2,167
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Text.Json.Serialization { /// <summary> /// Converts an object or value to or from JSON. /// </summary> /// <typeparam name="T">The <see cref="Type"/> to convert.</typeparam> public abstract partial class JsonConverter<T> : JsonConverter { /// <summary> /// When overidden, constructs a new <see cref="JsonConverter{T}"/> instance. /// </summary> protected internal JsonConverter() { // Today only typeof(object) can have polymorphic writes. // In the future, this will be check for !IsSealed (and excluding value types). CanBePolymorphic = TypeToConvert == JsonClassInfo.ObjectType; IsValueType = TypeToConvert.IsValueType; CanBeNull = !IsValueType || TypeToConvert.IsNullableOfT(); IsInternalConverter = GetType().Assembly == typeof(JsonConverter).Assembly; if (HandleNull) { HandleNullOnRead = true; HandleNullOnWrite = true; } // For the HandleNull == false case, either: // 1) The default values are assigned in this type's virtual HandleNull property // or // 2) A converter overroad HandleNull and returned false so HandleNullOnRead and HandleNullOnWrite // will be their default values of false. CanUseDirectReadOrWrite = !CanBePolymorphic && IsInternalConverter && ClassType == ClassType.Value; } /// <summary> /// Determines whether the type can be converted. /// </summary> /// <remarks> /// The default implementation is to return True when <paramref name="typeToConvert"/> equals typeof(T). /// </remarks> /// <param name="typeToConvert"></param> /// <returns>True if the type can be converted, False otherwise.</returns> public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(T); } internal override ClassType ClassType => ClassType.Value; internal sealed override JsonPropertyInfo CreateJsonPropertyInfo() { return new JsonPropertyInfo<T>(); } internal override sealed JsonParameterInfo CreateJsonParameterInfo() { return new JsonParameterInfo<T>(); } internal override Type? ElementType => null; /// <summary> /// Indicates whether <see langword="null"/> should be passed to the converter on serialization, /// and whether <see cref="JsonTokenType.Null"/> should be passed on deserialization. /// </summary> /// <remarks> /// The default value is <see langword="true"/> for converters for value types, and <see langword="false"/> for converters for reference types. /// </remarks> public virtual bool HandleNull { get { // HandleNull is only called by the framework once during initialization and any // subsequent calls elsewhere would just re-initialize to the same values (we don't // track a "hasInitialized" flag since that isn't necessary). // If the type doesn't support null, allow the converter a chance to modify. // These semantics are backwards compatible with 3.0. HandleNullOnRead = !CanBeNull; // The framework handles null automatically on writes. HandleNullOnWrite = false; return false; } } /// <summary> /// Does the converter want to be called when reading null tokens. /// </summary> internal bool HandleNullOnRead { get; private set; } /// <summary> /// Does the converter want to be called for null values. /// </summary> internal bool HandleNullOnWrite { get; private set; } /// <summary> /// Can <see langword="null"/> be assigned to <see cref="TypeToConvert"/>? /// </summary> internal bool CanBeNull { get; } // This non-generic API is sealed as it just forwards to the generic version. internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object? value, JsonSerializerOptions options, ref WriteStack state) { T valueOfT = (T)value!; return TryWrite(writer, valueOfT, options, ref state); } // Provide a default implementation for value converters. internal virtual bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { Write(writer, value, options); return true; } // Provide a default implementation for value converters. internal virtual bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T? value) { value = Read(ref reader, typeToConvert, options); return true; } /// <summary> /// Read and convert the JSON to T. /// </summary> /// <remarks> /// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON is invalid. /// </remarks> /// <param name="reader">The <see cref="Utf8JsonReader"/> to read from.</param> /// <param name="typeToConvert">The <see cref="Type"/> being converted.</param> /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> /// <returns>The value that was converted.</returns> public abstract T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T? value) { if (ClassType == ClassType.Value) { // A value converter should never be within a continuation. Debug.Assert(!state.IsContinuation); // For perf and converter simplicity, handle null here instead of forwarding to the converter. if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } value = default; return true; } #if !DEBUG // For performance, only perform validation on internal converters on debug builds. if (IsInternalConverter) { if (state.Current.NumberHandling != null) { value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value); } else { value = Read(ref reader, typeToConvert, options); } } else #endif { JsonTokenType originalPropertyTokenType = reader.TokenType; int originalPropertyDepth = reader.CurrentDepth; long originalPropertyBytesConsumed = reader.BytesConsumed; if (state.Current.NumberHandling != null) { value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value); } else { value = Read(ref reader, typeToConvert, options); } VerifyRead( originalPropertyTokenType, originalPropertyDepth, originalPropertyBytesConsumed, isValueConverter: true, ref reader); } if (CanBePolymorphic && options.ReferenceHandler != null && value is JsonElement element) { // Edge case where we want to lookup for a reference when parsing into typeof(object) // instead of return `value` as a JsonElement. Debug.Assert(TypeToConvert == typeof(object)); if (JsonSerializer.TryGetReferenceFromJsonElement(ref state, element, out object? referenceValue)) { value = (T?)referenceValue; } } return true; } bool success; // Remember if we were a continuation here since Push() may affect IsContinuation. bool wasContinuation = state.IsContinuation; state.Push(); #if !DEBUG // For performance, only perform validation on internal converters on debug builds. if (IsInternalConverter) { if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead && !wasContinuation) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } // For perf and converter simplicity, handle null here instead of forwarding to the converter. value = default; success = true; } else { success = OnTryRead(ref reader, typeToConvert, options, ref state, out value); } } else #endif { if (!wasContinuation) { // For perf and converter simplicity, handle null here instead of forwarding to the converter. if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } value = default; state.Pop(true); return true; } Debug.Assert(state.Current.OriginalTokenType == JsonTokenType.None); state.Current.OriginalTokenType = reader.TokenType; Debug.Assert(state.Current.OriginalDepth == 0); state.Current.OriginalDepth = reader.CurrentDepth; } success = OnTryRead(ref reader, typeToConvert, options, ref state, out value); if (success) { if (state.IsContinuation) { // The resumable converter did not forward to the next converter that previously returned false. ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } VerifyRead( state.Current.OriginalTokenType, state.Current.OriginalDepth, bytesConsumed: 0, isValueConverter: false, ref reader); // No need to clear state.Current.* since a stack pop will occur. } } state.Pop(success); return success; } internal override sealed bool TryReadAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state, out object? value) { bool success = TryRead(ref reader, TypeToConvert, options, ref state, out T? typedValue); value = typedValue; return success; } internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions options, ref WriteStack state) { if (writer.CurrentDepth >= options.EffectiveMaxDepth) { ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); } if (CanBePolymorphic) { if (value == null) { if (!HandleNullOnWrite) { writer.WriteNullValue(); } else { Debug.Assert(ClassType == ClassType.Value); Debug.Assert(!state.IsContinuation); int originalPropertyDepth = writer.CurrentDepth; Write(writer, value, options); VerifyWrite(originalPropertyDepth, writer); } return true; } Type type = value.GetType(); if (type == JsonClassInfo.ObjectType) { writer.WriteStartObject(); writer.WriteEndObject(); return true; } if (type != TypeToConvert && IsInternalConverter) { // For internal converter only: Handle polymorphic case and get the new converter. // Custom converter, even though polymorphic converter, get called for reading AND writing. JsonConverter jsonConverter = state.Current.InitializeReEntry(type, options); if (jsonConverter != this) { // We found a different converter; forward to that. return jsonConverter.TryWriteAsObject(writer, value, options, ref state); } } } else if (value == null && !HandleNullOnWrite) { // We do not pass null values to converters unless HandleNullOnWrite is true. Null values for properties were // already handled in GetMemberAndWriteJson() so we don't need to check for IgnoreNullValues here. writer.WriteNullValue(); return true; } if (ClassType == ClassType.Value) { Debug.Assert(!state.IsContinuation); int originalPropertyDepth = writer.CurrentDepth; if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) { WriteNumberWithCustomHandling(writer, value, state.Current.NumberHandling.Value); } else { Write(writer, value, options); } VerifyWrite(originalPropertyDepth, writer); return true; } bool isContinuation = state.IsContinuation; state.Push(); if (!isContinuation) { Debug.Assert(state.Current.OriginalDepth == 0); state.Current.OriginalDepth = writer.CurrentDepth; } bool success = OnTryWrite(writer, value, options, ref state); if (success) { VerifyWrite(state.Current.OriginalDepth, writer); // No need to clear state.Current.OriginalDepth since a stack pop will occur. } state.Pop(success); return success; } internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { Debug.Assert(value != null); if (!IsInternalConverter) { return TryWrite(writer, value, options, ref state); } Debug.Assert(this is JsonDictionaryConverter<T>); if (writer.CurrentDepth >= options.EffectiveMaxDepth) { ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); } JsonDictionaryConverter<T> dictionaryConverter = (JsonDictionaryConverter<T>)this; bool isContinuation = state.IsContinuation; bool success; state.Push(); if (!isContinuation) { Debug.Assert(state.Current.OriginalDepth == 0); state.Current.OriginalDepth = writer.CurrentDepth; } // Ignore the naming policy for extension data. state.Current.IgnoreDictionaryKeyPolicy = true; success = dictionaryConverter.OnWriteResume(writer, value, options, ref state); if (success) { VerifyWrite(state.Current.OriginalDepth, writer); } state.Pop(success); return success; } internal sealed override Type TypeToConvert => typeof(T); internal void VerifyRead(JsonTokenType tokenType, int depth, long bytesConsumed, bool isValueConverter, ref Utf8JsonReader reader) { switch (tokenType) { case JsonTokenType.StartArray: if (reader.TokenType != JsonTokenType.EndArray) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } else if (depth != reader.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } break; case JsonTokenType.StartObject: if (reader.TokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } else if (depth != reader.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } break; default: // A non-value converter (object or collection) should always have Start and End tokens. // A value converter should not make any reads. if (!isValueConverter || reader.BytesConsumed != bytesConsumed) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } // Should not be possible to change token type. Debug.Assert(reader.TokenType == tokenType); break; } } internal void VerifyWrite(int originalDepth, Utf8JsonWriter writer) { if (originalDepth != writer.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); } } /// <summary> /// Write the value as JSON. /// </summary> /// <remarks> /// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON /// cannot be created. /// </remarks> /// <param name="writer">The <see cref="Utf8JsonWriter"/> to write to.</param> /// <param name="value">The value to convert.</param> /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> public abstract void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options); internal virtual T ReadWithQuotes(ref Utf8JsonReader reader) => throw new InvalidOperationException(); internal virtual void WriteWithQuotes(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options, ref WriteStack state) => throw new InvalidOperationException(); internal sealed override void WriteWithQuotesAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) => WriteWithQuotes(writer, (T)value, options, ref state); internal virtual T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) => throw new InvalidOperationException(); internal virtual void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T value, JsonNumberHandling handling) => throw new InvalidOperationException(); } }
40.137066
152
0.549565
[ "MIT" ]
ANISSARIZKY/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs
20,791
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Gov.Lclb.Cllb.Public.ViewModels { public class Contact { public string id { get; set; } public string name { get; set; } public string firstname { get; set; } public string middlename { get; set; } public string lastname { get; set; } public string emailaddress1 { get; set; } public string telephone1 { get; set; } public string address1_line1 { get; set; } public string address1_city { get; set; } public string address1_country { get; set; } public string address1_stateorprovince { get; set; } public string address1_postalcode { get; set; } public string address2_line1 { get; set; } public string address2_city { get; set; } public string address2_country { get; set; } public string address2_stateorprovince { get; set; } public string address2_postalcode { get; set; } public Boolean? adoxio_cansignpermanentchangeapplications { get; set; } public Boolean? adoxio_canattendeducationsessions { get; set; } public Boolean? adoxio_cansigntemporarychangeapplications { get; set; } public Boolean? adoxio_canattendcompliancemeetings { get; set; } public Boolean? adoxio_canobtainlicenceinfofrombranch { get; set; } public Boolean? adoxio_canrepresentlicenseeathearings { get; set; } public Boolean? adoxio_cansigngrocerystoreproofofsalesrevenue { get; set; } } }
26.733333
83
0.666459
[ "Apache-2.0" ]
danieltruong/ag-lclb-cllc-public
cllc-public-app/ViewModels/Contact.cs
1,606
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Automation.Peers.GridViewColumnHeaderAutomationPeer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Automation.Peers { public partial class GridViewColumnHeaderAutomationPeer : FrameworkElementAutomationPeer, System.Windows.Automation.Provider.IInvokeProvider, System.Windows.Automation.Provider.ITransformProvider { #region Methods and constructors protected override AutomationControlType GetAutomationControlTypeCore() { return default(AutomationControlType); } protected override string GetClassNameCore() { return default(string); } public override Object GetPattern(PatternInterface patternInterface) { return default(Object); } public GridViewColumnHeaderAutomationPeer(System.Windows.Controls.GridViewColumnHeader owner) : base (default(System.Windows.FrameworkElement)) { } void System.Windows.Automation.Provider.IInvokeProvider.Invoke() { } void System.Windows.Automation.Provider.ITransformProvider.Move(double x, double y) { } void System.Windows.Automation.Provider.ITransformProvider.Resize(double width, double height) { } void System.Windows.Automation.Provider.ITransformProvider.Rotate(double degrees) { } #endregion #region Properties and indexers bool System.Windows.Automation.Provider.ITransformProvider.CanMove { get { return default(bool); } } bool System.Windows.Automation.Provider.ITransformProvider.CanResize { get { return default(bool); } } bool System.Windows.Automation.Provider.ITransformProvider.CanRotate { get { return default(bool); } } #endregion } }
34.476636
463
0.746544
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/PresentationFramework/Sources/System.Windows.Automation.Peers.GridViewColumnHeaderAutomationPeer.cs
3,689
C#
using Bellatrix.Web.GettingStarted._12._Page_Objects; using NUnit.Framework; namespace Bellatrix.Web.GettingStarted { [TestFixture] public class PageObjectsTests : NUnit.WebTest { // 1. As you most probably noticed this is like the 4th time we use almost the same elements and logic inside our tests. // Similar test writing approach leads to unreadable and hard to maintain tests. // Because of that people use the so-called Page Object design pattern to reuse their elements and pages' logic. // BELLATRIX comes with powerful built-in page objects which are much more readable and maintainable than regular vanilla WebDriver ones. // 2. On most pages, you need to define elements. Placing them in a single place makes the changing of the locators easy. // It is a matter of choice whether to have action methods or not. If you use the same combination of same actions against a group of elements then // it may be a good idea to wrap them in a page object action method. In our example, we can wrap the filling the billing info such a method. // // 3. In the assertions file, we may place some predefined Validate methods. For example, if you always check the same email or title of a page, // there is no need to hardcode the string in each test. Later if the title is changed, you can do it in a single place. // The same is true about most of the things you can assert in your tests. // // This is the same test that doesn't use page objects. [Test] [Category(Categories.CI)] public void PurchaseRocketWithoutPageObjects() { App.Navigation.Navigate("http://demos.bellatrix.solutions/"); // Home page elements Select sortDropDown = App.Components.CreateByNameEndingWith<Select>("orderby"); Anchor protonMReadMoreButton = App.Components.CreateByInnerTextContaining<Anchor>("Read more"); Anchor addToCartFalcon9 = App.Components.CreateByAttributesContaining<Anchor>("data-product_id", "28").ToBeClickable(); Anchor viewCartButton = App.Components.CreateByClassContaining<Anchor>("added_to_cart wc-forward").ToBeClickable(); // Home Page actions sortDropDown.SelectByText("Sort by price: low to high"); protonMReadMoreButton.Hover(); addToCartFalcon9.Focus(); addToCartFalcon9.Click(); viewCartButton.Click(); // Cart page elements TextField couponCodeTextField = App.Components.CreateById<TextField>("coupon_code"); Button applyCouponButton = App.Components.CreateByValueContaining<Button>("Apply coupon"); Div messageAlert = App.Components.CreateByClassContaining<Div>("woocommerce-message"); Number quantityBox = App.Components.CreateByClassContaining<Number>("input-text qty text"); Button updateCart = App.Components.CreateByValueContaining<Button>("Update cart").ToBeClickable(); Span totalSpan = App.Components.CreateByXpath<Span>("//*[@class='order-total']//span"); Anchor proceedToCheckout = App.Components.CreateByClassContaining<Anchor>("checkout-button button alt wc-forward"); // Cart page actions couponCodeTextField.SetText("happybirthday"); applyCouponButton.Click(); messageAlert.ToHasContent().ToBeVisible().WaitToBe(); messageAlert.ValidateInnerTextIs("Coupon code applied successfully."); App.Browser.WaitForAjax(); totalSpan.ValidateInnerTextIs("54.00€"); proceedToCheckout.Click(); // Checkout page elements Heading billingDetailsHeading = App.Components.CreateByInnerTextContaining<Heading>("Billing details"); Anchor showLogin = App.Components.CreateByInnerTextContaining<Anchor>("Click here to login"); TextArea orderCommentsTextArea = App.Components.CreateById<TextArea>("order_comments"); TextField billingFirstName = App.Components.CreateById<TextField>("billing_first_name"); TextField billingLastName = App.Components.CreateById<TextField>("billing_last_name"); TextField billingCompany = App.Components.CreateById<TextField>("billing_company"); Select billingCountry = App.Components.CreateById<Select>("billing_country"); TextField billingAddress1 = App.Components.CreateById<TextField>("billing_address_1"); TextField billingAddress2 = App.Components.CreateById<TextField>("billing_address_2"); TextField billingCity = App.Components.CreateById<TextField>("billing_city"); Select billingState = App.Components.CreateById<Select>("billing_state").ToBeVisible().ToBeClickable(); TextField billingZip = App.Components.CreateById<TextField>("billing_postcode"); Phone billingPhone = App.Components.CreateById<Phone>("billing_phone"); Email billingEmail = App.Components.CreateById<Email>("billing_email"); CheckBox createAccountCheckBox = App.Components.CreateById<CheckBox>("createaccount"); RadioButton checkPaymentsRadioButton = App.Components.CreateByAttributesContaining<RadioButton>("for", "payment_method_cheque"); // Checkout page actions billingDetailsHeading.ToBeVisible().WaitToBe(); showLogin.ValidateHrefIs("http://demos.bellatrix.solutions/checkout/#"); showLogin.ValidateCssClassIs("showlogin"); orderCommentsTextArea.ScrollToVisible(); orderCommentsTextArea.SetText("Please send the rocket to my door step! And don't use the elevator, they don't like when it is not clean..."); billingFirstName.SetText("In"); billingLastName.SetText("Deepthought"); billingCompany.SetText("Automate The Planet Ltd."); billingCountry.SelectByText("Bulgaria"); billingAddress1.ValidatePlaceholderIs("House number and street name"); billingAddress1.SetText("bul. Yerusalim 5"); billingAddress2.SetText("bul. Yerusalim 6"); billingCity.SetText("Sofia"); billingState.SelectByText("Sofia-Grad"); billingZip.SetText("1000"); billingPhone.SetPhone("+00359894646464"); billingEmail.SetEmail("info@bellatrix.solutions"); createAccountCheckBox.Check(); checkPaymentsRadioButton.Click(); } [Test] public void PurchaseRocketWithPageObjects() { // 6. You can use the App GoTo method to navigate to the page and gets an instance of it. var homePage = App.GoTo<HomePage>(); // 7. After you have the instance, you can directly start using the action methods of the page. // As you can see the test became much shorter and more readable. // The additional code pays off in future when changes are made to the page, or you need to reuse some of the methods. homePage.FilterProducts(ProductFilter.Popularity); homePage.AddProductById(28); homePage.ViewCartButton.Click(); // 8. Navigate to the shopping cart page by clicking the view cart button, so we do not have to call the GoTo method. // But we still need an instance. We can get only an instance of the page through the App Create method. var cartPage = App.Create<CartPage>(); // 9. Removing all elements and some implementation details from the test made it much more clear and readable. // This is one of the strategies to follow for long-term successful automated testing. cartPage.ApplyCoupon("happybirthday"); cartPage.UpdateProductQuantity(1, 2); cartPage.AssertTotalPrice("114.00"); cartPage.ProceedToCheckout.Click(); // You can move the creation of the data objects in a separate factory method or class. var billingInfo = new BillingInfo { FirstName = "In", LastName = "Deepthought", Company = "Automate The Planet Ltd.", Country = "Bulgaria", Address1 = "bul. Yerusalim 5", Address2 = "bul. Yerusalim 6", City = "Sofia", State = "Sofia-Grad", Zip = "1000", Phone = "+00359894646464", Email = "info@bellatrix.solutions", ShouldCreateAccount = true, OrderCommentsTextArea = "cool product", }; var checkoutPage = App.Create<CheckoutPage>(); checkoutPage.FillBillingInfo(billingInfo); checkoutPage.CheckPaymentsRadioButton.Click(); } } }
63.60274
155
0.635042
[ "Apache-2.0" ]
48x16/BELLATRIX
templates/Bellatrix.Web.GettingStarted/12. Page Objects/PageObjectsTests.cs
9,290
C#
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using UnityEngine; using System.Collections; using UnityEngine.SocialPlatforms; public class MainGui : MonoBehaviour { private const float FontSizeMult = 0.05f; private bool mWaitingForAuth = false; private string mStatusText = "Ready."; private bool dumpedToken = false; void Start() { // Select the Google Play Games platform as our social platform implementation GooglePlayGames.PlayGamesPlatform.Activate(); } void OnGUI() { GUI.skin.button.fontSize = (int)(FontSizeMult * Screen.height); GUI.skin.label.fontSize = (int)(FontSizeMult * Screen.height); GUI.Label(new Rect(20, 20, Screen.width, Screen.height * 0.25f), mStatusText); Rect buttonRect = new Rect(0.25f * Screen.width, 0.10f * Screen.height, 0.5f * Screen.width, 0.25f * Screen.height); Rect imageRect = new Rect(buttonRect.x + buttonRect.width / 4f, buttonRect.y + buttonRect.height * 1.1f, buttonRect.width / 2f, buttonRect.width / 2f); if (mWaitingForAuth) { return; } string buttonLabel; if (Social.localUser.authenticated) { buttonLabel = "Sign Out"; if (Social.localUser.image != null) { GUI.DrawTexture(imageRect, Social.localUser.image, ScaleMode.ScaleToFit); } else { GUI.Label(imageRect, "No image available"); } mStatusText = "Ready"; if (!dumpedToken) { string token = GooglePlayGames.PlayGamesPlatform.Instance.GetToken(); Debug.Log("AccessToken = " + token); dumpedToken = token != null && token.Length > 0; } } else { buttonLabel = "Authenticate"; } if (GUI.Button(buttonRect, buttonLabel)) { if (!Social.localUser.authenticated) { // Authenticate mWaitingForAuth = true; mStatusText = "Authenticating..."; Social.localUser.Authenticate((bool success) => { mWaitingForAuth = false; if (success) { mStatusText = "Welcome " + Social.localUser.userName; } else { mStatusText = "Authentication failed."; } }); } else { // Sign out! mStatusText = "Signing out."; ((GooglePlayGames.PlayGamesPlatform)Social.Active).SignOut(); } } } }
31.688073
86
0.537348
[ "Apache-2.0" ]
cheongyongkim/playgameservices
samples/Minimal/Source/Assets/Minimal/MainGui.cs
3,454
C#
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using Aurora.Simulation.Base; using OpenSim.Services.Interfaces; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Services.CapsService { public class CapsService : ICapsService, IService { #region Declares /// <summary> /// A list of all clients and their Client Caps Handlers /// </summary> protected Dictionary<UUID, IClientCapsService> m_ClientCapsServices = new Dictionary<UUID, IClientCapsService>(); /// <summary> /// A list of all regions Caps Services /// </summary> protected Dictionary<ulong, IRegionCapsService> m_RegionCapsServices = new Dictionary<ulong, IRegionCapsService>(); protected IRegistryCore m_registry; public IRegistryCore Registry { get { return m_registry; } } protected IHttpServer m_server; public IHttpServer Server { get { return m_server; } } public string HostUri { get { return m_server.ServerURI; } } #endregion #region IService members public string Name { get { return GetType().Name; } } public void Initialize(IConfigSource config, IRegistryCore registry) { IConfig handlerConfig = config.Configs["Handlers"]; if (handlerConfig.GetString("CapsHandler", "") != Name) return; m_registry = registry; registry.RegisterModuleInterface<ICapsService>(this); } public void Start(IConfigSource config, IRegistryCore registry) { ISimulationBase simBase = registry.RequestModuleInterface<ISimulationBase>(); m_server = simBase.GetHttpServer(0); if (MainConsole.Instance != null) MainConsole.Instance.Commands.AddCommand("show presences", "show presences", "Shows all presences in the grid", ShowUsers); } public void FinishedStartup() { } #endregion #region Console Commands protected void ShowUsers(string[] cmd) { //Check for all or full to show child agents bool showChildAgents = cmd.Length == 3 && (cmd[2] == "all" || (cmd[2] == "full")); #if (!ISWIN) int count = 0; foreach (IRegionCapsService regionCaps in m_RegionCapsServices.Values) foreach (IRegionClientCapsService client in regionCaps.GetClients()) { if ((client.RootAgent || showChildAgents)) count++; } #else int count = m_RegionCapsServices.Values.SelectMany(regionCaps => regionCaps.GetClients()).Count(clientCaps => (clientCaps.RootAgent || showChildAgents)); #endif MainConsole.Instance.WarnFormat ("{0} agents found: ", count); foreach (IClientCapsService clientCaps in m_ClientCapsServices.Values) { foreach(IRegionClientCapsService caps in clientCaps.GetCapsServices()) { if((caps.RootAgent || showChildAgents)) { MainConsole.Instance.InfoFormat("Region - {0}, User {1}, {2}, {3}", caps.Region.RegionName, clientCaps.AccountInfo.Name, caps.RootAgent ? "Root Agent" : "Child Agent", caps.Disabled ? "Disabled" : "Not Disabled"); } } } } #endregion #region ICapsService members #region Client Caps /// <summary> /// Remove the all of the user's CAPS from the system /// </summary> /// <param name="AgentID"></param> public void RemoveCAPS(UUID AgentID) { if(m_ClientCapsServices.ContainsKey(AgentID)) { IClientCapsService perClient = m_ClientCapsServices[AgentID]; perClient.Close(); m_ClientCapsServices.Remove(AgentID); m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UserLogout", AgentID); } } /// <summary> /// Create a Caps URL for the given user/region. Called normally by the EventQueueService or the LLLoginService on login /// </summary> /// <param name="AgentID"></param> /// <param name="CAPSBase"></param> /// <param name="regionHandle"></param> /// <param name="IsRootAgent">Will this child be a root agent</param> /// <param name="circuitData"></param> /// <param name = "port">The port to use for the CAPS service</param> /// <returns></returns> public string CreateCAPS (UUID AgentID, string CAPSBase, ulong regionHandle, bool IsRootAgent, AgentCircuitData circuitData, uint port) { //Now make sure we didn't use an old one or something IClientCapsService service = GetOrCreateClientCapsService(AgentID); IRegionClientCapsService clientService = service.GetOrCreateCapsService(regionHandle, CAPSBase, circuitData, port); //Fix the root agent status clientService.RootAgent = IsRootAgent; m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UserLogin", AgentID); MainConsole.Instance.Debug("[CapsService]: Adding Caps URL " + clientService.CapsUrl + " for agent " + AgentID); return clientService.CapsUrl; } /// <summary> /// Get or create a new Caps Service for the given client /// Note: This does not add them to a region if one is created. /// </summary> /// <param name="AgentID"></param> /// <returns></returns> public IClientCapsService GetOrCreateClientCapsService(UUID AgentID) { if (!m_ClientCapsServices.ContainsKey(AgentID)) { PerClientBasedCapsService client = new PerClientBasedCapsService(); client.Initialise(this, AgentID); m_ClientCapsServices.Add(AgentID, client); } return m_ClientCapsServices[AgentID]; } /// <summary> /// Get a Caps Service for the given client /// </summary> /// <param name="AgentID"></param> /// <returns></returns> public IClientCapsService GetClientCapsService(UUID AgentID) { if (!m_ClientCapsServices.ContainsKey(AgentID)) return null; return m_ClientCapsServices[AgentID]; } public List<IClientCapsService> GetClientsCapsServices() { return new List<IClientCapsService>(m_ClientCapsServices.Values); } #endregion #region Region Caps /// <summary> /// Get a region handler for the given region /// </summary> /// <param name="RegionHandle"></param> public IRegionCapsService GetCapsForRegion(ulong RegionHandle) { IRegionCapsService service; if (m_RegionCapsServices.TryGetValue(RegionHandle, out service)) { return service; } return null; } /// <summary> /// Create a caps handler for the given region /// </summary> /// <param name="RegionHandle"></param> public void AddCapsForRegion(ulong RegionHandle) { if (!m_RegionCapsServices.ContainsKey(RegionHandle)) { IRegionCapsService service = new PerRegionCapsService(); service.Initialise(RegionHandle, Registry); m_RegionCapsServices.Add(RegionHandle, service); } } /// <summary> /// Remove the handler for the given region /// </summary> /// <param name="RegionHandle"></param> public void RemoveCapsForRegion(ulong RegionHandle) { if (m_RegionCapsServices.ContainsKey(RegionHandle)) m_RegionCapsServices.Remove(RegionHandle); } public List<IRegionCapsService> GetRegionsCapsServices() { return new List<IRegionCapsService>(m_RegionCapsServices.Values); } #endregion #endregion } }
38.996269
166
0.598986
[ "BSD-3-Clause" ]
BillyWarrhol/Aurora-Sim
OpenSim/Services/CapsService/CapsService.cs
10,451
C#
using MTProto.NET.Attributes; namespace MTProto.NET.Schema.TL { [MTObject(0x35553762)] public class TLTextAnchor : TLAbsRichText { public override uint Constructor { get { return 0x35553762; } } [MTParameter(Order = 0)] public TLAbsRichText Text { get; set; } [MTParameter(Order = 1)] public string Name { get; set; } } }
18.75
47
0.531111
[ "MIT" ]
Gostareh-Negar/TeleNet
MTProto.NET/Schema/TL/_generated/TLTextAnchor.cs
450
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Demo12.Models { public class Student { public int Id { get; set; } [Required] [StringLength(40)] public string FirstName { get; set; } [Required] [StringLength(50)] public string LastName { get; set; } // Nullable<DateTime> is optional! public DateTime? DateOfBirth { get; set; } // Reverse Navigation Properties public List<Enrollment> Enrollments { get; set; } public List<Transcript> Grades { get; set; } } }
22.193548
57
0.619186
[ "MIT" ]
DeltaVCode/cedar-c-do-401d5
class-16/Demo/Demo12/Models/Student.cs
690
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /*using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Bot.Builder.Adapters; using Microsoft.Bot.Builder.Dialogs.Choices; using Microsoft.Recognizers.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Bot.Builder.Dialogs.Tests { [TestClass] public class DialogChoicePromptTests { private List<string> colorChoices = new List<string> { "red", "green", "blue" }; [TestMethod] public async Task BasicChoicePrompt() { var dialogs = new DialogSet(); dialogs.Add("test-prompt", new ChoicePrompt(Culture.English) { Style = ListStyle.Inline }); var promptOptions = new ChoicePromptOptions { Choices = new List<Choice> { new Choice { Value = "red" }, new Choice { Value = "green" }, new Choice { Value = "blue" }, } }; dialogs.Add("test", new WaterfallStep[] { async (dc, args, next) => { await dc.PromptAsync("test-prompt", "favorite color?", promptOptions); }, async (dc, args, next) => { var choiceResult = (ChoiceResult)args; await dc.Context.SendActivityAsync($"Bot received the choice '{choiceResult.Value.Value}'."); await dc.EndAsync(); } } ); ConversationState convoState = new ConversationState(new MemoryStorage()); var testProperty = convoState.CreateProperty<Dictionary<string, object>>("test"); TestAdapter adapter = new TestAdapter() .Use(convoState); await new TestFlow(adapter, async (turnContext, cancellationToken) => { var state = await testProperty.GetAsync(turnContext, () => new Dictionary<string, object>()); var dc = dialogs.CreateContext(turnContext, state); await dc.ContinueAsync(); if (!turnContext.Responded) { await dc.BeginAsync("test"); } }) .Send("hello") .AssertReply("favorite color? (1) red, (2) green, or (3) blue") .Send("green") .AssertReply("Bot received the choice 'green'.") .StartTestAsync(); } } }*/
34.727273
117
0.522812
[ "MIT" ]
APiZFiBlockChain4/botbuilder-dotnet
tests/Microsoft.Bot.Builder.Dialogs.Tests/DialogChoicePromptTests.cs
2,676
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 StudentInfo.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("StudentInfo.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap BackIMG { get { object obj = ResourceManager.GetObject("BackIMG", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap DarlBlue { get { object obj = ResourceManager.GetObject("DarlBlue", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap fees { get { object obj = ResourceManager.GetObject("fees", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
41.265957
177
0.586234
[ "MIT" ]
sumee147/SchoolFees
StudentInfo/Properties/Resources.Designer.cs
3,881
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Program.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using AM; using AM.Collections; using AM.Windows.Forms; using CodeJam; using IrbisUI.Universal; using JetBrains.Annotations; using ManagedIrbis; using ManagedIrbis.Batch; using ManagedIrbis.Readers; using Newtonsoft.Json; using CM = System.Configuration.ConfigurationManager; #endregion namespace BeriChitai { static class Program { static void _ThreadException ( object sender, ThreadExceptionEventArgs eventArgs ) { ExceptionBox.Show(eventArgs.Exception); Environment.FailFast ( "Shutting down", eventArgs.Exception ); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { try { Application.SetUnhandledExceptionMode ( UnhandledExceptionMode.Automatic ); Application.ThreadException += _ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); UniversalForm form = new MainForm(); UniversalForm.Run(form, args); } catch (Exception exception) { ExceptionBox.Show(exception); } } } }
23.376344
84
0.584177
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Apps/BeriChitai/Source/Program.cs
2,176
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Core.Annotations; namespace Xenko.Core.Diagnostics { /// <summary> /// A set of extensions method to use with the <see cref="LogMessage"/> class. /// </summary> public static class LogMessageExtensions { /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Debug"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Debug"/> message, <c>false</c> otherwise.</returns> public static bool IsDebug([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Debug; } /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Verbose"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Verbose"/> message, <c>false</c> otherwise.</returns> public static bool IsVerbose([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Verbose; } /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Info"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Info"/> message, <c>false</c> otherwise.</returns> public static bool IsInfo([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Info; } /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Warning"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Warning"/> message, <c>false</c> otherwise.</returns> public static bool IsWarning([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Warning; } /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Error"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Error"/> message, <c>false</c> otherwise.</returns> public static bool IsError([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Error; } /// <summary> /// Gets whether the given log message is a <see cref="LogMessageType.Fatal"/> message type /// </summary> /// <param name="logMessage">The log message.</param> /// <returns><c>true</c> if the given log message is a <see cref="LogMessageType.Fatal"/> message, <c>false</c> otherwise.</returns> public static bool IsFatal([NotNull] this ILogMessage logMessage) { return logMessage.Type == LogMessageType.Fatal; } /// <summary> /// Gets whether the given log message is at least as severe as the given severity level. /// </summary> /// <param name="logMessage">The log message.</param> /// <param name="minSeverity">The minimal severity level.</param> /// <returns><c>true</c> if the given log message is at least as severe as the given severity level, <c>false</c> otherwise.</returns> public static bool IsAtLeast([NotNull] this ILogMessage logMessage, LogMessageType minSeverity) { return logMessage.Type >= minSeverity; } /// <summary> /// Gets whether the given log message is at most as severe as the given severity level. /// </summary> /// <param name="logMessage">The log message.</param> /// <param name="maxSeverity">The maximal severity level.</param> /// <returns><c>true</c> if the given log message is at most as severe as the given severity level, <c>false</c> otherwise.</returns> public static bool IsAtMost([NotNull] this ILogMessage logMessage, LogMessageType maxSeverity) { return logMessage.Type <= maxSeverity; } } }
48.822917
142
0.624493
[ "MIT" ]
Aminator/xenko
sources/core/Xenko.Core/Diagnostics/LogMessageExtensions.cs
4,687
C#
using System.Reactive.Disposables; using ReactiveUI; using Xamarin.Forms.Xaml; namespace BoutiqueXamarin.Views.Clothes.Choices.ChoiceViewItems { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ChoiceCategoryView : ChoiceCategoryBase { public ChoiceCategoryView() { InitializeComponent(); this.WhenActivated(disposable => { this.OneWayBind(ViewModel, x => x.CategoryName, x => x.CategoryName.Text). DisposeWith(disposable); }); } } }
27.761905
90
0.631218
[ "MIT" ]
rubilnik4/VeraBoutique
BoutiqueXamarin/BoutiqueXamarin/Views/Clothes/Choices/ChoiceViewItems/ChoiceCategoryView.xaml.cs
585
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("Vettvangur.IcelandAuth.Sample.Umbraco7")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Vettvangur.IcelandAuth.Sample.Umbraco7")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("11b18dd8-10ea-48d7-91e3-5cc972b26f63")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.138889
84
0.753726
[ "MIT" ]
djgunni86/Vettvangur.IcelandAuth
src/Samples/Vettvangur.IcelandAuth.Sample.Umbraco7/Properties/AssemblyInfo.cs
1,412
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementSizeConstraintStatementFieldToMatchSingleHeaderGetArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementSizeConstraintStatementFieldToMatchSingleHeaderGetArgs() { } } }
37.346154
180
0.740474
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementSizeConstraintStatementFieldToMatchSingleHeaderGetArgs.cs
971
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Ec2.Inputs { public sealed class GetNetworkInterfacesFilterInputArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the field to filter by, as defined by /// [the underlying AWS API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkInterfaces.html). /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; [Input("values", required: true)] private InputList<string>? _values; /// <summary> /// Set of values that are accepted for the given field. /// </summary> public InputList<string> Values { get => _values ?? (_values = new InputList<string>()); set => _values = value; } public GetNetworkInterfacesFilterInputArgs() { } } }
31.128205
128
0.626853
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Ec2/Inputs/GetNetworkInterfacesFilterArgs.cs
1,214
C#
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Result { /* * Complete the 'minimumPasses' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts following parameters: * 1. LONG_INTEGER m * 2. LONG_INTEGER w * 3. LONG_INTEGER p * 4. LONG_INTEGER n */ public static long minimumPasses(long m, long w, long p, long n) { long outOut = 0; long pCount = 0; long pass = 0; while (m * w <= n) { pass++; Console.WriteLine("m:{0} w:{1}", m, w); outOut = m * w; Console.WriteLine("outOut:{0}", outOut); pCount = outOut / p; Console.WriteLine("pCount:{0}-{1}-{2}---{3}-{4}---{5}-{6}", pCount, Math.Round((decimal)(m / (m + w))), Math.Round((decimal)(m / (m + w))), (long)(m / (m + w)), (long)(w / (m + w)), (m * 100 / (m + w)), (w * 100 / (m + w))); Console.WriteLine("new m:{0} w:{1} =={2}-{3}", m, w, ((m * 100 / (m + w)) * pCount), ((w * 100 / (m + w)) * pCount)); w = w + (long) Math.Round(((decimal)m / (m + w)) * pCount); m = m + (long) Math.Round(((decimal)w / (m + w)) * pCount); Console.WriteLine("new m:{0} w:{1}", m, w); } return pass; } } class Solution { public static void Mainsdadfasdf(string[] args) { TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true); string[] firstMultipleInput = Console.ReadLine().TrimEnd().Split(' '); //long m = Convert.ToInt64(firstMultipleInput[0]); //long w = Convert.ToInt64(firstMultipleInput[1]); //long p = Convert.ToInt64(firstMultipleInput[2]); //long n = Convert.ToInt64(firstMultipleInput[3]); //long result = Result.minimumPasses(m, w, p, n); // long result = Result.minimumPasses(3, 1, 2, 12); //textWriter.WriteLine(result); textWriter.Flush(); textWriter.Close(); } }
30.818182
236
0.572693
[ "MIT" ]
bobhatepradip/leet
leet/MakingCandies.cs
2,375
C#
using System; using System.Globalization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using PriceCalculator.Models; namespace PriceCalculator { class Program { private static ServiceProvider _serviceProvider; private static IConfiguration _configuration; /// <summary> /// Main entry point /// </summary> /// <param name="args">Command line args expected as `Milk Bread Apple` etc.</param> static void Main(string[] args) { // Make sure, the currency output is formatted like £1.23 CultureInfo.CurrentCulture = new CultureInfo("en-GB", false); // Load configuration _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) .Build(); // I normally would think twice about setting up DI for such a // small project but an emphasis on extensibility was given in the spec. // Setup DI RegisterServices(); // Run app IServiceScope scope = _serviceProvider.CreateScope(); var result = scope.ServiceProvider.GetRequiredService<PriceCalculator>().Calculate(args); // Write result out to the console Console.WriteLine(result.ToString()); // Tear down DI DisposeServices(); } /// <summary> /// Registers all the DI services /// </summary> private static void RegisterServices() { IServiceCollection services = new ServiceCollection(); services.Configure<PriceCalculatorConfig>(_configuration.GetSection(PriceCalculatorConfig.Section)); services.AddSingleton<PriceCalculator>(); _serviceProvider = services.BuildServiceProvider(true); } /// <summary> /// Disposes all DI services /// </summary> private static void DisposeServices() { if (_serviceProvider == null) { return; } if (_serviceProvider is IDisposable) { ((IDisposable)_serviceProvider).Dispose(); } } } }
32.432432
113
0.57
[ "MIT" ]
tkglaser/challenge.shell.01
PriceCalculator/Program.cs
2,403
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1015_48ba-89334343")] public void Method_1015_48ba() { ii(0x1015_48ba, 5); push(0x30); /* push 0x30 */ ii(0x1015_48bf, 5); call(Definitions.sys_check_available_stack_size, 0x1_148e);/* call 0x10165d52 */ ii(0x1015_48c4, 1); push(ebx); /* push ebx */ ii(0x1015_48c5, 1); push(ecx); /* push ecx */ ii(0x1015_48c6, 1); push(edx); /* push edx */ ii(0x1015_48c7, 1); push(esi); /* push esi */ ii(0x1015_48c8, 1); push(edi); /* push edi */ ii(0x1015_48c9, 1); push(ebp); /* push ebp */ ii(0x1015_48ca, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x1015_48cc, 6); sub(esp, 0x14); /* sub esp, 0x14 */ ii(0x1015_48d2, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x1015_48d5, 2); xor(eax, eax); /* xor eax, eax */ ii(0x1015_48d7, 5); mov(al, memb[ds, 0x101c_37da]); /* mov al, [0x101c37da] */ ii(0x1015_48dc, 3); movsx(edx, ax); /* movsx edx, ax */ ii(0x1015_48df, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_48e2, 5); call(0x1007_6074, -0xd_e873); /* call 0x10076074 */ ii(0x1015_48e7, 2); test(al, al); /* test al, al */ ii(0x1015_48e9, 2); if(jnz(0x1015_48f4, 9)) goto l_0x1015_48f4;/* jnz 0x101548f4 */ ii(0x1015_48eb, 7); cmp(memb[ds, 0x101c_3980], 0); /* cmp byte [0x101c3980], 0x0 */ ii(0x1015_48f2, 2); if(jz(0x1015_48fa, 6)) goto l_0x1015_48fa;/* jz 0x101548fa */ l_0x1015_48f4: ii(0x1015_48f4, 4); mov(memb[ss, ebp - 8], 1); /* mov byte [ebp-0x8], 0x1 */ ii(0x1015_48f8, 2); jmp(0x1015_48fe, 4); goto l_0x1015_48fe;/* jmp 0x101548fe */ l_0x1015_48fa: ii(0x1015_48fa, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ l_0x1015_48fe: ii(0x1015_48fe, 3); mov(al, memb[ss, ebp - 8]); /* mov al, [ebp-0x8] */ ii(0x1015_4901, 3); mov(memb[ss, ebp - 12], al); /* mov [ebp-0xc], al */ ii(0x1015_4904, 4); cmp(memb[ss, ebp - 12], 0); /* cmp byte [ebp-0xc], 0x0 */ ii(0x1015_4908, 2); if(jz(0x1015_4912, 8)) goto l_0x1015_4912;/* jz 0x10154912 */ ii(0x1015_490a, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_490d, 5); call(0x1014_9fa8, -0xa96a); /* call 0x10149fa8 */ l_0x1015_4912: ii(0x1015_4912, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4915, 4); mov(dx, memw[ds, eax + 26]); /* mov dx, [eax+0x1a] */ ii(0x1015_4919, 3); shl(edx, 6); /* shl edx, 0x6 */ ii(0x1015_491c, 3); add(edx, 0x20); /* add edx, 0x20 */ ii(0x1015_491f, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4922, 4); sub(dx, memw[ds, eax + 22]); /* sub dx, [eax+0x16] */ ii(0x1015_4926, 3); mov(memd[ss, ebp - 16], edx); /* mov [ebp-0x10], edx */ ii(0x1015_4929, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_492c, 4); mov(dx, memw[ds, eax + 28]); /* mov dx, [eax+0x1c] */ ii(0x1015_4930, 3); shl(edx, 6); /* shl edx, 0x6 */ ii(0x1015_4933, 3); add(edx, 0x20); /* add edx, 0x20 */ ii(0x1015_4936, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4939, 4); sub(dx, memw[ds, eax + 24]); /* sub dx, [eax+0x18] */ ii(0x1015_493d, 3); mov(memd[ss, ebp - 20], edx); /* mov [ebp-0x14], edx */ ii(0x1015_4940, 4); movsx(ebx, memw[ss, ebp - 20]); /* movsx ebx, word [ebp-0x14] */ ii(0x1015_4944, 4); movsx(edx, memw[ss, ebp - 16]); /* movsx edx, word [ebp-0x10] */ ii(0x1015_4948, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_494b, 5); call(0x1014_9c2f, -0xad21); /* call 0x10149c2f */ ii(0x1015_4950, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4953, 4); test(memb[ds, eax + 18], 0x40); /* test byte [eax+0x12], 0x40 */ ii(0x1015_4957, 2); if(jz(0x1015_4962, 9)) goto l_0x1015_4962;/* jz 0x10154962 */ ii(0x1015_4959, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_495c, 4); test(memb[ds, eax + 20], 1); /* test byte [eax+0x14], 0x1 */ ii(0x1015_4960, 2); if(jnz(0x1015_4964, 2)) goto l_0x1015_4964;/* jnz 0x10154964 */ l_0x1015_4962: ii(0x1015_4962, 2); jmp(0x1015_4986, 0x22); goto l_0x1015_4986;/* jmp 0x10154986 */ l_0x1015_4964: ii(0x1015_4964, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4967, 9); mov(memw[ds, eax + 219], 0xffc0); /* mov word [eax+0xdb], 0xffc0 */ ii(0x1015_4970, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4973, 7); mov(dx, memw[ds, eax + 219]); /* mov dx, [eax+0xdb] */ ii(0x1015_497a, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_497d, 7); mov(memw[ds, eax + 217], dx); /* mov [eax+0xd9], dx */ ii(0x1015_4984, 2); jmp(0x1015_49a6, 0x20); goto l_0x1015_49a6;/* jmp 0x101549a6 */ l_0x1015_4986: ii(0x1015_4986, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4989, 9); mov(memw[ds, eax + 219], 0); /* mov word [eax+0xdb], 0x0 */ ii(0x1015_4992, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_4995, 7); mov(dx, memw[ds, eax + 219]); /* mov dx, [eax+0xdb] */ ii(0x1015_499c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_499f, 7); mov(memw[ds, eax + 217], dx); /* mov [eax+0xd9], dx */ l_0x1015_49a6: ii(0x1015_49a6, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_49a9, 5); call(0x1014_9cd1, -0xacdd); /* call 0x10149cd1 */ ii(0x1015_49ae, 4); cmp(memb[ss, ebp - 12], 0); /* cmp byte [ebp-0xc], 0x0 */ ii(0x1015_49b2, 2); if(jz(0x1015_49bc, 8)) goto l_0x1015_49bc;/* jz 0x101549bc */ ii(0x1015_49b4, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1015_49b7, 5); call(0x1014_9fa8, -0xaa14); /* call 0x10149fa8 */ l_0x1015_49bc: ii(0x1015_49bc, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x1015_49be, 1); pop(ebp); /* pop ebp */ ii(0x1015_49bf, 1); pop(edi); /* pop edi */ ii(0x1015_49c0, 1); pop(esi); /* pop esi */ ii(0x1015_49c1, 1); pop(edx); /* pop edx */ ii(0x1015_49c2, 1); pop(ecx); /* pop ecx */ ii(0x1015_49c3, 1); pop(ebx); /* pop ebx */ ii(0x1015_49c4, 1); ret(); /* ret */ } } }
78.980769
114
0.451424
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1015-48ba.cs
8,214
C#
using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Sentry.Internal.Extensions { internal static class CollectionsExtensions { public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) { foreach (var i in items) { collection.Add(i); } } public static TValue GetOrCreate<TValue>( this ConcurrentDictionary<string, object> dictionary, string key) where TValue : class, new() => (TValue) dictionary.GetOrAdd(key, _ => new TValue()); public static void TryCopyTo<TKey, TValue>(this IDictionary<TKey, TValue> from, IDictionary<TKey, TValue> to) where TKey : notnull { foreach (var (key, value) in from) { if (!to.ContainsKey(key)) { to[key] = value; } } } public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) where TKey : notnull => source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } }
31.3
126
0.559904
[ "MIT" ]
Mitch528/sentry-dotnet
src/Sentry/Internal/Extensions/CollectionsExtensions.cs
1,252
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20180401.Outputs { [OutputType] public sealed class MonitorConfigResponseExpectedStatusCodeRanges { /// <summary> /// Max status code. /// </summary> public readonly int? Max; /// <summary> /// Min status code. /// </summary> public readonly int? Min; [OutputConstructor] private MonitorConfigResponseExpectedStatusCodeRanges( int? max, int? min) { Max = max; Min = min; } } }
24.361111
81
0.607754
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20180401/Outputs/MonitorConfigResponseExpectedStatusCodeRanges.cs
877
C#
/* gm_swappanel.cs * 10.28.2019 * Balloon Physics Simulator * Author: Team NoName * Description: Swaps panels in betweenn wind and radius panels * */ using UnityEngine; public class gm_swappanel : MonoBehaviour { public JSONconfig config; private bool radiusSlider; private bool inflateDeflateButton; public GameObject _radiusPanelParent; //radius parent panel public GameObject _windPanelParent; //wind parent panel public GameObject _radiusSliderUI; // radius slider object public GameObject _inflateDeflatePanel; // inflate deflate buttons void Start() { radiusSlider = config.loadedConfig.radiusSlider; inflateDeflateButton = config.loadedConfig.inflateDeflateButton; } /// <summary> /// Enables radius panel, hides wind panel /// </summary> public void SetRadiusPanelEnabled() { _radiusPanelParent.SetActive(true); if (radiusSlider == true && inflateDeflateButton == true) { _radiusPanelParent.SetActive(true); _windPanelParent.SetActive(false); } else if (radiusSlider == true && inflateDeflateButton == false) { _radiusSliderUI.SetActive(true); _inflateDeflatePanel.SetActive(false); _windPanelParent.SetActive(false); } else if (radiusSlider == false && inflateDeflateButton == true) { _radiusSliderUI.SetActive(false); _inflateDeflatePanel.SetActive(true); _windPanelParent.SetActive(false); } else { _radiusPanelParent.SetActive(false); _windPanelParent.SetActive(false); } } /// <summary> /// Enables wind panel, hides radius panel /// </summary> public void SetWindPanelEnabled() { _radiusPanelParent.SetActive(false); _windPanelParent.SetActive(true); } }
30.212121
73
0.623872
[ "BSD-2-Clause" ]
Class41/BalloonSimulator
Assets/Scripts/GameManager/gm_swappanel.cs
1,996
C#
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System; using System.Collections.Generic; using System.Collections.Specialized; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.Tests.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.Prism.Tests.Regions { [TestClass] public class RegionManagerFixture { [TestMethod] public void CanAddRegion() { IRegion region1 = new MockPresentationRegion(); region1.Name = "MainRegion"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(region1); IRegion region2 = regionManager.Regions["MainRegion"]; Assert.AreSame(region1, region2); } [TestMethod] [ExpectedException(typeof(KeyNotFoundException))] public void ShouldFailIfRegionDoesntExists() { RegionManager regionManager = new RegionManager(); IRegion region = regionManager.Regions["nonExistentRegion"]; } [TestMethod] public void CanCheckTheExistenceOfARegion() { RegionManager regionManager = new RegionManager(); bool result = regionManager.Regions.ContainsRegionWithName("noRegion"); Assert.IsFalse(result); IRegion region = new MockPresentationRegion(); region.Name = "noRegion"; regionManager.Regions.Add(region); result = regionManager.Regions.ContainsRegionWithName("noRegion"); Assert.IsTrue(result); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void AddingMultipleRegionsWithSameNameThrowsArgumentException() { var regionManager = new RegionManager(); regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" }); regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" }); } [TestMethod] public void AddPassesItselfAsTheRegionManagerOfTheRegion() { var regionManager = new RegionManager(); var region = new MockPresentationRegion(); region.Name = "region"; regionManager.Regions.Add(region); Assert.AreSame(regionManager, region.RegionManager); } [TestMethod] public void CreateRegionManagerCreatesANewInstance() { var regionManager = new RegionManager(); var createdRegionManager = regionManager.CreateRegionManager(); Assert.IsNotNull(createdRegionManager); Assert.IsInstanceOfType(createdRegionManager, typeof(RegionManager)); Assert.AreNotSame(regionManager, createdRegionManager); } [TestMethod] public void CanRemoveRegion() { var regionManager = new RegionManager(); IRegion region = new MockPresentationRegion(); region.Name = "TestRegion"; regionManager.Regions.Add(region); regionManager.Regions.Remove("TestRegion"); Assert.IsFalse(regionManager.Regions.ContainsRegionWithName("TestRegion")); } [TestMethod] public void ShouldRemoveRegionManagerWhenRemoving() { var regionManager = new RegionManager(); var region = new MockPresentationRegion(); region.Name = "TestRegion"; regionManager.Regions.Add(region); regionManager.Regions.Remove("TestRegion"); Assert.IsNull(region.RegionManager); } [TestMethod] public void UpdatingRegionsGetsCalledWhenAccessingRegionMembers() { var listener = new MySubscriberClass(); try { RegionManager.UpdatingRegions += listener.OnUpdatingRegions; RegionManager regionManager = new RegionManager(); regionManager.Regions.ContainsRegionWithName("TestRegion"); Assert.IsTrue(listener.OnUpdatingRegionsCalled); listener.OnUpdatingRegionsCalled = false; regionManager.Regions.Add(new MockPresentationRegion() { Name = "TestRegion" }); Assert.IsTrue(listener.OnUpdatingRegionsCalled); listener.OnUpdatingRegionsCalled = false; var region = regionManager.Regions["TestRegion"]; Assert.IsTrue(listener.OnUpdatingRegionsCalled); listener.OnUpdatingRegionsCalled = false; regionManager.Regions.Remove("TestRegion"); Assert.IsTrue(listener.OnUpdatingRegionsCalled); listener.OnUpdatingRegionsCalled = false; regionManager.Regions.GetEnumerator(); Assert.IsTrue(listener.OnUpdatingRegionsCalled); } finally { RegionManager.UpdatingRegions -= listener.OnUpdatingRegions; } } [TestMethod] public void ShouldSetObservableRegionContextWhenRegionContextChanges() { var region = new MockPresentationRegion(); var view = new MockDependencyObject(); var observableObject = RegionContext.GetObservableContext(view); bool propertyChangedCalled = false; observableObject.PropertyChanged += (sender, args) => propertyChangedCalled = true; Assert.IsNull(observableObject.Value); RegionManager.SetRegionContext(view, "MyContext"); Assert.IsTrue(propertyChangedCalled); Assert.AreEqual("MyContext", observableObject.Value); } [TestMethod] public void ShouldNotPreventSubscribersToStaticEventFromBeingGarbageCollected() { var subscriber = new MySubscriberClass(); RegionManager.UpdatingRegions += subscriber.OnUpdatingRegions; RegionManager.UpdateRegions(); Assert.IsTrue(subscriber.OnUpdatingRegionsCalled); WeakReference subscriberWeakReference = new WeakReference(subscriber); subscriber = null; GC.Collect(); Assert.IsFalse(subscriberWeakReference.IsAlive); } [TestMethod] public void ExceptionMessageWhenCallingUpdateRegionsShouldBeClear() { try { ExceptionExtensions.RegisterFrameworkExceptionType(typeof(FrameworkException)); RegionManager.UpdatingRegions += new EventHandler(RegionManager_UpdatingRegions); try { RegionManager.UpdateRegions(); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex.Message.Contains("Abcde")); } } finally { RegionManager.UpdatingRegions -= new EventHandler(RegionManager_UpdatingRegions); } } public void RegionManager_UpdatingRegions(object sender, EventArgs e) { try { throw new Exception("Abcde"); } catch (Exception ex) { throw new FrameworkException(ex); } } public class MySubscriberClass { public bool OnUpdatingRegionsCalled; public void OnUpdatingRegions(object sender, EventArgs e) { OnUpdatingRegionsCalled = true; } } [TestMethod] public void WhenAddingRegions_ThenRegionsCollectionNotifiesUpdate() { var regionManager = new RegionManager(); var region1 = new Region { Name = "region1" }; var region2 = new Region { Name = "region2" }; NotifyCollectionChangedEventArgs args = null; regionManager.Regions.CollectionChanged += (s, e) => args = e; regionManager.Regions.Add(region1); Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action); CollectionAssert.AreEqual(new object[] { region1 }, args.NewItems); Assert.AreEqual(0, args.NewStartingIndex); Assert.IsNull(args.OldItems); Assert.AreEqual(-1, args.OldStartingIndex); regionManager.Regions.Add(region2); Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action); CollectionAssert.AreEqual(new object[] { region2 }, args.NewItems); Assert.AreEqual(0, args.NewStartingIndex); Assert.IsNull(args.OldItems); Assert.AreEqual(-1, args.OldStartingIndex); } [TestMethod] public void WhenRemovingRegions_ThenRegionsCollectionNotifiesUpdate() { var regionManager = new RegionManager(); var region1 = new Region { Name = "region1" }; var region2 = new Region { Name = "region2" }; regionManager.Regions.Add(region1); regionManager.Regions.Add(region2); NotifyCollectionChangedEventArgs args = null; regionManager.Regions.CollectionChanged += (s, e) => args = e; regionManager.Regions.Remove("region2"); Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action); CollectionAssert.AreEqual(new object[] { region2 }, args.OldItems); Assert.AreEqual(0, args.OldStartingIndex); Assert.IsNull(args.NewItems); Assert.AreEqual(-1, args.NewStartingIndex); regionManager.Regions.Remove("region1"); Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action); CollectionAssert.AreEqual(new object[] { region1 }, args.OldItems); Assert.AreEqual(0, args.OldStartingIndex); Assert.IsNull(args.NewItems); Assert.AreEqual(-1, args.NewStartingIndex); } [TestMethod] public void WhenRemovingNonExistingRegion_ThenRegionsCollectionDoesNotNotifyUpdate() { var regionManager = new RegionManager(); var region1 = new Region { Name = "region1" }; regionManager.Regions.Add(region1); NotifyCollectionChangedEventArgs args = null; regionManager.Regions.CollectionChanged += (s, e) => args = e; regionManager.Regions.Remove("region2"); Assert.IsNull(args); } } internal class FrameworkException : Exception { public FrameworkException(Exception inner) : base(string.Empty, inner) { } } }
37.333333
98
0.58631
[ "MIT" ]
cointoss1973/Prism4.1-WPF
PrismLibrary/Desktop/Prism.Tests/Regions/RegionManagerFixture.cs
12,096
C#
/* * Copyright Beijing 58 Information Technology Co.,Ltd. * * 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. */ //---------------------------------------------------------------------- //<Copyright company="58.com"> // Team:SPAT // Blog:http://blog.58.com/spat/ // Website:http://www.58.com //</Copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Text; using System.Collections.Generic; using Com.Bj58.Spat.Gaea.Client.Configuration; namespace Com.Bj58.Spat.Gaea.Client.Utility.Logger { internal class UDPLogger : LoggerBase { System.Net.Sockets.UdpClient uc; string _host; int _port; public UDPLogger(LoggerConfig config) { _host = config.UDP.Host; _port = config.UDP.Port; uc = new System.Net.Sockets.UdpClient(); } public override Level Level { get; set; } public override void Debug(string msg) { if (Level <= Level.Debug) { SendData(msg, Level.Debug); } } public override void Error(string msg) { if (Level <= Level.Error) { SendData(msg, Level.Error); } } public override void Fatal(string msg) { if (Level <= Level.Fatal) { SendData(msg, Level.Fatal); } } public override void Info(string msg) { if (Level <= Level.Info) { SendData(msg, Level.Info); } } public override void Notice(string msg) { if (Level <= Level.Notice) { SendData(msg, Level.Notice); } } public override void Warn(string msg) { if (Level <= Level.Warn) { SendData(msg, Level.Warn); } } private void SendData(string msg, Level level) { StringBuilder content = new StringBuilder(); content.Append("Gaea-Time:" + DateTime.Now.ToString("yy-MM-dd hh:mm:ss")); content.Append(" level:" + level); content.Append(" message:" + msg.Replace("\n", string.Empty)); try { byte[] data = Encoding.UTF8.GetBytes(content.ToString()); uc.Send(data, data.Length, _host, _port); } catch { } } } }
30.417391
87
0.508005
[ "Apache-2.0" ]
58code/Gaea
client/net/client/Com.Bj58.Spat.Gaea.Client/Utility/Logger/UDPLogger.cs
3,500
C#
using Windows.Foundation; using System; using System.Collections.Generic; using System.Text; using System.Threading; using Uno; using Uno.UI.Xaml.Input; using Windows.System; using Windows.UI.Core; using Windows.UI.Input; namespace Windows.UI.Xaml.Input { public sealed partial class PointerRoutedEventArgs : RoutedEventArgs, ICancellableRoutedEventArgs, CoreWindow.IPointerEventArgs { public PointerRoutedEventArgs() { // This is acceptable as all ctors of this class are internal CoreWindow.GetForCurrentThread().SetLastPointerEvent(this); } /// <inheritdoc /> Point CoreWindow.IPointerEventArgs.GetLocation() => GetCurrentPoint(null).Position; public IList<PointerPoint> GetIntermediatePoints(UIElement relativeTo) => new List<PointerPoint>(1) {GetCurrentPoint(relativeTo)}; internal uint FrameId { get; } internal bool CanceledByDirectManipulation { get; set; } public bool IsGenerated { get; } = false; // Generated events are not supported by UNO public bool Handled { get; set; } public VirtualKeyModifiers KeyModifiers { get; } public Pointer Pointer { get; } /// <inheritdoc /> public override string ToString() => $"PointerRoutedEventArgs({Pointer}@{GetCurrentPoint(null).Position})"; } }
27.304348
128
0.755573
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UI/UI/Xaml/Input/PointerRoutedEventArgs.cs
1,258
C#