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 IoTWork.Contracts; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace IoTWork.Samples.Sensors { [Serializable] public class SensorTimeUpSample: IIoTSample { [DataMember] public Int64 ElapsedMilliseconds { get; set; } } public class SensorTimeUp : IIoTSensor { private Stopwatch sw = null; private Int64? ErrorsReading = null; private Int64? NumberOfAcquires = null; public IIoTSample Acquire() { NumberOfAcquires++; if (sw != null) { return new SensorTimeUpSample() { ElapsedMilliseconds = sw.ElapsedMilliseconds }; } else { ErrorsReading++; return null; } } public bool Close(string Parameters) { if (sw != null) { sw.Reset(); sw = null; return true; } else return false; } public string GetErrors() { return ErrorsReading.HasValue ? "ErrorsReading " + ErrorsReading : "No Errors"; } public string GetStats() { return NumberOfAcquires.HasValue ? "NumberOfAcquires " + NumberOfAcquires : "No Statistics"; } public bool Init(string Parameters) { if (sw == null) { ErrorsReading = 0; NumberOfAcquires = 0; sw = new Stopwatch(); sw.Start(); return true; } else return false; } public bool Pause() { if (sw != null) { sw.Stop(); return true; } else return false; } public bool Play() { if (sw != null) { sw.Start(); return true; } else return false; } public bool Stop() { if (sw != null) { sw.Reset(); return true; } else return false; } } public class SubtractOneSecond : IIoTPipe { public IIoTSample CrossIt(IIoTSample sample) { SensorTimeUpSample realsample = sample as SensorTimeUpSample; if (realsample != null) { SensorTimeUpSample newvalue = new SensorTimeUpSample(); newvalue.ElapsedMilliseconds = realsample.ElapsedMilliseconds - 1000; return newvalue; } else return sample; } } }
23.815385
105
0.440891
[ "MIT" ]
samnium/IoTWork.Reader
IoTWork.Samples.net4/Sensors/TimeUp.cs
3,098
C#
// <OWNER>[....]</OWNER> namespace Microsoft.Win32.SafeHandles { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; // Introduce this handle to replace internal SafeTokenHandle, // which is mainly used to hold Windows thread or process access token [SecurityCritical] public sealed class SafeAccessTokenHandle : SafeHandle { private SafeAccessTokenHandle() : base(IntPtr.Zero, true) { } // 0 is an Invalid Handle public SafeAccessTokenHandle(IntPtr handle) : base(IntPtr.Zero, true) { SetHandle(handle); } public static SafeAccessTokenHandle InvalidHandle { [SecurityCritical] get { return new SafeAccessTokenHandle(IntPtr.Zero); } } public override bool IsInvalid { [SecurityCritical] get { return handle == IntPtr.Zero || handle == new IntPtr(-1); } } [SecurityCritical] protected override bool ReleaseHandle() { return Win32Native.CloseHandle(handle); } } #if !FEATURE_PAL [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLsaLogonProcessHandle() : base (true) {} // 0 is an Invalid Handle internal SafeLsaLogonProcessHandle(IntPtr handle) : base (true) { SetHandle(handle); } internal static SafeLsaLogonProcessHandle InvalidHandle { get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); } } [System.Security.SecurityCritical] override protected bool ReleaseHandle() { // LsaDeregisterLogonProcess returns an NTSTATUS return Win32Native.LsaDeregisterLogonProcess(handle) >= 0; } } [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaMemoryHandle : SafeBuffer { private SafeLsaMemoryHandle() : base(true) {} // 0 is an Invalid Handle internal SafeLsaMemoryHandle(IntPtr handle) : base (true) { SetHandle(handle); } internal static SafeLsaMemoryHandle InvalidHandle { get { return new SafeLsaMemoryHandle( IntPtr.Zero ); } } [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.LsaFreeMemory(handle) == 0; } } [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLsaPolicyHandle() : base(true) {} // 0 is an Invalid Handle internal SafeLsaPolicyHandle(IntPtr handle) : base (true) { SetHandle(handle); } internal static SafeLsaPolicyHandle InvalidHandle { get { return new SafeLsaPolicyHandle( IntPtr.Zero ); } } [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.LsaClose(handle) == 0; } } [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaReturnBufferHandle : SafeBuffer { private SafeLsaReturnBufferHandle() : base (true) {} // 0 is an Invalid Handle internal SafeLsaReturnBufferHandle(IntPtr handle) : base (true) { SetHandle(handle); } internal static SafeLsaReturnBufferHandle InvalidHandle { get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); } } [System.Security.SecurityCritical] override protected bool ReleaseHandle() { // LsaFreeReturnBuffer returns an NTSTATUS return Win32Native.LsaFreeReturnBuffer(handle) >= 0; } } [System.Security.SecurityCritical] // auto-generated internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeProcessHandle() : base (true) {} // 0 is an Invalid Handle internal SafeProcessHandle(IntPtr handle) : base (true) { SetHandle(handle); } internal static SafeProcessHandle InvalidHandle { get { return new SafeProcessHandle(IntPtr.Zero); } } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] override protected bool ReleaseHandle() { return Win32Native.CloseHandle(handle); } } [System.Security.SecurityCritical] // auto-generated internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeThreadHandle() : base (true) {} // 0 is an Invalid Handle internal SafeThreadHandle(IntPtr handle) : base (true) { SetHandle(handle); } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] override protected bool ReleaseHandle() { return Win32Native.CloseHandle(handle); } } #endif // !FEATURE_PAL }
32.176471
89
0.637843
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/clr/src/BCL/system/security/safesecurityhandles.cs
5,470
C#
using System; namespace Netcore.BackgroundTask.Core.Entities { public class Customer : EntityBase { public Customer() : base() { } public Customer(Guid id) : base(id) { } public string Name { get; set; } public string LastName { get; set; } public string FullName => $"{Name} {LastName}"; } }
23.2
55
0.591954
[ "MIT" ]
andreslon/NetCore.BackgroundTask
Netcore.BackgroundTask.Core/Entities/Customer.cs
350
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Win32; namespace joystick_feedback { public static class SteamPath { // FROM https://stackoverflow.com/questions/54767662/finding-game-launcher-executables-in-directory-c-sharp public static string FindSteamEliteDirectory() { var steamGameDirs = new List<string>(); const string steam32 = "SOFTWARE\\VALVE\\"; const string steam64 = "SOFTWARE\\Wow6432Node\\Valve\\"; var key32 = Registry.LocalMachine.OpenSubKey(steam32); var key64 = Registry.LocalMachine.OpenSubKey(steam64); if (key32 != null && (key64?.ToString() == null || key64.ToString() == "")) { foreach (var k32SubKey in key32.GetSubKeyNames()) { using (var subKey = key32.OpenSubKey(k32SubKey)) { var steam32Path = subKey.GetValue("InstallPath")?.ToString(); if (steam32Path != null) { var config32Path = steam32Path + "/steamapps/libraryfolders.vdf"; string driveRegex = @"[A-Z]:\\"; if (File.Exists(config32Path)) { string[] configLines = File.ReadAllLines(config32Path); foreach (var item in configLines) { //Console.WriteLine("32: " + item); Match match = Regex.Match(item, driveRegex); if (item != string.Empty && match.Success) { string matched = match.ToString(); string item2 = item.Substring(item.IndexOf(matched)); item2 = item2.Replace("\\\\", "\\"); item2 = item2.Replace("\"", "\\steamapps\\common\\"); steamGameDirs.Add(item2); } } steamGameDirs.Add(steam32Path + "\\steamapps\\common\\"); } } } } } if (key64 != null) { foreach (var k64SubKey in key64.GetSubKeyNames()) { using (RegistryKey subKey = key64.OpenSubKey(k64SubKey)) { var steam64path = subKey.GetValue("InstallPath")?.ToString(); if (steam64path != null) { var config64path = steam64path + "/steamapps/libraryfolders.vdf"; var driveRegex = @"[A-Z]:\\"; if (File.Exists(config64path)) { var configLines = File.ReadAllLines(config64path); foreach (var item in configLines) { //Console.WriteLine("64: " + item); Match match = Regex.Match(item, driveRegex); if (item != string.Empty && match.Success) { var matched = match.ToString(); var item2 = item.Substring(item.IndexOf(matched)); item2 = item2.Replace("\\\\", "\\"); item2 = item2.Replace("\"", "\\steamapps\\common\\"); steamGameDirs.Add(item2); } } steamGameDirs.Add(steam64path + "\\steamapps\\common\\"); } } } } } foreach (var path in steamGameDirs) { var controlSchemePath64 = @"Elite Dangerous\Products\elite-dangerous-64\ControlSchemes\"; if (Directory.Exists(path + controlSchemePath64)) { return path + controlSchemePath64; } } return null; } } }
44.130841
115
0.40449
[ "MIT" ]
mhwlng/joystick-feedback
joystick-feedback/SteamPath.cs
4,724
C#
singleton Material(Cliff_01_LayeredGrayStone001) { mapTo = "LayeredGrayStone001"; diffuseMap[0] = "3TD_LayeredGrayStone_001.JPG"; specular[0] = "0.9 0.9 0.9 1"; specularPower[0] = "56"; translucentBlendOp = "None"; normalMap[0] = "3TD_LayeredGrayStone_001_NRM.png"; pixelSpecular[0] = "1"; useAnisotropic[0] = "1"; doubleSided = "1"; }; singleton Material(Cliff_01_ColColor) { mapTo = "ColColor"; diffuseColor[0] = "0.588235 0.588235 0.588235 1"; specular[0] = "0.9 0.9 0.9 1"; specularPower[0] = "10"; translucentBlendOp = "None"; };
26.130435
54
0.633943
[ "Unlicense" ]
Torque3D-Games-Demos/FreeRPG
art/shapes/CaveFeatures/Cliff_01/materials.cs
579
C#
using System.Collections.Generic; namespace ServiceStack.DesignPatterns.Command { public interface ICommandIList<T> : IList<T> { } }
18.125
48
0.731034
[ "BSD-3-Clause" ]
Dashboard-X/ServiceStack
src/ServiceStack.Interfaces/DesignPatterns/Command/ICommandIList.cs
145
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System.Collections.Generic; namespace EdFi.Ods.Api.IntegrationTestHarness { public class TestHarnessConfiguration { public List<Vendor> Vendors { get; set; } } public class Vendor { public string Email { get; set; } public string VendorName { get; set; } public List<Application> Applications { get; set; } public List<string> NamespacePrefixes { get; set; } } public class Application { public string ApplicationName { get; set; } public string ClaimSetName { get; set; } public List<ApiClient> ApiClients { get; set; } public List<string> Profiles { get; set; } } public class ApiClient { public string ApiClientName { get; set; } public string Key { get; set; } public string Secret { get; set; } public List<int> LocalEducationOrganizations { get; set; } public string OwnershipToken { get; set; } public List<string> ApiClientOwnershipTokens { get; set; } } }
25.018868
86
0.645551
[ "Apache-2.0" ]
milanatedufied/Ed-Fi-ODS-Implementation
Application/EdFi.Ods.Api.IntegrationTestHarness/TestHarnessConfiguration.cs
1,328
C#
// *********************************************************************** // Assembly : StarMath // Author : MICampbell // Created : 05-14-2015 // // Last Modified By : MICampbell // Last Modified On : 07-16-2015 // *********************************************************************** // <copyright file="add subtract multiply.cs" company="Design Engineering Lab -- MICampbell"> // 2014 // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Collections.Generic; using System.Linq; namespace StarMathLib { public class SparseMatrix { #region Fields and Properties public bool TopologyChanged { get; private set; } = true; public bool ValuesChanged { get; private set; } = true; private readonly List<SparseCell> cellsRowbyRow; /// <summary> /// The first non-zero cell in each row. /// </summary> internal SparseCell[] Diagonals { get; } /// <summary> /// The first non-zero cell in each row. /// </summary> internal SparseCell[] RowFirsts { get; private set; } /// <summary> /// The last non-zero cell in each row. /// </summary> internal SparseCell[] RowLasts { get; private set; } /// <summary> /// The first non-zero cell in each column. /// </summary> internal SparseCell[] ColFirsts { get; private set; } /// <summary> /// The last non-zero cell in each column. /// </summary> internal SparseCell[] ColLasts { get; private set; } /// <summary> /// The number non zero /// </summary> public int NumNonZero { get; private set; } /// <summary> /// The number cols /// </summary> public int NumCols { get; private set; } /// <summary> /// The number rows /// </summary> public int NumRows { get; private set; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SparseMatrix" /> class. /// </summary> /// <param name="rowIndices">The row indices.</param> /// <param name="colIndices">The col indices.</param> /// <param name="values">The values.</param> /// <param name="numRows">The number rows.</param> /// <param name="numCols">The number cols.</param> public SparseMatrix(IList<int> rowIndices, IList<int> colIndices, IList<double> values, int numRows, int numCols) : this(numRows, numCols) { var count = values.Count; for (int i = 0; i < count; i++) this[rowIndices[i], colIndices[i]] += values[i]; NumNonZero = cellsRowbyRow.Count; } /// <summary> /// Initializes a new instance of the <see cref="SparseMatrix"/> class. /// </summary> /// <param name="indices">The row by row indices.</param> /// <param name="values">The values.</param> /// <param name="numRows">The number rows.</param> /// <param name="numCols">The number cols.</param> /// <param name="InRowOrder">The in row order.</param> public SparseMatrix(IList<int> indices, IList<double> values, int numRows, int numCols, bool InRowOrder = true) : this(numRows, numCols) { if (InRowOrder) { #region Fill-in In Order /* this is an elaborate method to speed up the stitching together of new cells */ var rowI = 0; var rowLowerLimit = 0; var rowUpperLimit = NumCols; var newRow = true; for (var i = 0; i < values.Count; i++) { var index = indices[i]; var value = values[i]; while (i < values.Count - 1 && indices[i] == indices[i + 1]) { i++; value += values[i]; } while (index >= rowUpperLimit) { newRow = true; rowI++; rowLowerLimit += NumCols; rowUpperLimit += NumCols; } var colI = index - rowLowerLimit; var cell = new SparseCell(rowI, colI, value); if (rowI == colI) Diagonals[rowI] = cell; cellsRowbyRow.Add(cell); if (newRow) { RowFirsts[rowI] = cell; RowLasts[rowI] = cell; newRow = false; } else { cell.Left = RowLasts[rowI]; RowLasts[rowI].Right = cell; RowLasts[rowI] = cell; } if (ColFirsts[colI] == null) { ColFirsts[colI] = cell; ColLasts[colI] = cell; } else { cell.Up = ColLasts[colI]; ColLasts[colI].Down = cell; ColLasts[colI] = cell; } } #endregion } else { var count = values.Count; for (int i = 0; i < count; i++) { var index = indices[i]; var rowI = index / NumCols; var colI = index % NumCols; this[rowI, colI] += values[i]; } } NumNonZero = cellsRowbyRow.Count; } /// <summary> /// Initializes a new instance of the <see cref="SparseMatrix"/> class. /// </summary> /// <param name="cellDictionary">The cell dictionary with keys as [i,j] pairs.</param> /// <param name="numRows">The number rows.</param> /// <param name="numCols">The number cols.</param> public SparseMatrix(Dictionary<int[], double> cellDictionary, int numRows, int numCols) : this(numRows, numCols) { foreach (var keyValuePair in cellDictionary) this[keyValuePair.Key[0], keyValuePair.Key[1]] += keyValuePair.Value; NumNonZero = cellsRowbyRow.Count; } /// <summary> /// Initializes a new instance of the <see cref="SparseMatrix"/> class. /// </summary> /// <param name="numRows">The number rows.</param> /// <param name="numCols">The number cols.</param> public SparseMatrix(int numRows, int numCols) { cellsRowbyRow = new List<SparseCell>(); NumRows = numRows; NumCols = numCols; Diagonals = new SparseCell[numRows]; RowFirsts = new SparseCell[numRows]; RowLasts = new SparseCell[numRows]; ColFirsts = new SparseCell[numCols]; ColLasts = new SparseCell[numCols]; } /// <summary> /// Updates the values. /// </summary> /// <param name="rowIndices">The row indices.</param> /// <param name="colIndices">The col indices.</param> /// <param name="values">The values.</param> public void UpdateValues(IList<int> rowIndices, IList<int> colIndices, IList<double> values) { ValuesChanged = true; foreach (var sparseCell in cellsRowbyRow) sparseCell.Value = 0; var count = values.Count; for (int i = 0; i < count; i++) this[rowIndices[i], colIndices[i]] += values[i]; } /// <summary> /// Initializes a new instance of the <see cref="SparseMatrix" /> class. /// </summary> /// <param name="rowByRowIndices">The row by row indices.</param> /// <param name="values">The values.</param> /// <param name="InRowOrder">The in row order.</param> public void UpdateValues(IList<int> rowByRowIndices, IList<double> values, bool InRowOrder) { ValuesChanged = true; foreach (var sparseCell in cellsRowbyRow) sparseCell.Value = 0; var count = values.Count; if (InRowOrder) { var i = 0; foreach (var sparseCell in cellsRowbyRow) { var cellIndex = rowByRowIndices[i]; do { sparseCell.Value += values[i++]; } while (i < count && rowByRowIndices[i] == cellIndex); } } else { for (int i = 0; i < count; i++) { var index = rowByRowIndices[i]; var rowI = index / NumCols; var colI = index % NumCols; this[rowI, colI] += values[i]; } } } #endregion /// <summary> /// Converts the sparse matrix to a dense matrix. /// </summary> /// <returns>System.Double[].</returns> public double[,] ConvertSparseToDenseMatrix() { var A = new double[NumRows, NumCols]; for (int i = 0; i < NumRows; i++) { var cell = RowFirsts[i]; while (cell != null) { A[i, cell.ColIndex] = cell.Value; cell = cell.Right; } } return A; } #region Finding Cell(s) Methods /// <summary> /// Gets or sets the <see cref="System.Double" /> with the specified row i. /// </summary> /// <param name="rowI">The row i.</param> /// <param name="colI">The col i.</param> /// <returns>System.Double.</returns> public double this[int rowI, int colI] { get { var c = CellAt(rowI, colI); if (c == null) return 0.0; else return c.Value; } set { var c = CellAt(rowI, colI); if (c == null) AddCell(rowI, colI, value); else c.Value = value; ValuesChanged = true; } } private SparseCell CellAt(int rowI, int colI) { if (rowI == colI) return Diagonals[rowI]; if (rowI >= colI) return SearchRightToCell(colI, RowFirsts[rowI]); return SearchDownToCell(rowI, ColFirsts[colI]); } /// <summary> /// Searches the left to. /// </summary> /// <param name="colIndex">Index of the col.</param> /// <param name="startCell">The start cell.</param> /// <returns>SparseCell.</returns> private Boolean TrySearchRightToCell(int colIndex, ref SparseCell startCell) { while (true) { if (startCell == null || startCell.ColIndex > colIndex) return false; if (startCell.ColIndex == colIndex) return true; startCell = startCell.Right; } } /// <summary> /// Searches the left to. /// </summary> /// <param name="colIndex">Index of the col.</param> /// <param name="startCell">The start cell.</param> /// <returns>SparseCell.</returns> private SparseCell SearchRightToCell(int colIndex, SparseCell startCell) { while (true) { if (startCell == null || startCell.ColIndex > colIndex) return null; if (startCell.ColIndex == colIndex) return startCell; startCell = startCell.Right; } } /// <summary> /// Searches down to. /// </summary> /// <param name="rowIndex">Index of the row.</param> /// <param name="startCell">The start cell.</param> /// <returns>SparseCell.</returns> /// <exception cref="ArithmeticException">No non-zero sparse matrix cell found at the location.</exception> private SparseCell SearchDownToCell(int rowIndex, SparseCell startCell) { while (true) { if (startCell == null || startCell.RowIndex > rowIndex) return null; if (startCell.RowIndex == rowIndex) return startCell; startCell = startCell.Down; } } #endregion public SparseMatrix Copy() { return new SparseMatrix(cellsRowbyRow.Select(x => x.RowIndex * NumCols + x.ColIndex).ToArray(), cellsRowbyRow.Select(c => c.Value).ToArray(), NumRows, NumCols); } private void RemoveCell(SparseCell cell) { if (cell.Left == null) RowFirsts[cell.RowIndex] = cell.Right; else cell.Left.Right = cell.Right; if (cell.Right == null) RowLasts[cell.RowIndex] = cell.Left; else cell.Right.Left = cell.Left; if (cell.Up == null) ColFirsts[cell.ColIndex] = cell.Down; else cell.Up.Down = cell.Down; if (cell.Down == null) ColLasts[cell.ColIndex] = cell.Up; else cell.Down.Up = cell.Up; cellsRowbyRow.Remove(cell); NumNonZero--; TopologyChanged = true; } private SparseCell AddCell(int rowI, int colI, double value = Double.NaN) { var cell = new SparseCell(rowI, colI, value); // stitch it into the rows if (RowFirsts[rowI] == null && RowLasts[rowI] == null) RowFirsts[rowI] = RowLasts[rowI] = cell; else if (RowFirsts[rowI] == null || RowFirsts[rowI].ColIndex > colI) { cell.Right = RowFirsts[rowI]; RowFirsts[rowI].Left = cell; RowFirsts[rowI] = cell; } else if (RowLasts[rowI].ColIndex < colI) { cell.Left = RowLasts[rowI]; RowLasts[rowI].Right = cell; RowLasts[rowI] = cell; } else { var startCell = RowFirsts[rowI]; while (startCell.ColIndex < colI) startCell = startCell.Right; cell.Right = startCell; cell.Left = startCell.Left; cell.Left.Right = cell; startCell.Left = cell; } // stitch it into the colums if (ColFirsts[colI] == null && ColLasts[colI] == null) ColFirsts[colI] = ColLasts[colI] = cell; else if (ColFirsts[colI].RowIndex > rowI) { cell.Down = ColFirsts[colI]; ColFirsts[colI].Up = cell; ColFirsts[colI] = cell; } else if (ColLasts[colI].RowIndex < rowI) { cell.Up = ColLasts[colI]; ColLasts[colI].Down = cell; ColLasts[colI] = cell; } else { var startCell = ColFirsts[colI]; while (startCell.RowIndex < rowI) startCell = startCell.Down; cell.Down = startCell; cell.Up = startCell.Up; cell.Up.Down = cell; startCell.Up = cell; } if (rowI == colI) Diagonals[rowI] = cell; cellsRowbyRow.Add(cell); NumNonZero++; TopologyChanged = true; return cell; } /// <summary> /// Finds the index of the insertion within the cellsRowbyRow. Of course, there are built-in functions to do this, /// but the idea with writing our own is that we can make a faster search given information that is known about /// this . /// </summary> /// <param name="cell">The cell.</param> /// <returns>System.Int32.</returns> //private int FindInsertionIndex(SparseCell cell) //{ //int i= cellsRowbyRow.IndexOf(cell); // if (i >= 0) return i; //var averageCellPerRow = NumNonZero / NumRows; //var index = Math.Min(averageCellPerRow * cell.RowIndex + cell.ColIndex, NumNonZero - 1); //int step = averageCellPerRow; //do //{ // if (cell.RowIndex < cellsRowbyRow[index].RowIndex // || (cell.RowIndex == cellsRowbyRow[index].RowIndex // && cell.ColIndex < cellsRowbyRow[index].ColIndex)) // { // if (index == 0 || step == 1) step = 0; // else if (step > 0) step = -step / 2; // } // else if (cell.RowIndex > cellsRowbyRow[index].RowIndex // || (cell.RowIndex == cellsRowbyRow[index].RowIndex // && cell.ColIndex > cellsRowbyRow[index].ColIndex)) // { // if (index == NumNonZero - 1 || step == -1) step = 0; // else if (step < 0) step = -step / 2; // } // else step = 0; // index += step; // if (index < 0) // { // step -= index; // index = 0; // } // else if (index >= NumNonZero) // { // step = index - (NumNonZero - 1); // index = NumNonZero - 1; // } //} while (step != 0); //return index; //} /// <summary> /// Removes the row. /// </summary> /// <param name="rowIndexToRemove">The row index to remove.</param> public void RemoveRow(int rowIndexToRemove) { TopologyChanged = true; var thisCell = RowFirsts[rowIndexToRemove]; while (thisCell != null) { var nextCell = thisCell.Right; RemoveCell(thisCell); if (thisCell.ColIndex == rowIndexToRemove) Diagonals[rowIndexToRemove] = null; thisCell = nextCell; } NumRows--; var newRowFirsts = new SparseCell[NumRows]; var newRowLasts = new SparseCell[NumRows]; for (int i = 0; i < rowIndexToRemove; i++) { newRowFirsts[i] = RowFirsts[i]; newRowLasts[i] = RowLasts[i]; } for (int i = rowIndexToRemove; i < NumRows; i++) { newRowFirsts[i] = RowFirsts[i + 1]; newRowLasts[i] = RowLasts[i + 1]; var cell = RowFirsts[i + 1]; while (cell != null) { cell.RowIndex = i; if (cell.ColIndex == i) Diagonals[i] = cell; cell = cell.Right; } } RowFirsts = newRowFirsts; RowLasts = newRowLasts; } /// <summary> /// Removes the column. /// </summary> /// <param name="colIndexToRemove">The col index to remove.</param> public void RemoveColumn(int colIndexToRemove) { TopologyChanged = true; var thisCell = ColFirsts[colIndexToRemove]; while (thisCell != null) { var nextCell = thisCell.Down; RemoveCell(thisCell); if (thisCell.RowIndex == colIndexToRemove) Diagonals[colIndexToRemove] = null; thisCell = nextCell; } NumCols--; var newColFirsts = new SparseCell[NumCols]; var newColLasts = new SparseCell[NumCols]; for (int i = 0; i < colIndexToRemove; i++) { newColFirsts[i] = ColFirsts[i]; newColLasts[i] = ColLasts[i]; } for (int i = colIndexToRemove; i < NumCols; i++) { newColFirsts[i] = ColFirsts[i + 1]; newColLasts[i] = ColLasts[i + 1]; var cell = ColFirsts[i + 1]; while (cell != null) { cell.ColIndex = i; if (cell.RowIndex == i) Diagonals[i] = cell; cell = cell.Down; } } ColFirsts = newColFirsts; ColLasts = newColLasts; } /// <summary> /// Removes the rows. /// </summary> /// <param name="rowIndicesToRemove">The row indices to remove.</param> public void RemoveRows(IList<int> rowIndicesToRemove) { TopologyChanged = true; var numToRemove = rowIndicesToRemove.Count; var removeIndices = rowIndicesToRemove.OrderBy(i => i).ToArray(); for (int i = 0; i < numToRemove; i++) { var cell = RowFirsts[removeIndices[i]]; while (cell != null) { var nextCell = cell.Right; RemoveCell(cell); if (cell.ColIndex == cell.RowIndex) Diagonals[cell.RowIndex] = null; cell = nextCell; } } NumRows -= numToRemove; var newRowFirsts = new SparseCell[NumRows]; var newRowLasts = new SparseCell[NumRows]; var offset = 0; for (int i = 0; i < NumRows; i++) { while (offset < numToRemove && (i + offset) == removeIndices[offset]) offset++; newRowFirsts[i] = RowFirsts[i + offset]; newRowLasts[i] = RowLasts[i + offset]; var cell = RowFirsts[i + offset]; while (cell != null) { cell.RowIndex = i; if (cell.ColIndex == i) Diagonals[i] = cell; cell = cell.Right; } } RowFirsts = newRowFirsts; RowLasts = newRowLasts; } /// <summary> /// Removes the columns. /// </summary> /// <param name="colIndicesToRemove">The col indices to remove.</param> public void RemoveColumns(IList<int> colIndicesToRemove) { TopologyChanged = true; var numToRemove = colIndicesToRemove.Count; var removeIndices = colIndicesToRemove.OrderBy(i => i).ToArray(); for (int i = 0; i < numToRemove; i++) { var cell = ColFirsts[removeIndices[i]]; while (cell != null) { var nextCell = cell.Down; RemoveCell(cell); if (cell.ColIndex == cell.RowIndex) Diagonals[cell.RowIndex] = null; cell = nextCell; } } NumCols -= numToRemove; var newColFirsts = new SparseCell[NumCols]; var newColLasts = new SparseCell[NumCols]; var offset = 0; for (int i = 0; i < NumCols; i++) { while (offset < numToRemove && (i + offset) == removeIndices[offset]) offset++; newColFirsts[i] = ColFirsts[i + offset]; newColLasts[i] = ColLasts[i + offset]; var cell = ColFirsts[i + offset]; while (cell != null) { cell.ColIndex = i; if (cell.RowIndex == i) Diagonals[i] = cell; cell = cell.Down; } } ColFirsts = newColFirsts; ColLasts = newColLasts; } public void Transpose() { TopologyChanged = true; var tempArray = RowFirsts; RowFirsts = ColFirsts; ColFirsts = tempArray; tempArray = RowLasts; RowLasts = ColLasts; ColLasts = tempArray; foreach (var sparseCell in cellsRowbyRow) { var tempCell = sparseCell.Right; sparseCell.Right = sparseCell.Down; sparseCell.Down = tempCell; tempCell = sparseCell.Left; sparseCell.Left = sparseCell.Up; sparseCell.Up = tempCell; var tempIndex = sparseCell.RowIndex; sparseCell.RowIndex = sparseCell.ColIndex; sparseCell.ColIndex = tempIndex; } var tempLimit = NumRows; NumRows = NumCols; NumCols = tempLimit; //cellsRowbyRow.Clear(); //for (int i = 0; i < NumRows; i++) //{ // var cell = RowFirsts[i]; // while (cell != null) // { // cellsRowbyRow.Add(cell); // cell = cell.Right; // } //} } #region Scalars multiplying matrices /// <summary> /// Multiplies all elements of this sparse matrix with a double value. /// </summary> /// <param name="a">The double value to be multiplied</param> /// <returns>A 2D double array that contains the product</returns> public void multiply(double a) { foreach (var sparseCell in cellsRowbyRow) sparseCell.Value *= a; } /// <summary> /// Divides all elements of this sparse matrix with a double value. /// </summary> /// <param name="a">The double value to be divided by.</param> /// <returns>A 2D double array that contains the product</returns> public void Divide(double a) { multiply(1 / a); } #endregion #region Matrix(2D) to matrix(2D) multiplication /// <summary> /// Multiplies this sparse matrix by a 2D double array. This sparse matrix is /// altered to reflect the result. /// </summary> /// <param name="A">a.</param> /// <exception cref="NotImplementedException"></exception> public void multiplyInPlace(double[,] A) { throw new NotImplementedException(); //var C = new double[numRows, numCols]; //for (var i = 0; i NumRows; i++) // for (var j = 0; j != numCols; j++) // { // C[i, j] = 0.0; // for (var k = 0; k != A.GetLength(1); k++) // C[i, j] += A[i, k] * B[k, j]; // } //return C; } /// <summary> /// Multiplies this sparse matrix by a 2D double array, and returns a new double array. /// </summary> /// <param name="A">a.</param> /// <returns>System.Double[].</returns> /// <exception cref="NotImplementedException"></exception> public double[,] multiply(double[,] A) { throw new NotImplementedException(); } #endregion #region Multiply matrix to a vector (and vice versa) /// <summary> /// Multiplies the specified x. /// </summary> /// <param name="x">The x.</param> /// <returns>System.Double[].</returns> /// <exception cref="ArithmeticException">Matrix number of columns does not match length of vector.</exception> public double[] multiply(IList<double> x) { var length = x.Count; if (length != NumCols) throw new ArithmeticException("Matrix number of columns does not match length of vector."); var b = new double[length]; for (int i = 0; i < NumRows; i++) { var sum = 0.0; var cell = RowFirsts[i]; while (cell != null) { sum += cell.Value * x[cell.ColIndex]; cell = cell.Right; } b[i] = sum; } return b; } #endregion /// <summary> /// Adds the specified 2D double array, A to this sparse matrix to create a new /// 2D double array. /// </summary> /// <param name="A">a.</param> /// <returns>System.Double[].</returns> /// <exception cref="NotImplementedException"></exception> public double[,] add(double[,] A) { var numRows = A.GetLength(0); if (NumRows != numRows) throw new ArithmeticException("Cannot add matrices of different sizes."); var numCols = A.GetLength(1); if (NumCols != numCols) throw new ArithmeticException("Cannot add matrices of different sizes."); var C = (double[,])A.Clone(); for (var i = 0; i < numRows; i++) { var cell = RowFirsts[i]; while (cell != null) { C[i, cell.ColIndex] += cell.Value; cell = cell.Right; } } return C; } /// <summary> /// Subtracts the specified 2D double array, A to this sparse matrix to create a new /// 2D double array. /// </summary> /// <param name="A">a.</param> /// <returns>System.Double[].</returns> /// <exception cref="System.ArithmeticException"> /// Cannot subtract matrices of different sizes. /// </exception> public double[,] subtract(double[,] A) { var numRows = A.GetLength(0); if (NumRows != numRows) throw new ArithmeticException("Cannot subtract matrices of different sizes."); var numCols = A.GetLength(1); if (NumCols != numCols) throw new ArithmeticException("Cannot subtract matrices of different sizes."); var C = (double[,])A.Clone(); for (var i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) C[i, j] = -C[i, j]; var cell = RowFirsts[i]; while (cell != null) { C[i, cell.ColIndex] += cell.Value; cell = cell.Right; } } return C; } /// <summary> /// Adds the specified 2D double array, A to this sparse matrix and writes over /// this sparse matrix with the result. /// </summary> /// <param name="A">a.</param> /// <exception cref="System.ArithmeticException">Adding Sparse Matrices can only be accomplished if both are the same size.</exception> public void addInPlace(SparseMatrix A) { if (NumRows != A.NumRows || NumCols != A.NumCols) throw new ArithmeticException( "Adding Sparse Matrices can only be accomplished if both are the same size."); for (var i = 0; i < NumRows; i++) { var thisCell = RowFirsts[i]; var ACell = A.RowFirsts[i]; while (thisCell != null || ACell != null) { if (thisCell == null || (ACell != null && ACell.ColIndex < thisCell.ColIndex)) { AddCell(i, ACell.ColIndex, ACell.Value); ACell = ACell.Right; } else if (ACell == null || thisCell.ColIndex < ACell.ColIndex) { thisCell = thisCell.Right; } else //then the two values must be at the same cell { thisCell.Value += ACell.Value; thisCell = thisCell.Right; ACell = ACell.Right; } } } } /// <summary> /// Subtracts the specified 2D double array, A from this sparse matrix and writes over /// this sparse matrix with the result. /// </summary> /// <param name="A">a.</param> /// <exception cref="System.ArithmeticException">Adding Sparse Matrices can only be accomplished if both are the same size.</exception> public void subtractInPlace(SparseMatrix A) { if (NumRows != A.NumRows || NumCols != A.NumCols) throw new ArithmeticException( "Adding Sparse Matrices can only be accomplished if both are the same size."); for (var i = 0; i < NumRows; i++) { var thisCell = RowFirsts[i]; var ACell = A.RowFirsts[i]; while (thisCell != null || ACell != null) { if (thisCell == null || (ACell != null && ACell.ColIndex < thisCell.ColIndex)) { AddCell(i, ACell.ColIndex, -ACell.Value); ACell = ACell.Right; } else if (ACell == null || thisCell.ColIndex < ACell.ColIndex) { thisCell = thisCell.Right; } else //then the two values must be at the same cell { thisCell.Value -= ACell.Value; thisCell = thisCell.Right; ACell = ACell.Right; } } } } /// <summary> /// Adds the specified 2D double array, A to this sparse matrix to create a new /// 2D double array. /// </summary> /// <param name="A">a.</param> /// <returns>System.Double[].</returns> /// <exception cref="NotImplementedException"></exception> public SparseMatrix add(SparseMatrix A) { var copy = this.Copy(); copy.addInPlace(A); return copy; } /// <summary> /// Subtracts the specified 2D double array, A from this sparse matrix to create a new /// 2D double array. /// </summary> /// <param name="A">a.</param> /// <returns>System.Double[].</returns> /// <exception cref="NotImplementedException"></exception> public SparseMatrix subtract(SparseMatrix A) { var copy = this.Copy(); copy.subtractInPlace(A); return copy; } /// <summary> /// Sums all elements. /// </summary> /// <returns>System.Double.</returns> public double SumAllElements() { return SumAllRows().Sum(); } /// <summary> /// Sums all of the rows. /// </summary> /// <returns>System.Double[].</returns> public double[] SumAllRows() { var rowSums = new double[NumRows]; for (int i = 0; i < NumRows; i++) rowSums[i] = SumRow(i); return rowSums; } /// <summary> /// Sums the values of a specified row. /// </summary> /// <returns>System.Double[].</returns> public double SumRow(int index) { var sum = 0.0; var cell = RowFirsts[index]; while (cell != null) { sum += cell.Value; cell = cell.Right; } return sum; } /// <summary> /// Sums the columns. /// </summary> /// <returns>System.Double[].</returns> public double[] SumAllColumns() { var colSums = new double[NumCols]; for (int i = 0; i < NumCols; i++) colSums[i] = SumColumn(i); return colSums; } /// <summary> /// Sums the values of a specified column. /// </summary> /// <returns>System.Double[].</returns> public double SumColumn(int index) { var sum = 0.0; var cell = ColFirsts[index]; while (cell != null) { sum += cell.Value; cell = cell.Down; } return sum; } private SymbolicFactorization symbolicFactorizationMat; private double[] D; private CompressedColumnStorage FactorizationMatrix; private CompressedColumnStorage MatrixInCCS; /// <summary> /// Solves the system of equations where this Sparse Matrix is 'A' in Ax = b. /// The resulting x is returned. /// </summary> /// <param name="b">The b.</param> /// <param name="initialGuess">The initial guess.</param> /// <param name="IsASymmetric">The is a symmetric.</param> /// <returns>System.Double[].</returns> /// <exception cref="System.ArithmeticException">Spare Matrix must be square to solve Ax = b. /// or /// Sparse Matrix must be have the same number of rows as the vector, b.</exception> /// <exception cref="ArithmeticException">Spare Matrix must be square to solve Ax = b. /// or /// Sparse Matrix must be have the same number of rows as the vector, b.</exception> public IList<double> solve(IList<double> b, IList<double> initialGuess = null, bool IsASymmetric = false) { if (NumRows != NumCols) throw new ArithmeticException("Spare Matrix must be square to solve Ax = b."); if (NumRows != b.Count) throw new ArithmeticException("Sparse Matrix must be have the same number of rows as the vector, b."); if (isGaussSeidelAppropriate(b, out var potentialDiagonals, ref initialGuess)) return SolveIteratively(b, initialGuess, potentialDiagonals); /****** need code to determine when to switch between ***** ****** this analytical approach and the SOR approach *****/ return SolveAnalytically(b, IsASymmetric); } public double[] solve(IList<double> bValues, IList<int> bIndices, IList<double> initialGuess = null, bool IsASymmetric = false) { if (NumRows != NumCols) throw new ArithmeticException("Spare Matrix must be square to solve Ax = b."); if (isGaussSeidelAppropriate(bValues, bIndices, out var potentialDiagonals, ref initialGuess)) return SolveIteratively(bValues, bIndices, initialGuess, potentialDiagonals); /****** need code to determine when to switch between ***** ****** this analytical approach and the SOR approach *****/ return SolveAnalytically(bValues, bIndices, IsASymmetric); } private double[] SolveIteratively(IList<double> bValues, IList<int> bIndices, IList<double> initialGuess, List<int>[] potentialDiagonals) { throw new NotImplementedException(); } private bool isGaussSeidelAppropriate(IList<double> bValues, IList<int> bIndices, out List<int>[] potentialDiagonals, ref IList<double> initialGuess) { throw new NotImplementedException(); } private double[] SolveAnalytically(IList<double> bValues, IList<int> bIndices, bool isASymmetric) { throw new NotImplementedException(); } /// <summary> /// Solves the system of equations analytically. /// </summary> /// <param name="b">The b.</param> /// <param name="IsASymmetric">if set to <c>true</c> [a is symmetric].</param> /// <param name="potentialDiagonals">The potential diagonals.</param> /// <returns>System.Double[].</returns> public IList<double> SolveAnalytically(IList<double> b, bool IsASymmetric = false) { if (IsASymmetric) { if (ValuesChanged || TopologyChanged) MatrixInCCS = convertToCCS(this); if (TopologyChanged) symbolicFactorizationMat = CSparse.SymbolicAnalysisLDL(MatrixInCCS); if (ValuesChanged || TopologyChanged) CSparse.FactorizeLDL(MatrixInCCS, symbolicFactorizationMat, out D, out FactorizationMatrix); TopologyChanged = ValuesChanged = false; return CSparse.SolveLDL(b, FactorizationMatrix, D, symbolicFactorizationMat.InversePermute); } else { var ccs = convertToCCS(this); var columnPermutation = ApproximateMinimumDegree.Generate( new SymbolicColumnStorage(ccs), NumCols); // Numeric LU factorization CSparse.FactorizeLU(ccs, columnPermutation, out var L, out var U, out var pinv); var x = CSparse.ApplyInverse(pinv, b, NumCols); // x = b(p) CSparse.SolveLower(L, x); // x = L\x. CSparse.SolveUpper(U, x); // x = U\x. return CSparse.ApplyInverse(columnPermutation, x, NumCols); // b(q) = x } } private static CompressedColumnStorage convertToCCS(SparseMatrix sparseMatrix) { var cellCounter = 0; var colCounter = 0; var ccs = new CompressedColumnStorage(sparseMatrix.NumRows, sparseMatrix.NumCols, sparseMatrix.NumNonZero); var columnPointers = new int[sparseMatrix.NumCols + 1]; columnPointers[0] = cellCounter; var rowIndices = new int[sparseMatrix.NumNonZero]; var values = new double[sparseMatrix.NumNonZero]; foreach (var topcell in sparseMatrix.ColFirsts) { var cell = topcell; while (cell != null) { values[cellCounter] = cell.Value; rowIndices[cellCounter] = cell.RowIndex; cell = cell.Down; cellCounter++; } columnPointers[++colCounter] = cellCounter; } ccs.ColumnPointers = columnPointers; ccs.RowIndices = rowIndices; ccs.Values = values; return ccs; } #region Gauss-Seidel or Successive Over-Relaxation private bool isGaussSeidelAppropriate(IList<double> b, out List<int>[] potentialDiagonals, ref IList<double> initialGuess) { potentialDiagonals = null; if (NumRows < StarMath.GaussSeidelMinimumMatrixSize) return false; if (initialGuess == null) initialGuess = makeInitialGuess(b); var error = StarMath.norm1(StarMath.subtract(b, multiply(initialGuess))) / b.norm1(); if (error > StarMath.MaxErrorForUsingGaussSeidel) return false; return findPotentialDiagonals(out potentialDiagonals, StarMath.GaussSeidelDiagonalDominanceRatio); } private bool findPotentialDiagonals(out List<int>[] potentialDiagonals, double minimalConsideration) { potentialDiagonals = new List<int>[NumRows]; for (var i = 0; i < NumRows; i++) { var cell = RowFirsts[i]; var norm1 = 0.0; do { norm1 += Math.Abs(cell.Value); cell = cell.Right; } while (cell != null); var potentialIndices = new List<int>(); cell = RowFirsts[i]; do { if (Math.Abs(cell.Value) / (norm1 - cell.Value) > minimalConsideration) potentialIndices.Add(cell.ColIndex); cell = cell.Right; } while (cell != null); if (potentialIndices.Count == 0) return false; potentialDiagonals[i] = potentialIndices; } return potentialDiagonals.SelectMany(x => x).Distinct().Count() == NumRows; } public double[] SolveIteratively(IList<double> b, IList<double> initialGuess = null, List<int>[] potentialDiagonals = null) { double[] x; if (initialGuess == null) x = makeInitialGuess(b); else x = initialGuess.ToArray(); if (potentialDiagonals == null && !findPotentialDiagonals(out potentialDiagonals, StarMath.GaussSeidelDiagonalDominanceRatio)) return null; var order = Enumerable.Range(0, NumRows).ToArray(); if (!order.All(rowIndex => potentialDiagonals[rowIndex].Contains(rowIndex))) order = reorderMatrixForDiagonalDominance(NumRows, potentialDiagonals); if (order == null) return null; var bNorm1 = StarMath.norm1(b); var error = StarMath.norm1(StarMath.subtract(b, multiply(x))) / bNorm1; var success = error <= StarMath.GaussSeidelMaxError; var xWentNaN = false; var iteration = NumRows * StarMath.GaussSeidelMaxIterationFactor; while (!xWentNaN && !success && iteration-- > 0) { for (var i = 0; i < NumRows; i++) { var rowI = order[i]; var diagCell = Diagonals[i]; var adjust = b[rowI]; var cell = RowFirsts[rowI]; do { if (cell != diagCell) adjust -= cell.Value * x[cell.ColIndex]; cell = cell.Right; } while (cell != null); x[rowI] = (1 - StarMath.GaussSeidelRelaxationOmega) * x[rowI] + StarMath.GaussSeidelRelaxationOmega * adjust / this[rowI, i]; } xWentNaN = x.Any(double.IsNaN); error = StarMath.norm1(StarMath.subtract(b, multiply(x))) / bNorm1; success = error <= StarMath.GaussSeidelMaxError; } if (!success) return null; return x; } private double[] makeInitialGuess(IList<double> b) { var initialGuess = new double[NumRows]; var initGuessValue = StarMath.SumAllElements(b) / SumAllElements(); for (var i = 0; i < NumRows; i++) initialGuess[i] = initGuessValue; return initialGuess; } private int[] reorderMatrixForDiagonalDominance(int length, List<int>[] potentialIndices) { var popularity = new int[length]; for (var i = 0; i < length; i++) popularity[i] = potentialIndices.Count(r => r.Contains(i)); var orderToAddress = StarMath.makeLinearProgression(length, 1).OrderBy(x => popularity[x]).ToList(); var stack = new Stack<int[]>(); var seed = new int[length]; int[] candidate; var solutionFound = false; for (var i = 0; i < length; i++) seed[i] = -1; stack.Push(seed); do { candidate = stack.Pop(); var numToFill = candidate.Count(x => x == -1); if (numToFill == 0) solutionFound = true; else { var colIndex = orderToAddress[length - numToFill]; var possibleIndicesForRow = new List<int>(); for (var oldRowIndex = 0; oldRowIndex < length; oldRowIndex++) { if (!potentialIndices[oldRowIndex].Contains(colIndex)) continue; if (candidate.Contains(oldRowIndex)) continue; possibleIndicesForRow.Add(oldRowIndex); } if (possibleIndicesForRow.Count == 1) { candidate[colIndex] = possibleIndicesForRow[0]; stack.Push(candidate); } else { possibleIndicesForRow = possibleIndicesForRow.OrderBy(r => Math.Abs(this[r, colIndex])).ToList(); foreach (var i in possibleIndicesForRow) { var child = (int[])candidate.Clone(); child[colIndex] = i; stack.Push(child); } } } } while (!solutionFound && stack.Count > 0); if (solutionFound) return candidate; return null; } #endregion } }
38.352025
157
0.487227
[ "MIT" ]
DesignEngrLab/StarMath
StarMath.NET Standard/Sparse Matrix/SparseMatrix.cs
49,246
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.Databricks.Outputs { [OutputType] public sealed class JobNewClusterClusterLogConf { public readonly Outputs.JobNewClusterClusterLogConfDbfs? Dbfs; public readonly Outputs.JobNewClusterClusterLogConfS3? S3; [OutputConstructor] private JobNewClusterClusterLogConf( Outputs.JobNewClusterClusterLogConfDbfs? dbfs, Outputs.JobNewClusterClusterLogConfS3? s3) { Dbfs = dbfs; S3 = s3; } } }
27.666667
88
0.691566
[ "ECL-2.0", "Apache-2.0" ]
XBeg9/pulumi-databricks
sdk/dotnet/Outputs/JobNewClusterClusterLogConf.cs
830
C#
using System; using System.Collections.Generic; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using rhoruntime; namespace rho { namespace PrintingZebraImpl { public class PrintingZebra : IPrintingZebraImpl { public PrintingZebra() { var _runtime = new PrintingZebraRuntimeComponent(this); } public void enable(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { // implement this method in C# here } public void start(IMethodResult oResult) { // implement this method in C# here } public void stop(IMethodResult oResult) { // implement this method in C# here } public void disable(IMethodResult oResult) { // implement this method in C# here } public void take(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { // implement this method in C# here } public void getProperty(string propertyName, IMethodResult oResult) { // implement this method in C# here } public void getProperties(IReadOnlyList<string> arrayofNames, IMethodResult oResult) { // implement this method in C# here } public void getAllProperties(IMethodResult oResult) { // implement this method in C# here } public void setProperty(string propertyName, string propertyValue, IMethodResult oResult) { // implement this method in C# here } public void setProperties(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { // implement this method in C# here } public void clearAllProperties(IMethodResult oResult) { // implement this method in C# here } } public class PrintingZebraSingleton : IPrintingZebraSingletonImpl { public PrintingZebraSingleton() { var _runtime = new PrintingZebraSingletonComponent(this); } public void enumerate(IMethodResult oResult) { // implement this method in C# here } } public class PrintingZebraFactory : IPrintingZebraFactoryImpl { public IPrintingZebraImpl getImpl() { return new PrintingZebra(); } public IPrintingZebraSingletonImpl getSingletonImpl() { return new PrintingZebraSingleton(); } } } }
26.273585
105
0.623339
[ "MIT" ]
esskar/rhodes
lib/commonAPI/printing_zebra/ext/platform/wp8/src/PrintingZebra_impl.cs
2,785
C#
using UnityEngine; using UnityEditor; namespace RealtimeCSG { [CustomPropertyDrawer(typeof(EnumAsFlagsAttribute))] [System.Reflection.Obfuscation(Exclude = true)] public sealed class EnumAsFlagsPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { property.intValue = EditorGUI.MaskField(position, label, property.intValue, property.enumNames); } } }
27.4375
99
0.792711
[ "MIT" ]
Cheebang/high-stakes
Assets/Plugins/RealtimeCSG/Editor/Scripts/View/GUI/PropertyDrawers/EnumAsFlags.PropertyDrawer.cs
441
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace EddiEvents { public class CrewFiredEvent : Event { public const string NAME = "Crew fired"; public const string DESCRIPTION = "Triggered when you fire crew"; public const string SAMPLE = "{\"timestamp\":\"2016-08-09T08: 46:29Z\",\"event\":\"CrewFire\",\"Name\":\"Margaret Parrish\"}"; public static Dictionary<string, string> VARIABLES = new Dictionary<string, string>(); static CrewFiredEvent() { VARIABLES.Add("name", "The name of the crewmember being fired"); } [JsonProperty("name")] public string name { get; private set; } public CrewFiredEvent(DateTime timestamp, string name) : base(timestamp, NAME) { this.name = name; } } }
30.428571
134
0.618545
[ "Apache-2.0" ]
Juggernaut93/EDDI
Events/CrewFiredEvent.cs
854
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.480) // Version 5.480.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Navigator { /// <summary> /// Navigator view element for drawing a selected check button for the Outlook mini mode. /// </summary> internal class ViewDrawNavOutlookMini : ViewDrawNavCheckButtonBase { #region Instance Fields private OutlookMiniController _controller; private readonly EventHandler _finishDelegate; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawNavOutlookSelected class. /// </summary> /// <param name="navigator">Owning navigator instance.</param> /// <param name="page">Page this check button represents.</param> /// <param name="orientation">Orientation for the check button.</param> public ViewDrawNavOutlookMini(KryptonNavigator navigator, KryptonPage page, VisualOrientation orientation) : base(navigator, page, orientation, navigator.StateDisabled.MiniButton, navigator.StateNormal.MiniButton, navigator.StateTracking.MiniButton, navigator.StatePressed.MiniButton, navigator.StateSelected.MiniButton, navigator.OverrideFocus.MiniButton) { // Create the finish handler for when popup is removed _finishDelegate = OnPopupFinished; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawNavOutlookMini:" + Id + " Text:" + Page.Text; } #endregion #region Page /// <summary> /// Gets the page this view represents. /// </summary> public override KryptonPage Page { set { base.Page = value; if (Page != null) { _overrideDisabled.SetPalettes(Page.OverrideFocus.MiniButton, Page.StateDisabled.MiniButton); _overrideNormal.SetPalettes(Page.OverrideFocus.MiniButton, Page.StateNormal.MiniButton); _overrideTracking.SetPalettes(Page.OverrideFocus.MiniButton, Page.StateTracking.MiniButton); _overridePressed.SetPalettes(Page.OverrideFocus.MiniButton, Page.StatePressed.MiniButton); _overrideSelected.SetPalettes(Page.OverrideFocus.MiniButton, Page.StateSelected.MiniButton); } else { _overrideDisabled.SetPalettes(Navigator.OverrideFocus.MiniButton, Navigator.StateDisabled.MiniButton); _overrideNormal.SetPalettes(Navigator.OverrideFocus.MiniButton, Navigator.StateNormal.MiniButton); _overrideTracking.SetPalettes(Navigator.OverrideFocus.MiniButton, Navigator.StateTracking.MiniButton); _overridePressed.SetPalettes(Navigator.OverrideFocus.MiniButton, Navigator.StatePressed.MiniButton); _overrideSelected.SetPalettes(Navigator.OverrideFocus.MiniButton, Navigator.StateSelected.MiniButton); } } } #endregion #region AllowButtonSpecs /// <summary> /// Gets a value indicating if button specs are allowed on the button. /// </summary> public override bool AllowButtonSpecs => false; #endregion #region IContentValues /// <summary> /// Gets the content image. /// </summary> /// <param name="state">The state for which the image is needed.</param> /// <returns>Image value.</returns> public override Image GetImage(PaletteState state) { return Page?.GetImageMapping(Navigator.Outlook.Mini.MiniMapImage); } /// <summary> /// Gets the content short text. /// </summary> /// <returns>String value.</returns> public override string GetShortText() { return Page?.GetTextMapping(Navigator.Outlook.Mini.MiniMapText) ?? string.Empty; } /// <summary> /// Gets the content long text. /// </summary> /// <returns>String value.</returns> public override string GetLongText() { return Page?.GetTextMapping(Navigator.Outlook.Mini.MiniMapExtraText) ?? string.Empty; } #endregion #region CreateMouseController /// <summary> /// Create a mouse controller appropriate for operating this button. /// </summary> /// <returns>Reference to IMouseController interface.</returns> protected override IMouseController CreateMouseController() { _controller = new OutlookMiniController(this, OnNeedPaint); _controller.Click += OnMiniClick; return _controller; } #endregion #region Implementation private void OnMiniClick(object sender, EventArgs e) { // Ask the navigator to show the specified page as a popup window // relative to our location as an element and firing the provided // delegate when the popup is dismissed. Navigator.ShowPopupPage(Page, this, _finishDelegate); } private void OnPopupFinished(object sender, EventArgs e) { // Remove the fixed display of the button, now the associated popup has been removed _controller.RemoveFixed(); } #endregion } }
41.575
157
0.60448
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.480
Source/Krypton Components/ComponentFactory.Krypton.Navigator/View Draw/ViewDrawNavOutlookMini.cs
6,655
C#
using System; using System.Collections.Generic; using System.Text; namespace GameSalesProject { public interface ISalesService { void DiscountRate(Game game); } }
16.333333
38
0.673469
[ "MIT" ]
yilmaziscoding/CustomerManager
ISalesService.cs
198
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StockMarketClient.StockMarketService; namespace StockMarketClient { class Program { static async Task Main(string[] args) { var client = new StockInfoServiceClient("BasicHttpBinding_IStockInfoService"); var stocks = await client.GetStocksAsync(); for (var i = 0; i < stocks.Length; i++) { var stock = stocks[i]; Console.WriteLine($"[{i+1}] {stock.Code}:\t{stock.Name}"); } Console.WriteLine("[Q] Quit"); Console.Write("Choose: "); var input = Console.ReadLine(); while (!"q".Equals(input, StringComparison.OrdinalIgnoreCase)) { if (int.TryParse(input, out int index) && index > 0 && index <= stocks.Length) { var stock = stocks[index - 1]; var now = DateTimeOffset.UtcNow; var price = await client.GetPriceAsync(stock.Code, now); Console.WriteLine(); Console.WriteLine($"{stock.Code} = {price} at {now:G}"); } Console.Write("Choose: "); input = Console.ReadLine(); } } } }
33.069767
95
0.507736
[ "MIT" ]
VisualReCode/VSToolboxDemo
StockMarketConsole/Program.cs
1,424
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// StoreOrderDTO Data Structure. /// </summary> public class StoreOrderDTO : AlipayObject { /// <summary> /// 买家id /// </summary> [JsonPropertyName("buyer_id")] public string BuyerId { get; set; } /// <summary> /// 联系电话 /// </summary> [JsonPropertyName("contact_phone")] public string ContactPhone { get; set; } /// <summary> /// 业务场景对应的扩展字段 /// </summary> [JsonPropertyName("ext")] public List<OrderExt> Ext { get; set; } /// <summary> /// 订单相关的商品信息 /// </summary> [JsonPropertyName("goods_info_list")] public List<StoreOrderGood> GoodsInfoList { get; set; } /// <summary> /// 订单的描述 /// </summary> [JsonPropertyName("memo")] public string Memo { get; set; } /// <summary> /// 订单的ID /// </summary> [JsonPropertyName("order_id")] public string OrderId { get; set; } /// <summary> /// 外部业务号 /// </summary> [JsonPropertyName("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 卖家id /// </summary> [JsonPropertyName("seller_id")] public string SellerId { get; set; } /// <summary> /// 姓名 /// </summary> [JsonPropertyName("user_name")] public string UserName { get; set; } } }
24.439394
63
0.508369
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Domain/StoreOrderDTO.cs
1,701
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Wolf.Utility.Core.Exceptions; using Wolf.Utility.Core.Logging; using Wolf.Utility.Core.Logging.Enum; namespace Wolf.Utility.Core.Transport { public class JsonManipulator { /// <summary> /// Parses Json file, and returns the attribute specified by 'propertyName'. /// </summary> /// <typeparam name="T">The type returned, from the property named after the input 'propertyName'.</typeparam> /// <param name="path">Path of the Json file.</param> /// <param name="propertyName">Name of the property to return.</param> /// <returns></returns> public static T ReadValueViaPath<T>(string path, string propertyName) { if (!File.Exists(path)) throw new ArgumentNullException(nameof(path), $@"No file Exist on the specified path => {path}"); if (path.Split('.').Last().ToLowerInvariant() != "json") throw new ArgumentException("The path given did not end in 'json'"); try { var json = File.ReadAllText(path); var obj = JObject.Parse(json); if (obj != null) return obj[propertyName].ToObject<T>(); throw new OperationFailedException($"Failed to parse Json from the file located at => {path}"); } catch (Exception ex) { throw; } } /// <summary> /// Deserializes Json file into specified model, and returns the property from it by the value specified in 'propertyName'. /// </summary> /// <typeparam name="T">The type returned, from the property named after the input 'propertyName'.</typeparam> /// <typeparam name="U">The model that is deserialized into, and from which the property is taken and returned.</typeparam> /// <param name="path">Path of the Json file.</param> /// <param name="propertyName">Name of the property to return.</param> /// <returns></returns> public static T ReadValueViaModelViaPath<T, U>(string path, string propertyName) where U : class, ISettingsModel { if (!File.Exists(path)) throw new ArgumentNullException(nameof(path), $@"No file Exist on the specified path => {path}"); if (path.Split('.').Last().ToLowerInvariant() != "json") throw new ArgumentException("The path given did not end in 'json'"); try { var json = File.ReadAllText(path); var obj = JsonConvert.DeserializeObject<U>(json, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.All }); var prop = obj.GetType().GetProperties().First(x => x.Name == propertyName); return (T)prop.GetValue(obj); } catch (Exception) { throw; } } public static U ReadModelFormPath<U>(string path) where U : class, ISettingsModel { if (!File.Exists(path)) throw new ArgumentNullException(nameof(path), $@"No file Exist on the specified path => {path}"); if ((path.Split('.')).Last().ToLowerInvariant() != "json") throw new ArgumentException("The path given did not end in 'json'"); try { var json = File.ReadAllText(path); var model = JsonConvert.DeserializeObject<U>(json, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }); return model; } catch (Exception e) { throw; } } public static void WriteModelToPath<U>(string path, U newModel, bool onlyUpdateIfDefault = false, params string[] propertyNames) where U : class, ISettingsModel { if (!File.Exists(path)) throw new ArgumentNullException(nameof(path), $@"No file Exist on the specified path => {path}"); if ((path.Split('.')).Last().ToLowerInvariant() != "json") throw new ArgumentException("The path given did not end in 'json'"); try { if (propertyNames.Length == 0) { SerializeAndWriteModel(path, newModel); } else { var oldJson = File.ReadAllText(path); var oldModel = JsonConvert.DeserializeObject<U>(oldJson, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }) ?? Activator.CreateInstance<U>(); foreach (var name in propertyNames) { var prop = newModel.GetType().GetProperties().First(x => x.Name == name); var isEmptyOrDefault = oldJson.Length == 0 || prop.GetValue(oldModel) == default; if (isEmptyOrDefault && onlyUpdateIfDefault) { prop.SetValue(oldModel, prop.GetValue(newModel)); } else if (!onlyUpdateIfDefault) { prop.SetValue(oldModel, prop.GetValue(newModel)); } } SerializeAndWriteModel(path, oldModel); } } catch (Exception) { throw; } } private static void SerializeAndWriteModel<U>(string path, U model) where U : class, ISettingsModel { var newJson = JsonConvert.SerializeObject(model, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }); File.WriteAllText(path, newJson); } public static void InitializeJsonDoc<U>(string path, U model, params string[] defaultElements) where U : class, ISettingsModel { if ((path.Split('.')).Last().ToLowerInvariant() != "json") throw new ArgumentException("The path given did not end in 'json'"); if (!File.Exists(path)) File.Create(path).Dispose(); WriteModelToPath(path, model, true, defaultElements); } } }
37.727778
168
0.535856
[ "MIT" ]
andr9528/Wolf.Utility.Core
Wolf.Utility.Core/Transport/JsonManipulator.cs
6,793
C#
namespace MercadoPagoCore.Client.Preference { /// <summary> /// Item information related to the category. /// </summary> public class PreferenceCategoryDescriptorRequest { /// <summary> /// Passenger information. /// </summary> public PreferencePassengerRequest Passenger { get; set; } /// <summary> /// Flight information. /// </summary> public PreferenceRouteRequest Route { get; set; } } }
25.421053
65
0.592133
[ "MIT" ]
cantte/MercadoPagoCore
MercadoPagoCore/Client/Preference/PreferenceCategoryDescriptorRequest.cs
485
C#
using CasaDoCodigo.Models; using Microsoft.EntityFrameworkCore; namespace CasaDoCodigo.Repositories { public class BaseRepository<T> where T : BaseModel { protected readonly ApplicationContext contexto; protected readonly DbSet<T> dbSet; public BaseRepository(ApplicationContext contexto) { this.contexto = contexto; dbSet = contexto.Set<T>(); } } }
22.631579
58
0.660465
[ "MIT" ]
danielnagami/Alura
dotNet/Asp.Net Core Parte 1/Aulas/Aula1/CasaDoCodigo/Repositories/BaseRepository.cs
432
C#
/** * Copyright 2017 The Nakama Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace Nakama { public class NSpaceJoinAck : INSpaceJoinAck { public string SpaceId { get; private set; } public IList<INEntity> Entities { get; private set; } public long SpaceSeq { get; private set; } public int UserSeq { get; private set; } internal NSpaceJoinAck(TSpaceJoinAck message) { SpaceId = message.SpaceId; var entities = new List<INEntity>(); foreach (var entity in message.Entities) { entities.Add(new NEntity(entity)); } Entities = entities.ToArray(); SpaceSeq = message.SpaceSeq; UserSeq = message.UserSeq; } public override string ToString() { var entities = new List<string>(); foreach (var entity in Entities){ entities.Add(entity.ToString()); } var entityStr = "["+string.Join(",\n", entities.ToArray())+"]"; var f = "NSpaceJoinAck(SpaceId={0},SpaceSeq={1},UserSeq={2},NEntities={3}"; return String.Format(f, SpaceId, SpaceSeq, UserSeq, entityStr); } } }
32
87
0.618421
[ "Apache-2.0" ]
auroraland-vr/auroraland-client
Assets/Nakama/Plugins/Nakama/NSpaceJoinAck.cs
1,824
C#
using Abp.Configuration; using Abp.Net.Mail; using Abp.Net.Mail.Smtp; using Abp.Runtime.Security; namespace YiHan.Cms.Emailing { public class CmsSmtpEmailSenderConfiguration : SmtpEmailSenderConfiguration { public CmsSmtpEmailSenderConfiguration(ISettingManager settingManager) : base(settingManager) { } public override string Password => SimpleStringCipher.Instance.Decrypt(GetNotEmptySettingValue(EmailSettingNames.Smtp.Password)); } }
28.588235
137
0.761317
[ "MIT" ]
Letheloney/YiHanCms
src/YiHan.Cms.Core/Emailing/CmsSmtpEmailSenderConfiguration.cs
488
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("ImageSort")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ImageSort")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
42.392857
98
0.706403
[ "MIT" ]
benkostr/ImageSort-CSharp
ImageSort/Properties/AssemblyInfo.cs
2,377
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.elasticsearch.Model.V20170613 { public class UpdateCollectorNameResponse : AcsResponse { private string requestId; private UpdateCollectorName_Result result; public string RequestId { get { return requestId; } set { requestId = value; } } public UpdateCollectorName_Result Result { get { return result; } set { result = value; } } public class UpdateCollectorName_Result { private string gmtCreatedTime; private string gmtUpdateTime; private string name; private string resId; private string resVersion; private string vpcId; private string resType; private string ownerId; private string status; private bool? dryRun; private List<UpdateCollectorName_ConfigsItem> configs; private List<UpdateCollectorName_ExtendConfigsItem> extendConfigs; private List<string> collectorPaths; public string GmtCreatedTime { get { return gmtCreatedTime; } set { gmtCreatedTime = value; } } public string GmtUpdateTime { get { return gmtUpdateTime; } set { gmtUpdateTime = value; } } public string Name { get { return name; } set { name = value; } } public string ResId { get { return resId; } set { resId = value; } } public string ResVersion { get { return resVersion; } set { resVersion = value; } } public string VpcId { get { return vpcId; } set { vpcId = value; } } public string ResType { get { return resType; } set { resType = value; } } public string OwnerId { get { return ownerId; } set { ownerId = value; } } public string Status { get { return status; } set { status = value; } } public bool? DryRun { get { return dryRun; } set { dryRun = value; } } public List<UpdateCollectorName_ConfigsItem> Configs { get { return configs; } set { configs = value; } } public List<UpdateCollectorName_ExtendConfigsItem> ExtendConfigs { get { return extendConfigs; } set { extendConfigs = value; } } public List<string> CollectorPaths { get { return collectorPaths; } set { collectorPaths = value; } } public class UpdateCollectorName_ConfigsItem { private string fileName; private string content; public string FileName { get { return fileName; } set { fileName = value; } } public string Content { get { return content; } set { content = value; } } } public class UpdateCollectorName_ExtendConfigsItem { private string configType; private string instanceId; private string instanceType; private string protocol; private string userName; private bool? enableMonitoring; private string type; private string groupId; private string host; private string kibanaHost; private List<UpdateCollectorName_MachinesItem> machines; private List<string> hosts; public string ConfigType { get { return configType; } set { configType = value; } } public string InstanceId { get { return instanceId; } set { instanceId = value; } } public string InstanceType { get { return instanceType; } set { instanceType = value; } } public string Protocol { get { return protocol; } set { protocol = value; } } public string UserName { get { return userName; } set { userName = value; } } public bool? EnableMonitoring { get { return enableMonitoring; } set { enableMonitoring = value; } } public string Type { get { return type; } set { type = value; } } public string GroupId { get { return groupId; } set { groupId = value; } } public string Host { get { return host; } set { host = value; } } public string KibanaHost { get { return kibanaHost; } set { kibanaHost = value; } } public List<UpdateCollectorName_MachinesItem> Machines { get { return machines; } set { machines = value; } } public List<string> Hosts { get { return hosts; } set { hosts = value; } } public class UpdateCollectorName_MachinesItem { private string instanceId; private string agentStatus; public string InstanceId { get { return instanceId; } set { instanceId = value; } } public string AgentStatus { get { return agentStatus; } set { agentStatus = value; } } } } } } }
14.413361
70
0.508691
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-elasticsearch/Elasticsearch/Model/V20170613/UpdateCollectorNameResponse.cs
6,904
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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; using SoonLearning.Math.Data; namespace SoonLearning.Math.Fast.RapidCalculation { /// <summary> /// Interaction logic for Question_a_b_c_PrintControl.xaml /// </summary> public partial class Question_a_b_c_PrintControl : UserControl { public bool ShowAnswer { set { if (!value) this.correctAnswerLabel.Visibility = System.Windows.Visibility.Hidden; else this.correctAnswerLabel.Visibility = System.Windows.Visibility.Visible; } } public bool ShowResult { set { if (!value) { this.feedbackImage.Visibility = System.Windows.Visibility.Hidden; this.resultLabel.Visibility = System.Windows.Visibility.Hidden; } else { this.feedbackImage.Visibility = System.Windows.Visibility.Visible; this.resultLabel.Visibility = System.Windows.Visibility.Visible; } } } public Question Question { set { this.DataContext = value; Question_a_b_c abc = value as Question_a_b_c; if (abc != null) this.SetOPImage(abc.Op); } } public Question_a_b_c_PrintControl(float fontSize, FontWeight fontWeight) { InitializeComponent(); foreach (UIElement element in this.rootGrid.Children) { if (element is Control) { Control ctrl = element as Control; ctrl.FontSize = fontSize; ctrl.FontWeight = FontWeight; } } if (MathSetting.Instance.SelectedMaxNumber < 100) { this.alabel.Width = 60; this.blabel.Width = 60; } else if (MathSetting.Instance.SelectedMaxNumber > 100 && MathSetting.Instance.SelectedMaxNumber < 1000) { this.alabel.Width = 100; this.blabel.Width = 100; } else { this.alabel.Width = 160; this.blabel.Width = 160; } } public Question_a_b_c_PrintControl(float fontSize, FontWeight fontWeight, SolidColorBrush foreground) { InitializeComponent(); foreach (UIElement element in this.rootGrid.Children) { if (element is Control) { Control ctrl = element as Control; ctrl.FontSize = fontSize; ctrl.FontWeight = FontWeight; ctrl.Foreground = foreground; } } if (MathSetting.Instance.SelectedMaxNumber < 100) { this.alabel.Width = 60; this.blabel.Width = 60; } else if (MathSetting.Instance.SelectedMaxNumber > 100 && MathSetting.Instance.SelectedMaxNumber < 1000) { this.alabel.Width = 100; this.blabel.Width = 100; } else { this.alabel.Width = 160; this.blabel.Width = 160; } } private void SetOPImage(Operator op) { switch (op) { case Operator.Plus: this.opImage.Source = new BitmapImage(new Uri(@"pack:\\application:,,,/Math;Component/Resources/add_print.png")); break; case Operator.Minus: this.opImage.Source = new BitmapImage(new Uri(@"pack:\\application:,,,/Math;Component/Resources/minus_print.png")); break; case Operator.Multiply: this.opImage.Source = new BitmapImage(new Uri(@"pack:\\application:,,,/Math;Component/Resources/mu_printl.png")); break; case Operator.Division: this.opImage.Source = new BitmapImage(new Uri(@"pack:\\application:,,,/Math;Component/Resources/div_print.png")); break; } } } }
32.496599
135
0.511199
[ "MIT" ]
LigangSun/AppCenter
source/Apps/Math/RapidCalculation/Question_a_b_c_PrintControl.xaml.cs
4,779
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 CustomBarcode.Generator.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.925926
151
0.585343
[ "MIT" ]
tsankoandreev/CustomBarcode
CustomBarcode.Generator/Properties/Settings.Designer.cs
1,080
C#
using LimitedLiability.Content; using LimitedLiability.Descriptors; using System; using System.Collections.Generic; using System.Linq; namespace LimitedLiability.Agents { public class JobFactory { private readonly Random random = new Random(); private readonly List<Job> jobs = new List<Job>(); public JobFactory(ContentManager contentManager) { IReadOnlyList<JobMetadata> jobMetadata = contentManager.Jobs; foreach (var job in jobMetadata) { List<JobLevel> jobLevels = new List<JobLevel>(); foreach (var jobLevel in job.JobLevelMetadata) { string prefix = jobLevel.Prefix; int salary; Int32.TryParse(jobLevel.Salary, out salary); int requiredIntelligence; Int32.TryParse(jobLevel.Intelligence, out requiredIntelligence); int requiredCreativity; Int32.TryParse(jobLevel.Creativitity, out requiredCreativity); int requiredCommunication; Int32.TryParse(jobLevel.Communication, out requiredCommunication); int requiredLeadership; Int32.TryParse(jobLevel.Leadership, out requiredLeadership); JobLevel newJobLevel = new JobLevel(prefix, salary, (Skills.Rating)requiredIntelligence, (Skills.Rating)requiredCreativity, (Skills.Rating)requiredCommunication, (Skills.Rating)requiredLeadership); jobLevels.Add(newJobLevel); } Job newJob = new Job(job.Title, jobLevels); jobs.Add(newJob); } } /// <summary> /// Return a random job at a random job level. For example: Janitor at Junior level or Sales at Senior level. /// </summary> /// <returns></returns> public Job CreateRandomJob() { int randomJobIndex = random.Next(0, jobs.Count - 1); int randomJobLevel = random.Next(0, 4); var job = jobs[randomJobIndex]; // return a copy because there is the potential for the employee to be promoted/demoted which will affect the individual state of the job object // if we returned a reference to the stored job object, every employee who had that reference would simultaneously be promoted/demoted var jobCopy = job.Copy(); for(int i = 0; i <= randomJobLevel; i++) jobCopy.Promote(); return jobCopy; } } }
31.735294
202
0.728916
[ "MIT" ]
babelshift/LimitedLiability
LimitedLiability/Agents/JobFactory.cs
2,160
C#
// Copyright (c) Christophe Gondouin (CGO Conseils). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading; using System.Windows.Forms; using DefinitionManager; namespace XrmFramework.DefinitionManager { class CustomListViewItem<T> : ListViewItem where T : AbstractDefinition { private Dictionary<string, ListViewSubItem> _subItems = new(); public CustomListViewItem(T definition) { Definition = definition; Checked = Definition.IsSelected; Text = definition.Name; foreach (var column in definition.GetColumns()) { if (column.Property.Name == "Name") { continue; } var item = new ListViewSubItem(this, column.Property.GetValue(definition) as string); _subItems.Add(column.Property.Name, item); SubItems.Add(item); } definition.PropertyChanged += definition_PropertyChanged; } void definition_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (_subItems.ContainsKey(e.PropertyName)) { var item = _subItems[e.PropertyName]; item.Text = typeof(T).GetProperty(e.PropertyName).GetValue(Definition) as string; } else if (e.PropertyName == "Name") { (new Thread(() => { Thread.Sleep(50); SetText(Definition.Name); })).Start(); } } delegate void SetTextCallback(string text); private void SetText(string text) { if (this.ListView == null) { return; } // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.ListView.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.ListView.Invoke(d, new object[] { text }); } else { this.Text = text; } } public T Definition { get; private set; } } }
30.864198
104
0.5464
[ "MIT" ]
PeteGuy/XrmFramework
src/XrmFramework.DefinitionManager/Utils/CustomListViewItem.cs
2,502
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> //------------------------------------------------------------------------------ // // This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 14.0.23107.0 // namespace TimeTrack.Client.UWP.TimeTrackService { using System.Runtime.Serialization; [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Project", Namespace="http://schemas.datacontract.org/2004/07/TimeTrack.Model")] public partial class Project : object, System.ComponentModel.INotifyPropertyChanged { private int ClosedField; private int FKProjectManagerField; private System.DateTime FinishDateField; private int IdField; private string NameField; private System.DateTime StartDateField; [System.Runtime.Serialization.DataMemberAttribute()] public int Closed { get { return this.ClosedField; } set { if ((this.ClosedField.Equals(value) != true)) { this.ClosedField = value; this.RaisePropertyChanged("Closed"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int FKProjectManager { get { return this.FKProjectManagerField; } set { if ((this.FKProjectManagerField.Equals(value) != true)) { this.FKProjectManagerField = value; this.RaisePropertyChanged("FKProjectManager"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime FinishDate { get { return this.FinishDateField; } set { if ((this.FinishDateField.Equals(value) != true)) { this.FinishDateField = value; this.RaisePropertyChanged("FinishDate"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime StartDate { get { return this.StartDateField; } set { if ((this.StartDateField.Equals(value) != true)) { this.StartDateField = value; this.RaisePropertyChanged("StartDate"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Employee", Namespace="http://schemas.datacontract.org/2004/07/TimeTrack.Model")] public partial class Employee : object, System.ComponentModel.INotifyPropertyChanged { private string FullNameField; private int IdField; [System.Runtime.Serialization.DataMemberAttribute()] public string FullName { get { return this.FullNameField; } set { if ((object.ReferenceEquals(this.FullNameField, value) != true)) { this.FullNameField = value; this.RaisePropertyChanged("FullName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="Timesheet", Namespace="http://schemas.datacontract.org/2004/07/TimeTrack.Model")] public partial class Timesheet : object, System.ComponentModel.INotifyPropertyChanged { private System.DateTime DateField; private int FkEmployeeField; private int FkProjectField; private int IdField; private string NotesField; private double SpendTimeField; [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime Date { get { return this.DateField; } set { if ((this.DateField.Equals(value) != true)) { this.DateField = value; this.RaisePropertyChanged("Date"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int FkEmployee { get { return this.FkEmployeeField; } set { if ((this.FkEmployeeField.Equals(value) != true)) { this.FkEmployeeField = value; this.RaisePropertyChanged("FkEmployee"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int FkProject { get { return this.FkProjectField; } set { if ((this.FkProjectField.Equals(value) != true)) { this.FkProjectField = value; this.RaisePropertyChanged("FkProject"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Notes { get { return this.NotesField; } set { if ((object.ReferenceEquals(this.NotesField, value) != true)) { this.NotesField = value; this.RaisePropertyChanged("Notes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public double SpendTime { get { return this.SpendTimeField; } set { if ((this.SpendTimeField.Equals(value) != true)) { this.SpendTimeField = value; this.RaisePropertyChanged("SpendTime"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="TimeTrackService.TimeTrackService")] public interface TimeTrackService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetProjects", ReplyAction="http://tempuri.org/TimeTrackService/GetProjectsResponse")] System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Project>> GetProjectsAsync(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetProjectById", ReplyAction="http://tempuri.org/TimeTrackService/GetProjectByIdResponse")] System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Project> GetProjectByIdAsync(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/AddProject", ReplyAction="http://tempuri.org/TimeTrackService/AddProjectResponse")] System.Threading.Tasks.Task AddProjectAsync(TimeTrack.Client.UWP.TimeTrackService.Project project); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/UpdateProject", ReplyAction="http://tempuri.org/TimeTrackService/UpdateProjectResponse")] System.Threading.Tasks.Task UpdateProjectAsync(TimeTrack.Client.UWP.TimeTrackService.Project project); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/DeleteProjectById", ReplyAction="http://tempuri.org/TimeTrackService/DeleteProjectByIdResponse")] System.Threading.Tasks.Task DeleteProjectByIdAsync(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetEmployees", ReplyAction="http://tempuri.org/TimeTrackService/GetEmployeesResponse")] System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Employee>> GetEmployeesAsync(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetEmployeeById", ReplyAction="http://tempuri.org/TimeTrackService/GetEmployeeByIdResponse")] System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Employee> GetEmployeeByIdAsync(System.Nullable<int> id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/AddEmployee", ReplyAction="http://tempuri.org/TimeTrackService/AddEmployeeResponse")] System.Threading.Tasks.Task AddEmployeeAsync(TimeTrack.Client.UWP.TimeTrackService.Employee employee); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/UpdateEmployee", ReplyAction="http://tempuri.org/TimeTrackService/UpdateEmployeeResponse")] System.Threading.Tasks.Task UpdateEmployeeAsync(TimeTrack.Client.UWP.TimeTrackService.Employee employee); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/DeleteEmployeeById", ReplyAction="http://tempuri.org/TimeTrackService/DeleteEmployeeByIdResponse")] System.Threading.Tasks.Task DeleteEmployeeByIdAsync(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetTimeSheets", ReplyAction="http://tempuri.org/TimeTrackService/GetTimeSheetsResponse")] System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Timesheet>> GetTimeSheetsAsync(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/GetTimeSheetById", ReplyAction="http://tempuri.org/TimeTrackService/GetTimeSheetByIdResponse")] System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Timesheet> GetTimeSheetByIdAsync(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/AddTimesheet", ReplyAction="http://tempuri.org/TimeTrackService/AddTimesheetResponse")] System.Threading.Tasks.Task AddTimesheetAsync(TimeTrack.Client.UWP.TimeTrackService.Timesheet timesheet); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/UpdateTimeSheet", ReplyAction="http://tempuri.org/TimeTrackService/UpdateTimeSheetResponse")] System.Threading.Tasks.Task UpdateTimeSheetAsync(TimeTrack.Client.UWP.TimeTrackService.Timesheet timesheet); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/TimeTrackService/DeleteTimesheetById", ReplyAction="http://tempuri.org/TimeTrackService/DeleteTimesheetByIdResponse")] System.Threading.Tasks.Task DeleteTimesheetByIdAsync(int id); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface TimeTrackServiceChannel : TimeTrack.Client.UWP.TimeTrackService.TimeTrackService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class TimeTrackServiceClient : System.ServiceModel.ClientBase<TimeTrack.Client.UWP.TimeTrackService.TimeTrackService>, TimeTrack.Client.UWP.TimeTrackService.TimeTrackService { public TimeTrackServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Project>> GetProjectsAsync() { return base.Channel.GetProjectsAsync(); } public System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Project> GetProjectByIdAsync(int id) { return base.Channel.GetProjectByIdAsync(id); } public System.Threading.Tasks.Task AddProjectAsync(TimeTrack.Client.UWP.TimeTrackService.Project project) { return base.Channel.AddProjectAsync(project); } public System.Threading.Tasks.Task UpdateProjectAsync(TimeTrack.Client.UWP.TimeTrackService.Project project) { return base.Channel.UpdateProjectAsync(project); } public System.Threading.Tasks.Task DeleteProjectByIdAsync(int id) { return base.Channel.DeleteProjectByIdAsync(id); } public System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Employee>> GetEmployeesAsync() { return base.Channel.GetEmployeesAsync(); } public System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Employee> GetEmployeeByIdAsync(System.Nullable<int> id) { return base.Channel.GetEmployeeByIdAsync(id); } public System.Threading.Tasks.Task AddEmployeeAsync(TimeTrack.Client.UWP.TimeTrackService.Employee employee) { return base.Channel.AddEmployeeAsync(employee); } public System.Threading.Tasks.Task UpdateEmployeeAsync(TimeTrack.Client.UWP.TimeTrackService.Employee employee) { return base.Channel.UpdateEmployeeAsync(employee); } public System.Threading.Tasks.Task DeleteEmployeeByIdAsync(int id) { return base.Channel.DeleteEmployeeByIdAsync(id); } public System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<TimeTrack.Client.UWP.TimeTrackService.Timesheet>> GetTimeSheetsAsync() { return base.Channel.GetTimeSheetsAsync(); } public System.Threading.Tasks.Task<TimeTrack.Client.UWP.TimeTrackService.Timesheet> GetTimeSheetByIdAsync(int id) { return base.Channel.GetTimeSheetByIdAsync(id); } public System.Threading.Tasks.Task AddTimesheetAsync(TimeTrack.Client.UWP.TimeTrackService.Timesheet timesheet) { return base.Channel.AddTimesheetAsync(timesheet); } public System.Threading.Tasks.Task UpdateTimeSheetAsync(TimeTrack.Client.UWP.TimeTrackService.Timesheet timesheet) { return base.Channel.UpdateTimeSheetAsync(timesheet); } public System.Threading.Tasks.Task DeleteTimesheetByIdAsync(int id) { return base.Channel.DeleteTimesheetByIdAsync(id); } public virtual System.Threading.Tasks.Task OpenAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); } public virtual System.Threading.Tasks.Task CloseAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); } } }
46.90099
241
0.637904
[ "MIT" ]
Mogikan/timetrack
TimeTrack.Client.UWP/Service References/TimeTrackService/Reference.cs
18,950
C#
using SunokoLibrary.Web.GooglePlus; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Metrooz.Models { public class StreamManager { public StreamManager(Account account) { _accountModel = account; Streams = new ObservableCollection<Stream>(); } readonly SemaphoreSlim _streamSyncer = new SemaphoreSlim(1, 1); Account _accountModel; public ObservableCollection<Stream> Streams { get; private set; } public async Task<bool> Activate() { await Deactivate(); try { await _accountModel.PlusClient.People.UpdateCirclesAndBlockAsync(false, CircleUpdateLevel.Loaded); await _streamSyncer.WaitAsync(); Streams.Add(new Stream(_accountModel.PlusClient.People.YourCircle)); foreach (var item in _accountModel.PlusClient.People.Circles) Streams.Add(new Stream(item)); return true; } catch (FailToOperationException) { return false; } finally { _streamSyncer.Release(); } } public async Task Deactivate() { try { await _streamSyncer.WaitAsync(); var tmp = Streams.ToArray(); Streams.Clear(); foreach (var item in tmp) item.Dispose(); } finally { _streamSyncer.Release(); } } } }
31.698113
114
0.58631
[ "MIT" ]
namoshika/Metrooz
Metrooz/Models/Stream/StreamManager.cs
1,682
C#
#region Header // // Copyright 2003-2021 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using RevitLookup.Core.Snoop; using RevitLookup.Forms; // Each command is implemented as a class that provides the IExternalCommand Interface namespace RevitLookup.Commands { #pragma warning disable CS4014 // Because calls to SnoopAndShow method, which is async, are not awaited, execution of the commands continues before the calls are completed /// <summary> /// Search by and Snoop command: Browse /// elements found by the condition /// </summary> [Transaction(TransactionMode.Manual)] public class SearchCommand : IExternalCommand { public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems) { var revitDoc = cmdData.Application.ActiveUIDocument; var dbdoc = revitDoc.Document; var form = new SearchBy(dbdoc); ModelessWindowFactory.Show(form); return Result.Succeeded; } } #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
37.789474
171
0.731662
[ "MIT" ]
ricaun/RevitLookup
RevitLookup/Commands/SearchCommand.cs
2,156
C#
using SRDP.Application.Repositories; using SRDP.Domain.Depositos; using SRDP.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SRDP.Persitence.InMemoryDataAccess.Repositories { public class DepositoRepository : IDepositoReadOnlyRepository { private readonly Context _context; public DepositoRepository(Context context) { _context = context; } public async Task Add(DepositoMayor10K deposito) { _context.Depositos.Add(deposito); await Task.CompletedTask; } public async Task Delete(DepositoMayor10K deposito) { var depositoAnterior = _context.Depositos .Where(c => c.ID == deposito.ID && c.DeclaracionID == deposito.DeclaracionID) .SingleOrDefault(); _context.Depositos.Remove(depositoAnterior); await Task.CompletedTask; } public async Task Update(DepositoMayor10K deposito) { var depositoAnterior = _context.Depositos .Where(c => c.ID == deposito.ID && c.DeclaracionID == deposito.DeclaracionID) .SingleOrDefault(); depositoAnterior = deposito; await Task.CompletedTask; } public async Task<DepositoMayor10K> Get(Guid depositoID) { var deposito = _context.Depositos .Where(c => c.ID == depositoID) .SingleOrDefault(); return await Task.FromResult<DepositoMayor10K>(deposito); } public async Task<ICollection<DepositoMayor10K>> GetByDeclaracion(Guid declaracionID) { var depositos = _context.Depositos .Where(c => c.DeclaracionID == declaracionID) .ToList(); return await Task.FromResult<List<DepositoMayor10K>>(depositos); } } }
32.295082
93
0.619797
[ "MIT" ]
guidoblado/declaraciones-patrimoniales
src/SRDP/SRDP.Persitence/InMemoryDataAccess/Repositories/DepositoRepository.cs
1,972
C#
namespace Motor.Extensions.Hosting.RabbitMQ.Options { public record RabbitMQPublisherOptions<T> : RabbitMQBaseOptions { public RabbitMQBindingOptions PublishingTarget { get; set; } = new(); public byte? DefaultPriority { get; set; } = null; } }
30.333333
77
0.695971
[ "MIT" ]
rageagainsthepc/motornet
src/Motor.Extensions.Hosting.RabbitMQ/Options/RabbitMQPublisherOptions.cs
273
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.Collections.Generic; namespace Microsoft.Protocols.TestManager.RDPClientPlugin { public enum TriggerMethod { Powershell, Manual, Managed, Shell } /// <summary> /// The detection information /// </summary> public class DetectionInfo { // Parameters for Detecting public string SUTName; public string UserNameInTC; public string UserPwdInTC; public string ProxyIP;//The Proxy IP in SUT side if there's proxy setup. public string IsWindowsImplementation; public string DropConnectionForInvalidRequest; public int AgentListenPort; public int RDPServerPort; public TriggerMethod TriggerMethod; // Detect Result public bool? IsSupportTransportTypeUdpFECR; public bool? IsSupportTransportTypeUdpFECL; public bool? IsSupportAutoReconnect; public bool? IsSupportServerRedirection; public bool? IsSupportNetcharAutoDetect; public bool? IsSupportHeartbeatPdu; public bool? IsSupportStaticVirtualChannel; public bool? IsSupportRDPEVOR; public bool? IsSupportRDPEGFX; public bool? IsSupportRDPEDISP; public bool? IsSupportRDPEI; public bool? IsSupportRDPEUSB; public bool? IsSupportRDPEFS; public bool? IsSupportRDPRFX; public bool? IsSupportRDPEUDP; public bool? IsSupportRDPEMT; public string RdpVersion; } }
32.269231
101
0.671633
[ "MIT" ]
G-arj/WindowsProtocolTestSuites
TestSuites/RDP/Client/src/Plugin/RDPClientPlugin/Types.cs
1,678
C#
// A single tile in a map. public class MapTile { public MapTile( float height, MapTileType type, AbstractBuilding building = null ) { Height = height; Type = type; Building = building; } public float Height { get; } public MapTileType Type { get; } // The building that is placed on this tile. public AbstractBuilding Building { get; set; } public override string ToString() { string result = string.Format( "MapTile(height: {0}, type: {1}, building: {2})", Height, Type, Building ); return result; } public override bool Equals(object other) { var otherTile = other as MapTile; if (otherTile == null) return false; var equals = ( Height == otherTile.Height && Type == otherTile.Type && ( Building == otherTile.Building || Building.Equals(otherTile.Building) ) ); return equals; } public override int GetHashCode() { var properties = (Height, Type, Building); var hashCode = properties.GetHashCode(); return hashCode; } public MapTile Clone() { var clone = new MapTile( height: Height, type: Type, building: Building ); return clone; } }
22.935484
72
0.528129
[ "MIT" ]
toklinke/IGDSS20
Assets/Scripts/Code/Map/MapTile.cs
1,422
C#
namespace DomainServices.Abstractions { /// <summary> /// Interface INamedEntity /// </summary> /// <typeparam name="TId">The type of the identifier.</typeparam> public interface INamedEntity<out TId> : ISecuredEntity<TId> where TId : notnull { /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> string Name { get; } } }
28.2
84
0.560284
[ "MIT" ]
larsmichael/DomainServices
Source/DomainServices/Abstractions/Entities/INamedEntity.cs
425
C#
using System.Collections.Generic; namespace SIS.Framework.Security.Contracts { public interface IIdentity { string Email { get; set; } bool IsAuthenticated { get; set; } string PasswordHash { get; set; } IEnumerable<string> Roles { get; set; } string Username { get; set; } } }
21.214286
42
0.690236
[ "MIT" ]
AscenKeeprov/CSharp-Web-Basics
Exercise10-ViewEngineAndSecurity/SIS.Framework/Security/Contracts/IIdentity.cs
299
C#
using System.Windows; using System.Threading; using System.Windows.Threading; using System; using System.Linq; using System.IO; using System.Windows.Controls; using System.Collections.ObjectModel; using System.Security.Cryptography; //using Neo.Wallets; using AntShares.Wallets; namespace AddressGenerator { public partial class MainWindow : Window { bool pause = true; bool requireContains = false; bool requireStartWith = false; bool requireEndWith = false; bool requireLength = false; bool requireUppercase = false; bool requireAll = false; int goodLength; int uppercase; string[] startWith; string[] contains; string[] endWith; ObservableCollection<GoodAddress> goodAddresses = new ObservableCollection<GoodAddress>(); Thread[] threads = new Thread[8]; public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { textProcessorCount.Text = Environment.ProcessorCount.ToString(); dataGrid1.ItemsSource = goodAddresses; } private void Button_Click(object sender, RoutedEventArgs e) { var count = 0; if (pause) { pause = false; for (int i = 0; i < Math.Min(Environment.ProcessorCount - 1, 7); i++) { threads[i] = new Thread(Run); threads[i].Start(); count++; } } else { pause = true; } textWorkingStatus.Text = pause ? "Paused": "Working..."; textThreadCount.Text = count.ToString(); (sender as Button).Content = pause ? "Start" : "Stop"; } public void Run() { byte[] privateKey = new byte[32]; while (!pause) { using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(privateKey); } Account key = new Account(privateKey); // KeyPair key = new KeyPair(privateKey); // Array.Clear(privateKey, 0, privateKey.Length); Generate(key); } } public void Generate(Account key) { var contract = Contract.CreateSignatureContract(key.PublicKey); var address = contract.Address; var length = contract.Address.Sum(p => p.Length()); if (!requireAll) { if ( (requireStartWith && startWith.Any(p => address.StartsWith(p))) || (requireContains && contains.Any(p => address.Contains(p))) || (requireEndWith && endWith.Any(p => address.EndsWith(p))) || (requireLength && length < goodLength) || (requireUppercase && contract.Address.Count(p => p >= 'A' && p <= 'Z') < uppercase) ) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate () { goodAddresses.Add(new GoodAddress() { Address = contract.Address, Privatekey = key.Export() }); }); } } if (requireAll) { if ( ((requireStartWith && startWith.Any(p => address.StartsWith(p))) || !requireStartWith) && ((requireContains && contains.Any(p => address.Contains(p))) || !requireContains) && ((requireEndWith && endWith.Any(p => address.EndsWith(p))) || !requireEndWith) && ((requireLength && length < goodLength) || !requireLength) && ((requireUppercase && contract.Address.Count(p => p >= 'A' && p <= 'Z') < uppercase) || !requireUppercase) ) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate () { goodAddresses.Add(new GoodAddress() { Address = contract.Address, Privatekey = key.Export() }); }); } } } private void Window_Closed(object sender, EventArgs e) { Environment.Exit(0); } private void StartWith_Checked(object sender, RoutedEventArgs e) { if (pause) { requireStartWith = requireStartWith ? false : true; startWith = File.ReadAllLines("StartWith.txt"); } } private void StartWith_Unchecked(object sender, RoutedEventArgs e) { if (pause) { requireStartWith = false; startWith = new string[] { }; } } private void EndWith_Checked(object sender, RoutedEventArgs e) { if (pause) { requireEndWith = requireEndWith ? false : true; endWith = File.ReadAllLines("EndWith.txt"); } } private void EndWith_Unchecked(object sender, RoutedEventArgs e) { if (pause) { requireEndWith = false; endWith = new string[] { }; } } private void Contains_Checked(object sender, RoutedEventArgs e) { if (pause) { requireContains = requireContains ? false : true; contains = File.ReadAllLines("Contains.txt"); } } private void Contains_Unchecked(object sender, RoutedEventArgs e) { if (pause) { requireContains = false; contains = new string[] { }; } } private void Length_Checked(object sender, RoutedEventArgs e) { if (pause) { requireLength = requireLength ? false : true; goodLength = Convert.ToInt32(File.ReadAllText("GoodLength.txt")); } } private void Length_Unchecked(object sender, RoutedEventArgs e) { if (pause) { requireLength = false; goodLength = 0xffff; } } private void Uppercase_Checked(object sender, RoutedEventArgs e) { if (pause) { requireUppercase = requireUppercase ? false : true; uppercase = Convert.ToInt32(File.ReadAllText("Uppercase.txt")); } } private void Uppercase_Unchecked(object sender, RoutedEventArgs e) { if (pause) { requireUppercase = false; uppercase = 0xffff; } } private void MeetAll_Checked(object sender, RoutedEventArgs e) { if (pause) { requireAll= true; } } private void MeetAny_Checked(object sender, RoutedEventArgs e) { if (pause) { requireAll = false; } } } }
31.295082
126
0.477737
[ "MIT" ]
mgao6767/NEOAddressGenerator
NEOAddressGenerator/MainWindow.xaml.cs
7,638
C#
using ProtoBuf; using avaness.PluginLoader.GUI; using Sandbox.Graphics.GUI; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml.Serialization; using VRage.Utils; using VRage; namespace avaness.PluginLoader.Data { [XmlInclude(typeof(WorkshopPlugin))] [XmlInclude(typeof(SEPMPlugin))] [XmlInclude(typeof(GitHubPlugin))] [XmlInclude(typeof(ModPlugin))] [ProtoContract] [ProtoInclude(100, typeof(SteamPlugin))] [ProtoInclude(103, typeof(GitHubPlugin))] [ProtoInclude(104, typeof(ModPlugin))] public abstract class PluginData : IEquatable<PluginData> { public abstract string Source { get; } [XmlIgnore] public Version Version { get; protected set; } [XmlIgnore] public virtual PluginStatus Status { get; set; } = PluginStatus.None; public virtual string StatusString { get { switch (Status) { case PluginStatus.PendingUpdate: return "Pending Update"; case PluginStatus.Updated: return "Updated"; case PluginStatus.Error: return "Error!"; case PluginStatus.Blocked: return "Not whitelisted!"; default: return ""; } } } [XmlIgnore] public bool IsLocal => Source == MyTexts.GetString(MyCommonTexts.Local); [ProtoMember(1)] public virtual string Id { get; set; } [ProtoMember(2)] public string FriendlyName { get; set; } = "Unknown"; [ProtoMember(3)] public bool Hidden { get; set; } = false; [ProtoMember(4)] public string GroupId { get; set; } [ProtoMember(5)] public string Tooltip { get; set; } [ProtoMember(6)] public string Author { get; set; } [ProtoMember(7)] public string Description { get; set; } [XmlIgnore] public List<PluginData> Group { get; } = new List<PluginData>(); [XmlIgnore] public bool Enabled => Main.Instance.Config.IsEnabled(Id); protected PluginData() { } public abstract Assembly GetAssembly(); public virtual bool TryLoadAssembly(out Assembly a) { if (Status == PluginStatus.Error) { a = null; return false; } try { // Get the file path a = GetAssembly(); if (Status == PluginStatus.Blocked) return false; if (a == null) { LogFile.WriteLine("Failed to load " + ToString()); Error(); return false; } // Precompile the entire assembly in order to force any missing method exceptions LogFile.WriteLine("Precompiling " + a); LoaderTools.Precompile(a); return true; } catch (Exception e) { string name = ToString(); LogFile.WriteLine($"Failed to load {name} because of an error: " + e); if (e is MissingMemberException) LogFile.WriteLine($"Is {name} up to date?"); if (e is NotSupportedException && e.Message.Contains("loadFromRemoteSources")) Error($"The plugin {name} was blocked by windows. Please unblock the file in the dll file properties."); else Error(); a = null; return false; } } public override bool Equals(object obj) { return Equals(obj as PluginData); } public bool Equals(PluginData other) { return other != null && Id == other.Id; } public override int GetHashCode() { return 2108858624 + EqualityComparer<string>.Default.GetHashCode(Id); } public static bool operator ==(PluginData left, PluginData right) { return EqualityComparer<PluginData>.Default.Equals(left, right); } public static bool operator !=(PluginData left, PluginData right) { return !(left == right); } public override string ToString() { return Id + '|' + FriendlyName; } public void Error(string msg = null) { Status = PluginStatus.Error; if (msg == null) msg = $"The plugin '{this}' caused an error. It is recommended that you disable this plugin and restart. The game may be unstable beyond this point. See loader.log or the game log for details."; string file = MyLog.Default.GetFilePath(); if(File.Exists(file) && file.EndsWith(".log")) { MyLog.Default.Flush(); msg += "\n\nWould you like to open the game log?"; DialogResult result = MessageBox.Show(LoaderTools.GetMainForm(), msg, "Plugin Loader", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) Process.Start(file); } else { MessageBox.Show(LoaderTools.GetMainForm(), msg, "Plugin Loader", MessageBoxButtons.OK, MessageBoxIcon.Error); } } protected void ErrorSecurity(string hash) { Status = PluginStatus.Blocked; MessageBox.Show(LoaderTools.GetMainForm(), $"Unable to load the plugin {this} because it is not whitelisted!", "Plugin Loader", MessageBoxButtons.OK, MessageBoxIcon.Error); LogFile.WriteLine("Error: " + this + " with an sha256 of " + hash + " is not on the whitelist!"); } public abstract void Show(); public virtual void GetDescriptionText(MyGuiControlMultilineText textbox) { textbox.Visible = true; textbox.Clear(); if (string.IsNullOrEmpty(Description)) { if (string.IsNullOrEmpty(Tooltip)) textbox.AppendText("No description"); else textbox.AppendText(CapLength(Tooltip, 1000)); return; } else { string text = CapLength(Description, 1000); int textStart = 0; foreach (Match m in Regex.Matches(text, @"https?:\/\/(www\.)?[\w-.]{2,256}\.[a-z]{2,4}\b[\w-.@:%\+~#?&//=]*")) { int textLen = m.Index - textStart; if (textLen > 0) textbox.AppendText(text.Substring(textStart, textLen)); textbox.AppendLink(m.Value, m.Value); textStart = m.Index + m.Length; } if (textStart < text.Length) textbox.AppendText(text.Substring(textStart)); } } private string CapLength(string s, int len) { if (s.Length > len) return s.Substring(0, len); return s; } public virtual bool OpenContextMenu(MyGuiControlContextMenu menu) { return false; } public virtual void ContextMenuClicked(MyGuiScreenPluginConfig screen, MyGuiControlContextMenu.EventArgs args) { } } }
32.410788
210
0.525797
[ "MIT" ]
sepluginloader/PluginLoader
PluginLoader/Data/PluginData.cs
7,813
C#
using System; namespace Tizen.NUI.Xaml { internal interface IXamlNodeVisitor { TreeVisitingMode VisitingMode { get; } bool StopOnDataTemplate { get; } bool VisitNodeOnDataTemplate { get; } bool StopOnResourceDictionary { get; } void Visit(ValueNode node, INode parentNode); void Visit(MarkupNode node, INode parentNode); void Visit(ElementNode node, INode parentNode); void Visit(RootNode node, INode parentNode); void Visit(ListNode node, INode parentNode); bool SkipChildren(INode node, INode parentNode); bool IsResourceDictionary(ElementNode node); } internal enum TreeVisitingMode { TopDown, BottomUp } internal class XamlNodeVisitor : IXamlNodeVisitor { readonly Action<INode, INode> action; public XamlNodeVisitor(Action<INode, INode> action, TreeVisitingMode visitingMode = TreeVisitingMode.TopDown, bool stopOnDataTemplate = false, bool visitNodeOnDataTemplate = true) { this.action = action; VisitingMode = visitingMode; StopOnDataTemplate = stopOnDataTemplate; VisitNodeOnDataTemplate = visitNodeOnDataTemplate; } public TreeVisitingMode VisitingMode { get; } public bool StopOnDataTemplate { get; } public bool StopOnResourceDictionary { get; } public bool VisitNodeOnDataTemplate { get; } public void Visit(ValueNode node, INode parentNode) => action(node, parentNode); public void Visit(MarkupNode node, INode parentNode) => action(node, parentNode); public void Visit(ElementNode node, INode parentNode) => action(node, parentNode); public void Visit(RootNode node, INode parentNode) => action(node, parentNode); public void Visit(ListNode node, INode parentNode) => action(node, parentNode); public bool SkipChildren(INode node, INode parentNode) => false; public bool IsResourceDictionary(ElementNode node) => false; } }
39.480769
187
0.679981
[ "Apache-2.0", "MIT" ]
MoonheeChoi/TizenFX
src/Tizen.NUI/src/internal/Xaml/XamlNodeVisitor.cs
2,055
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Lumbricus Shared")] [assembly: AssemblyDescription("Shared files for the Lumbricus IRC bot")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2015 Benjamin Nolan (TwoWholeWorms)")] [assembly: AssemblyTrademark("")] //[assembly: AssemblyCulture("en-GB")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
37.892857
81
0.749293
[ "MIT" ]
BenjaminNolan/lumbricus
LumbricusShared/Properties/AssemblyInfo.cs
1,063
C#
namespace Dayo { public interface IStore { Note ReadMemoryList(); void StoreMemoryList(Note note); } }
16.375
40
0.603053
[ "MIT" ]
GDMaster113/Dayo
src/Dayo/IStore.cs
133
C#
using UnityEngine; public class OptionsDriver : MonoBehaviour { [SerializeField] private OptionsController controller; [SerializeField] private OptionsView view; private void Start() { this.controller.View = this.view; } }
19.416667
44
0.76824
[ "MIT" ]
Software-Developers-Association/maze
Assets/App/Scripts/UI/Menus/Options/OptionsDriver.cs
235
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; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.InMemory.Internal; using Microsoft.EntityFrameworkCore.InMemory.ValueGeneration.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Update; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.InMemory.Storage.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class InMemoryTable<TKey> : IInMemoryTable { // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 private readonly IEntityType _entityType; private readonly IPrincipalKeyValueFactory<TKey> _keyValueFactory; private readonly bool _sensitiveLoggingEnabled; private readonly Dictionary<TKey, object[]> _rows; private readonly IList<(int, ValueConverter)> _valueConverters; private readonly IList<(int, ValueComparer)> _valueComparers; private Dictionary<int, IInMemoryIntegerValueGenerator> _integerGenerators; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public InMemoryTable([NotNull] IEntityType entityType, bool sensitiveLoggingEnabled) { _entityType = entityType; // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 _keyValueFactory = entityType.FindPrimaryKey().GetPrincipalKeyValueFactory<TKey>(); _sensitiveLoggingEnabled = sensitiveLoggingEnabled; _rows = new Dictionary<TKey, object[]>(_keyValueFactory.EqualityComparer); foreach (var property in entityType.GetProperties()) { var converter = property.FindTypeMapping()?.Converter ?? property.GetValueConverter(); if (converter != null) { if (_valueConverters == null) { _valueConverters = new List<(int, ValueConverter)>(); } _valueConverters.Add((property.GetIndex(), converter)); } var comparer = property.GetKeyValueComparer(); if (!comparer.HasDefaultBehavior) { if (_valueComparers == null) { _valueComparers = new List<(int, ValueComparer)>(); } _valueComparers.Add((property.GetIndex(), comparer)); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InMemoryIntegerValueGenerator<TProperty> GetIntegerValueGenerator<TProperty>(IProperty property) { if (_integerGenerators == null) { _integerGenerators = new Dictionary<int, IInMemoryIntegerValueGenerator>(); } // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 var propertyIndex = EntityFrameworkCore.Metadata.Internal.PropertyBaseExtensions.GetIndex(property); if (!_integerGenerators.TryGetValue(propertyIndex, out var generator)) { generator = new InMemoryIntegerValueGenerator<TProperty>(propertyIndex); _integerGenerators[propertyIndex] = generator; foreach (var row in _rows.Values) { generator.Bump(row); } } return (InMemoryIntegerValueGenerator<TProperty>)generator; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<object[]> SnapshotRows() { var rows = _rows.Values.ToList(); var rowCount = rows.Count; var properties = _entityType.GetProperties().ToList(); var propertyCount = properties.Count; for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) { var snapshotRow = new object[propertyCount]; Array.Copy(rows[rowIndex], snapshotRow, propertyCount); if (_valueConverters != null) { foreach (var (index, converter) in _valueConverters) { snapshotRow[index] = converter.ConvertFromProvider(snapshotRow[index]); } } if (_valueComparers != null) { foreach (var (index, comparer) in _valueComparers) { snapshotRow[index] = comparer.Snapshot(snapshotRow[index]); } } rows[rowIndex] = snapshotRow; } return rows; } private static List<ValueComparer> GetKeyComparers(IEnumerable<IProperty> properties) => properties.Select(p => p.GetKeyValueComparer()).ToList(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Create(IUpdateEntry entry) { var row = entry.EntityType.GetProperties() .Select(p => SnapshotValue(p, p.GetKeyValueComparer(), entry)) .ToArray(); _rows.Add(CreateKey(entry), row); BumpValueGenerators(row); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Delete(IUpdateEntry entry) { var key = CreateKey(entry); if (_rows.ContainsKey(key)) { var properties = entry.EntityType.GetProperties().ToList(); var concurrencyConflicts = new Dictionary<IProperty, object>(); for (var index = 0; index < properties.Count; index++) { IsConcurrencyConflict(entry, properties[index], _rows[key][index], concurrencyConflicts); } if (concurrencyConflicts.Count > 0) { ThrowUpdateConcurrencyException(entry, concurrencyConflicts); } _rows.Remove(key); } else { throw new DbUpdateConcurrencyException(InMemoryStrings.UpdateConcurrencyException, new[] { entry }); } } private static bool IsConcurrencyConflict( IUpdateEntry entry, IProperty property, object rowValue, Dictionary<IProperty, object> concurrencyConflicts) { if (property.IsConcurrencyToken) { var comparer = property.GetKeyValueComparer(); var originalValue = entry.GetOriginalValue(property); if ((comparer != null && !comparer.Equals(rowValue, originalValue)) || (comparer == null && !StructuralComparisons.StructuralEqualityComparer.Equals(rowValue, originalValue))) { concurrencyConflicts.Add(property, rowValue); return true; } } return false; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Update(IUpdateEntry entry) { var key = CreateKey(entry); if (_rows.ContainsKey(key)) { var properties = entry.EntityType.GetProperties().ToList(); var comparers = GetKeyComparers(properties); var valueBuffer = new object[properties.Count]; var concurrencyConflicts = new Dictionary<IProperty, object>(); for (var index = 0; index < valueBuffer.Length; index++) { if (IsConcurrencyConflict(entry, properties[index], _rows[key][index], concurrencyConflicts)) { continue; } valueBuffer[index] = entry.IsModified(properties[index]) ? SnapshotValue(properties[index], comparers[index], entry) : _rows[key][index]; } if (concurrencyConflicts.Count > 0) { ThrowUpdateConcurrencyException(entry, concurrencyConflicts); } _rows[key] = valueBuffer; BumpValueGenerators(valueBuffer); } else { throw new DbUpdateConcurrencyException(InMemoryStrings.UpdateConcurrencyException, new[] { entry }); } } private void BumpValueGenerators(object[] row) { if (_integerGenerators != null) { foreach (var generator in _integerGenerators.Values) { generator.Bump(row); } } } // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 private TKey CreateKey(IUpdateEntry entry) => _keyValueFactory.CreateFromCurrentValues((InternalEntityEntry)entry); private static object SnapshotValue(IProperty property, ValueComparer comparer, IUpdateEntry entry) { var value = SnapshotValue(comparer, entry.GetCurrentValue(property)); var converter = property.FindTypeMapping()?.Converter ?? property.GetValueConverter(); if (converter != null) { value = converter.ConvertToProvider(value); } return value; } private static object SnapshotValue(ValueComparer comparer, object value) => comparer == null ? value : comparer.Snapshot(value); /// <summary> /// Throws an exception indicating that concurrency conflicts were detected. /// </summary> /// <param name="entry"> The update entry which resulted in the conflict(s). </param> /// <param name="concurrencyConflicts"> The conflicting properties with their associated database values. </param> protected virtual void ThrowUpdateConcurrencyException( [NotNull] IUpdateEntry entry, [NotNull] Dictionary<IProperty, object> concurrencyConflicts) { Check.NotNull(entry, nameof(entry)); Check.NotNull(concurrencyConflicts, nameof(concurrencyConflicts)); if (_sensitiveLoggingEnabled) { throw new DbUpdateConcurrencyException( InMemoryStrings.UpdateConcurrencyTokenExceptionSensitive( entry.EntityType.DisplayName(), entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey().Properties), entry.BuildOriginalValuesString(concurrencyConflicts.Keys), "{" + string.Join( ", ", concurrencyConflicts.Select( c => c.Key.Name + ": " + Convert.ToString(c.Value, CultureInfo.InvariantCulture))) + "}"), new[] { entry }); } throw new DbUpdateConcurrencyException( InMemoryStrings.UpdateConcurrencyTokenException( entry.EntityType.DisplayName(), concurrencyConflicts.Keys.Format()), new[] { entry }); } } }
45.097923
135
0.598237
[ "Apache-2.0" ]
EricStG/efcore
src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
15,198
C#
using OOP.Objetos; using System; namespace OOP { public static class VerificarCor { public static void FormaECor(Retangulo ret) { var tipo = "retangulo"; if (ret is Quadrado) { tipo = "quadrado"; } Console.WriteLine($"O {tipo} de largura {ret.largura} é da cor {ret.GetCor()}"); } } }
20.047619
93
0.47981
[ "Apache-2.0" ]
gcacars/mentoria-mais1code-projeto-cs
OOP/VerificarCor.cs
424
C#
using System.Threading.Tasks; using Acme.BookStore.BookManagement.Controllers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Volo.Abp; namespace Acme.BookStore.BookManagement.Samples { [RemoteService] [Route("api/BookManagement/sample")] public class SampleController : BookManagementController, ISampleAppService { private readonly ISampleAppService _sampleAppService; public SampleController(ISampleAppService sampleAppService) { _sampleAppService = sampleAppService; } [HttpGet] public async Task<SampleDto> GetAsync() { return await _sampleAppService.GetAsync(); } [HttpGet] [Route("authorized")] [Authorize] public async Task<SampleDto> GetAuthorizedAsync() { return await _sampleAppService.GetAsync(); } } }
26.314286
79
0.669924
[ "MIT" ]
271943794/abp-samples
BookStore-Modular/modules/book-management/src/Acme.BookStore.BookManagement.HttpApi/Samples/SampleController.cs
923
C#
using System; using System.Linq.Expressions; using System.Reflection; using FubuCore.Reflection; using FubuMVC.Core.Registration.Nodes; namespace FubuMVC.Core.Registration.Querying { public interface IChainResolver { BehaviorChain Find(Type handlerType, MethodInfo method, string category = null); BehaviorChain FindUnique(object model, string category = null); BehaviorChain FindUniqueByType(Type modelType, string category = null); BehaviorChain FindCreatorOf(Type type); void RootAt(string baseUrl); BehaviorChain Find(ChainSearch search); } public static class ChainResolverExtensions { public static BehaviorChain Find<T>(this IChainResolver resolver, Expression<Action<T>> expression, string category = null) { return resolver.Find(typeof (T), ReflectionHelper.GetMethod(expression), category); } } public enum CategorySearchMode { /// <summary> /// Only match if the category of the chains explicitly matches the search criteria /// </summary> Strict, /// <summary> /// If only one chain is found for all the other criteria, it's okay /// to ignore the exact match on Category /// </summary> Relaxed } public enum TypeSearchMode { Any, InputModelOnly, HandlerOnly, ResourceModelOnly } }
28.807692
132
0.632176
[ "Apache-2.0" ]
DarthFubuMVC/fubumvc
src/FubuMVC.Core/Registration/Querying/IChainResolver.cs
1,500
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Models.AccountViewModels { public class ExternalLoginViewModel { [Required] [EmailAddress] public string Email { get; set; } } }
20.3125
44
0.72
[ "MIT" ]
StefanDeWitHR/PartyCoins
WebAPI/Models/AccountViewModels/ExternalLoginViewModel.cs
325
C#
// The MIT License (MIT) // // Copyright(c) 2016 Vitaliy Tsivanyuk <tsivanyukve@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; namespace Ranger { public class VirtualRange<TValue, TOffset> : IVirtualRange<TValue, TOffset> where TValue : IComparable where TOffset : IComparable { #region Ctors public VirtualRange(TValue from, UInt64 count, TOffset offset) { if (count == 0) { throw new ArgumentOutOfRangeException("count equals 0"); } this.from = from; this.count = count; this.offset = offset; this.to = this.from; for (UInt64 i = 1; i < this.count; i++) { this.to += this.offset; } } public VirtualRange(TValue from, UInt64 count, TOffset offset, Func<IVirtualRange<TValue, TOffset>, IVirtualRange<TValue, TOffset>, Int32> comparer) : this(from, count, offset) { this.comparer = comparer; } public VirtualRange(TValue from, TValue to, TOffset offset) { if (from.CompareTo(to) == 1) { throw new ArgumentOutOfRangeException("from > to"); } this.from = from; this.to = to; this.offset = offset; this.count = 1; var tempTo = this.from; while (tempTo.CompareTo(this.to) == -1) { tempTo += this.offset; this.count += 1; } if (this.to.CompareTo(tempTo) == 1) { throw new ArgumentOutOfRangeException("params incorrect"); } } public VirtualRange(TValue from, TValue to, TOffset offset, Func<IVirtualRange<TValue, TOffset>, IVirtualRange<TValue, TOffset>, Int32> comparer) : this(from, to, offset) { this.comparer = comparer; } public VirtualRange(TValue from, TValue to, UInt64 count, TOffset offset) { if (count == 0) { throw new ArgumentOutOfRangeException("count equals 0"); } if (from.CompareTo(to) == 1) { throw new ArgumentOutOfRangeException("from > to"); } this.from = from; this.to = to; this.count = count; this.offset = offset; UInt64 tempCount = 1; var tempTo = this.from; while (tempTo.CompareTo(this.to) == -1) { tempTo += this.offset; tempCount += 1; } if (this.to.CompareTo(tempTo) == 1 || tempCount.CompareTo(this.count) != 0) { throw new ArgumentOutOfRangeException("params incorrect"); } } public VirtualRange(TValue from, TValue to, UInt64 count, TOffset offset, Func<IVirtualRange<TValue, TOffset>, IVirtualRange<TValue, TOffset>, Int32> comparer) : this(from, to, count, offset) { this.comparer = comparer; } #endregion #region Memders protected Func<IVirtualRange<TValue, TOffset>, IVirtualRange<TValue, TOffset>, Int32> comparer = (l, r) => { return l.From.CompareTo(r.From) == 0 ? l.To.CompareTo(r.To) == 0 ? 0 : l.To.CompareTo(r.To) : l.From.CompareTo(r.From); }; protected dynamic from; protected dynamic to; protected dynamic offset; protected UInt64 count; #endregion #region Properties public TValue From { get { return this.from; } } public TValue To { get { return this.to; } } public TOffset Offset { get { return this.offset; } } public UInt64 Count { get { return this.count; } } public TValue this[UInt64 index] { get { var result = this.from; for (UInt64 i = 1; i < index; i++) { result += this.offset; } return result; } } #endregion #region Functions private Boolean Sync(dynamic thisValue, dynamic otherValue, dynamic thisOffset, dynamic otherOffset) { if (thisOffset.CompareTo(otherOffset) != 0) { throw new ArgumentOutOfRangeException("Offsets is not equal."); } var minValue = thisValue.CompareTo(otherValue) == -1 ? thisValue : otherValue; var maxValue = thisValue.CompareTo(otherValue) == -1 ? otherValue : thisValue; var compareResult = -1; while ((compareResult = minValue.CompareTo(maxValue)) == -1) { minValue += thisOffset; } return compareResult == 0; } #endregion #region Methods public Boolean Contains(TValue value) { if (!this.Sync(this.From, value, this.Offset, this.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } return (this.From.CompareTo(value) < 1 && this.To.CompareTo(value) > -1); } public Boolean Contains(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } return (this.From.CompareTo(other.From) < 1 && this.To.CompareTo(other.To) > -1); } public Boolean Overlaps(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } return !((this.From.CompareTo(other.From) == 1 && this.From.CompareTo(other.To) == 1) || (this.To.CompareTo(other.From) == -1 && this.To.CompareTo(other.To) == -1)); } public Int32 CompareTo(IVirtualRange<TValue, TOffset> other) { return this.comparer(this, other); } public List<IVirtualRange<TValue, TOffset>> UnionWith(TValue value) { if (!this.Sync(this.From, value, this.Offset, this.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (this.From.CompareTo(value) == -1) { if (value.CompareTo(this.To) == 1) { if (this.to + this.offset == (dynamic)value) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, value, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { this, new VirtualRange<TValue, TOffset>(value, value, this.Offset) }; } } else { if (this.To.CompareTo(value) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, value, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { this }; } } } else { if (this.From.CompareTo(value) == 1) { if ((dynamic)value + this.offset == this.from) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, value, this.Offset), this }; } } else { if (this.To.CompareTo(value) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, value, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, this.To, this.Offset) }; } } } } public List<IVirtualRange<TValue, TOffset>> UnionWith(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (this.From.CompareTo(other.From) == -1) { if (other.From.CompareTo(this.To) == 1) { if (this.to + this.offset == (dynamic)other.From) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, other.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { this, other }; } } else { if (this.To.CompareTo(other.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, other.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { this }; } } } else { if (this.From.CompareTo(other.To) == 1) { if ((dynamic)other.To + this.offset == this.from) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(other.From, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { other, this }; } } else { if (this.To.CompareTo(other.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { other }; } else { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(other.From, this.To, this.Offset) }; } } } } public List<IVirtualRange<TValue, TOffset>> ExceptWith(TValue value) { if (!this.Sync(this.From, value, this.Offset, this.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (((this.From.CompareTo(value) == 1 && this.From.CompareTo(value) == 1) || (this.To.CompareTo(value) == -1 && this.To.CompareTo(value) == -1))) { return new List<IVirtualRange<TValue, TOffset>>() { this }; } if (this.From.CompareTo(value) == -1) { if (value.CompareTo(this.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)value - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)value + this.offset, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)value - this.offset, this.Offset) }; } } else { if (value.CompareTo(this.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>((dynamic)value + this.offset, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>(); } } } public List<IVirtualRange<TValue, TOffset>> ExceptWith(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (((this.From.CompareTo(other.From) == 1 && this.From.CompareTo(other.To) == 1) || (this.To.CompareTo(other.From) == -1 && this.To.CompareTo(other.To) == -1))) { return new List<IVirtualRange<TValue, TOffset>>() { this }; } if (this.From.CompareTo(other.From) == -1) { if (other.To.CompareTo(this.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)other.From - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)other.To + this.offset, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)other.From - this.offset, this.Offset) }; } } else { if (other.To.CompareTo(this.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>((dynamic)other.To + this.offset, this.To, this.Offset) }; } else { return new List<IVirtualRange<TValue, TOffset>>(); } } } public List<IVirtualRange<TValue, TOffset>> SymmetricExceptWith(TValue value) { if (!this.Sync(this.From, value, this.Offset, this.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (this.From.CompareTo(value) == 1 && this.From.CompareTo(value) == 1) { return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, value, this.Offset), this }; } if (this.To.CompareTo(value) == -1 && this.To.CompareTo(value) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { this, new VirtualRange<TValue, TOffset>(value, value, this.Offset) }; } switch (this.From.CompareTo(value)) { case -1: switch (value.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)value - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)value + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)value - this.offset, this.Offset) }; default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)value - this.offset, this.Offset), new VirtualRange<TValue, TOffset>(this.to + this.offset, value, this.Offset) }; } case 0: switch (value.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>((dynamic)value + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>(); default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.to + this.offset, value, this.Offset) }; } default: switch (value.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, this.from - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)value + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, this.from - this.offset, this.Offset) }; default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(value, this.from - this.offset, this.Offset), new VirtualRange<TValue, TOffset>(this.to + this.offset, value, this.Offset) }; } } } public List<IVirtualRange<TValue, TOffset>> SymmetricExceptWith(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (this.From.CompareTo(other.From) == 1 && this.From.CompareTo(other.To) == 1) { return new List<IVirtualRange<TValue, TOffset>>() { other, this }; } if (this.To.CompareTo(other.From) == -1 && this.To.CompareTo(other.To) == -1) { return new List<IVirtualRange<TValue, TOffset>>() { this, other }; } switch (this.From.CompareTo(other.From)) { case -1: switch (other.To.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)other.From - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)other.To + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)other.From - this.offset, this.Offset) }; default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.From, (dynamic)other.From - this.offset, this.Offset), new VirtualRange<TValue, TOffset>(this.to + this.offset, other.To, this.Offset) }; } case 0: switch (other.To.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>((dynamic)other.To + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>(); default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(this.to + this.offset, other.To, this.Offset) }; } default: switch (other.To.CompareTo(this.To)) { case -1: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(other.From, this.from - this.offset, this.Offset), new VirtualRange<TValue, TOffset>((dynamic)other.To + this.offset, this.To, this.Offset) }; case 0: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(other.From, this.from - this.offset, this.Offset) }; default: return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>(other.From, this.from - this.offset, this.Offset), new VirtualRange<TValue, TOffset>(this.to + this.offset, other.To, this.Offset) }; } } } public List<IVirtualRange<TValue, TOffset>> IntersectWith(TValue value) { if (!this.Sync(this.From, value, this.Offset, this.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (((this.From.CompareTo(value) == 1 && this.From.CompareTo(value) == 1) || (this.To.CompareTo(value) == -1 && this.To.CompareTo(value) == -1))) { return new List<IVirtualRange<TValue, TOffset>>(); } return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>( value.CompareTo(this.From) == 1 ?value : this.From, value.CompareTo(this.To) == 1 ? this.To : value, this.Offset) }; } public List<IVirtualRange<TValue, TOffset>> IntersectWith(IVirtualRange<TValue, TOffset> other) { if (!this.Sync(this.From, other.From, this.Offset, other.Offset)) { throw new ArgumentOutOfRangeException("Ranges is not sync."); } if (((this.From.CompareTo(other.From) == 1 && this.From.CompareTo(other.To) == 1) || (this.To.CompareTo(other.From) == -1 && this.To.CompareTo(other.To) == -1))) { return new List<IVirtualRange<TValue, TOffset>>(); } return new List<IVirtualRange<TValue, TOffset>>() { new VirtualRange<TValue, TOffset>( other.From.CompareTo(this.From) == 1 ? other.From : this.From, other.To.CompareTo(this.To) == 1 ? this.To : other.To, this.Offset) }; } public IEnumerator<TValue> GetEnumerator() { for (TValue i = this.from; i <= this.to; i += this.offset) { yield return i; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } }
45.256604
265
0.510715
[ "MIT" ]
TsivanyukVE/Ranger
source/Ranger.Library/sources/VirtualRange/VirtualRange.cs
23,986
C#
namespace StinkyEngine.Pipelines.SpriteFactoryPipeline { public class SpriteFactoryCycle { public int[] Frames { get; set; } public bool IsLooping { get; set; } public float FrameDuration { get; set; } public SpriteFactoryCycle(bool isLooping, int[] frames, float frameDuration) { IsLooping = isLooping; Frames = frames; FrameDuration = frameDuration; } } }
22.105263
78
0.657143
[ "MIT" ]
shmellyorc/SpriteFactoryProcessor
SpriteFactoryPipeline/SpriteFactoryCycle.cs
420
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System.Collections; #endregion namespace DotNetNuke.Services.Search { /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index /// Class: SearchContentModuleInfoCollection /// ----------------------------------------------------------------------------- /// <summary> /// Represents a collection of <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> objects. /// </summary> /// <remarks> /// </remarks> /// ----------------------------------------------------------------------------- #pragma warning disable 0618 public class SearchContentModuleInfoCollection : CollectionBase { #region "Constructors" /// <summary> /// Initializes a new instance of the <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> class. /// </summary> public SearchContentModuleInfoCollection() { } /// <summary> /// Initializes a new instance of the <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> class containing the elements of the specified source collection. /// </summary> /// <param name="value">A <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> with which to initialize the collection.</param> public SearchContentModuleInfoCollection(SearchContentModuleInfoCollection value) { AddRange(value); } /// <summary> /// Initializes a new instance of the <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> class containing the specified array of <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> objects. /// </summary> /// <param name="value">An array of <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> objects with which to initialize the collection. </param> public SearchContentModuleInfoCollection(SearchContentModuleInfo[] value) { AddRange(value); } #endregion #region "Properties" /// <summary> /// Gets the <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> at the specified index in the collection. /// <para> /// In VB.Net, this property is the indexer for the <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> class. /// </para> /// </summary> public SearchContentModuleInfo this[int index] { get { return (SearchContentModuleInfo) List[index]; } set { List[index] = value; } } #endregion #region "Public Methods" /// <summary> /// Add an element of the specified <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> to the end of the collection. /// </summary> /// <param name="value">An object of type <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> to add to the collection.</param> public int Add(SearchContentModuleInfo value) { return List.Add(value); } /// <summary> /// Gets the index in the collection of the specified <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see>, if it exists in the collection. /// </summary> /// <param name="value">The <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> to locate in the collection.</param> /// <returns>The index in the collection of the specified object, if found; otherwise, -1.</returns> public int IndexOf(SearchContentModuleInfo value) { return List.IndexOf(value); } /// <summary> /// Add an element of the specified <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> to the collection at the designated index. /// </summary> /// <param name="index">An <see cref="System.Int32">Integer</see> to indicate the location to add the object to the collection.</param> /// <param name="value">An object of type <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> to add to the collection.</param> public void Insert(int index, SearchContentModuleInfo value) { List.Insert(index, value); } /// <summary> /// Remove the specified object of type <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> from the collection. /// </summary> /// <param name="value">An object of type <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> to remove to the collection.</param> public void Remove(SearchContentModuleInfo value) { List.Remove(value); } /// <summary> /// Gets a value indicating whether the collection contains the specified <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see>. /// </summary> /// <param name="value">The <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> to search for in the collection.</param> /// <returns><b>true</b> if the collection contains the specified object; otherwise, <b>false</b>.</returns> public bool Contains(SearchContentModuleInfo value) { //If value is not of type SearchContentModuleInfo, this will return false. return List.Contains(value); } /// <summary> /// Copies the elements of the specified <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> array to the end of the collection. /// </summary> /// <param name="value">An array of type <see cref="SearchContentModuleInfo">SearchContentModuleInfo</see> containing the objects to add to the collection.</param> public void AddRange(SearchContentModuleInfo[] value) { for (int i = 0; i <= value.Length - 1; i++) { Add(value[i]); } } /// <summary> /// Adds the contents of another <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> to the end of the collection. /// </summary> /// <param name="value">A <see cref="SearchContentModuleInfoCollection">SearchContentModuleInfoCollection</see> containing the objects to add to the collection. </param> public void AddRange(SearchContentModuleInfoCollection value) { for (int i = 0; i <= value.Count - 1; i++) { Add((SearchContentModuleInfo) value.List[i]); } } /// <summary> /// Copies the collection objects to a one-dimensional <see cref="T:System.Array">Array</see> instance beginning at the specified index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the destination of the values copied from the collection.</param> /// <param name="index">The index of the array at which to begin inserting.</param> public void CopyTo(SearchContentModuleInfo[] array, int index) { List.CopyTo(array, index); } /// <summary> /// Creates a one-dimensional <see cref="T:System.Array">Array</see> instance containing the collection items. /// </summary> /// <returns>Array of type SearchContentModuleInfo</returns> public SearchContentModuleInfo[] ToArray() { var arr = new SearchContentModuleInfo[Count]; CopyTo(arr, 0); return arr; } #endregion } #pragma warning restore 0618 }
45.876404
246
0.629194
[ "MIT" ]
CMarius94/Dnn.Platform
DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs
8,168
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Enums.cs" company="Whem"> // Enum class // </copyright> // <summary> // Defines the Enums type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace LotteryLib.Tools { /// <summary> /// The enums. /// </summary> public partial class Enums { /// <summary> /// The generate type. /// </summary> public enum GenerateType { /// <summary> /// The each by each. /// </summary> EachByEach, /// <summary> /// The get the best. /// </summary> GetTheBest, /// <summary> /// The unique. /// </summary> Unique } /// <summary> /// The lottery type. /// </summary> public enum LotteryType { /// <summary> /// The the five number draw. /// </summary> TheFiveNumberDraw = 5, /// <summary> /// The the six number draw. /// </summary> TheSixNumberDraw = 6, /// <summary> /// The the seven number draw. /// </summary> TheSevenNumberDraw = 7, // EuroJackPot, // Custom, } } }
24.301587
120
0.344219
[ "MIT" ]
Whem/lotteryGuesser
src/LotteryGuesserFrameworkWpf/LotteryGuesserFrameworkLib/Tools/Enums.cs
1,533
C#
using System; using System.Threading.Tasks; using Settings; using UniRx; using UnityEngine; namespace Units.Movement { public class EnemyMover : MonoBehaviour { [SerializeField] private float _speed; [SerializeField] private Transform _player; [SerializeField] private Transform _formationCell; [SerializeField] private Rigidbody2D _rigidbody; [SerializeField] private float _rotationSpeed; private MovementActionStrategy _currentStrategy; public void Setup(float speed, float rotationSpeed, Transform player, Transform formationCell) { _speed = speed; _rotationSpeed = rotationSpeed; _player = player; _formationCell = formationCell; _rigidbody = GetComponent<Rigidbody2D>(); } public async Task DoMovement(MovementCommandsQueue movementCommandsQueue) { transform.SetParent(null); foreach (var movementAction in movementCommandsQueue.Actions) { if (enabled && gameObject.activeInHierarchy) await DoAction(movementAction); } _currentStrategy = null; if (enabled && gameObject.activeInHierarchy) { transform.SetParent(_formationCell); transform.localRotation = Quaternion.identity; transform.localPosition = Vector3.zero; } } private void Update() { _currentStrategy?.Tick(); } private Task DoAction(MovementAction action) { var strategy = GetStrategy(action); var tcs = new TaskCompletionSource<Unit>(); strategy.Finished += () => tcs.TrySetResult(Unit.Default); _currentStrategy = strategy; return tcs.Task; } private MovementActionStrategy GetStrategy(MovementAction action) { switch (action.Type) { case MovementType.StartPoint: return new StartPointStrategy(_rigidbody, action.Point, _formationCell); case MovementType.MoveToPoint: return new MoveToPointStrategy(_rigidbody, action.Point, _speed, _rotationSpeed); case MovementType.MoveToPlayer: return new MoveToPlayerStrategy(_rigidbody, _player, action.Point, _speed, _rotationSpeed); case MovementType.MoveToFormation: return new MoveToFormationStrategy(_rigidbody, _formationCell, _speed, _rotationSpeed); case MovementType.JoinFormation: return new JoinFormationStrategy(_rigidbody, _formationCell); case MovementType.GoOffscreen: return new MoveOffscreenStrategy(_rigidbody, _speed, _rotationSpeed); default: throw new ArgumentOutOfRangeException(); } } private void OnDisable() { _currentStrategy?.Cancel(); } } }
35.25
111
0.603159
[ "MIT" ]
Volodej/GalagaTestProject
Assets/Scripts/Units/Movement/EnemyMover.cs
3,102
C#
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using Avalonia.Controls.Primitives; using Avalonia.HtmlRenderer; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using TheArtOfDev.HtmlRenderer.Core; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Avalonia; using TheArtOfDev.HtmlRenderer.Avalonia.Adapters; namespace Avalonia.Controls.Html { /// <summary> /// Provides HTML rendering using the text property.<br/> /// Avalonia control that will render html content in it's client rectangle.<br/> /// The control will handle mouse and keyboard events on it to support html text selection, copy-paste and mouse clicks.<br/> /// <para> /// The major differential to use HtmlPanel or HtmlLabel is size and scrollbars.<br/> /// If the size of the control depends on the html content the HtmlLabel should be used.<br/> /// If the size is set by some kind of layout then HtmlPanel is more suitable, also shows scrollbars if the html contents is larger than the control client rectangle.<br/> /// </para> /// <para> /// <h4>LinkClicked event:</h4> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </para> /// <para> /// <h4>StylesheetLoad event:</h4> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </para> /// <para> /// <h4>ImageLoad event:</h4> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </para> /// <para> /// <h4>RenderError event:</h4> /// Raised when an error occurred during html rendering.<br/> /// </para> /// </summary> public class HtmlControl : Control { /// <summary> /// Underline html container instance. /// </summary> protected readonly HtmlContainer _htmlContainer; /// <summary> /// the base stylesheet data used in the control /// </summary> protected CssData _baseCssData; /// <summary> /// The last position of the scrollbars to know if it has changed to update mouse /// </summary> protected Point _lastScrollOffset; public static readonly AvaloniaProperty AvoidImagesLateLoadingProperty = PropertyHelper.Register<HtmlControl, bool>(nameof(AvoidImagesLateLoading), false, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty IsSelectionEnabledProperty = PropertyHelper.Register<HtmlControl, bool>(nameof(IsSelectionEnabled), true, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty IsContextMenuEnabledProperty = PropertyHelper.Register<HtmlControl, bool>(nameof(IsContextMenuEnabled), true, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty BaseStylesheetProperty = PropertyHelper.Register<HtmlControl, string>(nameof(BaseStylesheet), null, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty TextProperty = PropertyHelper.Register<HtmlControl, string>(nameof(Text), null, OnAvaloniaProperty_valueChanged); public static readonly StyledProperty<IBrush> BackgroundProperty = Border.BackgroundProperty.AddOwner<HtmlControl>(); public static readonly AvaloniaProperty BorderThicknessProperty = AvaloniaProperty.Register<HtmlControl, Thickness>(nameof(BorderThickness), new Thickness(0)); public static readonly AvaloniaProperty BorderBrushProperty = AvaloniaProperty.Register<HtmlControl, IBrush>(nameof(BorderBrush)); public static readonly AvaloniaProperty PaddingProperty = AvaloniaProperty.Register<HtmlControl, Thickness>(nameof(Padding), new Thickness(0)); public static readonly RoutedEvent LoadCompleteEvent = RoutedEvent.Register<RoutedEventArgs>("LoadComplete", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent LinkClickedEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlLinkClickedEventArgs>>("LinkClicked", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent RenderErrorEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlRenderErrorEventArgs>>("RenderError", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent RefreshEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlRefreshEventArgs>>("Refresh", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent StylesheetLoadEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlStylesheetLoadEventArgs>>("StylesheetLoad", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent ImageLoadEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlImageLoadEventArgs>>("ImageLoad", RoutingStrategies.Bubble, typeof (HtmlControl)); static HtmlControl() { FocusableProperty.OverrideDefaultValue(typeof(HtmlControl), true); AffectsRender(TextProperty); } /// <summary> /// Creates a new HtmlPanel and sets a basic css for it's styling. /// </summary> protected HtmlControl() { _htmlContainer = new HtmlContainer(); _htmlContainer.LoadComplete += OnLoadComplete; _htmlContainer.LinkClicked += OnLinkClicked; _htmlContainer.RenderError += OnRenderError; _htmlContainer.Refresh += OnRefresh; _htmlContainer.StylesheetLoad += OnStylesheetLoad; _htmlContainer.ImageLoad += OnImageLoad; } //Hack for adapter internal bool LeftMouseButton { get; private set; } /// <summary> /// Raised when the set html document has been fully loaded.<br/> /// Allows manipulation of the html dom, scroll position, etc. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<EventArgs>> LoadComplete { add { AddHandler(LoadCompleteEvent, value); } remove { RemoveHandler(LoadCompleteEvent, value); } } /// <summary> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlLinkClickedEventArgs>> LinkClicked { add { AddHandler(LinkClickedEvent, value); } remove { RemoveHandler(LinkClickedEvent, value); } } /// <summary> /// Raised when an error occurred during html rendering.<br/> /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlRenderErrorEventArgs>> RenderError { add { AddHandler(RenderErrorEvent, value); } remove { RemoveHandler(RenderErrorEvent, value); } } /// <summary> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlStylesheetLoadEventArgs>> StylesheetLoad { add { AddHandler(StylesheetLoadEvent, value); } remove { RemoveHandler(StylesheetLoadEvent, value); } } /// <summary> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlImageLoadEventArgs>> ImageLoad { add { AddHandler(ImageLoadEvent, value); } remove { RemoveHandler(ImageLoadEvent, value); } } /// <summary> /// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/> /// True - images are loaded as soon as the html is parsed.<br/> /// False - images that are not visible because of scroll location are not loaded until they are scrolled to. /// </summary> /// <remarks> /// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large /// amount of images, as all image loading is delayed (downloading and loading into memory).<br/> /// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded /// resulting in layout change during user scroll.<br/> /// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they /// will push the html elements down. /// </remarks> [Category("Behavior")] [Description("If image loading only when visible should be avoided")] public bool AvoidImagesLateLoading { get { return (bool)GetValue(AvoidImagesLateLoadingProperty); } set { SetValue(AvoidImagesLateLoadingProperty, value); } } /// <summary> /// Is content selection is enabled for the rendered html (default - true).<br/> /// If set to 'false' the rendered html will be static only with ability to click on links. /// </summary> [Category("Behavior")] [Description("Is content selection is enabled for the rendered html.")] public bool IsSelectionEnabled { get { return (bool)GetValue(IsSelectionEnabledProperty); } set { SetValue(IsSelectionEnabledProperty, value); } } /// <summary> /// Is the build-in context menu enabled and will be shown on mouse right click (default - true) /// </summary> [Category("Behavior")] [Description("Is the build-in context menu enabled and will be shown on mouse right click.")] public bool IsContextMenuEnabled { get { return (bool)GetValue(IsContextMenuEnabledProperty); } set { SetValue(IsContextMenuEnabledProperty, value); } } /// <summary> /// Set base stylesheet to be used by html rendered in the panel. /// </summary> [Category("Appearance")] [Description("Set base stylesheet to be used by html rendered in the control.")] public string BaseStylesheet { get { return (string)GetValue(BaseStylesheetProperty); } set { SetValue(BaseStylesheetProperty, value); } } /// <summary> /// Gets or sets the text of this panel /// </summary> [Description("Sets the html of this control.")] public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public Thickness BorderThickness { get { return (Thickness) GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } public IBrush BorderBrush { get { return (IBrush)GetValue(BorderBrushProperty); } set { SetValue(BorderThicknessProperty, value); } } public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } public IBrush Background { get { return (IBrush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value);} } /// <summary> /// Get the currently selected text segment in the html. /// </summary> [Browsable(false)] public virtual string SelectedText { get { return _htmlContainer.SelectedText; } } /// <summary> /// Copy the currently selected html segment with style. /// </summary> [Browsable(false)] public virtual string SelectedHtml { get { return _htmlContainer.SelectedHtml; } } /// <summary> /// Get html from the current DOM tree with inline style. /// </summary> /// <returns>generated html</returns> public virtual string GetHtml() { return _htmlContainer != null ? _htmlContainer.GetHtml() : null; } /// <summary> /// Get the rectangle of html element as calculated by html layout.<br/> /// Element if found by id (id attribute on the html element).<br/> /// Note: to get the screen rectangle you need to adjust by the hosting control.<br/> /// </summary> /// <param name="elementId">the id of the element to get its rectangle</param> /// <returns>the rectangle of the element or null if not found</returns> public virtual Rect? GetElementRectangle(string elementId) { return _htmlContainer != null ? _htmlContainer.GetElementRectangle(elementId) : null; } /// <summary> /// Clear the current selection. /// </summary> public void ClearSelection() { if (_htmlContainer != null) _htmlContainer.ClearSelection(); } //HACK: We don't have support for RenderSize for now private Size RenderSize => new Size(Bounds.Width, Bounds.Height); public override void Render(DrawingContext context) { context.FillRectangle(Background, new Rect(RenderSize)); if (BorderThickness != new Thickness(0) && BorderBrush != null) { var brush = new SolidColorBrush(Colors.Black); if (BorderThickness.Top > 0) context.FillRectangle(brush, new Rect(0, 0, RenderSize.Width, BorderThickness.Top)); if (BorderThickness.Bottom > 0) context.FillRectangle(brush, new Rect(0, RenderSize.Height - BorderThickness.Bottom, RenderSize.Width, BorderThickness.Bottom)); if (BorderThickness.Left > 0) context.FillRectangle(brush, new Rect(0, 0, BorderThickness.Left, RenderSize.Height)); if (BorderThickness.Right > 0) context.FillRectangle(brush, new Rect(RenderSize.Width - BorderThickness.Right, 0, BorderThickness.Right, RenderSize.Height)); } var htmlWidth = HtmlWidth(RenderSize); var htmlHeight = HtmlHeight(RenderSize); if (_htmlContainer != null && htmlWidth > 0 && htmlHeight > 0) { /* //TODO: Revert antialiasing fixes var windows = Window.GetWindow(this); if (windows != null) { // adjust render location to round point so we won't get anti-alias smugness var wPoint = TranslatePoint(new Point(0, 0), windows); wPoint.Offset(-(int)wPoint.X, -(int)wPoint.Y); var xTrans = wPoint.X < .5 ? -wPoint.X : 1 - wPoint.X; var yTrans = wPoint.Y < .5 ? -wPoint.Y : 1 - wPoint.Y; context.PushTransform(new TranslateTransform(xTrans, yTrans)); }*/ using (context.PushClip(new Rect(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top, htmlWidth, (int) htmlHeight))) { _htmlContainer.Location = new Point(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top); _htmlContainer.PerformPaint(context, new Rect(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top, htmlWidth, htmlHeight)); } if (!_lastScrollOffset.Equals(_htmlContainer.ScrollOffset)) { _lastScrollOffset = _htmlContainer.ScrollOffset; InvokeMouseMove(); } } } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_htmlContainer != null) _htmlContainer.HandleMouseMove(this, e.GetPosition(this)); } /// <summary> /// Handle mouse leave to handle cursor change. /// </summary> protected override void OnPointerLeave(PointerEventArgs e) { base.OnPointerLeave(e); if (_htmlContainer != null) _htmlContainer.HandleMouseLeave(this); } /// <summary> /// Handle mouse down to handle selection. /// </summary> protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); LeftMouseButton = true; _htmlContainer?.HandleLeftMouseDown(this, e); } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); LeftMouseButton = false; if (_htmlContainer != null) _htmlContainer.HandleLeftMouseUp(this, e); } //TODO: Implement double click /* /// <summary> /// Handle mouse double click to select word under the mouse. /// </summary> protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { base.OnMouseDoubleClick(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDoubleClick(this, e); } */ /// <summary> /// Handle key down event for selection, copy and scrollbars handling. /// </summary> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (_htmlContainer != null) _htmlContainer.HandleKeyDown(this, e); } void RaiseRouted<T>(RoutedEvent ev, T arg) { var e =new HtmlRendererRoutedEventArgs<T> { Event = arg, Source = this, RoutedEvent = ev, Route = ev.RoutingStrategies }; RaiseEvent(e); } /// <summary> /// Propagate the LoadComplete event from root container. /// </summary> protected virtual void OnLoadComplete(EventArgs e) => RaiseRouted(LoadCompleteEvent, e); /// <summary> /// Propagate the LinkClicked event from root container. /// </summary> protected virtual void OnLinkClicked(HtmlLinkClickedEventArgs e) => RaiseRouted(LinkClickedEvent, e); /// <summary> /// Propagate the Render Error event from root container. /// </summary> protected virtual void OnRenderError(HtmlRenderErrorEventArgs e) => RaiseRouted(RenderErrorEvent, e); /// <summary> /// Propagate the stylesheet load event from root container. /// </summary> protected virtual void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e) => RaiseRouted(StylesheetLoadEvent, e); /// <summary> /// Propagate the image load event from root container. /// </summary> protected virtual void OnImageLoad(HtmlImageLoadEventArgs e) => RaiseRouted(ImageLoadEvent, e); /// <summary> /// Handle html renderer invalidate and re-layout as requested. /// </summary> protected virtual void OnRefresh(HtmlRefreshEventArgs e) { if (e.Layout) InvalidateMeasure(); InvalidateVisual(); } /// <summary> /// Get the width the HTML has to render in (not including vertical scroll iff it is visible) /// </summary> protected virtual double HtmlWidth(Size size) { return size.Width - Padding.Left - Padding.Right - BorderThickness.Left - BorderThickness.Right; } /// <summary> /// Get the width the HTML has to render in (not including vertical scroll iff it is visible) /// </summary> protected virtual double HtmlHeight(Size size) { return size.Height - Padding.Top - Padding.Bottom - BorderThickness.Top - BorderThickness.Bottom; } /// <summary> /// call mouse move to handle paint after scroll or html change affecting mouse cursor. /// </summary> protected virtual void InvokeMouseMove() { _htmlContainer.HandleMouseMove(this, (this.GetVisualRoot() as IInputRoot)?.MouseDevice?.GetPosition(this) ?? default(Point)); } /// <summary> /// Handle when dependency property value changes to update the underline HtmlContainer with the new value. /// </summary> private static void OnAvaloniaProperty_valueChanged(AvaloniaObject AvaloniaObject, AvaloniaPropertyChangedEventArgs e) { var control = AvaloniaObject as HtmlControl; if (control != null) { var htmlContainer = control._htmlContainer; if (e.Property == AvoidImagesLateLoadingProperty) { htmlContainer.AvoidImagesLateLoading = (bool) e.NewValue; } else if (e.Property == IsSelectionEnabledProperty) { htmlContainer.IsSelectionEnabled = (bool) e.NewValue; } else if (e.Property == IsContextMenuEnabledProperty) { htmlContainer.IsContextMenuEnabled = (bool) e.NewValue; } else if (e.Property == BaseStylesheetProperty) { var baseCssData = CssData.Parse(AvaloniaAdapter.Instance, (string) e.NewValue); control._baseCssData = baseCssData; htmlContainer.SetHtml(control.Text, baseCssData); } else if (e.Property == TextProperty) { htmlContainer.ScrollOffset = new Point(0, 0); htmlContainer.SetHtml((string) e.NewValue, control._baseCssData); control.InvalidateMeasure(); control.InvalidateVisual(); if (control.VisualRoot != null) { control.InvokeMouseMove(); } } } } private void OnLoadComplete(object sender, EventArgs e) { if (CheckAccess()) OnLoadComplete(e); else Dispatcher.UIThread.InvokeAsync(() => OnLoadComplete(e)).Wait(); } private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e) { if (CheckAccess()) OnLinkClicked(e); else Dispatcher.UIThread.InvokeAsync(() => OnLinkClicked(e)).Wait(); } private void OnRenderError(object sender, HtmlRenderErrorEventArgs e) { if (CheckAccess()) OnRenderError(e); else Dispatcher.UIThread.InvokeAsync(() => OnRenderError(e)).Wait(); } private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e) { if (CheckAccess()) OnStylesheetLoad(e); else Dispatcher.UIThread.InvokeAsync(() => OnStylesheetLoad(e)).Wait(); } private void OnImageLoad(object sender, HtmlImageLoadEventArgs e) { if (CheckAccess()) OnImageLoad(e); else Dispatcher.UIThread.InvokeAsync(() => OnImageLoad(e)).Wait(); } private void OnRefresh(object sender, HtmlRefreshEventArgs e) { if (CheckAccess()) OnRefresh(e); else Dispatcher.UIThread.InvokeAsync(() => OnRefresh(e)).Wait(); } } }
41.518699
175
0.606877
[ "MIT" ]
Solexid/Avalonia.HtmlRenderer
HtmlControl.cs
25,534
C#
namespace LHelper.Web.Infrastructure.Extensions { using Microsoft.AspNetCore.Mvc.ViewFeatures; public static class TempDataDictionaryExitensions { public static void AddSuccessMessage(this ITempDataDictionary tempData, string message) { tempData[WebConstants.TempDataSuccessMessageKey] = message; } } }
27.461538
95
0.719888
[ "MIT" ]
k0ma/LHelper
LHelper/LHelper.Web/Infrastructure/Extensions/TempDataDictionaryExitensions.cs
359
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel { using System.ServiceModel.Channels; public enum MsmqEncryptionAlgorithm { RC4Stream, Aes } static class MsmqEncryptionAlgorithmHelper { public static bool IsDefined(MsmqEncryptionAlgorithm algorithm) { return algorithm == MsmqEncryptionAlgorithm.RC4Stream || algorithm == MsmqEncryptionAlgorithm.Aes; } public static int ToInt32(MsmqEncryptionAlgorithm algorithm) { switch (algorithm) { case MsmqEncryptionAlgorithm.RC4Stream: return UnsafeNativeMethods.CALG_RC4; case MsmqEncryptionAlgorithm.Aes: return UnsafeNativeMethods.CALG_AES; default: return -1; } } } }
29.542857
110
0.526112
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/MsmqEncryptionAlgorithm.cs
1,034
C#
// <copyright file="TelemetryDispatchMessageInspector.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if NETFRAMEWORK using System; using System.Collections.Generic; using System.Diagnostics; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Instrumentation.Wcf.Implementation; using OpenTelemetry.Internal; using OpenTelemetry.Trace; namespace OpenTelemetry.Instrumentation.Wcf { /// <summary> /// An <see cref="IDispatchMessageInspector"/> implementation which adds telemetry to incoming requests. /// </summary> public class TelemetryDispatchMessageInspector : IDispatchMessageInspector { private readonly IDictionary<string, ActionMetadata> actionMappings; internal TelemetryDispatchMessageInspector(IDictionary<string, ActionMetadata> actionMappings) { Guard.ThrowIfNull(actionMappings); this.actionMappings = actionMappings; } /// <inheritdoc/> public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { try { if (WcfInstrumentationActivitySource.Options == null || WcfInstrumentationActivitySource.Options.IncomingRequestFilter?.Invoke(request) == false) { WcfInstrumentationEventSource.Log.RequestIsFilteredOut(); return null; } } catch (Exception ex) { WcfInstrumentationEventSource.Log.RequestFilterException(ex); return null; } var textMapPropagator = Propagators.DefaultTextMapPropagator; var ctx = textMapPropagator.Extract(default, request, WcfInstrumentationActivitySource.MessageHeaderValuesGetter); Activity activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( WcfInstrumentationActivitySource.IncomingRequestActivityName, ActivityKind.Server, ctx.ActivityContext); if (activity != null) { string action; if (!string.IsNullOrEmpty(request.Headers.Action)) { action = request.Headers.Action; activity.DisplayName = action; } else { action = string.Empty; } if (activity.IsAllDataRequested) { activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) { actionMetadata = new ActionMetadata { ContractName = null, OperationName = action, }; } activity.SetTag(WcfInstrumentationConstants.RpcServiceTag, actionMetadata.ContractName); activity.SetTag(WcfInstrumentationConstants.RpcMethodTag, actionMetadata.OperationName); if (WcfInstrumentationActivitySource.Options.SetSoapMessageVersion) { activity.SetTag(WcfInstrumentationConstants.SoapMessageVersionTag, request.Version.ToString()); } var localAddressUri = channel.LocalAddress?.Uri; if (localAddressUri != null) { activity.SetTag(WcfInstrumentationConstants.NetHostNameTag, localAddressUri.Host); activity.SetTag(WcfInstrumentationConstants.NetHostPortTag, localAddressUri.Port); activity.SetTag(WcfInstrumentationConstants.WcfChannelSchemeTag, localAddressUri.Scheme); activity.SetTag(WcfInstrumentationConstants.WcfChannelPathTag, localAddressUri.LocalPath); } try { WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.AfterReceiveRequest, request); } catch (Exception ex) { WcfInstrumentationEventSource.Log.EnrichmentException(ex); } } if (!(textMapPropagator is TraceContextPropagator)) { Baggage.Current = ctx.Baggage; } } return activity; } /// <inheritdoc/> public void BeforeSendReply(ref Message reply, object correlationState) { if (correlationState is Activity activity) { if (activity.IsAllDataRequested && reply != null) { if (reply.IsFault) { activity.SetStatus(Status.Error); } activity.SetTag(WcfInstrumentationConstants.SoapReplyActionTag, reply.Headers.Action); try { WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.BeforeSendReply, reply); } catch (Exception ex) { WcfInstrumentationEventSource.Log.EnrichmentException(ex); } } activity.Stop(); if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator)) { Baggage.Current = default; } } } } } #endif
39.349398
161
0.583742
[ "Apache-2.0" ]
mic-max/opentelemetry-dotnet-contrib
src/OpenTelemetry.Instrumentation.Wcf/TelemetryDispatchMessageInspector.cs
6,534
C#
using AutoMoqCore; using Moq; using NUnit.Framework; namespace UnitTests { public abstract class With_an_automocked<T> { public T ClassUnderTest { get; set; } private AutoMoqer mocker; [SetUp] public void WithAnAutoMockedSetup() { mocker = new AutoMoqer(); ClassUnderTest = mocker.Create<T>(); } protected Mock<TMock> GetMock<TMock>() where TMock : class { return mocker.GetMock<TMock>(); } protected TAny IsAny<TAny>() { return It.IsAny<TAny>(); } } }
20.433333
66
0.549755
[ "MIT" ]
allan-stewart/star-wars-character-of-the-day
UnitTests/With_an_automocked.cs
613
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class StartDebuggerEvent { public static readonly NotificationType<object, object> Type = NotificationType<object, object>.Create("powerShell/startDebugger"); } }
32
101
0.742188
[ "MIT" ]
Benny1007/PowerShellEditorServices
src/PowerShellEditorServices.Protocol/LanguageServer/StartDebuggerEvent.cs
512
C#
using System.Collections.Generic; using WABA360Dialog.ApiClient.Payloads.Enums; using WABA360Dialog.Common.Converters.Base; namespace WABA360Dialog.ApiClient.Payloads.Converters { internal class MessageStatusConverter : EnumConverter<MessageStatus> { protected override MessageStatus GetEnumValue(string value) => EnumStringConverter.GetMessageStatus(value); protected override string GetStringValue(MessageStatus value) => value.GetString(); } public static partial class EnumStringConverter { private static readonly IReadOnlyDictionary<string, MessageStatus> MessageStatusStringToEnum = new Dictionary<string, MessageStatus> { { "delivered", MessageStatus.delivered }, { "read", MessageStatus.read }, { "sent", MessageStatus.sent }, { "failed", MessageStatus.failed }, { "deleted", MessageStatus.deleted }, { "warning", MessageStatus.warning }, }; private static readonly IReadOnlyDictionary<MessageStatus, string> MessageStatusEnumToString = new Dictionary<MessageStatus, string> { { MessageStatus.delivered, "delivered" }, { MessageStatus.read, "read" }, { MessageStatus.sent, "sent" }, { MessageStatus.failed, "failed" }, { MessageStatus.deleted, "deleted" }, { MessageStatus.warning, "warning" }, }; public static string GetString(this MessageStatus status) => MessageStatusEnumToString.TryGetValue(status, out var stringValue) ? stringValue : "unknown"; public static MessageStatus GetMessageStatus(string status) => MessageStatusStringToEnum.TryGetValue(status, out var enumValue) ? enumValue : 0; } }
38.627451
102
0.611675
[ "MIT" ]
yuenkik6/360Dialog.NET
WABA360Dialog.NET/ApiClient/Payloads/Converters/MessageStatusConverter.cs
1,972
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.Composition.Tests { using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Composition.EmbeddedTypeReceiver; using Xunit; using MefV1 = System.ComponentModel.Composition; public class BaseGenericTypeTests { [MefFact(CompositionEngines.V1Compat, typeof(PublicExport), typeof(DerivedType))] public void GenericBaseTypeWithImportsTest(IContainer container) { var instance = container.GetExportedValue<DerivedType>(); Assert.NotNull(instance.ImportingPropertyAccessor); } internal class GenericBaseType<T> { [MefV1.Import] protected PublicExport ImportingProperty { get; set; } = null!; } [MefV1.Export] internal class DerivedType : GenericBaseType<IList<IList<IFoo>>> { internal PublicExport ImportingPropertyAccessor { get { return this.ImportingProperty; } } } internal interface IFoo { } [MefV1.Export] public class PublicExport { } } }
31.021277
101
0.661866
[ "MIT" ]
AArnott/vs-mef
test/Microsoft.VisualStudio.Composition.Tests/BaseGenericTypeTests.cs
1,460
C#
using RinnaiPortal.FactoryMethod; using RinnaiPortal.Repository.Sign.Forms; using RinnaiPortal.Tools; using RinnaiPortal.ViewModel.Sign.Forms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace RinnaiPortal.Area.Sign.Forms { //簽核頁面中的受訓單 public partial class TrainData : System.Web.UI.Page { private TrainViewModel model = null; private TrainDetailRepository _trainDetaiRepo = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { _trainDetaiRepo = RepositoryFactory.CreateTrainDetailRepo(); //從QueryString取得 簽核代碼 string docID = String.IsNullOrEmpty(Request["SignDocID"]) ? String.Empty : Request["SignDocID"].ToString(); //根據查詢的 簽核代碼 搜尋忘刷單 model = _trainDetaiRepo.GetData(docID); WebUtils.PageDataBind(model, this.Page); Signed.NavigateUrl = "~/Area/Sign/WorkflowDetail.aspx?signDocID=" + docID; } PageInit(); } protected void PageInit() { if (!String.IsNullOrEmpty(Request["SignDocID"])) { PlaceHolder1.Controls.Clear(); var QuestionDataList = _trainDetaiRepo.QueryQuestionDataBySignDocID(Request["SignDocID"]); QuestionDataList.All(row => { PlaceHolder1.Controls.Add(new LiteralControl("<hr style='margin:6px;height:1px;border:0px;background-color:#D5D5D5;color:#D5D5D5;'/>")); PlaceHolder1.Controls.Add(new LiteralControl("&nbsp;&nbsp")); //序號 Label myLabel = new Label(); myLabel.Text = ""; myLabel.Text = row["serial_no"].ToString(); myLabel.ID = "Label" + row["serial_no"].ToString(); //myLabel.BackColor = "#FFFFFF"; myLabel.Width = 10; PlaceHolder1.Controls.Add(myLabel); PlaceHolder1.Controls.Add(new LiteralControl("&nbsp;&nbsp")); //題目 Label mylblName = new Label(); mylblName.Text = ""; mylblName.Text = row["CODENAME"].ToString(); mylblName.ID = "LabelName" + row["serial_no"].ToString(); mylblName.Width = 300; PlaceHolder1.Controls.Add(mylblName); PlaceHolder1.Controls.Add(new LiteralControl("&nbsp;&nbsp")); //答案 if (row["ANSTYPE"].ToString() == "C")//填文字 { TextBox txtAns = new TextBox(); txtAns.Text = ""; txtAns.ID = "textbox" + row["serial_no"].ToString(); txtAns.Text = row["ANS"].ToString(); //txtAns.TabIndex = (i + 1).ToString(); txtAns.TextMode = TextBoxMode.MultiLine; txtAns.Width = 500; txtAns.Height = 80; PlaceHolder1.Controls.Add(txtAns); } else if (row["ANSTYPE"].ToString() == "N")//選分數 { TextBox txtAns = new TextBox(); txtAns.Text = ""; txtAns.ID = "textbox" + row["serial_no"].ToString(); txtAns.Text = row["ANS"].ToString(); //txtAns.TabIndex = (i + 1).ToString(); //txtAns.TextMode = TextBoxMode.MultiLine; txtAns.Width = 50; txtAns.Height = 50; PlaceHolder1.Controls.Add(txtAns); } return true; }); } } } }
44.891304
157
0.485472
[ "MIT" ]
systemgregorypc/Agatha-inteligencia-artificial-
agathaIA-voice/agathaiaportal/Area/Sign/Forms/TrainData.aspx.cs
4,216
C#
using System; using System.Threading.Tasks; using System.Linq; using EmailService.Dtos.Requests; using EmailService.Dtos.Responses; using EmailService.Dtos.Responses.Factories; using EmailService.Models; using EmailService.Service; using EmailService.Utils; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; namespace EmailService.Controllers { [Route("api/email/logs")] [ApiController] public class EmailLogController : Controller { private readonly IEmailLoggingService _loggingService; private readonly EmailPreviewController _emailPreviewController; public EmailLogController(IEmailLoggingService emailLoggingService, EmailPreviewController emailPreviewController) { _loggingService = emailLoggingService; _emailPreviewController = emailPreviewController; } // GET api/email/log/{id} /// <summary> /// Return information about an email that has been sent by the service. This endpoint is only usable /// if you are storing email logs with the database method. /// </summary> /// <param name="id">The id of the email log entry.</param> /// <param name="receiversToTest">A JSON array containing receivers to test if they were receivers of the /// email. Since the email receivers are hashed in the logs we can only know if someone was included in the email /// or not, but not get a list of who were included. The output parameter "MatchedReceiversToTest" reflects /// if the match was true or not.</param> /// <response code="200">If the request was valid.</response> /// <response code="400">If the request was bad.</response> [HttpGet] [Route("{id}", Name = "GetEmailLog")] [ProducesResponseType(typeof(SentEmailResponse), 200)] public async Task<IActionResult> Get([FromRoute] string id, [FromQuery(Name = "receiversToTest")] string receiversToTest = null) { bool isValidId = Guid.TryParse(id, out Guid guid); if (!isValidId) { return new BadRequestObjectResult("The id specified had an invalid format."); } LogEntry logEntry = await _loggingService.GetAsync(guid); bool noLogEntryFound = logEntry == null; if (noLogEntryFound) { return new BadRequestObjectResult("No logs found for the id provided."); } JObject content = JObject.Parse(logEntry.Content); JObject personalContent = JObject.Parse(logEntry.PersonalContent); EmailSendRequest request = new EmailSendRequest() { Content = content, PersonalContent = personalContent, Template = logEntry.Template, To = new string[0] }; OkObjectResult actionResult = await _emailPreviewController.Post(request) as OkObjectResult; EmailPreviewResponse previewResponse = (EmailPreviewResponse) actionResult.Value; string[] receiversToTestArray = RestUtility.GetArrayQueryParam(receiversToTest); bool hasReceiversToTestArray = receiversToTestArray != null && receiversToTestArray.Length > 0; bool isReceiversMatch; if (hasReceiversToTestArray) { isReceiversMatch = TestReceiversMatch(receiversToTestArray, logEntry); } else { isReceiversMatch = false; } SentEmailResponse response = SentEmailResponseFactory.Create(logEntry, previewResponse, isReceiversMatch); return new OkObjectResult(response); } private bool TestReceiversMatch(string[] receiversToTestArray, LogEntry logEntry) { string[] logEntryTo = ArrayUtility.GetArrayFromCommaSeparatedString(logEntry.To); bool isSameSize = logEntryTo.Length == receiversToTestArray.Length; if (!isSameSize) { return false; } foreach (string receiver in receiversToTestArray) { string hashedReceiver = HashUtility.GetStringHash(receiver); bool isReceiverInLogEntry = logEntryTo.Contains(hashedReceiver); if (!isReceiverInLogEntry) { return false; } } return true; } } }
32.226891
116
0.745502
[ "MIT" ]
ourstudio-se/email-service
EmailService/Controllers/EmailLogController.cs
3,837
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Account.Entities")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Account.Entities")] [assembly: System.Reflection.AssemblyTitleAttribute("Account.Entities")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Создано классом WriteCodeFragment MSBuild.
41.391304
80
0.64916
[ "Apache-2.0" ]
FairyFox5700/AniDate
src/Services/Account/Account.Entities/obj/Debug/netcoreapp3.1/Account.Entities.AssemblyInfo.cs
966
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.Cognito.Outputs { [OutputType] public sealed class UserPoolInviteMessageTemplate { public readonly string? EmailMessage; public readonly string? EmailSubject; public readonly string? SMSMessage; [OutputConstructor] private UserPoolInviteMessageTemplate( string? emailMessage, string? emailSubject, string? sMSMessage) { EmailMessage = emailMessage; EmailSubject = emailSubject; SMSMessage = sMSMessage; } } }
25.970588
81
0.663647
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/Cognito/Outputs/UserPoolInviteMessageTemplate.cs
883
C#
using Xamarin.Forms; using Xamvvm; namespace DLToolkitControlsSamples.SamplesFlowListView { public partial class GroupingAdvancedPage : ContentPage, IBasePage<GroupingAdvancedPageModel> { public GroupingAdvancedPage() { InitializeComponent(); } public void FlowScrollTo(object item) { flowListView.FlowScrollTo(item, ScrollToPosition.MakeVisible, true); } } }
22.105263
97
0.711905
[ "Apache-2.0" ]
TingtingAn/DLToolkit.Forms.Controls-master
Samples/DLToolkitControlsSamples/SamplesFlowListView/GroupingAdvancedPage.xaml.cs
422
C#
namespace Evol.Ant.Web.Startup { public class PageNames { public const string Home = "Home"; public const string About = "About"; public const string Tenants = "Tenants"; public const string Users = "Users"; public const string Roles = "Roles"; } }
25.25
48
0.60396
[ "MIT" ]
supernebula/ant-saas
aspnet-core/src/Evol.Ant.Web.Mvc/Startup/PageNames.cs
305
C#
using AAS.API.Discovery.Models; using AAS.API.Services.ADT; using AAS.API.WebApp.Filters; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Identity.Web; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using System; namespace AAS.API.Discovery.Server { /// <summary> /// Startup /// </summary> public class Startup { private readonly IWebHostEnvironment _hostingEnv; private IConfiguration Configuration { get; } /// <summary> /// Constructor /// </summary> /// <param name="env"></param> /// <param name="configuration"></param> public Startup(IWebHostEnvironment env, IConfiguration configuration) { _hostingEnv = env; Configuration = configuration; } /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd")); // Add framework services. services .AddMvc(options => { options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>(); options.OutputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter>(); options.ModelBinderProviders.Insert(0, new IdentifierKeyValuePairModelBinderProvider()); }) .AddNewtonsoftJson(opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); opts.SerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy())); }) .AddXmlSerializerFormatters(); services .AddSwaggerGen(c => { c.SwaggerDoc("Final-Draft", new OpenApiInfo { Version = "Final-Draft", Title = "DotAAS Part 2 | HTTP/REST | Entire Interface Collection", Description = "DotAAS Part 2 | HTTP/REST | Entire Interface Collection (ASP.NET Core 3.1)", Contact = new OpenApiContact() { Name = "Michael Hoffmeister, Torben Miny, Andreas Orzelski, Manuel Sauer, Constantin Ziesche", Url = new Uri("https://github.com/swagger-api/swagger-codegen"), Email = "" }, TermsOfService = new Uri("https://github.com/admin-shell-io/aas-specs") }); c.CustomSchemaIds(type => type.FullName); //c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); // Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..) // Use [ValidateModelState] on Actions to actually validate it in C# as well! c.OperationFilter<GeneratePathParamsValidationFilter>(); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty<string>() } }); }); services.AddSingleton<DigitalTwinsClientFactory, StdDigitalTwinsClientFactory>(); services.AddSingleton<AASDiscovery, ADTAASDiscovery>(); } /// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="loggerFactory"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { app.UseRouting(); //TODO: Uncomment this if you need wwwroot folder //app.UseStaticFiles(); app.UseAuthentication(); app.UseAuthorization(); app.UseSwagger(options => { options.SerializeAsV2 = Configuration.GetValue<bool>("OPENAPI_JSON_VERSION_2"); }); app.UseSwaggerUI(c => { //TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes) c.SwaggerEndpoint("/swagger/Final-Draft/swagger.json", "Asset Administration Shell Part 2 | HTTP/REST | Discovery Interface"); //TODO: Or alternatively use the original Swagger contract that's included in the static files - Dont forget to uncomment app.UseStaticFiles //c.SwaggerEndpoint("/swagger-original-discovery.json", "Asset Administration Shell Part 2 | HTTP/REST | Discovery Interface"); }); //TODO: Use Https Redirection // app.UseHttpsRedirection(); app.UseEndpoints(endpoints => { if (env.IsDevelopment()) endpoints.MapControllers().WithMetadata(new AllowAnonymousAttribute()); else endpoints.MapControllers(); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { //TODO: Enable production exception handling (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling) app.UseExceptionHandler("/Error"); app.UseHsts(); } } } }
42.394118
156
0.557652
[ "MIT" ]
JMayrbaeurl/opendigitaltwins-aas-azureservices
src/aas-api-webapp-discovery/Startup.cs
7,207
C#
namespace ArduinoDriver.SerialProtocol { public class PinModeResponse : ArduinoResponse { public int Pin { get; private set; } public PinMode Mode { get; private set; } public PinModeResponse(byte pin, PinMode mode) { Pin = pin; Mode = mode; } } }
22.533333
54
0.547337
[ "MIT" ]
RickLuiken/ArduinoDriver
Source/ArduinoDriver/SerialProtocol/PinModeResponse.cs
340
C#
namespace BGLib.SDK.V4.System { public class Info { public Info(ushort major, ushort minor, ushort patch, ushort build, ushort llVersion, byte protocolVersion, byte hw) { Major = major; Minor = minor; Patch = patch; Build = build; LLVersion = llVersion; ProtocolVersion = protocolVersion; HW = hw; } /// <summary> /// Major software version /// </summary> public ushort Major { get; } /// <summary> /// Minor software version /// </summary> public ushort Minor { get; } /// <summary> /// Patch ID /// </summary> public ushort Patch { get; } /// <summary> /// Build version /// </summary> public ushort Build { get; } /// <summary> /// Link layer version /// </summary> public ushort LLVersion { get; } /// <summary> /// BGAPI protocol version /// </summary> public byte ProtocolVersion { get; } /// <summary> /// Hardware version /// </summary> public byte HW { get; } } }
27.066667
124
0.477011
[ "MIT" ]
yanshouwang/BGLib.NET
BGLib.SDK/V4/System/Info.cs
1,220
C#
using Synology.SurveillanceStation; using Synology.Extensions; using Synology.Interfaces; namespace Synology { /// <summary> /// /// </summary> public static class SynologyConnectionSurveillanceStationExtension { /// <summary> /// /// </summary> /// <param name="connection"></param> /// <returns></returns> public static ISurveillanceStationApi SurveillanceStation(this ISynologyConnection connection) => connection.Api<ISurveillanceStationApi>(); } }
23.75
142
0.730526
[ "Apache-2.0" ]
mitch-b/Synology
Synology/SurveillanceStation/SynologyConnectionSurveillanceStationExtension.cs
477
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. namespace Microsoft.EntityFrameworkCore.Query.Pipeline { public abstract class EntityQueryableTranslatorFactory : IEntityQueryableTranslatorFactory { public abstract EntityQueryableTranslator Create(QueryCompilationContext2 queryCompilationContext); } }
40.272727
111
0.799097
[ "Apache-2.0" ]
Wrank/EntityFrameworkCore
src/EFCore/Query/Pipeline/EntityQueryableExpressionVisitorsFactory.cs
445
C#
using Captura.Audio; using Captura.FFmpeg; using Captura.Models; using Captura.Video; namespace Captura.Fakes { public class FakesModule : IModule { public void OnLoad(IBinder Binder) { Binder.Bind<IMessageProvider, FakeMessageProvider>(); Binder.Bind<IRegionProvider>(() => FakeRegionProvider.Instance); Binder.Bind<ISystemTray, FakeSystemTray>(); Binder.Bind<IMainWindow, FakeWindowProvider>(); Binder.Bind<IPreviewWindow, FakePreviewWindow>(); Binder.Bind<IVideoSourcePicker>(() => FakeVideoSourcePicker.Instance); Binder.Bind<IAudioPlayer, FakeAudioPlayer>(); Binder.Bind<IFFmpegViewsProvider, FakeFFmpegViewsProvider>(); Binder.Bind<IFFmpegLogRepository, FakeFFmpegLogRepository>(); } public void Dispose() { } } }
34.96
82
0.660183
[ "MIT" ]
121986645/Captura
src/Captura.Fakes/FakesModule.cs
876
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Activation Object /// </summary> public class ActivationUnmarshaller : IUnmarshaller<Activation, XmlUnmarshallerContext>, IUnmarshaller<Activation, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> Activation IUnmarshaller<Activation, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Activation Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; Activation unmarshalledObject = new Activation(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ActivationId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ActivationId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreatedDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreatedDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DefaultInstanceName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DefaultInstanceName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ExpirationDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.ExpirationDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Expired", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.Expired = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("IamRole", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.IamRole = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RegistrationLimit", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.RegistrationLimit = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RegistrationsCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.RegistrationsCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Tags", targetDepth)) { var unmarshaller = new ListUnmarshaller<Tag, TagUnmarshaller>(TagUnmarshaller.Instance); unmarshalledObject.Tags = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ActivationUnmarshaller _instance = new ActivationUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ActivationUnmarshaller Instance { get { return _instance; } } } }
40.369863
144
0.571089
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/ActivationUnmarshaller.cs
5,894
C#
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Mozilla.Glean.FFI; using Mozilla.Glean.Net; using Mozilla.Glean.Private; using Serilog; using static Mozilla.Glean.GleanMetrics.GleanInternalMetricsOuter; using static Mozilla.Glean.GleanPings.GleanInternalPingsOuter; using static Mozilla.Glean.Utils.GleanLogger; namespace Mozilla.Glean { /// <summary> /// The Glean Gneral API. /// </summary> public sealed class Glean { // Initialize the singleton using the `Lazy` facilities. private static readonly Lazy<Glean> lazy = new Lazy<Glean>(() => new Glean()); public static Glean GleanInstance => lazy.Value; private bool initialized = false; // Keep track of this flag before Glean is initialized private bool uploadEnabled = true; // Keep track of ping types that have been registered before Glean is initialized. private HashSet<PingTypeBase> pingTypeQueue = new HashSet<PingTypeBase>(); private Configuration configuration; // This is the wrapped http uploading mechanism: provides base functionalities // for logging and delegates the actual upload to the implementation in // the `Configuration`. private BaseUploader httpClient; // The version of the application sending Glean data. private string applicationVersion; /// <summary> /// This is the tag used for logging from this class. /// </summary> private const string LogTag = "glean/Glean"; /// <summary> /// This is the name of the language used by this Glean binding. /// </summary> private readonly static string LanguageBindingName = "C#"; /// <summary> /// A logger configured for this class /// </summary> private static readonly ILogger Log = GetLogger(LogTag); private Glean() { // Private constructor to disallow instantiation since // this is meant to be a singleton. It only wires up the // glean-core logging on the Rust side. LibGleanFFI.glean_enable_logging(); } /// <summary> /// Initialize the Glean SDK. /// /// This should only be initialized once by the application, and not by /// libraries using the Glean SDK. A message is logged to error and no /// changes are made to the state if initialize is called a more than /// once. /// /// This method must be called from the main thread. /// </summary> /// <param name="applicationId">The application id to use when sending pings.</param> /// <param name="applicationVersion">The version of the application sending /// Glean data.</param> /// <param name="uploadEnabled">A `bool` that determines whether telemetry is enabled. /// If disabled, all persisted metrics, events and queued pings (except first_run_date) /// are cleared.</param> /// <param name="configuration">A Glean `Configuration` object with global settings</param> /// <param name="dataDir">The path to the Glean data directory.</param> [MethodImpl(MethodImplOptions.Synchronized)] public void Initialize( string applicationId, string applicationVersion, bool uploadEnabled, Configuration configuration, string dataDir ) { /* // Glean initialization must be called on the main thread, or lifecycle // registration may fail. This is also enforced at build time by the // @MainThread decorator, but this run time check is also performed to // be extra certain. ThreadUtils.assertOnUiThread() // In certain situations Glean.initialize may be called from a process other than the main // process. In this case we want initialize to be a no-op and just return. if (!isMainProcess(applicationContext)) { Log.e(LOG_TAG, "Attempted to initialize Glean on a process other than the main process") return } this.applicationContext = applicationContext*/ if (IsInitialized()) { Log.Error("Glean should not be initialized multiple times"); return; } this.configuration = configuration; this.applicationVersion = applicationVersion; httpClient = new BaseUploader(configuration.httpClient); // this.gleanDataDir = File(applicationContext.applicationInfo.dataDir, GLEAN_DATA_DIR) // We know we're not initialized, so we can skip the check inside `setUploadEnabled` // by setting the variable directly. this.uploadEnabled = uploadEnabled; Dispatchers.ExecuteTask(() => { RegisterPings(GleanInternalPings); IntPtr maxEventsPtr = IntPtr.Zero; if (configuration.maxEvents != null) { maxEventsPtr = Marshal.AllocHGlobal(sizeof(int)); // It's safe to call `configuration.maxEvents.Value` because we know // `configuration.maxEvents` is not null. Marshal.WriteInt32(maxEventsPtr, configuration.maxEvents.Value); } LibGleanFFI.FfiConfiguration cfg = new LibGleanFFI.FfiConfiguration { data_dir = dataDir, package_name = applicationId, language_binding_name = LanguageBindingName, upload_enabled = uploadEnabled, max_events = maxEventsPtr, delay_ping_lifetime_io = false }; // To work around a bug in the version of Mono shipped with Unity 2019.4.1f1, // copy the FFI configuration structure to unmanaged memory and pass that over // to glean-core, otherwise calling `glean_initialize` will crash and have // `__icall_wrapper_mono_struct_delete_old` in the stack. See bug 1648784 for // more details. IntPtr ptrCfg = Marshal.AllocHGlobal(Marshal.SizeOf(cfg)); Marshal.StructureToPtr(cfg, ptrCfg, false); initialized = LibGleanFFI.glean_initialize(ptrCfg) != 0; // This is safe to call even if `maxEventsPtr = IntPtr.Zero`. Marshal.FreeHGlobal(maxEventsPtr); // We were able to call `glean_initialize`, free the memory allocated for the // FFI configuration object. Marshal.FreeHGlobal(ptrCfg); // If initialization of Glean fails we bail out and don't initialize further. if (!initialized) { return; } // If any pings were registered before initializing, do so now. // We're not clearing this queue in case Glean is reset by tests. lock (this) { foreach (var ping in pingTypeQueue) { RegisterPingType(ping); } } // If this is the first time ever the Glean SDK runs, make sure to set // some initial core metrics in case we need to generate early pings. // The next times we start, we would have them around already. bool isFirstRun = LibGleanFFI.glean_is_first_run() != 0; if (isFirstRun) { InitializeCoreMetrics(); } // Deal with any pending events so we can start recording new ones bool pingSubmitted = LibGleanFFI.glean_on_ready_to_submit_pings() != 0; // We need to enqueue the BaseUploader in these cases: // 1. Pings were submitted through Glean and it is ready to upload those pings; // 2. Upload is disabled, to upload a possible deletion-request ping. if (pingSubmitted || !uploadEnabled) { httpClient.TriggerUpload(configuration); } /* // Set up information and scheduling for Glean owned pings. Ideally, the "metrics" // ping startup check should be performed before any other ping, since it relies // on being dispatched to the API context before any other metric. metricsPingScheduler = MetricsPingScheduler(applicationContext) metricsPingScheduler.schedule() // Check if the "dirty flag" is set. That means the product was probably // force-closed. If that's the case, submit a 'baseline' ping with the // reason "dirty_startup". We only do that from the second run. if (!isFirstRun && LibGleanFFI.INSTANCE.glean_is_dirty_flag_set().toBoolean()) { submitPingByNameSync("baseline", "dirty_startup") // Note: while in theory we should set the "dirty flag" to true // here, in practice it's not needed: if it hits this branch, it // means the value was `true` and nothing needs to be done. }*/ // From the second time we run, after all startup pings are generated, // make sure to clear `lifetime: application` metrics and set them again. // Any new value will be sent in newly generated pings after startup. if (!isFirstRun) { LibGleanFFI.glean_clear_application_lifetime_metrics(); InitializeCoreMetrics(); } // Upload might have been changed in between the call to `initialize` // and this task actually running. // This actually enqueues a task, which will execute after other user-submitted tasks // as part of the queue flush below. if (this.uploadEnabled != uploadEnabled) { SetUploadEnabled(this.uploadEnabled); } // Signal Dispatcher that init is complete Dispatchers.FlushQueuedInitialTasks(); /* // At this point, all metrics and events can be recorded. // This should only be called from the main thread. This is enforced by // the @MainThread decorator and the `assertOnUiThread` call. MainScope().launch { ProcessLifecycleOwner.get().lifecycle.addObserver(gleanLifecycleObserver) }*/ }); } /// <summary> /// Whether or not the Glean SDK has been initialized. /// </summary> /// <returns>Returns true if the Glean SDK has been initialized.</returns> internal bool IsInitialized() { return initialized; } /// <summary> /// Enable or disable Glean collection and upload. /// /// Metric collection is enabled by default. /// /// When uploading is disabled, metrics aren't recorded at all and no data /// is uploaded. /// /// When disabling, all pending metrics, events and queued pings are cleared /// and a `deletion-request` is generated. /// /// When enabling, the core Glean metrics are recreated. /// </summary> /// <param name="enabled">When `true`, enable metric collection.</param> public void SetUploadEnabled(bool enabled) { if (IsInitialized()) { bool originalEnabled = GetUploadEnabled(); Dispatchers.LaunchAPI(() => { LibGleanFFI.glean_set_upload_enabled(enabled); if (!enabled) { // Cancel any pending workers here so that we don't accidentally upload or // collect data after the upload has been disabled. // TODO: metricsPingScheduler.cancel() // Cancel any pending workers here so that we don't accidentally upload // data after the upload has been disabled. httpClient.CancelUploads(); } if (!originalEnabled && enabled) { // If uploading is being re-enabled, we have to restore the // application-lifetime metrics. InitializeCoreMetrics(); } if (originalEnabled && !enabled) { // If uploading is disabled, we need to send the deletion-request ping httpClient.TriggerUpload(configuration); } }); } else { uploadEnabled = enabled; } } /// <summary> /// Get whether or not Glean is allowed to record and upload data. /// </summary> /// <returns>`true` if Glean is allowed to record and upload data.</returns> public bool GetUploadEnabled() { if (IsInitialized()) { return LibGleanFFI.glean_is_upload_enabled() != 0; } else { return uploadEnabled; } } /// <summary> /// TEST ONLY FUNCTION. /// Resets the Glean state and triggers init again. /// </summary> /// <param name="applicationId">The application id to use when sending pings.</param> /// <param name="applicationVersion">The version of the application sending /// Glean data.</param> /// <param name="uploadEnabled">A `bool` that determines whether telemetry is enabled. /// If disabled, all persisted metrics, events and queued pings (except first_run_date) /// are cleared.</param> /// <param name="configuration">A Glean `Configuration` object with global settings</param> /// <param name="dataDir">The path to the Glean data directory.</param> /// <param name="clearStores">If `true` clear the contents of all stores.</param> internal void Reset( string applicationId, string applicationVersion, bool uploadEnabled, Configuration configuration, string dataDir, bool clearStores = true) { Dispatchers.TestingMode = true; if (IsInitialized() && clearStores) { // Clear all the stored data. LibGleanFFI.glean_test_clear_all_stores(); } // TODO: isMainProcess = null // Init Glean. TestDestroyGleanHandle(); Initialize(applicationId, applicationVersion, uploadEnabled, configuration, dataDir); } /// <summary> /// TEST ONLY FUNCTION. /// Destroy the owned glean-core handle. /// </summary> internal void TestDestroyGleanHandle() { if (!IsInitialized()) { // We don't need to destroy Glean: it wasn't initialized. return; } LibGleanFFI.glean_destroy_glean(); initialized = false; } private void InitializeCoreMetrics() { // The `Environment.OSVersion` object will return a version that represents an approximate // version of the OS. As the MSDN docs state, this is unreliable: // https://docs.microsoft.com/en-us/dotnet/api/system.environment.osversion?redirectedfrom=MSDN&view=netstandard-2.0 // However, there's really nothing we could do about it. Unless the product using the // Glean SDK correctly marks their manifest as Windows 10 compatible, this API will report // Windows 8 version (6.2). See the remarks section here: // https://docs.microsoft.com/en-gb/windows/win32/api/winnt/ns-winnt-osversioninfoexa?redirectedfrom=MSDN#remarks try { GleanInternalMetrics.osVersion.SetSync(Environment.OSVersion.Version.ToString()); } catch (InvalidOperationException) { GleanInternalMetrics.osVersion.SetSync("Unknown"); } // Possible values for `RuntimeInformation.OSArchitecture` are documented here: // https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.architecture?view=netstandard-2.0 GleanInternalMetrics.architecture.SetSync(RuntimeInformation.OSArchitecture.ToString()); try { // CurrentUiCulture is used for representing the locale of the UI, coming from the OS, // while CurrentCulture is the general locale used for other things (e.g. currency). GleanInternalMetrics.locale.SetSync(CultureInfo.CurrentUICulture.Name); } catch (Exception) { GleanInternalMetrics.locale.SetSync("und"); } if (configuration.channel != null) { GleanInternalMetrics.appChannel.SetSync(configuration.channel); } GleanInternalMetrics.appDisplayVersion.SetSync(applicationVersion); GleanInternalMetrics.appBuild.SetSync(configuration.buildId ?? "Unknown"); } /// <summary> /// Register the pings generated from `ManualPings` with the Glean SDK. /// </summary> /// <param name="pings"> The `Pings` object generated for your library or application /// by the Glean SDK.</param> private void RegisterPings(object pings) { // Instantiating the Pings object to send this function is enough to // call the constructor and have it registered through [Glean.registerPingType]. Log.Information("Registering pings"); } /// <summary> /// Handle the background event and send the appropriate pings. /// </summary> internal void HandleBackgroundEvent() { GleanInternalPings.baseline.Submit(BaselineReasonCodes.background); GleanInternalPings.events.Submit(EventsReasonCodes.background); } /// <summary> /// Collect and submit a ping for eventual upload. /// /// The ping content is assembled as soon as possible, but upload is not /// guaranteed to happen immediately, as that depends on the upload /// policies. /// /// If the ping currently contains no content, it will not be assembled and /// queued for sending. /// </summary> /// <param name="ping">Ping to submit.</param> /// <param name="reason">The reason the ping is being submitted.</param> internal void SubmitPing(PingTypeBase ping, string reason = null) { SubmitPingByName(ping.name, reason); } /// <summary> /// Collect and submit a ping for eventual upload by name. /// /// The ping will be looked up in the known instances of `PingType`. If the /// ping isn't known, an error is logged and the ping isn't queued for uploading. /// /// The ping content is assembled as soon as possible, but upload is not /// guaranteed to happen immediately, as that depends on the upload /// policies. /// /// If the ping currently contains no content, it will not be assembled and /// queued for sending, unless explicitly specified otherwise in the registry /// file. /// </summary> /// <param name="name">Name of the ping to submit.</param> /// <param name="reason">The reason the ping is being submitted.</param> internal void SubmitPingByName(string name, string reason = null) { Dispatchers.LaunchAPI(() => { SubmitPingByNameSync(name, reason); }); } /// <summary> /// Collect and submit a ping (by its name) for eventual upload, synchronously. /// /// The ping will be looked up in the known instances of `PingType`. If the /// ping isn't known, an error is logged and the ping isn't queued for uploading. /// /// The ping content is assembled as soon as possible, but upload is not /// guaranteed to happen immediately, as that depends on the upload /// policies. /// /// If the ping currently contains no content, it will not be assembled and /// queued for sending, unless explicitly specified otherwise in the registry /// file. /// </summary> /// <param name="name">Name of the ping to submit.</param> /// <param name="reason">The reason the ping is being submitted.</param> internal void SubmitPingByNameSync(string name, string reason = null) { if (!IsInitialized()) { Log.Error("Glean must be initialized before submitting pings."); return; } if (!GetUploadEnabled()) { Log.Error("Glean disabled: not submitting any pings."); return; } bool hasSubmittedPing = Convert.ToBoolean(LibGleanFFI.glean_submit_ping_by_name(name, reason)); if (hasSubmittedPing) { httpClient.TriggerUpload(configuration); } } /// <summary> /// Register a [PingType] in the registry associated with this [Glean] object. /// </summary> [MethodImpl(MethodImplOptions.Synchronized)] internal void RegisterPingType(PingTypeBase pingType) { if (IsInitialized()) { LibGleanFFI.glean_register_ping_type( pingType.handle ); } // We need to keep track of pings, so they get re-registered after a reset. // This state is kept across Glean resets, which should only ever happen in test mode. // Or by the instrumentation tests (`connectedAndroidTest`), which relaunches the application activity, // but not the whole process, meaning globals, such as the ping types, still exist from the old run. // It's a set and keeping them around forever should not have much of an impact. pingTypeQueue.Add(pingType); } /// <summary> /// TEST ONLY FUNCTION. /// Returns true if a ping by this name is in the ping registry. /// </summary> internal bool TestHasPingType(string pingName) { return LibGleanFFI.glean_test_has_ping_type(pingName) != 0; } } }
42.669078
128
0.578996
[ "MPL-2.0" ]
a-s-dev/glean
glean-core/csharp/Glean/Glean.cs
23,598
C#
using DocuSign.CodeExamples.Models; using Microsoft.AspNetCore.Mvc; using eSignature.Examples; namespace DocuSign.CodeExamples.Controllers { [Area("eSignature")] [Route("eg009")] public class Eg009UseTemplateController : EgController { public Eg009UseTemplateController(DSConfiguration config, IRequestItemsService requestItemsService) : base(config, requestItemsService) { } public override string EgName => "eg009"; [HttpPost] public IActionResult Create(string signerEmail, string signerName, string ccEmail, string ccName) { // Data for this method // signerEmail // signerName // ccEmail // ccName var accessToken = RequestItemsService.User.AccessToken; var basePath = RequestItemsService.Session.BasePath + "/restapi"; var accountId = RequestItemsService.Session.AccountId; var templateId = RequestItemsService.TemplateId; bool tokenOk = CheckToken(3); if (!tokenOk) { // We could store the parameters of the requested operation // so it could be restarted automatically. // But since it should be rare to have a token issue here, // we'll make the user re-enter the form data after // authentication. RequestItemsService.EgName = EgName; return Redirect("/ds/mustAuthenticate"); } // Call the Examples API method to create the envelope from template and send it string envelopeId = CreateEnvelopeFromTemplate.SendEnvelopeFromTemplate(signerEmail, signerName, ccEmail, ccName, accessToken, basePath, accountId, templateId); // Process results RequestItemsService.EnvelopeId = envelopeId; ViewBag.message = "The envelope has been created and sent!<br/>Envelope ID " + envelopeId + "."; return View("example_done"); } } }
39.396226
117
0.618774
[ "MIT" ]
BrenoRidolfi/poc_docuSign
launcher-csharp/eSignature/Controllers/Eg009UseTemplateController.cs
2,090
C#
namespace Manatee.Trello.Internal.Searching { internal class TextSearchParameter : ISearchParameter { public string Query { get; } public TextSearchParameter(string text) { Query = text; } } }
18.25
55
0.689498
[ "MIT" ]
Muhammad1Nouman/Manatee.Trello
Manatee.Trello/Internal/Searching/TextSearchParameter.cs
221
C#
using System.Text; using DN.WebApi.Application.Common.Constants; using DN.WebApi.Application.Common.Interfaces; using DN.WebApi.Application.Multitenancy; using DN.WebApi.Domain.Constants; using DN.WebApi.Infrastructure.Persistence.Contexts; using DN.WebApi.Shared.DTOs.Multitenancy; using Mapster; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; namespace DN.WebApi.Infrastructure.Multitenancy; public class TenantService : ITenantService { private readonly ISerializerService _serializer; private readonly ICacheService _cache; private readonly IStringLocalizer<TenantService> _localizer; private readonly DatabaseSettings _options; private readonly TenantManagementDbContext _context; private TenantDto? _currentTenant; public TenantService( IOptions<DatabaseSettings> options, IStringLocalizer<TenantService> localizer, TenantManagementDbContext context, ICacheService cache, ISerializerService serializer) { _localizer = localizer; _options = options.Value; _context = context; _cache = cache; _serializer = serializer; } public string? GetConnectionString() { return _currentTenant?.ConnectionString; } public string? GetDatabaseProvider() { return _options.DBProvider; } public TenantDto? GetCurrentTenant() { return _currentTenant; } public void SetCurrentTenant(string tenant) { if (_currentTenant != null) { throw new Exception("Method reserved for in-scope initialization"); } TenantDto? tenantDto = default; string cacheKey = CacheKeys.GetCacheKey("tenant", tenant); byte[]? cachedData = !string.IsNullOrWhiteSpace(cacheKey) ? _cache.Get(cacheKey) : null; if (cachedData != null) { _cache.Refresh(cacheKey); tenantDto = _serializer.Deserialize<TenantDto>(Encoding.Default.GetString(cachedData)); } else { var tenantInfo = _context.Tenants.Where(a => a.Key == tenant).FirstOrDefault(); if (tenantInfo is not null) { tenantDto = tenantInfo.Adapt<TenantDto>(); var options = new DistributedCacheEntryOptions(); byte[] serializedData = Encoding.Default.GetBytes(_serializer.Serialize(tenantDto)); _cache.Set(cacheKey, serializedData, options); } } if (tenantDto == null) { throw new InvalidTenantException(_localizer["tenant.invalid"]); } if (tenantDto.Key != MultitenancyConstants.Root.Key) { if (!tenantDto.IsActive) { throw new InvalidTenantException(_localizer["tenant.inactive"]); } if (DateTime.UtcNow > tenantDto.ValidUpto) { throw new InvalidTenantException(_localizer["tenant.expired"]); } } _currentTenant = tenantDto; if (string.IsNullOrEmpty(_currentTenant.ConnectionString)) { _currentTenant.ConnectionString = _options.ConnectionString; } } }
29.981818
100
0.648878
[ "MIT" ]
bbday/dotnet-webapi-boilerplate
src/Infrastructure/Multitenancy/TenantService.cs
3,298
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeEverywhere() { var fixAllActionId = CSharpFeaturesResources.UseExplicitType; var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestAsync(input, expected, options: ExplicitTypeEverywhere(), fixAllActionEquivalenceKey: fixAllActionId); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_PreferExplicitTypeEverywhere() { var fixAllActionId = CSharpFeaturesResources.UseExplicitType; var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInProject:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestAsync(input, expected, options: ExplicitTypeEverywhere(), fixAllActionEquivalenceKey: fixAllActionId); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_PreferExplicitTypeEverywhere() { var fixAllActionId = CSharpFeaturesResources.UseExplicitType; var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInSolution:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { var i3 = 0; var p3 = new Program2(); var tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestAsync(input, expected, options: ExplicitTypeEverywhere(), fixAllActionEquivalenceKey: fixAllActionId); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeExceptWhereApparent() { var fixAllActionId = CSharpFeaturesResources.UseExplicitType; var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} p = this; var i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { Program p = this; int i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestAsync(input, expected, options: ExplicitTypeExceptWhereApparent(), fixAllActionEquivalenceKey: fixAllActionId); } #endregion } }
22.360775
161
0.58484
[ "Apache-2.0" ]
OceanYan/roslyn
src/EditorFeatures/CSharpTest/Diagnostics/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.cs
9,237
C#
namespace SupermarketCheckout.WebAPI.Tests.V1.Models.Automapper { using AutoMapper; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using SupermarketCheckout.WebAPI.V1.Models.Automapper.Profiles; [TestFixture] public class AutomapperTests { [Test] public void AutoMapper_Configuration_IsValid() { ServiceCollection services = new ServiceCollection(); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.test.json") .Build(); Startup.ConfigureBusinessServices(services, config); var serviceProvider = services.BuildServiceProvider(); var mapper = serviceProvider.GetRequiredService<IMapper>(); Mapper.AssertConfigurationIsValid(); } } }
28.83871
71
0.665548
[ "MIT" ]
thorstenalpers/Kata_Supermarketcheckout
tests/SupermarketCheckout.WebAPI.Tests/V1/Models/Automapper/AutomapperTests.cs
896
C#
using RegistryPluginBase.Interfaces; namespace RegistryPlugin.MountedDevices { public class ValuesOut:IValueOut { public ValuesOut(string deviceName, string deviceData) { DeviceName = deviceName; DeviceData = deviceData; } public string DeviceName { get; } public string DeviceData { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Name: {DeviceName}"; public string BatchValueData2 => $"Data: {DeviceData})"; public string BatchValueData3 => string.Empty ; } }
29.954545
64
0.634294
[ "MIT" ]
sjosz/RegistryPlugins
RegistryExplorer.MountedDevices/ValuesOut.cs
661
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("SolrNet.Cloud.Unity")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("EPAM Systems")] [assembly: AssemblyProduct("SolrNet.Cloud.Unity")] [assembly: AssemblyCopyright("Copyright © EPAM Systems 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fecf5826-7036-4d36-8530-cdb227a22957")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.783784
84
0.747735
[ "Apache-2.0" ]
nicholaspei/SoleCloudNet
SolrNet.Cloud.Unity/Properties/AssemblyInfo.cs
1,438
C#
using ooohCar.Shared.Settings; using System.Threading.Tasks; namespace ooohCar.Shared.Managers { public interface IPreferenceManager { Task SetPreference(IPreference preference); Task<IPreference> GetPreference(); } }
19.153846
51
0.722892
[ "MIT" ]
codeBalok/ooohcarBlazor-backend
ooohCar.Shared/Managers/IPreferenceManager.cs
251
C#
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 12.20Release // Tag = $Name$ //////////////////////////////////////////////////////////////////////////////// #endregion namespace FitFilePreviewer.Decode.Fit.Types { /// <summary> /// Implements the profile LeftRightBalance type as a class /// </summary> public static class LeftRightBalance { public const byte Mask = 0x7F; // % contribution public const byte Right = 0x80; // data corresponds to right if set, otherwise unknown public const byte Invalid = (byte)0xFF; } }
40.058824
92
0.596916
[ "Apache-2.0" ]
linal/FitFilePreviewer
FitFilePreviewer.Decode/Fit/Types/LeftRightBalance.cs
1,362
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; namespace Roslyn.Hosting.Diagnostics.PerfMargin { /// <summary> /// Interaction logic for StatusIndicator.xaml /// </summary> public partial class StatusIndicator : UserControl { private readonly ActivityLevel _activityLevel; private bool _changedSinceLastUpdate; internal StatusIndicator(ActivityLevel activityLevel) { InitializeComponent(); _activityLevel = activityLevel; _changedSinceLastUpdate = activityLevel.IsActive; } // Don't use WPF one way binding since it allocates too much memory for this high-frequency event internal void Subscribe() { _activityLevel.IsActiveChanged += this.ActivityLevel_IsActiveChanged; } internal void Unsubscribe() { _activityLevel.IsActiveChanged -= this.ActivityLevel_IsActiveChanged; } private void ActivityLevel_IsActiveChanged(object sender, EventArgs e) { _changedSinceLastUpdate = true; } private const double MinimumScale = 0.2; private static readonly DoubleAnimation s_growAnimation = new DoubleAnimation(1.0, new Duration(TimeSpan.FromSeconds(1.0)), FillBehavior.HoldEnd); private static readonly DoubleAnimation s_shrinkAnimation = new DoubleAnimation(0.0, new Duration(TimeSpan.FromSeconds(0.33333)), FillBehavior.HoldEnd); public void UpdateOnUIThread() { if (!_changedSinceLastUpdate) { return; } _changedSinceLastUpdate = false; // Remove existing animation this.clipScale.BeginAnimation(ScaleTransform.ScaleXProperty, null); // For very short durations, the growth animation hasn't even begun yet, so make // sure something is visible. this.clipScale.ScaleX = Math.Max(this.clipScale.ScaleX, MinimumScale); DoubleAnimation anim = _activityLevel.IsActive ? s_growAnimation : s_shrinkAnimation; this.clipScale.BeginAnimation(ScaleTransform.ScaleXProperty, anim, HandoffBehavior.SnapshotAndReplace); } } }
36.426471
160
0.677029
[ "Apache-2.0" ]
0x53A/roslyn
src/Test/Diagnostics/PerfMargin/StatusIndicator.xaml.cs
2,477
C#
using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Response { /// <summary> /// AlipayMarketingCardBenefitModifyResponse. /// </summary> public class AlipayMarketingCardBenefitModifyResponse : AopResponse { /// <summary> /// 权益修改结果;true成功:false失败 /// </summary> [XmlElement("result")] public bool Result { get; set; } } }
23.352941
71
0.622166
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Response/AlipayMarketingCardBenefitModifyResponse.cs
421
C#
using System; using System.Collections.Generic; using System.Linq; using System.Collections; namespace UnEngine { /// <summary> /// provides a dictionary where the key is an integer, but provides array-time lookups /// TODO: implement a trimming function /// TODO: implemnt ICollections interface /// </summary> /// <remarks> /// Benefits: access speed is identical to an array /// Downsides: /// collection takes up more memory than a dictionary of the same size of objects /// Of note: as this takes up as much memory as the last index + bool array the same size, this should probably be used for small collections. /// </remarks> /// <typeparam name="T"></typeparam> public class IntDictionary<T> : IEnumerable { readonly List<T> _collection; readonly List<bool> _hasValueCollection; /// <summary> /// /// </summary> /// <param name="collectionSize">initial size of the internal collection</param> public IntDictionary(int collectionSize = 32) { _collection = new List<T>(collectionSize); _hasValueCollection = new List<bool>(collectionSize); } /// <summary> /// returns the values stored in the dictionary. keys where there is no value will be return as default(T) /// </summary> /// <returns></returns> public T[] Values { get { return _collection.ToArray(); } } /// <summary> /// get an array for the size of the internal array, that says if a value is contained for that key /// </summary> public bool[] HasValues { get { return _hasValueCollection.ToArray(); } } //not using stack because of need to remove from somewhere in the middle readonly List<int> _keyReuse = new List<int>(); /// <summary> /// adds the object to the collection, and returns the key that was assigned to the object /// </summary> /// <param name="add"></param> /// <returns></returns> public int Add(T add) { var index = -1; if (_keyReuse.Count > 0) { //pop index = _keyReuse[_keyReuse.Count - 1]; _keyReuse.RemoveAt(_keyReuse.Count - 1); } if (index != -1) { _collection[index] = add; _hasValueCollection[index] = true; return index; } _collection.Add(add); _hasValueCollection.Add(true); return _collection.Count - 1; } /// <summary> /// remove the item at the specified key /// </summary> /// <param name="key"></param> public void Remove(int key) { if (key < _collection.Count) { _collection[key] = default(T); var hadValue = _hasValueCollection[key]; if (hadValue) { //push _keyReuse.Add(key); } _hasValueCollection[key] = false; } } /// <summary> /// clear out all keys/values /// </summary> public void Clear() { _collection.Clear(); _hasValueCollection.Clear(); _keyReuse.Clear(); } /// <summary> /// NOT RECOMMENDED. /// This will overwrite the previous value if the key already exists. /// </summary> /// <param name="key"></param> /// <param name="add"></param> public void Add(int key, T add) { if (_collection.Count <= key) { //collections not big enough. need to resize. var range = key - _collection.Count + 1; _collection.AddRange(Enumerable.Repeat<T>(default(T), range)); _hasValueCollection.AddRange(Enumerable.Repeat<bool>(false, range)); _collection[key] = add; _hasValueCollection[key] = true; } else { if (_keyReuse.Contains(key)) _keyReuse.Remove(key); _collection[key] = add; _hasValueCollection[key] = true; } } /// <summary> /// does a value exist for the specified key /// </summary> /// <param name="key"></param> /// <returns></returns> public bool HasValue(int key) { if (key < _collection.Count) { return _hasValueCollection[key]; } return false; } /// <summary> /// Try to get the value associated with the key /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool TryGetValue(int key, out T value) { if (key < _collection.Count) { value = _collection[key]; return _hasValueCollection[key]; } value = default(T); return false; } /// <summary> /// size of the collection array. can be used as upper bound for enumeration /// </summary> public int Capacity { get { return _collection.Count; } } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } /// <summary> /// get the enumerator to enumerate the collection /// </summary> /// <returns></returns> public IntDictionaryEnumerator<T> GetEnumerator() { return new IntDictionaryEnumerator<T>(_collection); } // Defines the enumerator for the Boxes collection. // (Some prefer this class nested in the collection class.) /// <summary> /// enumerator helper /// </summary> /// <typeparam name="U"></typeparam> public class IntDictionaryEnumerator<U> : IEnumerator<U> { private U currentT; private int curIndex; private List<U> m_Collection; /// <summary> /// create a new enumerator helper for the intdictionary /// </summary> /// <param name="m_Collection"></param> public IntDictionaryEnumerator(List<U> m_Collection) { // TODO: Complete member initialization this.m_Collection = m_Collection; curIndex = -1; currentT = default(U); } /// <summary> /// go to the next iem in the collection /// </summary> /// <returns></returns> public bool MoveNext() { //Avoids going beyond the end of the collection. if (++curIndex >= m_Collection.Count) { return false; } else { // Set current box to next item in collection. currentT = m_Collection[curIndex]; } return true; } /// <summary> /// reset the position of the enumerator /// </summary> public void Reset() { curIndex = -1; } void IDisposable.Dispose() { } /// <summary> /// current item in the enumeration /// </summary> public U Current { get { return currentT; } } object IEnumerator.Current { get { return Current; } } } } }
30.448669
146
0.488761
[ "MIT" ]
Phantasm-Studios/unity.dll
src/UnEngine/Engine/IntDictionary.cs
8,010
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace FibonacciUnitTests { [TestClass] public class FibonacciUnitTest { static List<int> FibonacciSequenceExpected = new List<int>() { 0,1,1,2,3,5,8,13,21,34,55,89,144 }; [TestMethod] public void Compute0And1() { Assert.AreEqual(0, Fibonacci.Compute(0)); Assert.AreEqual(1, Fibonacci.Compute(1)); } [TestMethod] public void ComputeFirst12Numbers() { for(var i = 0; i < FibonacciSequenceExpected.Count; i++) { Assert.AreEqual(FibonacciSequenceExpected[i], Fibonacci.Compute(i)); } } [TestMethod] public void ComputeFirst12Numbers_DynamicProgramming() { Fibonacci.PreComputeCache(FibonacciSequenceExpected.Count); for (var i = 0; i < FibonacciSequenceExpected.Count; i++) { Assert.AreEqual(FibonacciSequenceExpected[i], Fibonacci.Compute(i)); } } } }
26.97619
84
0.575463
[ "MIT" ]
fredericaltorres/FibonacciMemoizationDynamicProgramming
FibonacciUnitTests/FibonacciUnitTests.cs
1,133
C#
using System.ComponentModel.Composition; using System.Windows.Controls; namespace Plainion.RI.Editors { [Export] public partial class XmlEditorView : UserControl { [ImportingConstructor] internal XmlEditorView(XmlEditorViewModel viewModel) { InitializeComponent(); DataContext = viewModel; } } }
21.555556
61
0.626289
[ "BSD-3-Clause" ]
ronin4net/Plainion.Windows.Editors
src/Plainion.RI/Editors/XmlEditorView.xaml.cs
390
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.PowerFx.Core.Types; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Public.Types { /// <summary> /// Base class for type of a Formula. /// Formula Types are a class hiearchy. /// </summary> [DebuggerDisplay("{_type}")] public abstract class FormulaType { // protected isn't enough to let derived classes access this. internal readonly DType _type; public static FormulaType Blank { get; } = new BlankType(); // Well-known types public static FormulaType Boolean { get; } = new BooleanType(); public static FormulaType Number { get; } = new NumberType(); public static FormulaType String { get; } = new StringType(); public static FormulaType Time { get; } = new TimeType(); public static FormulaType Date { get; } = new DateType(); public static FormulaType DateTime { get; } = new DateTimeType(); public static FormulaType DateTimeNoTimeZone { get; } = new DateTimeNoTimeZoneType(); public static FormulaType UntypedObject { get; } = new UntypedObjectType(); public static FormulaType Hyperlink { get; } = new HyperlinkType(); /// <summary> /// Internal use only to represent an arbitrary (un-backed) option set value. /// Should be removed if possible. /// </summary> internal static FormulaType OptionSetValue { get; } = new OptionSetValueType(); // chained by derived type internal FormulaType(DType type) { _type = type; } // Get the correct derived type internal static FormulaType Build(DType type) { switch (type.Kind) { case DKind.ObjNull: return Blank; case DKind.Record: return new RecordType(type); case DKind.Table: return new TableType(type); case DKind.Number: return Number; case DKind.String: return String; case DKind.Boolean: return Boolean; case DKind.Currency: return Number; // TODO: validate case DKind.Hyperlink: return Hyperlink; case DKind.Time: return Time; case DKind.Date: return Date; case DKind.DateTime: return DateTime; case DKind.DateTimeNoTimeZone: return DateTimeNoTimeZone; case DKind.OptionSetValue: var isBoolean = type.OptionSetInfo?.IsBooleanValued; return isBoolean.HasValue && isBoolean.Value ? Boolean : OptionSetValue; // This isn't quite right, but once we're in the IR, an option set acts more like a record with optionsetvalue fields. case DKind.OptionSet: return new RecordType(DType.CreateRecord(type.GetAllNames(DPath.Root))); case DKind.UntypedObject: return UntypedObject; default: throw new NotImplementedException($"Not implemented type: {type}"); } } #region Equality // Aggregate Types (records, tables) can be complex. // Override op= like system.type does. public static bool operator ==(FormulaType a, FormulaType b) { // Use object.ReferenceEquals to avoid recursion. if (ReferenceEquals(a, null)) { return ReferenceEquals(b, null); } return a.Equals(b); } public static bool operator !=(FormulaType a, FormulaType b) => !(a == b); public override bool Equals(object other) { if (other is FormulaType t) { return _type.Equals(t._type); } return false; } public override int GetHashCode() { return _type.GetHashCode(); } #endregion // Equality public abstract void Visit(ITypeVistor vistor); } }
32.72093
135
0.584696
[ "MIT" ]
Grant-Archibald-MS/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Public/Types/FormulaType.cs
4,223
C#
using EasyEventSourcing.EventSourcing.Handlers; using EasyEventSourcing.Messages; namespace EasyEventSourcing.Application { public class CommandDispatcher : ICommandDispatcher { private readonly ICommandHandlerFactory factory; public CommandDispatcher(ICommandHandlerFactory factory) { this.factory = factory; } public void Send<TCommand>(TCommand command) where TCommand : ICommand { var handler = this.factory.Resolve<TCommand>(); handler.Handle(command); } } }
28.5
78
0.673684
[ "MIT" ]
SneakyPeet/EasyEventSourcing
src/EasyEventSourcing.Application/CommandDispatcher.cs
572
C#
/* * MundiAPI.Standard * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ using System; using MundiAPI.Standard.Controllers; using MundiAPI.Standard.Http.Client; using MundiAPI.Standard.Utilities; namespace MundiAPI.Standard { public partial class MundiAPIClient: IMundiAPIClient { /// <summary> /// Singleton access to Customers controller /// </summary> public ICustomersController Customers { get { return CustomersController.Instance; } } /// <summary> /// Singleton access to Charges controller /// </summary> public IChargesController Charges { get { return ChargesController.Instance; } } /// <summary> /// Singleton access to Recipients controller /// </summary> public IRecipientsController Recipients { get { return RecipientsController.Instance; } } /// <summary> /// Singleton access to Subscriptions controller /// </summary> public ISubscriptionsController Subscriptions { get { return SubscriptionsController.Instance; } } /// <summary> /// Singleton access to Invoices controller /// </summary> public IInvoicesController Invoices { get { return InvoicesController.Instance; } } /// <summary> /// Singleton access to Orders controller /// </summary> public IOrdersController Orders { get { return OrdersController.Instance; } } /// <summary> /// Singleton access to Sellers controller /// </summary> public ISellersController Sellers { get { return SellersController.Instance; } } /// <summary> /// Singleton access to Tokens controller /// </summary> public ITokensController Tokens { get { return TokensController.Instance; } } /// <summary> /// Singleton access to Plans controller /// </summary> public IPlansController Plans { get { return PlansController.Instance; } } /// <summary> /// Singleton access to Transactions controller /// </summary> public ITransactionsController Transactions { get { return TransactionsController.Instance; } } /// <summary> /// Singleton access to Transfers controller /// </summary> public ITransfersController Transfers { get { return TransfersController.Instance; } } /// <summary> /// The shared http client to use for all API calls /// </summary> public IHttpClient SharedHttpClient { get { return BaseController.ClientInstance; } set { BaseController.ClientInstance = value; } } #region Constructors /// <summary> /// Default constructor /// </summary> public MundiAPIClient() { } /// <summary> /// Client initialization constructor /// </summary> public MundiAPIClient(string basicAuthUserName, string basicAuthPassword) { Configuration.BasicAuthUserName = basicAuthUserName; Configuration.BasicAuthPassword = basicAuthPassword; } #endregion } }
24.403614
82
0.493212
[ "MIT" ]
mundipagg/MundiAPI-NetStandard
MundiAPI.Standard/MundiAPIClient.cs
4,051
C#
using Paillave.Etl.Core.Aggregation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Paillave.Etl.Core.Aggregation.AggregationInstances { public class FirstAggregationInstance : IAggregationInstance { private object _first = null; private bool _hasValue = false; public void Aggregate(object value) { if (!_hasValue) { _first = value; _hasValue = true; } } public object GetResult() { return _first; } } }
22.928571
64
0.595016
[ "MIT" ]
fossabot/Etl.Net
src/Paillave.Etl/Core/Aggregation/AggregationInstances/FirstAggregationInstance.cs
644
C#
using System; using System.Linq.Expressions; namespace RattrapDev.DDD.Block.Specification { public class AndNotSpecification<T> : CompositeSpecification<T> { private readonly ILinqSpecification<T> left; private readonly ILinqSpecification<T> right; public AndNotSpecification(ILinqSpecification<T> left, ILinqSpecification<T> right) { this.right = right; this.left = left; } public override Expression<Func<T, bool>> AsExpression() { return ((s) => left.IsSatisfiedBy(s) && !right.IsSatisfiedBy(s)); } } }
22.416667
85
0.734201
[ "MIT" ]
rattrapdev-public/Domain-Block-.net
RattrapDev.DDD.Block/Specification/AndNotSpecification.cs
538
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.Net; using System.Net.Sockets; namespace Microsoft.Unity.VisualStudio.Editor.Messaging { internal class Messager : IDisposable { public event EventHandler<MessageEventArgs> ReceiveMessage; public event EventHandler<ExceptionEventArgs> MessagerException; private readonly UdpSocket _socket; private readonly object _disposeLock = new object(); private bool _disposed; protected Messager(int port) { _socket = new UdpSocket(); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _socket.Bind(IPAddress.Any, port); BeginReceiveMessage(); } private void BeginReceiveMessage() { var buffer = new byte[UdpSocket.BufferSize]; var any = UdpSocket.Any(); try { lock (_disposeLock) { if (_disposed) return; _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref any, ReceiveMessageCallback, buffer); } } catch (SocketException se) { MessagerException?.Invoke(this, new ExceptionEventArgs(se)); BeginReceiveMessage(); } catch (ObjectDisposedException) { } } private void ReceiveMessageCallback(IAsyncResult result) { try { var endPoint = UdpSocket.Any(); lock (_disposeLock) { if (_disposed) return; _socket.EndReceiveFrom(result, ref endPoint); } var message = DeserializeMessage(UdpSocket.BufferFor(result)); if (message != null) { message.Origin = (IPEndPoint)endPoint; ReceiveMessage?.Invoke(this, new MessageEventArgs(message)); } } catch (ObjectDisposedException) { return; } catch (Exception e) { RaiseMessagerException(e); } BeginReceiveMessage(); } private void RaiseMessagerException(Exception e) { MessagerException?.Invoke(this, new ExceptionEventArgs(e)); } private static Message MessageFor(MessageType type, string value) { return new Message { Type = type, Value = value }; } public void SendMessage(IPEndPoint target, MessageType type, string value = "") { var message = MessageFor(type, value); var buffer = SerializeMessage(message); try { lock (_disposeLock) { if (_disposed) return; _socket.BeginSendTo(buffer, 0, Math.Min(buffer.Length, UdpSocket.BufferSize), SocketFlags.None, target, SendMessageCallback, null); } } catch (SocketException se) { MessagerException?.Invoke(this, new ExceptionEventArgs(se)); } } private void SendMessageCallback(IAsyncResult result) { try { lock (_disposeLock) { if (_disposed) return; _socket.EndSendTo(result); } } catch (SocketException se) { MessagerException?.Invoke(this, new ExceptionEventArgs(se)); } catch (ObjectDisposedException) { } } private static byte[] SerializeMessage(Message message) { var serializer = new Serializer(); serializer.WriteInt32((int)message.Type); serializer.WriteString(message.Value); return serializer.Buffer(); } private static Message DeserializeMessage(byte[] buffer) { if (buffer.Length < 4) return null; var deserializer = new Deserializer(buffer); var type = (MessageType)deserializer.ReadInt32(); var value = deserializer.ReadString(); return new Message { Type = type, Value = value }; } public static Messager BindTo(int port) { return new Messager(port); } public void Dispose() { lock (_disposeLock) { _disposed = true; _socket.Close(); } } } }
22.740113
136
0.654161
[ "MIT" ]
ASE-Blast/unity3dgames
Space Game/Library/PackageCache/com.unity.ide.visualstudio@2.0.0/Editor/Messaging/Messenger.cs
4,027
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TranscriptSegmentDeserializationTests.cs" company="CodeBlueDev"> // All rights reserved. // </copyright> // <summary> // Tests deserialization of PluralSight Transcript Segment objects. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace CodeBlueDev.PluralSight.Core.Models.Test { using Newtonsoft.Json; using NUnit.Framework; /// <summary> /// Tests deserialization of PluralSight Transcript Segment objects. /// </summary> [TestFixture] public class TranscriptSegmentDeserializationTests { /// <summary> /// Tests if a Transcript Segment JSON block can be deserialized to a Transcript Segment model. /// </summary> [Test, Category("Transcript Segment")] public void TranscriptSegmentJsonShouldDeserializeIntoTranscriptSegmentModel() { // Arrange const string Json = @" { ""text"": ""Hi, my name's Mark Heath"", ""displayTime"": 2.0 }"; // Act TranscriptModuleClipSegment transcriptSegment = JsonConvert.DeserializeObject<TranscriptModuleClipSegment>(Json); // Assert Assert.IsNotNull(transcriptSegment); Assert.AreEqual("Hi, my name's Mark Heath", transcriptSegment.Text); Assert.AreEqual(2.0, transcriptSegment.DisplayTime); } /// <summary> /// Tests if a Transcript Segment JSON block with multiple Transcript Segments can be deserialized to multiple Transcript Segment models. /// </summary> [Test, Category("Transcript Segment")] public void TranscriptSegmentJsonWithMultipleTranscriptSegmentsShouldDeserializeIntoMultipleTranscriptSegmentModels() { // Arrange const string Json = @" [ { ""text"": ""Hi, my name's Mark Heath"", ""displayTime"": 2.0 }, { ""text"": ""and welcome to this Pluralsight course"", ""displayTime"": 4.0 } ]"; // Act TranscriptModuleClipSegment[] transcriptSegments = JsonConvert.DeserializeObject<TranscriptModuleClipSegment[]>(Json); // Assert Assert.IsNotNull(transcriptSegments); Assert.AreEqual(2, transcriptSegments.Length); } } }
36.506849
145
0.537711
[ "MIT" ]
CodeBlueDev/CodeBlueDev.PluralSight.Core.Models
Source/CodeBlueDev.PluralSight.Core.Models.Test/TranscriptSegmentDeserializationTests.cs
2,667
C#
using System.Threading.Tasks; using Ducode.Wolk.Application.Exceptions; using Ducode.Wolk.Application.Interfaces; using Ducode.Wolk.Application.Interfaces.Identity; using Ducode.Wolk.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace Ducode.Wolk.Identity.Impl { public class TokenRenewalManager : ITokenRenewalManager { private readonly IJwtManager _jwtManager; private readonly IWolkDbContext _wolkDbContext; public TokenRenewalManager(IJwtManager jwtManager, IWolkDbContext wolkDbContext) { _jwtManager = jwtManager; _wolkDbContext = wolkDbContext; } public async Task<string> RenewTokenAsync(long userId) { var user = await _wolkDbContext.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) { throw new NotFoundException(nameof(User), userId); } return _jwtManager.CreateJwt(user); } } }
31.212121
92
0.652427
[ "MIT" ]
dukeofharen/wolk
src/Ducode.Wolk.Identity/Impl/TokenRenewalManager.cs
1,030
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SOFTTEK.SCMS.Entity.Shared { public class ApiError { /// <summary> /// Message to the user. /// </summary> public string Message { get; set; } /// <summary> /// Localized Description /// </summary> public string Description { get; set; } /// <summary> /// Localized reason for the failure. /// </summary> public string Reason { get; set; } /// <summary> /// Contact Url to get support for the error. /// </summary> public string SupportUrl { get; set; } /// <summary> /// Error code. /// </summary> public int Code { get; set; } } }
25.242424
53
0.536615
[ "MIT" ]
ingscarrero/dotNet
SOFTTEK/softtek.scms.net/SOFTTEK.SCMS.Entity/Shared/ApiError.cs
835
C#
using System.Linq; using AutoMapper; using DatingApp.API.Dtos; using DatingApp.API.Models; namespace DatingApp.API.Helpers { public class AutoMapperProfiles : Profile { public AutoMapperProfiles() { CreateMap<User, UserForListDto>() .ForMember(opt => opt.PhotoUrl, opt => opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge())); CreateMap<User, UserForDetailedDto>() .ForMember(opt => opt.PhotoUrl, opt => opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge())); CreateMap<Photo, PhotosForDetailedDto>(); CreateMap<UserForUpdateDto, User>(); CreateMap<PhotoForCreationDto, Photo>(); CreateMap<Photo, PhotoForReturnDto>(); CreateMap<UserForRegisterDto, User>(); CreateMap<MessageForCreationDto, Message>().ReverseMap(); CreateMap<Message, MessageToReturnDto>() .ForMember(opt => opt.SenderPhotoUrl, opt => opt.MapFrom(src => src.Sender.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(opt => opt.RecipientPhotoUrl, opt => opt.MapFrom(src => src.Recipient.Photos.FirstOrDefault(p => p.IsMain).Url)); } } }
38.097561
96
0.579385
[ "MIT" ]
pavanbadempet/Dating-App
DatingApp.API/Helpers/AutoMapperProfiles.cs
1,562
C#
using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using System; namespace Microsoft.Maui.Graphics.SharpDX { public class DXCanvasState : CanvasState { private readonly DXCanvasState _parentState; private readonly RenderTarget _renderTarget; private float _alpha = 1; private float[] _dashes; private Brush _fillBrush; private bool _fillBrushValid; private SolidColorBrush _fontBrush; private bool _fontBrushValid; private float _fontSize; private Vector2 _gradientPoint1; private Vector2 _gradientPoint2; private GradientStopCollection _gradientStopCollection; private RectangleGeometry _layerBounds; private RectangleGeometry _layerClipBounds; private PathGeometry _layerMask; private bool _needsStrokeStyle; private float _scale; private Color4 _shadowColor; private bool _shadowColorValid; private Color _sourceFillColor; private Paint _sourceFillpaint; private Color _sourceFontColor; private Color _sourceShadowColor; private Color _sourceStrokeColor; private SolidColorBrush _strokeBrush; private bool _strokeBrushValid; private StrokeStyle _strokeStyle; private StrokeStyleProperties _strokeStyleProperties; private int _layerCount; private readonly float _dpi; public DXCanvasState(float dpi, RenderTarget renderTarget) { _dpi = dpi; _renderTarget = renderTarget; _parentState = null; SetToDefaults(); } public DXCanvasState(DXCanvasState prototype) : base(prototype) { _dpi = prototype.Dpi; _parentState = prototype; _renderTarget = prototype._renderTarget; _strokeBrush = prototype._strokeBrush; _fillBrush = prototype._fillBrush; _fontBrush = prototype._fontBrush; _shadowColor = prototype._shadowColor; _sourceStrokeColor = prototype._sourceStrokeColor; _sourceFillpaint = prototype._sourceFillpaint; _sourceFillColor = prototype._sourceFillColor; _sourceFontColor = prototype._sourceFontColor; _sourceShadowColor = prototype._sourceShadowColor; _strokeBrushValid = prototype._strokeBrushValid; _fillBrushValid = prototype._fillBrushValid; _fontBrushValid = prototype._fontBrushValid; _shadowColorValid = prototype._shadowColorValid; _dashes = prototype._dashes; _strokeStyle = prototype._strokeStyle; _strokeStyleProperties = prototype._strokeStyleProperties; _needsStrokeStyle = prototype._needsStrokeStyle; IsShadowed = prototype.IsShadowed; ShadowOffset = prototype.ShadowOffset; ShadowBlur = prototype.ShadowBlur; Matrix = new Matrix3x2(prototype.Matrix.ToArray()); FontName = prototype.FontName; FontSize = prototype.FontSize; FontWeight = prototype.FontWeight; FontStyle = prototype.FontStyle; _alpha = prototype._alpha; _scale = prototype._scale; IsBlurred = prototype.IsBlurred; BlurRadius = prototype.BlurRadius; } public float Dpi => _dpi; public float ActualScale => _scale; public float ActualShadowBlur => ShadowBlur * Math.Abs(_scale); public Vector2 ShadowOffset { get; set; } public float ShadowBlur { get; set; } public Matrix3x2 Matrix { get; private set; } public String FontName { get; set; } public FontWeight FontWeight { get; set; } public FontStyle FontStyle { get; set; } private RenderingParams TextRenderingParams { get; set; } private DrawingStateBlock DrawingStateBlock { get; set; } public float FontSize { get => _fontSize; set => _fontSize = value; } public StrokeStyle StrokeStyle { get { if (_needsStrokeStyle) { if (_strokeStyle == null) { _strokeStyle = _dashes != null ? new StrokeStyle(_renderTarget.Factory, _strokeStyleProperties, _dashes) : new StrokeStyle(_renderTarget.Factory, _strokeStyleProperties); } return _strokeStyle; } return _strokeStyle; } } public float MiterLimit { set { _strokeStyleProperties.MiterLimit = value; InvalidateStrokeStyle(); _needsStrokeStyle = true; } } public Color StrokeColor { set { Color vValue = value ?? Colors.Black; if (!vValue.Equals(_sourceStrokeColor)) { _sourceStrokeColor = vValue; _strokeBrushValid = false; } } } public LineCap StrokeLineCap { set { switch (value) { case LineCap.Butt: _strokeStyleProperties.EndCap = CapStyle.Flat; _strokeStyleProperties.StartCap = CapStyle.Flat; break; case LineCap.Round: _strokeStyleProperties.EndCap = CapStyle.Round; _strokeStyleProperties.StartCap = CapStyle.Round; break; default: _strokeStyleProperties.EndCap = CapStyle.Square; _strokeStyleProperties.StartCap = CapStyle.Square; break; } InvalidateStrokeStyle(); _needsStrokeStyle = true; } } public LineJoin StrokeLineJoin { set { switch (value) { case LineJoin.Bevel: _strokeStyleProperties.LineJoin = global::SharpDX.Direct2D1.LineJoin.Bevel; break; case LineJoin.Round: _strokeStyleProperties.LineJoin = global::SharpDX.Direct2D1.LineJoin.Round; break; default: _strokeStyleProperties.LineJoin = global::SharpDX.Direct2D1.LineJoin.Miter; break; } InvalidateStrokeStyle(); _needsStrokeStyle = true; } } public Color FillColor { set { ReleaseFillBrush(); _fillBrushValid = false; _sourceFillColor = value; _sourceFillpaint = null; } } public float BlurRadius { get; private set; } public bool IsShadowed { get; set; } public bool IsBlurred { get; private set; } public Color FontColor { get => _sourceFontColor ?? Colors.Black; set { Color vValue = value ?? Colors.Black; if (!vValue.Equals(_sourceFontColor)) { _sourceFontColor = vValue; _fontBrushValid = false; } } } public float Alpha { get => _alpha; set { if (_alpha != value) { _alpha = value; InvalidateBrushes(); } } } public SolidColorBrush DxStrokeBrush { get { if (_strokeBrush == null || (!_strokeBrushValid && _parentState != null && _strokeBrush == _parentState._strokeBrush)) { _strokeBrush = new SolidColorBrush(_renderTarget, _sourceStrokeColor.AsDxColor(_alpha)); _strokeBrushValid = true; } else if (!_strokeBrushValid) { _strokeBrush.Color = _sourceStrokeColor.AsDxColor(_alpha); _strokeBrushValid = true; } return _strokeBrush; } } public Brush DxFillBrush { get { if (_fillBrush == null || !_fillBrushValid) { if (_sourceFillColor != null) { _fillBrush = new SolidColorBrush(_renderTarget, _sourceFillColor.AsDxColor(_alpha)); _fillBrushValid = true; } else if (_sourceFillpaint != null) { if (_sourceFillpaint.PaintType == PaintType.LinearGradient) { var linearGradientProperties = new LinearGradientBrushProperties(); var gradientStops = new global::SharpDX.Direct2D1.GradientStop[_sourceFillpaint.Stops.Length]; for (int i = 0; i < _sourceFillpaint.Stops.Length; i++) { gradientStops[i] = new global::SharpDX.Direct2D1.GradientStop { Position = _sourceFillpaint.Stops[i].Offset, Color = _sourceFillpaint.Stops[i].Color.AsDxColor(_alpha) }; } _gradientStopCollection = new GradientStopCollection(_renderTarget, gradientStops, ExtendMode.Clamp); _fillBrush = new LinearGradientBrush(_renderTarget, linearGradientProperties, _gradientStopCollection); ((LinearGradientBrush) _fillBrush).StartPoint = _gradientPoint1; ((LinearGradientBrush) _fillBrush).EndPoint = _gradientPoint2; } else { float radius = Geometry.GetDistance(_gradientPoint1.X, _gradientPoint1.Y, _gradientPoint2.X, _gradientPoint2.Y); var radialGradientBrushProperties = new RadialGradientBrushProperties(); var gradientStops = new global::SharpDX.Direct2D1.GradientStop[_sourceFillpaint.Stops.Length]; for (int i = 0; i < _sourceFillpaint.Stops.Length; i++) { gradientStops[i] = new global::SharpDX.Direct2D1.GradientStop { Position = _sourceFillpaint.Stops[i].Offset, Color = _sourceFillpaint.Stops[i].Color.AsDxColor(_alpha) }; } _gradientStopCollection = new GradientStopCollection(_renderTarget, gradientStops, ExtendMode.Clamp); _fillBrush = new RadialGradientBrush(_renderTarget, radialGradientBrushProperties, _gradientStopCollection); ((RadialGradientBrush) _fillBrush).Center = _gradientPoint1; ((RadialGradientBrush) _fillBrush).RadiusX = radius; ((RadialGradientBrush) _fillBrush).RadiusY = radius; } _fillBrushValid = true; } else { _fillBrush = new SolidColorBrush(_renderTarget, global::SharpDX.Color.White); _fillBrushValid = true; } } return _fillBrush; } } public Color4 ShadowColor { get { if (!_shadowColorValid) { _shadowColor = _sourceShadowColor?.AsDxColor(_alpha) ?? CanvasDefaults.DefaultShadowColor.AsDxColor(_alpha); } return _shadowColor; } } public SolidColorBrush FontBrush { get { if (_fontBrush == null || (!_fontBrushValid && _parentState != null && _fontBrush == _parentState._fontBrush)) { _fontBrush = new SolidColorBrush(_renderTarget, _sourceFontColor.AsDxColor(_alpha)); } else if (!_fontBrushValid) { _fontBrush.Color = _sourceFontColor.AsDxColor(_alpha); } return _fontBrush; } } public override void Dispose() { CloseResources(); if (TextRenderingParams != null) { TextRenderingParams.Dispose(); TextRenderingParams = null; } if (DrawingStateBlock != null) { DrawingStateBlock.Dispose(); DrawingStateBlock = null; } if (_strokeBrush != null && (_parentState == null || _strokeBrush != _parentState._strokeBrush)) { _strokeBrush.Dispose(); _strokeBrush = null; } if (_fontBrush != null && (_parentState == null || _fontBrush != _parentState._fontBrush)) { _fontBrush.Dispose(); _fontBrush = null; } if (_strokeStyle != null && (_parentState == null || _strokeStyle != _parentState._strokeStyle)) { _strokeStyle.Dispose(); _strokeStyle = null; } if (_fillBrush != null && (_parentState == null || _fillBrush != _parentState._fillBrush)) { _fillBrush.Dispose(); _fillBrush = null; } if (_gradientStopCollection != null) { _gradientStopCollection.Dispose(); _gradientStopCollection = null; } base.Dispose(); } public void SaveRenderTargetState() { /* DrawingStateDescription = new DrawingStateDescription(); TextRenderingParams = new RenderingParams(DXGraphicsService.FactoryDirectWrite); DrawingStateBlock = new DrawingStateBlock(renderTarget.Factory, DrawingStateDescription, TextRenderingParams); renderTarget.SaveDrawingState(DrawingStateBlock);*/ } public void CloseResources() { if (_layerMask != null) { _renderTarget.PopLayer(); _layerMask.Dispose(); _layerMask = null; } if (_layerBounds != null) { _layerBounds.Dispose(); _layerBounds = null; } if (_layerClipBounds != null) { _layerClipBounds.Dispose(); _layerClipBounds = null; } } public void RestoreRenderTargetState() { /*if (DrawingStateBlock != null) { renderTarget.RestoreDrawingState(DrawingStateBlock); DrawingStateBlock.Dispose(); DrawingStateBlock = null; TextRenderingParams.Dispose(); TextRenderingParams = null; }*/ _renderTarget.Transform = Matrix; } public void SetToDefaults() { _sourceStrokeColor = Colors.Black; _strokeBrushValid = false; _needsStrokeStyle = false; _strokeStyle = null; _strokeStyleProperties.DashCap = CapStyle.Flat; _strokeStyleProperties.DashOffset = 0; _strokeStyleProperties.DashStyle = DashStyle.Solid; _strokeStyleProperties.EndCap = CapStyle.Flat; _strokeStyleProperties.LineJoin = global::SharpDX.Direct2D1.LineJoin.Miter; _strokeStyleProperties.MiterLimit = CanvasDefaults.DefaultMiterLimit; _strokeStyleProperties.StartCap = CapStyle.Flat; _dashes = null; _sourceFillpaint = Colors.White.AsPaint(); _fillBrushValid = false; Matrix = Matrix3x2.Identity; IsShadowed = false; _sourceShadowColor = CanvasDefaults.DefaultShadowColor; FontName = "Arial"; FontSize = 12; FontWeight = FontWeight.Regular; FontStyle = FontStyle.Normal; _sourceFontColor = Colors.Black; _fontBrushValid = false; _alpha = 1; _scale = 1; IsBlurred = false; BlurRadius = 0; } public void SetStrokeDashPattern(float[] pattern, float strokeSize) { if (pattern == null || pattern.Length == 0) { if (_needsStrokeStyle == false) return; _strokeStyleProperties.DashStyle = DashStyle.Solid; _dashes = null; } else { _strokeStyleProperties.DashStyle = DashStyle.Custom; _dashes = pattern; } InvalidateStrokeStyle(); _needsStrokeStyle = true; } private void ReleaseFillBrush() { if (_fillBrush != null) { if (_parentState == null || _fillBrush != _parentState._fillBrush) { _fillBrush.Dispose(); if (_gradientStopCollection != null) { _gradientStopCollection.Dispose(); _gradientStopCollection = null; } } _fillBrush = null; } } public void SetLinearGradient(Paint aPaint, Vector2 aPoint1, Vector2 aPoint2) { ReleaseFillBrush(); _fillBrushValid = false; _sourceFillColor = null; _sourceFillpaint = aPaint; _gradientPoint1 = aPoint1; _gradientPoint2 = aPoint2; } public void SetRadialGradient(Paint aPaint, Vector2 aPoint1, Vector2 aPoint2) { ReleaseFillBrush(); _fillBrushValid = false; _sourceFillColor = null; _sourceFillpaint = aPaint; _gradientPoint1 = aPoint1; _gradientPoint2 = aPoint2; } private void InvalidateStrokeStyle() { if (_strokeStyle != null) { if (_parentState == null || _strokeStyle != _parentState._strokeStyle) { _strokeStyle.Dispose(); } _strokeStyle = null; } } public void SetShadow(SizeF aOffset, float aBlur, Color aColor) { if (aOffset != null) { IsShadowed = true; ShadowOffset = new Vector2(aOffset.Width, aOffset.Height); ShadowBlur = aBlur; _sourceShadowColor = aColor; _shadowColorValid = false; } else { IsShadowed = false; } } public void SetBlur(float aRadius) { if (aRadius > 0) { IsBlurred = true; BlurRadius = aRadius; } else { IsBlurred = false; BlurRadius = 0; } } public Matrix3x2 DxTranslate(float tx, float ty) { //Matrix = Matrix * Matrix3x2.Translation(tx, ty); Matrix = Matrix.Translate(tx, ty); return Matrix; } public Matrix3x2 DxConcatenateTransform(AffineTransform transform) { var values = new float[6]; transform.GetMatrix(values); Matrix = Matrix3x2.Multiply(Matrix, new Matrix3x2(values)); return Matrix; } public Matrix3x2 DxScale(float tx, float ty) { _scale *= tx; Matrix = Matrix.Scale(tx, ty); return Matrix; } public Matrix3x2 DxRotate(float aAngle) { float radians = Geometry.DegreesToRadians(aAngle); Matrix = Matrix.Rotate(radians); return Matrix; } public Matrix3x2 DxRotate(float aAngle, float x, float y) { float radians = Geometry.DegreesToRadians(aAngle); Matrix = Matrix.Translate(x, y); Matrix = Matrix.Rotate(radians); Matrix = Matrix.Translate(-x, -y); return Matrix; } private void InvalidateBrushes() { _strokeBrushValid = false; _fillBrushValid = false; _shadowColorValid = false; _fontBrushValid = false; } public void ClipPath(PathF path, WindingMode windingMode) { if (_layerMask != null) { throw new Exception("Only one clip operation currently supported."); } _layerMask = new PathGeometry(_renderTarget.Factory); var sink = _layerMask.Open(); sink.SetFillMode(windingMode == WindingMode.NonZero ? FillMode.Winding : FillMode.Alternate); var layerRect = new global::SharpDX.RectangleF(0, 0, _renderTarget.Size.Width, _renderTarget.Size.Height); _layerBounds = new RectangleGeometry(_renderTarget.Factory, layerRect); var clipGeometry = path.AsDxPath(_renderTarget.Factory); _layerBounds.Combine(clipGeometry, CombineMode.Intersect, sink); sink.Close(); var layerParameters = new LayerParameters1 { ContentBounds = layerRect, MaskTransform = Matrix3x2.Identity, MaskAntialiasMode = AntialiasMode.PerPrimitive, Opacity = 1, GeometricMask = _layerMask }; ((DeviceContext) _renderTarget).PushLayer(layerParameters, null); _layerCount++; } public void ClipRectangle(float x, float y, float width, float height) { var path = new PathF(); path.AppendRectangle(x, y, width, height); ClipPath(path, WindingMode.NonZero); } public void SubtractFromClip(float x, float y, float width, float height) { if (_layerMask != null) { throw new Exception("Only one subtraction currently supported."); } _layerMask = new PathGeometry(_renderTarget.Factory); var maskSink = _layerMask.Open(); var layerRect = new global::SharpDX.RectangleF(0, 0, _renderTarget.Size.Width, _renderTarget.Size.Height); _layerBounds = new RectangleGeometry(_renderTarget.Factory, layerRect); var boundsToSubtract = new global::SharpDX.RectangleF(x, y, width, height); _layerClipBounds = new RectangleGeometry(_renderTarget.Factory, boundsToSubtract); _layerBounds.Combine(_layerClipBounds, CombineMode.Exclude, maskSink); maskSink.Close(); var layerParameters = new LayerParameters1 { ContentBounds = layerRect, MaskTransform = Matrix3x2.Identity, MaskAntialiasMode = AntialiasMode.PerPrimitive, Opacity = 1, GeometricMask = _layerMask }; ((DeviceContext) _renderTarget).PushLayer(layerParameters, null); _layerCount++; } public void SetBitmapBrush(Brush bitmapBrush) { _fillBrush = bitmapBrush; _fillBrushValid = true; } } }
33.584932
140
0.5176
[ "MIT" ]
antonfirsov/Microsoft.Maui.Graphics
src/Microsoft.Maui.Graphics.SharpDX.Shared/DXCanvasState.cs
24,519
C#
namespace Cosmos.Security.Cryptography.Core { /// <summary> /// The entry used to trim the result of the Hash operation. /// </summary> internal class TrimOptions { /// <summary> /// Trim the ending character when decrypting /// </summary> public bool TrimTerminatorWhenDecrypting { get; set; } /// <summary> /// 十六进制数,输出时移除首位的 0,默认为 false /// </summary> public bool HexTrimLeadingZeroAsDefault { get; set; } public static TrimOptions Instance { get; } = new(); } }
28.25
64
0.587611
[ "Apache-2.0" ]
CosmosLoops/OneMore
src/Cosmos.Security.Cryptography/Cosmos/Security/Cryptography/Core/TrimOptions.cs
603
C#