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
/* * CatchCmd.java * * Copyright (c) 1997 Cornell University. * Copyright (c) 1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * * Included in SQLite3 port to C# for use in testharness only; 2008 Noah B Hart * * RCS @(#) $Id: CatchCmd.java,v 1.2 2000/08/20 06:08:42 mo Exp $ * */ using System; namespace tcl.lang { /// <summary> This class implements the built-in "catch" command in Tcl.</summary> class CatchCmd : Command { /// <summary> This procedure is invoked to process the "catch" Tcl command. /// See the user documentation for details on what it does. /// /// </summary> /// <param name="interp">the current interpreter. /// </param> /// <param name="argv">command arguments. /// </param> /// <exception cref=""> TclException if wrong number of arguments. /// </exception> public TCL.CompletionCode cmdProc( Interp interp, TclObject[] argv ) { if ( argv.Length != 2 && argv.Length != 3 ) { throw new TclNumArgsException( interp, 1, argv, "command ?varName?" ); } TclObject result; TCL.CompletionCode code = TCL.CompletionCode.OK; try { interp.eval( argv[1], 0 ); } catch ( TclException e ) { code = e.getCompletionCode(); } result = interp.getResult(); if ( argv.Length == 3 ) { try { interp.setVar( argv[2], result, 0 ); } catch ( TclException e ) { throw new TclException( interp, "couldn't save command result in variable" ); } } interp.resetResult(); interp.setResult( TclInteger.newInstance( (int)code ) ); return TCL.CompletionCode.RETURN; } } }
24.945946
87
0.594258
[ "MIT" ]
braegelno5/csharp-sqlite
TCL/src/commands/CatchCmd.cs
1,846
C#
// <copyright file="ConnectTests.cs" company="Hottinger Baldwin Messtechnik GmbH"> // // SharpJet, a library to communicate with Jet IPC. // // The MIT License (MIT) // // Copyright (C) Hottinger Baldwin Messtechnik GmbH // // 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. // // </copyright> namespace SharpJetTests { using NUnit.Framework; using Hbm.Devices.Jet; [TestFixture] public class FetchIdTests { [Test] public void TestGetId() { FetchId fetchId = new FetchId(42); Assert.AreEqual(42, fetchId.GetId()); } [Test] public void TestToString() { FetchId fetchId = new FetchId(42); Assert.AreEqual("42", fetchId.ToString()); } [Test] public void TestGetHashcodeReturnsId() { FetchId fetchId = new FetchId(42); Assert.AreEqual(42, fetchId.GetHashCode()); } [Test] public void TestEqualsObjIsNull() { FetchId fetchId = new FetchId(42); bool mustBeFalse = fetchId.Equals(null); Assert.IsFalse(mustBeFalse, "Expected 'Equals' call to be false."); } [Test] public void TestEqualsFetchIdMustReturnFalse() { FetchId fetchId = new FetchId(42); FetchId anotherFetchId = new FetchId(15); bool mustBeFalse = fetchId.Equals(anotherFetchId); Assert.IsFalse(mustBeFalse, "Expected 'Equals' call to be false."); } [Test] public void TestEqualsFetchIdMustReturnTrueSameReference() { FetchId fetchId = new FetchId(42); bool mustBeTrue = fetchId.Equals(fetchId); Assert.IsTrue(mustBeTrue, "Expected 'Equals' call to be true."); } [Test] public void TestEqualsFetchIdMustReturnTrueNewInstance() { FetchId fetchId = new FetchId(42); FetchId anotherFetchId = new FetchId(42); bool mustBeTrue = fetchId.Equals(anotherFetchId); Assert.IsTrue(mustBeTrue, "Expected 'Equals' call to be true."); } [Test] public void TestOperatorEqualsLeftOperandIsNull() { FetchId leftOperand = null; FetchId rightOperand = new FetchId(42); Assert.IsFalse(leftOperand == rightOperand, "Expected == call to be false."); } [Test] public void TestOperatorEqualsBothOperandsAreNull() { FetchId leftOperand = null; FetchId rightOperand = null; Assert.IsFalse(leftOperand == rightOperand, "Expected == call to be false."); } [Test] public void TestOperatorNotEqualsLeftOperandIsNull() { FetchId leftOperand = null; FetchId rightOperand = new FetchId(42); Assert.IsTrue(leftOperand != rightOperand, "Expected != call to be true."); } [Test] public void TestOperatorNotEqualsRightOperandIsNull() { FetchId leftOperand = new FetchId(42); FetchId rightOperand = null; Assert.IsTrue(leftOperand != rightOperand, "Expected != call to be true."); } [Test] public void TestOperatorNotEqualsBothOperandsAreNull() { FetchId leftOperand = null; FetchId rightOperand = null; Assert.IsTrue(leftOperand != rightOperand, "Expected != call to be true."); } [Test] public void TestOperatorNotEqualsDifferentFetchIdsMustReturnTrue() { FetchId leftOperand = new FetchId(15); FetchId rightOperand = new FetchId(42); Assert.IsTrue(leftOperand != rightOperand, "Expected != call to be true."); } [Test] public void TestOperatorNotEqualsSameIdsMustReturnFalse() { FetchId leftOperand = new FetchId(42); FetchId rightOperand = new FetchId(42); Assert.IsFalse(leftOperand != rightOperand, "Expected != call to be false."); } [Test] public void TestOperatorNotEqualsSameInstancesMustReturnFalse() { FetchId operand = new FetchId(42); Assert.IsFalse(operand.GetId() != 42, "Expected != call to be false."); } } }
34.221519
89
0.617348
[ "MIT" ]
gatzka/SharpJet
SharpJetTests/FetchIdTests.cs
5,409
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data; using System.Data.Common; namespace br.com.devdream.encurtador.dao { public class Url { public static bool Criar(vo.Url url) { bool resultado = false; Database database = Banco.ObterBancoDeDados(); DbCommand command = database.GetStoredProcCommand("procUrl_criar"); database.AddInParameter(command, "chave", DbType.String, url.Chave); database.AddInParameter(command, "endereco", DbType.String, url.Original); database.AddInParameter(command, "ip", DbType.String, url.Ip); if (database.ExecuteNonQuery(command) > 0) resultado = true; return resultado; } public static string ObterChaveUltimaUrlEncurtada() { string resultado = string.Empty; Database database = Banco.ObterBancoDeDados(); DbCommand command = database.GetStoredProcCommand("procUrlUltima_ler"); using (IDataReader reader = database.ExecuteReader(command)) { if (reader.Read()) { resultado = Convert.ToString(reader["chave"]); } } return resultado; } public static br.com.devdream.encurtador.vo.Url ObterPorChave(string chave) { vo.Url resultado = new vo.Url(); Database database = Banco.ObterBancoDeDados(); DbCommand command = database.GetStoredProcCommand("procUrl_Ler"); database.AddInParameter(command, "chave", DbType.String, chave); using (IDataReader reader = database.ExecuteReader(command)) { if (reader.Read()) { resultado.Encurtada = Convert.ToString(reader["chave"]); resultado.Original = Convert.ToString(reader["endereco"]); resultado.DataCriacao = Convert.ToDateTime(Convert.ToString(reader["dataCriacao"])); resultado.Chave = Convert.ToString(reader["chave"]); } } return resultado; } public static vo.Url ObterPorEndereco(string endereco) { vo.Url resultado = new vo.Url(); Database database = Banco.ObterBancoDeDados(); DbCommand command = database.GetStoredProcCommand("procUrlEndereco_Ler"); database.AddInParameter(command, "endereco", DbType.String, endereco); using (IDataReader reader = database.ExecuteReader(command)) { if (reader.Read()) { resultado.Chave = Convert.ToString(reader["chave"]); resultado.Encurtada = Convert.ToString(reader["chave"]); resultado.Original = Convert.ToString(reader["endereco"]); resultado.DataCriacao = Convert.ToDateTime(Convert.ToString(reader["dataCriacao"])); } } return resultado; } } }
32.454545
104
0.577653
[ "Apache-2.0" ]
oscarcasagrande/encurtadordeurl
br.com.devdream.encurtador.dao/Url.cs
3,215
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Data.SqlClient; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.SmoMetadataProvider; using Microsoft.SqlServer.Management.SqlParser.Binder; using Microsoft.SqlServer.Management.SqlParser.MetadataProvider; using Microsoft.Kusto.ServiceLayer.Connection; using Microsoft.Kusto.ServiceLayer.Connection.Contracts; using Microsoft.Kusto.ServiceLayer.SqlContext; using Microsoft.Kusto.ServiceLayer.Workspace; using Microsoft.Kusto.ServiceLayer.DataSource; using System.Threading; namespace Microsoft.Kusto.ServiceLayer.LanguageServices { public interface IConnectedBindingQueue { void CloseConnections(string serverName, string databaseName, int millisecondsTimeout); void OpenConnections(string serverName, string databaseName, int millisecondsTimeout); string AddConnectionContext(ConnectionInfo connInfo, string featureName = null, bool overwrite = false); void Dispose(); QueueItem QueueBindingOperation( string key, Func<IBindingContext, CancellationToken, object> bindOperation, Func<IBindingContext, object> timeoutOperation = null, Func<Exception, object> errorHandler = null, int? bindingTimeout = null, int? waitForLockTimeout = null); } public class SqlConnectionOpener { /// <summary> /// Virtual method used to support mocking and testing /// </summary> public virtual ServerConnection OpenServerConnection(ConnectionInfo connInfo, string featureName) { return ConnectionService.OpenServerConnection(connInfo, featureName); } } /// <summary> /// ConnectedBindingQueue class for processing online binding requests /// </summary> public class ConnectedBindingQueue : BindingQueue<ConnectedBindingContext>, IConnectedBindingQueue { internal const int DefaultBindingTimeout = 500; internal const int DefaultMinimumConnectionTimeout = 30; /// <summary> /// flag determing if the connection queue requires online metadata objects /// it's much cheaper to not construct these objects if not needed /// </summary> private bool needsMetadata; private SqlConnectionOpener connectionOpener; /// <summary> /// Gets the current settings /// </summary> internal SqlToolsSettings CurrentSettings { get { return WorkspaceService<SqlToolsSettings>.Instance.CurrentSettings; } } public ConnectedBindingQueue() : this(true) { } public ConnectedBindingQueue(bool needsMetadata) { this.needsMetadata = needsMetadata; this.connectionOpener = new SqlConnectionOpener(); } // For testing purposes only internal void SetConnectionOpener(SqlConnectionOpener opener) { this.connectionOpener = opener; } /// <summary> /// Generate a unique key based on the ConnectionInfo object /// </summary> /// <param name="connInfo"></param> internal static string GetConnectionContextKey(ConnectionDetails details) { string key = string.Format("{0}_{1}_{2}_{3}", details.ServerName ?? "NULL", details.DatabaseName ?? "NULL", details.UserName ?? "NULL", details.AuthenticationType ?? "NULL" ); if (!string.IsNullOrEmpty(details.DatabaseDisplayName)) { key += "_" + details.DatabaseDisplayName; } if (!string.IsNullOrEmpty(details.GroupId)) { key += "_" + details.GroupId; } return Uri.EscapeUriString(key); } /// <summary> /// Generate a unique key based on the ConnectionInfo object /// </summary> /// <param name="connInfo"></param> private string GetConnectionContextKey(string serverName, string databaseName) { return string.Format("{0}_{1}", serverName ?? "NULL", databaseName ?? "NULL"); } public void CloseConnections(string serverName, string databaseName, int millisecondsTimeout) { string connectionKey = GetConnectionContextKey(serverName, databaseName); var contexts = GetBindingContexts(connectionKey); foreach (var bindingContext in contexts) { if (bindingContext.BindingLock.WaitOne(millisecondsTimeout)) { bindingContext.ServerConnection.Disconnect(); } } } public void OpenConnections(string serverName, string databaseName, int millisecondsTimeout) { string connectionKey = GetConnectionContextKey(serverName, databaseName); var contexts = GetBindingContexts(connectionKey); foreach (var bindingContext in contexts) { if (bindingContext.BindingLock.WaitOne(millisecondsTimeout)) { try { bindingContext.ServerConnection.Connect(); } catch { //TODO: remove the binding context? } } } } public void RemoveBindigContext(ConnectionInfo connInfo) { string connectionKey = GetConnectionContextKey(connInfo.ConnectionDetails); if (BindingContextExists(connectionKey)) { RemoveBindingContext(connectionKey); } } /// <summary> /// Use a ConnectionInfo item to create a connected binding context /// </summary> /// <param name="connInfo">Connection info used to create binding context</param> /// <param name="overwrite">Overwrite existing context</param> public virtual string AddConnectionContext(ConnectionInfo connInfo, string featureName = null, bool overwrite = false) { if (connInfo == null) { return string.Empty; } // lookup the current binding contextna string connectionKey = GetConnectionContextKey(connInfo.ConnectionDetails); if (BindingContextExists(connectionKey)) { if (overwrite) { RemoveBindingContext(connectionKey); } else { // no need to populate the context again since the context already exists return connectionKey; } } IBindingContext bindingContext = this.GetOrCreateBindingContext(connectionKey); if (bindingContext.BindingLock.WaitOne()) { try { bindingContext.BindingLock.Reset(); // populate the binding context to work with the SMO metadata provider bindingContext.ServerConnection = connectionOpener.OpenServerConnection(connInfo, featureName); string connectionString = ConnectionService.BuildConnectionString(connInfo.ConnectionDetails); bindingContext.DataSource = DataSourceFactory.Create(DataSourceType.Kusto, connectionString, connInfo.ConnectionDetails.AzureAccountToken); if (this.needsMetadata) { bindingContext.SmoMetadataProvider = SmoMetadataProvider.CreateConnectedProvider(bindingContext.ServerConnection); bindingContext.MetadataDisplayInfoProvider = new MetadataDisplayInfoProvider(); bindingContext.MetadataDisplayInfoProvider.BuiltInCasing = this.CurrentSettings.SqlTools.IntelliSense.LowerCaseSuggestions.Value ? CasingStyle.Lowercase : CasingStyle.Uppercase; bindingContext.Binder = BinderProvider.CreateBinder(bindingContext.SmoMetadataProvider); } bindingContext.BindingTimeout = ConnectedBindingQueue.DefaultBindingTimeout; bindingContext.IsConnected = true; } catch (Exception) { bindingContext.IsConnected = false; } finally { bindingContext.BindingLock.Set(); } } return connectionKey; } } }
38.625532
159
0.592817
[ "MIT" ]
tamasvajk/sqltoolsservice
src/Microsoft.Kusto.ServiceLayer/LanguageServices/ConnectedBindingQueue.cs
9,077
C#
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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 VoltDB.Data.Client { /// <summary> /// Provides a shalow enumerable collection of strongly-typed rows that can easily be queried against using LINQ. /// This enumerator operates on a Table wrapper created for a table with 19 columns. /// </summary> /// <typeparam name="T1">Type of column 1 of the underlying table.</typeparam> /// <typeparam name="T2">Type of column 2 of the underlying table.</typeparam> /// <typeparam name="T3">Type of column 3 of the underlying table.</typeparam> /// <typeparam name="T4">Type of column 4 of the underlying table.</typeparam> /// <typeparam name="T5">Type of column 5 of the underlying table.</typeparam> /// <typeparam name="T6">Type of column 6 of the underlying table.</typeparam> /// <typeparam name="T7">Type of column 7 of the underlying table.</typeparam> /// <typeparam name="T8">Type of column 8 of the underlying table.</typeparam> /// <typeparam name="T9">Type of column 9 of the underlying table.</typeparam> /// <typeparam name="T10">Type of column 10 of the underlying table.</typeparam> /// <typeparam name="T11">Type of column 11 of the underlying table.</typeparam> /// <typeparam name="T12">Type of column 12 of the underlying table.</typeparam> /// <typeparam name="T13">Type of column 13 of the underlying table.</typeparam> /// <typeparam name="T14">Type of column 14 of the underlying table.</typeparam> /// <typeparam name="T15">Type of column 15 of the underlying table.</typeparam> /// <typeparam name="T16">Type of column 16 of the underlying table.</typeparam> /// <typeparam name="T17">Type of column 17 of the underlying table.</typeparam> /// <typeparam name="T18">Type of column 18 of the underlying table.</typeparam> /// <typeparam name="T19">Type of column 19 of the underlying table.</typeparam> public class RowCollection<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> : IEnumerable<Row<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>> { /// <summary> /// Table this row collection belongs to. /// </summary> private Table<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> Table; /// <summary> /// Internal constructor - row collections can only be spawned from an existing table (wrapper). /// </summary> /// <param name="tableWrapper">The table (wrapper) the row collection belongs to.</param> internal RowCollection(Table<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> tableWrapper) { this.Table = tableWrapper; } /// <summary> /// Returns a strongly-typed enumerator for the collection. /// </summary> /// <returns>The collection enumerator.</returns> public IEnumerator<Row<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>> GetEnumerator() { return new RowEnumerator<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(this.Table); } /// <summary> /// Returns a general enumerator for the collection. /// </summary> /// <returns>The collection enumerator.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new RowEnumerator<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(this.Table); } /// <summary> /// Enumerator class for the row collection. /// </summary> /// <typeparam name="E1">Type of column 1 of the underlying table.</typeparam> /// <typeparam name="E2">Type of column 2 of the underlying table.</typeparam> /// <typeparam name="E3">Type of column 3 of the underlying table.</typeparam> /// <typeparam name="E4">Type of column 4 of the underlying table.</typeparam> /// <typeparam name="E5">Type of column 5 of the underlying table.</typeparam> /// <typeparam name="E6">Type of column 6 of the underlying table.</typeparam> /// <typeparam name="E7">Type of column 7 of the underlying table.</typeparam> /// <typeparam name="E8">Type of column 8 of the underlying table.</typeparam> /// <typeparam name="E9">Type of column 9 of the underlying table.</typeparam> /// <typeparam name="E10">Type of column 10 of the underlying table.</typeparam> /// <typeparam name="E11">Type of column 11 of the underlying table.</typeparam> /// <typeparam name="E12">Type of column 12 of the underlying table.</typeparam> /// <typeparam name="E13">Type of column 13 of the underlying table.</typeparam> /// <typeparam name="E14">Type of column 14 of the underlying table.</typeparam> /// <typeparam name="E15">Type of column 15 of the underlying table.</typeparam> /// <typeparam name="E16">Type of column 16 of the underlying table.</typeparam> /// <typeparam name="E17">Type of column 17 of the underlying table.</typeparam> /// <typeparam name="E18">Type of column 18 of the underlying table.</typeparam> /// <typeparam name="E19">Type of column 19 of the underlying table.</typeparam> public class RowEnumerator<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19> : IEnumerator<Row<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19>> { /// <summary> /// Table (wrapper) the parent row collection belongs to. /// </summary> private Table<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19> Table; /// <summary> /// Position of the enumerator in the underlying collection. /// </summary> private int Position = -1; /// <summary> /// Protected constructor - instantiation is only allowed as part of the Table support framework. /// </summary> /// <param name="tableWrapper">The Table (wrapper) upon which the enumerator operates.</param> protected internal RowEnumerator(Table<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19> tableWrapper) { this.Table = tableWrapper; } /// <summary> /// Returns the (strongly-typed) element the enumerator currently points to. /// </summary> public Row<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19> Current { get { if ((this.Position > -1) && (this.Position < this.Table.RowCount)) return new Row<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19>(this.Table, this.Position); else throw new InvalidOperationException(); } } /// <summary> /// Moves the enumerator to the next element in the collection. /// </summary> /// <returns>true if the enumerator was successfully advanced to the next row; false if the enumerator has /// passed the end of the collection.</returns> public bool MoveNext() { this.Position++; return this.Position < this.Table.RowCount; } /// <summary> /// Rewinds the enumerator to the beginning. /// </summary> public void Reset() { this.Position = -1; } /// <summary> /// General interface implementation: Returns the (boxed) element the enumerator currently points to. /// </summary> object IEnumerator.Current { get { if ((this.Position > 0) && (this.Position < this.Table.RowCount)) return new Row<E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19>(this.Table, this.Position); else throw new InvalidOperationException(); } } /// <summary> /// Dispose of used resources. /// </summary> public void Dispose() { } } } }
54.852459
226
0.593046
[ "MIT" ]
VoltDB/voltdb-client-csharp
VoltDB.Data.Client/Types/RowEnumerator[T1,...,T19].cs
10,038
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using ImageFramework.ImageLoader; namespace ImageFramework.Utility { /// <summary> /// layer and mipmap count information (layer/mipmap > 0) /// </summary> public struct LayerMipmapCount { private int layers; private int mipmaps; public int Layers { get => layers; set { Debug.Assert(value > 0); layers = value; } } public int Mipmaps { get => mipmaps; set { Debug.Assert(value > 0); mipmaps = value; } } public bool IsMipmapInside(int mipmap) { return mipmap >= 0 && mipmap < Mipmaps; } public LayerMipmapCount(int layers, int mipmaps) { Debug.Assert(layers > 0); Debug.Assert(mipmaps > 0); this.layers = layers; this.mipmaps = mipmaps; } public static readonly LayerMipmapCount One = new LayerMipmapCount(1, 1); // iterates of all layers and mipmaps public IEnumerable<LayerMipmapSlice> Range { get { Debug.Assert(Layers > 0); Debug.Assert(Mipmaps > 0); for (int mip = 0; mip < Mipmaps; ++mip) for (int layer = 0; layer < Layers; ++layer) { yield return new LayerMipmapSlice(layer, mip); } } } // iterates over all layers and mipmaps within the given range public IEnumerable<LayerMipmapSlice> RangeOf(LayerMipmapRange range) { int maxMip = range.IsSingleMipmap ? range.FirstMipmap + 1 : Mipmaps; int maxLayer = range.IsSingleLayer ? range.FirstLayer + 1 : Layers; for (int mip = range.FirstMipmap; mip < maxMip; ++mip) for (int layer = range.FirstLayer; layer < maxLayer; ++layer) { yield return new LayerMipmapSlice(layer, mip); } } // iterates over all layers with the given mipmap level public IEnumerable<LayerMipmapSlice> LayersOfMipmap(int mipLevel) { Debug.Assert(IsMipmapInside(mipLevel)); for (int layer = 0; layer < Layers; ++layer) { yield return new LayerMipmapSlice(layer, mipLevel); } } public bool Equals(LayerMipmapCount other) { return Layers == other.Layers && Mipmaps == other.Mipmaps; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is LayerMipmapCount other && Equals(other); } public override int GetHashCode() { unchecked { return (layers * 397) ^ mipmaps; } } public static bool operator ==(LayerMipmapCount left, LayerMipmapCount right) { return left.Equals(right); } public static bool operator !=(LayerMipmapCount left, LayerMipmapCount right) { return !(left == right); } } }
29.04065
86
0.509239
[ "MIT" ]
gaybro8777/ImageViewer
ImageFramework/Utility/LayerMipmapCount.cs
3,574
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Media.Imaging; using NetSparkleUpdater.UI.Avalonia.ViewModels; namespace NetSparkleUpdater.UI.Avalonia { /// <summary> /// Interaction logic for MessageNotificationWindow.xaml. /// /// Window that shows a single message to the user (usually an error) regarding /// a software update. /// </summary> public class MessageNotificationWindow : Window { /// <summary> /// Construct the notification window for the message notification with the default /// <seealso cref="MessageNotificationWindowViewModel"/>. /// </summary> public MessageNotificationWindow() { this.InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif DataContext = new MessageNotificationWindowViewModel(); } /// <summary> /// Construct the notification window for the message notification with the provided /// <seealso cref="MessageNotificationWindowViewModel"/> /// </summary> /// <param name="viewModel">view model that has info on the message to show to the user</param> /// <param name="iconBitmap">Bitmap to use for the app's icon/graphic. Not currently used.</param> public MessageNotificationWindow(MessageNotificationWindowViewModel viewModel, IBitmap iconBitmap) { this.InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif DataContext = viewModel; /*var imageControl = this.FindControl<Image>("AppIcon"); if (imageControl != null) { imageControl.Source = iconBitmap; }*/ } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
33.339286
106
0.631494
[ "MIT" ]
DavosLi0bnip/daranguizu
SetUp/NetSparkle/src/NetSparkle.UI.Avalonia/MessageNotificationWindow.xaml.cs
1,869
C#
using MahApps.Metro.Controls; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Yomiage.GUI.Dialog { /// <summary> /// MetroDialogWindow.xaml の相互作用ロジック /// </summary> public partial class MetroDialogWindow : MetroWindow, IDialogWindow { public MetroDialogWindow() { InitializeComponent(); } public IDialogResult Result { get; set; } private void MetroWindow_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { this.Close(); } } } }
23.375
71
0.660963
[ "MIT" ]
InochiPM/YomiageLibrary
Yomiage.GUI/Dialog/MetroDialogWindow.xaml.cs
955
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using Microsoft.PythonTools.Analysis.Interpreter; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.PythonTools.PyAnalysis; namespace Microsoft.PythonTools.Analysis { /// <summary> /// Performs analysis of multiple Python code files and enables interrogation of the resulting analysis. /// </summary> public class PythonAnalyzer : IInterpreterState, IGroupableAnalysisProject { private readonly IPythonInterpreter _interpreter; private readonly Dictionary<string, ModuleReference> _modules; private readonly Dictionary<string, ModuleInfo> _modulesByFilename; private readonly Dictionary<object, object> _itemCache; private readonly BuiltinModule _builtinModule; private readonly Dictionary<string, XamlProjectEntry> _xamlByFilename = new Dictionary<string, XamlProjectEntry>(); internal readonly Namespace _propertyObj, _classmethodObj, _staticmethodObj, _typeObj, _intType, _rangeFunc, _frozensetType; internal readonly HashSet<Namespace> _objectSet; internal readonly Namespace _functionType; internal readonly BuiltinClassInfo _dictType, _listType, _tupleType, _generatorType, _stringType, _boolType, _setType; internal readonly ConstantInfo _noneInst; private readonly Deque<AnalysisUnit> _queue; private readonly KnownTypes _types; internal readonly IModuleContext _defaultContext; private readonly PythonLanguageVersion _langVersion; private static object _nullKey = new object(); public PythonAnalyzer(IPythonInterpreterFactory interpreterFactory) : this(interpreterFactory.CreateInterpreter(), interpreterFactory.GetLanguageVersion()) { } public PythonAnalyzer(IPythonInterpreter pythonInterpreter, PythonLanguageVersion langVersion) { _langVersion = langVersion; _interpreter = pythonInterpreter; _modules = new Dictionary<string, ModuleReference>(); _modulesByFilename = new Dictionary<string, ModuleInfo>(StringComparer.OrdinalIgnoreCase); _itemCache = new Dictionary<object, object>(); InitializeBuiltinModules(); pythonInterpreter.ModuleNamesChanged += new EventHandler(ModuleNamesChanged); _types = new KnownTypes(this); _builtinModule = (BuiltinModule)Modules["__builtin__"].Module; _propertyObj = GetBuiltin("property"); _classmethodObj = GetBuiltin("classmethod"); _staticmethodObj = GetBuiltin("staticmethod"); _typeObj = GetBuiltin("type"); _intType = GetBuiltin("int"); _stringType = (BuiltinClassInfo)GetBuiltin("str"); _objectSet = new HashSet<Namespace>(new[] { GetBuiltin("object") }); _setType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Set)); _rangeFunc = GetBuiltin("range"); _frozensetType = GetBuiltin("frozenset"); _functionType = GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Function)); _generatorType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Generator)); _dictType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Dict)); _boolType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Bool)); _noneInst = (ConstantInfo)GetNamespaceFromObjects(null); _listType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.List)); _tupleType = (BuiltinClassInfo)GetNamespaceFromObjects(_interpreter.GetBuiltinType(BuiltinTypeId.Tuple)); _queue = new Deque<AnalysisUnit>(); SpecializeFunction("__builtin__", "range", (n, unit, args) => unit.DeclaringModule.GetOrMakeNodeVariable(n, (nn) => new RangeInfo(_types.List, unit.ProjectState).SelfSet)); SpecializeFunction("__builtin__", "min", ReturnUnionOfInputs); SpecializeFunction("__builtin__", "max", ReturnUnionOfInputs); pythonInterpreter.Initialize(this); _defaultContext = pythonInterpreter.CreateModuleContext(); // cached for quick checks to see if we're a call to clr.AddReference try { SpecializeFunction("wpf", "LoadComponent", LoadComponent); } catch (KeyNotFoundException) { // IronPython.Wpf.dll isn't available... } } void ModuleNamesChanged(object sender, EventArgs e) { InitializeBuiltinModules(); } #region Public API public PythonLanguageVersion LanguageVersion { get { return _langVersion; } } /// <summary> /// Adds a new module of code to the list of available modules and returns a ProjectEntry object. /// </summary> /// <param name="moduleName">The name of the module; used to associate with imports</param> /// <param name="filePath">The path to the file on disk</param> /// <param name="cookie">An application-specific identifier for the module</param> /// <returns></returns> public IPythonProjectEntry AddModule(string moduleName, string filePath, IAnalysisCookie cookie = null) { var entry = new ProjectEntry(this, moduleName, filePath, cookie); if (moduleName != null) { Modules[moduleName] = new ModuleReference(entry.MyScope); } if (filePath != null) { _modulesByFilename[filePath] = entry.MyScope; } return entry; } public IXamlProjectEntry AddXamlFile(string filePath, IAnalysisCookie cookie = null) { var entry = new XamlProjectEntry(filePath); _xamlByFilename[filePath] = entry; return entry; } /// <summary> /// Gets a top-level list of all the available modules as a list of MemberResults. /// </summary> /// <returns></returns> public MemberResult[] GetModules(bool topLevelOnly = false) { var d = new Dictionary<string, HashSet<Namespace>>(); foreach (var keyValue in Modules) { var modName = keyValue.Key; var moduleRef = keyValue.Value; if (topLevelOnly && modName.IndexOf('.') != -1) { continue; } HashSet<Namespace> l; if (!d.TryGetValue(modName, out l)) { d[modName] = l = new HashSet<Namespace>(); } if (moduleRef != null && moduleRef.Module != null) { // The REPL shows up here with value=None l.Add(moduleRef.Module); } } var result = new MemberResult[d.Count]; int pos = 0; foreach (var kvp in d) { result[pos++] = new MemberResult(kvp.Key, kvp.Value); } return result; } public IPythonInterpreter Interpreter { get { return _interpreter; } } /// <summary> /// returns the MemberResults associated with modules in the specified /// list of names. The list of names is the path through the module, for example /// ['System', 'Runtime'] /// </summary> /// <returns></returns> public MemberResult[] GetModuleMembers(IModuleContext moduleContext, string[] names) { return GetModuleMembers(moduleContext, names, true); } /// <summary> /// returns the MemberResults associated with modules in the specified /// list of names. The list of names is the path through the module, for example /// ['System', 'Runtime'] /// </summary> /// <returns></returns> public MemberResult[] GetModuleMembers(IModuleContext moduleContext, string[] names, bool bottom) { IDictionary<string, ISet<Namespace>> d = null; ModuleReference moduleRef; if (Modules.TryGetValue(names[0], out moduleRef) && moduleRef.Module != null) { var module = moduleRef.Module; d = new Dictionary<string, ISet<Namespace>>(); var mod = module.SelfSet; if (bottom) { for (int i = 1; i < names.Length; i++) { var next = names[i]; // import Foo.Bar as Baz, we need to get Bar VariableDef def; ISet<Namespace> newMod = EmptySet<Namespace>.Instance; bool madeSet = false; foreach (var modItem in mod) { BuiltinModule builtinMod = modItem as BuiltinModule; if (builtinMod != null) { var mem = builtinMod._type.GetMember(moduleContext, next); if (mem != null) { newMod = newMod.Union(GetNamespaceFromObjects(mem), ref madeSet); } } else { ModuleInfo userMod = modItem as ModuleInfo; if (userMod != null && userMod.Scope.Variables.TryGetValue(next, out def)) { newMod = newMod.Union(def.Types, ref madeSet); } } } mod = newMod; if (mod.Count == 0) { break; } } } foreach (var modItem in mod) { Update(d, modItem.GetAllMembers(moduleContext)); } } MemberResult[] result; if (d != null) { result = new MemberResult[d.Count]; int pos = 0; foreach (var kvp in d) { result[pos++] = new MemberResult(kvp.Key, kvp.Value); } } else { result = new MemberResult[0]; } return result; } public void SpecializeFunction(string moduleName, string name, Action<CallExpression> dlg) { SpecializeFunction(moduleName, name, (call, unit, types) => { dlg(call); return null; }); } public static string PathToModuleName(string path) { string moduleName; string dirName; if (path == null) { return String.Empty; } else if (path.EndsWith("__init__.py")) { moduleName = Path.GetFileName(Path.GetDirectoryName(path)); dirName = Path.GetDirectoryName(path); } else { moduleName = Path.GetFileNameWithoutExtension(path); dirName = path; } while (dirName.Length != 0 && (dirName = Path.GetDirectoryName(dirName)).Length != 0 && File.Exists(Path.Combine(dirName, "__init__.py"))) { moduleName = Path.GetFileName(dirName) + "." + moduleName; } return moduleName; } #endregion #region Internal Implementation internal KnownTypes Types { get { return _types; } } /// <summary> /// Replaces a built-in function (specified by module name and function name) with a customized /// delegate which provides specific behavior for handling when that function is called. /// /// Currently this just provides a hook when the function is called - it could be expanded /// to providing the interpretation of when the function is called as well. /// </summary> private void SpecializeFunction(string moduleName, string name, Func<CallExpression, AnalysisUnit, ISet<Namespace>[], ISet<Namespace>> dlg) { var module = Modules[moduleName]; BuiltinModule builtin = module.Module as BuiltinModule; Debug.Assert(builtin != null); if (builtin != null) { foreach (var v in builtin[name]) { BuiltinFunctionInfo funcInfo = v as BuiltinFunctionInfo; if (funcInfo != null) { builtin[name] = new SpecializedBuiltinFunction(this, funcInfo.Function, dlg).SelfSet; break; } } } } private ISet<Namespace> LoadComponent(CallExpression node, AnalysisUnit unit, ISet<Namespace>[] args) { if (args.Length == 2 && Interpreter is IDotNetPythonInterpreter) { var xaml = args[1]; var self = args[0]; foreach (var arg in xaml) { string strConst = arg.GetConstantValue() as string; if (strConst == null) { byte[] bytes = arg.GetConstantValue() as byte[]; if (bytes != null) { var tmp = new System.Text.StringBuilder(); foreach(var curByte in bytes) { tmp.Append((char)curByte); } strConst = tmp.ToString(); } } if (strConst != null) { // process xaml file, add attributes to self string xamlPath = Path.Combine(Path.GetDirectoryName(unit.DeclaringModule.ProjectEntry.FilePath), strConst); XamlProjectEntry xamlProject; if (_xamlByFilename.TryGetValue(xamlPath, out xamlProject)) { // TODO: Get existing analysis if it hasn't changed. var analysis = xamlProject.Analysis; if (analysis == null) { xamlProject.Analyze(); analysis = xamlProject.Analysis; } xamlProject.AddDependency(unit.ProjectEntry); var evalUnit = unit.CopyForEval(); // add named objects to instance foreach (var keyValue in analysis.NamedObjects) { var type = keyValue.Value; if (type.Type.UnderlyingType != null) { var ns = GetNamespaceFromObjects(((IDotNetPythonInterpreter)Interpreter).GetBuiltinType(type.Type.UnderlyingType)); if (ns is BuiltinClassInfo) { ns = ((BuiltinClassInfo)ns).Instance; } self.SetMember(node, evalUnit, keyValue.Key, ns.SelfSet); } // TODO: Better would be if SetMember took something other than a node, then we'd // track references w/o this extra effort. foreach (var inst in self) { InstanceInfo instInfo = inst as InstanceInfo; if (instInfo != null) { VariableDef def; if (instInfo.InstanceAttributes.TryGetValue(keyValue.Key, out def)) { def.AddAssignment( new SimpleSrcLocation(type.LineNumber, type.LineOffset), xamlProject ); } } } } // add references to event handlers foreach (var keyValue in analysis.EventHandlers) { // add reference to methods... var member = keyValue.Value; // TODO: Better would be if SetMember took something other than a node, then we'd // track references w/o this extra effort. foreach (var inst in self) { InstanceInfo instInfo = inst as InstanceInfo; if (instInfo != null) { ClassInfo ci = instInfo.ClassInfo; VariableDef def; if (ci.Scope.Variables.TryGetValue(keyValue.Key, out def)) { def.AddReference( new SimpleSrcLocation(member.LineNumber, member.LineOffset), xamlProject ); } } } } } } } // load component returns self return self; } return EmptySet<Namespace>.Instance; } internal Deque<AnalysisUnit> Queue { get { return _queue; } } private void InitializeBuiltinModules() { var names = _interpreter.GetModuleNames(); foreach (string modName in names) { var mod = _interpreter.ImportModule(modName); if (mod != null) { ModuleReference modRef; if (Modules.TryGetValue(modName, out modRef)) { var existingBuiltin = modRef.Module as BuiltinModule; if (existingBuiltin != null && existingBuiltin._type == mod) { // don't replace existing module which is the same continue; } } Modules[modName] = new ModuleReference(new BuiltinModule(mod, this)); } } } internal BuiltinModule ImportModule(string modName, bool bottom = true) { IPythonModule mod; if (modName.IndexOf('.') != -1) { string[] names = modName.Split('.'); mod = _interpreter.ImportModule(names[0]); if (bottom) { int curIndex = 1; while (mod != null && curIndex < names.Length) { mod = mod.GetMember(_defaultContext, names[curIndex++]) as IPythonModule; } } } else { mod = _interpreter.ImportModule(modName); } if (mod != null) { return (BuiltinModule)GetNamespaceFromObjects(mod); } return null; } private ISet<Namespace> ReturnUnionOfInputs(CallExpression call, AnalysisUnit unit, ISet<Namespace>[] args) { ISet<Namespace> res = EmptySet<Namespace>.Instance; bool madeSet = false; foreach (var set in args) { res = res.Union(set, ref madeSet); } return res; } /// <summary> /// Gets a builtin value /// </summary> /// <param name="name"></param> /// <returns></returns> internal Namespace GetBuiltin(string name) { return _builtinModule[name].First(); } internal T GetCached<T>(object key, Func<T> maker) where T : class { object result; if (!_itemCache.TryGetValue(key, out result)) { _itemCache[key] = result = maker(); } else { Debug.Assert(result is T); } return (result as T); } internal BuiltinModule BuiltinModule { get { return _builtinModule; } } internal BuiltinInstanceInfo GetInstance(IPythonType type) { return GetBuiltinType(type).Instance; } internal IPythonType GetPythonType(BuiltinTypeId id) { return _interpreter.GetBuiltinType(id); } internal BuiltinClassInfo GetBuiltinType(IPythonType type) { return GetCached(type, () => MakeBuiltinType(type) ); } private BuiltinClassInfo MakeBuiltinType(IPythonType type) { switch(type.TypeId) { case BuiltinTypeId.List: return new ListBuiltinClassInfo(type, this); case BuiltinTypeId.Tuple: return new TupleBuiltinClassInfo(type, this); default: return new BuiltinClassInfo(type, this); } } internal Namespace GetNamespaceFromObjects(object attr) { var attrType = (attr != null) ? attr.GetType() : typeof(NoneType); if (attr is IPythonType) { return GetBuiltinType((IPythonType)attr); } else if (attr is IPythonFunction) { var bf = (IPythonFunction)attr; return GetCached(attr, () => new BuiltinFunctionInfo(bf, this)); } else if (attr is IPythonMethodDescriptor) { return GetCached(attr, () => new BuiltinMethodInfo((IPythonMethodDescriptor)attr, this)); } else if (attr is IBuiltinProperty) { return GetCached(attr, () => new BuiltinPropertyInfo((IBuiltinProperty)attr, this)); } else if (attr is IPythonModule) { return GetCached(attr, () => new BuiltinModule((IPythonModule)attr, this)); } else if (attr is IPythonEvent) { return GetCached(attr, () => new BuiltinEventInfo((IPythonEvent)attr, this)); } else if (attr is IPythonConstant) { return GetConstant((IPythonConstant)attr).First(); } else if (attrType == typeof(bool) || attrType == typeof(int) || attrType == typeof(Complex) || attrType == typeof(string) || attrType == typeof(long) || attrType == typeof(double) || attr == null) { return GetConstant(attr).First(); } else if (attr is IMemberContainer) { return GetCached(attr, () => new ReflectedNamespace((IMemberContainer)attr, this)); } else if (attr is IPythonMultipleMembers) { IPythonMultipleMembers multMembers = (IPythonMultipleMembers)attr; var members = multMembers.Members; return GetCached(attr, () => { Namespace[] nses = new Namespace[members.Count]; for (int i = 0; i < members.Count; i++) { nses[i] = GetNamespaceFromObjects(members[i]); } return new MultipleMemberInfo(nses); } ); } else { var pyAattrType = GetTypeFromObject(attr); return GetBuiltinType(pyAattrType).Instance; } } internal IDictionary<string, ISet<Namespace>> GetAllMembers(IMemberContainer container, IModuleContext moduleContext) { var names = container.GetMemberNames(moduleContext); var result = new Dictionary<string, ISet<Namespace>>(); foreach (var name in names) { result[name] = GetNamespaceFromObjects(container.GetMember(moduleContext, name)); } return result; } internal Dictionary<string, ModuleReference> Modules { get { return _modules; } } internal Dictionary<string, ModuleInfo> ModulesByFilename { get { return _modulesByFilename; } } internal ISet<Namespace> GetConstant(IPythonConstant value) { object key = value ?? _nullKey; return GetCached<ISet<Namespace>>(key, () => new ConstantInfo(value, this).SelfSet); } internal ISet<Namespace> GetConstant(object value) { object key = value ?? _nullKey; return GetCached<ISet<Namespace>>(key, () => new ConstantInfo(value, this).SelfSet); } private static void Update<K, V>(IDictionary<K, V> dict, IDictionary<K, V> newValues) { foreach (var kvp in newValues) { dict[kvp.Key] = kvp.Value; } } internal IPythonType GetTypeFromObject(object value) { if (value == null) { return Types.None; } switch (Type.GetTypeCode(value.GetType())) { case TypeCode.Boolean: return Types.Bool; case TypeCode.Double: return Types.Float; case TypeCode.Int32: return Types.Int; case TypeCode.String: return Types.Str; case TypeCode.Object: if (value.GetType() == typeof(Complex)) { return Types.Complex; } else if(value.GetType() == typeof(byte[])) { return Types.Str; } else if (value.GetType() == typeof(BigInteger)) { if (LanguageVersion.Is3x()) { return Types.Int; } else { return Types.Long; } } else if (value.GetType() == typeof(Ellipsis)) { return Types.Ellipsis; } break; } throw new InvalidOperationException(); } internal BuiltinClassInfo MakeGenericType(IAdvancedPythonType clrType, params IPythonType[] clrIndexType) { var res = clrType.MakeGenericType(clrIndexType); return (BuiltinClassInfo)GetNamespaceFromObjects(res); } #endregion #region IGroupableAnalysisProject Members void IGroupableAnalysisProject.AnalyzeQueuedEntries() { new DDG().Analyze(Queue); } #endregion } }
43.925633
184
0.528331
[ "Apache-2.0" ]
rsumner33/PTVS
Release/Product/Python/Analysis/PythonAnalyzer.cs
27,763
C#
namespace VanType { /// <summary> /// Then enumerations conversion type. /// </summary> public enum EnumConversionType { /// <summary> /// Converts CSharp enumerations to numeric TypeScript enumerations. /// </summary> Numeric, /// <summary> /// Converts CSharp enumerations to string TypeScript enumerations. /// </summary> String, } }
22.473684
76
0.566745
[ "MIT" ]
jgveire/VanType
src/VanType/EnumConversion.cs
429
C#
using System; using System.Collections.Generic; using System.Text; namespace Animals.Enumerator { public enum Gender { Male, Female } }
12.692308
33
0.648485
[ "MIT" ]
aalishov/SoftUni
04-CSharp-OOP-February-2020/02. CSharp-OOP-Inheritance-Skeleton/Animals/Enumerator/Gender.cs
167
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HangingLightBlink : MonoBehaviour { private MeshRenderer mesh; private Color color; private bool waiting = false; // Use this for initialization void Start () { mesh = GetComponent<MeshRenderer>(); color = mesh.material.GetColor("_EmissionColor"); } // Update is called once per frame void Update () { if (!waiting) { waiting = true; Invoke("Blink", Random.Range(0.1f, 3f)); } } void Blink() { mesh.material.SetColor("_EmissionColor", color * Random.Range(0f, 1f)); waiting = false; } }
18.818182
73
0.690821
[ "MIT" ]
CGDD-Savitr/TypeRider-Zombies
Assets/Scripts/HangingLightBlink.cs
623
C#
using System.Collections.Immutable; using System.Threading.Tasks; using FluentAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; namespace SourceExpander.Generate { public class LanguageVersionTest : EmbedderGeneratorTestBase { [Theory] [InlineData(LanguageVersion.Latest)] [InlineData(LanguageVersion.LatestMajor)] [InlineData(LanguageVersion.Preview)] [InlineData(LanguageVersion.CSharp7_3)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.CSharp10)] public async Task Generate(LanguageVersion languageVersion) { var embeddedFiles = ImmutableArray.Create( new SourceFileInfo ( "TestProject>Program.cs", new string[] { "Program" }, ImmutableArray.Create("using System;"), ImmutableArray.Create<string>(), @"class Program{static void Main()=>Console.WriteLine(1);}" )); const string embeddedSourceCode = "[{\"CodeBody\":\"class Program{static void Main()=>Console.WriteLine(1);}\",\"Dependencies\":[],\"FileName\":\"TestProject>Program.cs\",\"TypeNames\":[\"Program\"],\"Usings\":[\"using System;\"]}]"; var test = new Test { ParseOptions = new CSharpParseOptions(languageVersion), TestState = { AdditionalFiles = { enableMinifyJson, }, Sources = { ( "/home/source/Program.cs", @"using System; class Program { static void Main() => Console.WriteLine(1); } " ), }, GeneratedSources = { (typeof(EmbedderGenerator), "EmbeddedSourceCode.Metadata.cs", EnvironmentUtil.JoinByStringBuilder("using System.Reflection;", $"[assembly: AssemblyMetadataAttribute(\"SourceExpander.EmbedderVersion\",\"{EmbedderVersion}\")]", $"[assembly: AssemblyMetadataAttribute(\"SourceExpander.EmbeddedLanguageVersion\",\"{languageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString()}\")]", $"[assembly: AssemblyMetadataAttribute(\"SourceExpander.EmbeddedSourceCode\",{embeddedSourceCode.ToLiteral()})]") ), } } }; await test.RunAsync(); Newtonsoft.Json.JsonConvert.DeserializeObject<SourceFileInfo[]>(embeddedSourceCode) .Should() .BeEquivalentTo(embeddedFiles); System.Text.Json.JsonSerializer.Deserialize<SourceFileInfo[]>(embeddedSourceCode) .Should() .BeEquivalentTo(embeddedFiles); } } }
41.743243
245
0.548074
[ "MIT" ]
naminodarie/SourceExpander
Test/SourceExpander.Embedder.Test/Generate/LanguageVersionTest.cs
3,091
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using glowing.core; namespace glowing.db { public class SqliteConnectionWin :ISqliteConnection { SQLiteConnection _connection; public SqliteConnectionWin(string dbConnection) { _connection = new SQLiteConnection(dbConnection); } public void Open() { _connection.Open(); } public void Dispose() { _connection.Dispose(); } public ISqliteCommand CreateCommand(string sql) { var cmd = new SQLiteCommand(sql, _connection); return new SqliteCommandWin(cmd); } } public class SqliteCommandWin : ISqliteCommand { SQLiteCommand _cmd; public SqliteCommandWin(SQLiteCommand cmd) { _cmd = cmd; } public void Add(string name, string value) { _cmd.Parameters.Add(new SQLiteParameter(name)); _cmd.Parameters[name].Value = value; } public object ExecuteScalar() { return _cmd.ExecuteScalar(); } public int ExecuteNonQuery() { return _cmd.ExecuteNonQuery(); } } }
20.953846
61
0.572687
[ "Unlicense" ]
cannelle-plus/glowing-wookie
src/glowing/db/SqliteWin.cs
1,364
C#
using UIForia.Animation; using UIForia.Attributes; using UIForia.Elements; namespace SpaceGameDemo.SkillPointBar { [Template("SpaceGameDemo/SkillPointBar/SkillPointBar.xml")] public class SkillPointBar : UIElement { public int availablePoints; public int skillPoints; public void IncreaseSkill() { if (skillPoints < 25 && availablePoints > 0) { skillPoints++; availablePoints--; } else { UIElement skillBar = FindById("skill-bar"); skillBar.Animator.TryGetAnimationData("warning", out AnimationData animationData); skillBar.Animator.PlayAnimation(animationData); } } public void DecreaseSkill() { if (skillPoints > 1) { skillPoints--; availablePoints++; } else { UIElement skillBar = FindById("skill-bar"); skillBar.Animator.TryGetAnimationData("warning", out AnimationData animationData); skillBar.Animator.PlayAnimation(animationData); } } } }
30.842105
98
0.569966
[ "MIT" ]
criedel/UIForia
Assets/SpaceGameDemo/SkillPointBar/SkillPointBar.cs
1,174
C#
namespace AESGCMInBouncyCastle { #region using System; using System.IO; using System.Text; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; #endregion /// <summary> /// Code taken from this Stack question: /// http://codereview.stackexchange.com/questions/14892/review-of-simplified-secure-encryption-of-a-string /// /// The below code uses AES GCM using a 256bit key. /// /// A non secret payload byte[] can be provided as well that won't be encrypted but will be authenticated with GCM. /// </summary> public class EncryptionService : IEncryptionService { #region Constants and Fields private const int DEFAULT_KEY_BIT_SIZE = 256; private const int DEFAULT_MAC_BIT_SIZE = 128; private const int DEFAULT_NONCE_BIT_SIZE = 128; private readonly int _keySize; private readonly int _macSize; private readonly int _nonceSize; private readonly SecureRandom _random; #endregion #region Constructors and Destructors public EncryptionService() : this(DEFAULT_KEY_BIT_SIZE, DEFAULT_MAC_BIT_SIZE, DEFAULT_NONCE_BIT_SIZE) { } public EncryptionService(int keyBitSize, int macBitSize, int nonceBitSize) { _random = new SecureRandom(); _keySize = keyBitSize; _macSize = macBitSize; _nonceSize = nonceBitSize; } #endregion #region Public Methods and Operators /// <summary> /// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message /// </summary> /// <param name="encryptedMessage">The encrypted message.</param> /// <param name="key">The base 64 encoded 256 bit key.</param> /// <param name="nonSecretPayloadLength">Length of the optional non-secret payload.</param> /// <returns>Decrypted Message</returns> public string DecryptWithKey(string encryptedMessage, string key, int nonSecretPayloadLength = 0) { if (string.IsNullOrEmpty(encryptedMessage)) { throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); } var decodedKey = Convert.FromBase64String(key); var cipherText = Convert.FromBase64String(encryptedMessage); var plaintext = DecryptWithKey(cipherText, decodedKey, nonSecretPayloadLength); return Encoding.UTF8.GetString(plaintext); } /// <summary> /// Simple Encryption And Authentication (AES-GCM) of a UTF8 string. /// </summary> /// <param name="messageToEncrypt">The string to be encrypted.</param> /// <param name="key">The base 64 encoded 256 bit key.</param> /// <param name="nonSecretPayload">Optional non-secret payload.</param> /// <returns> /// Encrypted Message /// </returns> /// <exception cref="System.ArgumentException">Secret Message Required!;secretMessage</exception> /// <remarks> /// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64 /// </remarks> public string EncryptWithKey(string messageToEncrypt, string key, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(messageToEncrypt)) { throw new ArgumentException("Secret Message Required!", "messageToEncrypt"); } var decodedKey = Convert.FromBase64String(key); var plainText = Encoding.UTF8.GetBytes(messageToEncrypt); var cipherText = EncryptWithKey(plainText, decodedKey, nonSecretPayload); return Convert.ToBase64String(cipherText); } /// <summary> /// Helper that generates a random new key on each call. /// </summary> /// <returns>Base 64 encoded string</returns> public string NewKey() { var key = new byte[_keySize / 8]; _random.NextBytes(key); return Convert.ToBase64String(key); } #endregion #region Methods public byte[] DecryptWithKey(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0) { //User Error Checks CheckKey(key); if (encryptedMessage == null || encryptedMessage.Length == 0) { throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); } using (var cipherStream = new MemoryStream(encryptedMessage)) using (var cipherReader = new BinaryReader(cipherStream)) { //Grab Payload var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength); //Grab Nonce var nonce = cipherReader.ReadBytes(_nonceSize / 8); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), _macSize, nonce, nonSecretPayload); cipher.Init(false, parameters); //Decrypt Cipher Text var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0); cipher.DoFinal(plainText, len); return plainText; } } public byte[] EncryptWithKey(byte[] messageToEncrypt, byte[] key, byte[] nonSecretPayload = null) { //User Error Checks CheckKey(key); //Non-secret Payload Optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; //Using random nonce large enough not to repeat var nonce = new byte[_nonceSize / 8]; _random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), _macSize, nonce, nonSecretPayload); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var cipherText = new byte[cipher.GetOutputSize(messageToEncrypt.Length)]; var len = cipher.ProcessBytes(messageToEncrypt, 0, messageToEncrypt.Length, cipherText, 0); cipher.DoFinal(cipherText, len); //Assemble Message using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { //Prepend Authenticated Payload binaryWriter.Write(nonSecretPayload); //Prepend Nonce binaryWriter.Write(nonce); //Write Cipher Text binaryWriter.Write(cipherText); } return combinedStream.ToArray(); } } private void CheckKey(byte[] key) { if (key == null || key.Length != _keySize / 8) { throw new ArgumentException(String.Format("Key needs to be {0} bit! actual:{1}", _keySize, key?.Length * 8), "key"); } } #endregion } }
36.825243
132
0.598735
[ "MIT" ]
lukemerrett/Bouncy-Castle-AES-GCM-Encryption
EncryptionService.cs
7,588
C#
//---------------------- // <auto-generated> // This file was automatically generated. Any changes to it will be lost if and when the file is regenerated. // </auto-generated> //---------------------- #pragma warning disable using System; using SQEX.Luminous.Core.Object; using System.Collections.Generic; using CodeDom = System.CodeDom; namespace Black.Sequence.Variable { [Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")] public partial class SequenceVariableObjectStatus : SQEX.Ebony.Framework.Sequence.SequenceVariable { new public static ObjectType ObjectType { get; private set; } private static PropertyContainer fieldProperties; [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphVariableInputPin set_= new SQEX.Ebony.Framework.Node.GraphVariableInputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphVariableOutputPin get_= new SQEX.Ebony.Framework.Node.GraphVariableOutputPin(); public string labelName_= string.Empty; new public static void SetupObjectType() { if (ObjectType != null) { return; } var dummy = new SequenceVariableObjectStatus(); var properties = dummy.GetFieldProperties(); ObjectType = new ObjectType("Black.Sequence.Variable.SequenceVariableObjectStatus", 0, Black.Sequence.Variable.SequenceVariableObjectStatus.ObjectType, Construct, properties, 0, 280); } public override ObjectType GetObjectType() { return ObjectType; } protected override PropertyContainer GetFieldProperties() { if (fieldProperties != null) { return fieldProperties; } fieldProperties = new PropertyContainer("Black.Sequence.Variable.SequenceVariableObjectStatus", base.GetFieldProperties(), -245493251, 269025562); fieldProperties.AddIndirectlyProperty(new Property("refInPorts_", 1035088696, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 24, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("refOutPorts_", 283683627, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 40, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("set_.pinName_", 4139991867, "Base.String", 96, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("set_.name_", 2005822774, "Base.String", 112, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("set_.connections_", 3239018316, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 128, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("set_.pinValueType_", 1395572239, "Base.String", 160, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("get_.pinName_", 2751629047, "Base.String", 184, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("get_.name_", 278916258, "Base.String", 200, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("get_.connections_", 1205403120, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 216, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("get_.pinValueType_", 1060981547, "Base.String", 248, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddProperty(new Property("set_", 1265669588, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 88, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("get_", 1475015064, "SQEX.Ebony.Framework.Node.GraphVariableOutputPin", 176, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("labelName_", 2707696659, "String", 264, 16, 1, Property.PrimitiveType.String, 0, (char)0)); return fieldProperties; } private static BaseObject Construct() { return new SequenceVariableObjectStatus(); } } }
56.375
239
0.717517
[ "MIT" ]
Gurrimo/Luminaire
Assets/Editor/Generated/Black/Sequence/Variable/SequenceVariableObjectStatus.generated.cs
4,510
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Media.Outputs { [OutputType] public sealed class AkamaiAccessControlResponse { /// <summary> /// authentication key list /// </summary> public readonly ImmutableArray<Outputs.AkamaiSignatureHeaderAuthenticationKeyResponse> AkamaiSignatureHeaderAuthenticationKeyList; [OutputConstructor] private AkamaiAccessControlResponse(ImmutableArray<Outputs.AkamaiSignatureHeaderAuthenticationKeyResponse> akamaiSignatureHeaderAuthenticationKeyList) { AkamaiSignatureHeaderAuthenticationKeyList = akamaiSignatureHeaderAuthenticationKeyList; } } }
34.214286
158
0.751566
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Media/Outputs/AkamaiAccessControlResponse.cs
958
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Web.Inputs { /// <summary> /// The authentication client credentials of the custom Open ID Connect provider. /// </summary> public sealed class OpenIdConnectClientCredentialArgs : Pulumi.ResourceArgs { /// <summary> /// The app setting that contains the client secret for the custom Open ID Connect provider. /// </summary> [Input("clientSecretSettingName")] public Input<string>? ClientSecretSettingName { get; set; } /// <summary> /// The method that should be used to authenticate the user. /// </summary> [Input("method")] public Input<Pulumi.AzureNative.Web.ClientCredentialMethod>? Method { get; set; } public OpenIdConnectClientCredentialArgs() { } } }
31.971429
100
0.664879
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/Inputs/OpenIdConnectClientCredentialArgs.cs
1,119
C#
//----------------------------------------------------------------------- // <copyright file="HelpAttributeDrawer.cs" company="Google LLC"> // // Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System.Reflection; using UnityEditor; using UnityEngine; /// <summary> /// HelpAttribute drawer that draws a HelpBox below the property to display the help content. /// </summary> [CustomPropertyDrawer(typeof(HelpAttribute))] internal class HelpAttributeDrawer : PropertyDrawer { private const float _iconOffset = 40; /// <summary> /// Override Unity GetPropertyHeight to specify how tall the GUI for this field is /// in pixels. /// </summary> /// <param name="property">The SerializedProperty to make the custom GUI for.</param> /// <param name="label">The label of this property.</param> /// <returns>The height in pixels.</returns> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { if (IsHelpBoxEmpty()) { return GetOriginalPropertyHeight(property, label); } return GetOriginalPropertyHeight(property, label) + GetHelpAttributeHeight() + EditorStyles.helpBox.padding.vertical; } /// <summary> /// Override Unity OnGUI to make a custom GUI for the property with HelpAttribute. /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty to make the custom GUI for.</param> /// <param name="label">The label of this property.</param> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); Rect labelPosition = position; float labelHeight = base.GetPropertyHeight(property, label); float propertyHeight = GetOriginalPropertyHeight(property, label); labelPosition.height = labelHeight; // Draw property based on defualt Unity GUI behavior. string warningMessage = GetIncompatibleAttributeWarning(property); if (!string.IsNullOrEmpty(warningMessage)) { var warningContent = new GUIContent(warningMessage); EditorGUI.LabelField(labelPosition, label, warningContent); } else if (GetPropertyAttribute<TextAreaAttribute>() != null) { Rect textAreaPosition = position; textAreaPosition.y += labelHeight; textAreaPosition.height = propertyHeight - labelHeight; EditorGUI.LabelField(labelPosition, label); EditorGUI.BeginChangeCheck(); string text = EditorGUI.TextArea(textAreaPosition, property.stringValue); if (EditorGUI.EndChangeCheck()) { property.stringValue = text; } } else if (GetPropertyAttribute<MultilineAttribute>() != null) { Rect multilinePosition = position; multilinePosition.x += EditorGUIUtility.labelWidth; multilinePosition.width -= EditorGUIUtility.labelWidth; multilinePosition.height = propertyHeight; EditorGUI.LabelField(labelPosition, label); EditorGUI.BeginChangeCheck(); string text = EditorGUI.TextArea(multilinePosition, property.stringValue); if (EditorGUI.EndChangeCheck()) { property.stringValue = text; } } else if (GetPropertyAttribute<RangeAttribute>() != null) { var rangeAttribute = GetPropertyAttribute<RangeAttribute>(); if (property.propertyType == SerializedPropertyType.Integer) { EditorGUI.IntSlider(labelPosition, property, (int)rangeAttribute.min, (int)rangeAttribute.max, label); } else { EditorGUI.Slider(labelPosition, property, rangeAttribute.min, rangeAttribute.max, label); } } else { EditorGUI.PropertyField(labelPosition, property); } if (!IsHelpBoxEmpty()) { var helpBoxPosition = position; helpBoxPosition.y += propertyHeight + EditorStyles.helpBox.padding.top; helpBoxPosition.height = GetHelpAttributeHeight(); EditorGUI.HelpBox(helpBoxPosition, GetHelpAttribute().HelpMessage, (MessageType)GetHelpAttribute().MessageType); } EditorGUI.EndProperty(); } private HelpAttribute GetHelpAttribute() { return attribute as HelpAttribute; } private bool IsHelpBoxEmpty() { return string.IsNullOrEmpty(GetHelpAttribute().HelpMessage); } private bool IsIconVisible() { return GetHelpAttribute().MessageType != HelpAttribute.HelpMessageType.None; } private T GetPropertyAttribute<T>() where T : PropertyAttribute { var attributes = fieldInfo.GetCustomAttributes(typeof(T), true); return attributes != null && attributes.Length > 0 ? (T)attributes[0] : null; } private float GetOriginalPropertyHeight(SerializedProperty property, GUIContent label) { float labelHeight = base.GetPropertyHeight(property, label); string warningMessage = GetIncompatibleAttributeWarning(property); if (!string.IsNullOrEmpty(warningMessage)) { return labelHeight; } // Calculate property height for TextArea attribute. // TextArea is below property label. var textAreaAttribute = GetPropertyAttribute<TextAreaAttribute>(); if (textAreaAttribute != null) { var textAreaContent = new GUIContent(property.stringValue); var textAreaStyle = new GUIStyle(EditorStyles.textArea); var minHeight = (textAreaAttribute.minLines * textAreaStyle.lineHeight) + textAreaStyle.margin.vertical; var maxHeight = (textAreaAttribute.maxLines * textAreaStyle.lineHeight) + textAreaStyle.margin.vertical; var textAreaHeight = textAreaStyle.CalcHeight( textAreaContent, EditorGUIUtility.currentViewWidth); textAreaHeight = Mathf.Max(textAreaHeight, minHeight); textAreaHeight = Mathf.Min(textAreaHeight, maxHeight); return labelHeight + textAreaHeight; } // Calculate property height for Multiline attribute. // Multiline is on the same line of property label. var multilineAttribute = GetPropertyAttribute<MultilineAttribute>(); if (multilineAttribute != null) { var textFieldStyle = new GUIStyle(EditorStyles.textField); var multilineHeight = (textFieldStyle.lineHeight * multilineAttribute.lines) + textFieldStyle.margin.vertical; return Mathf.Max(labelHeight, multilineHeight); } return labelHeight; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "UnityRules.UnityStyleRules", "US1300:LinesMustBe100CharactersOrShorter", Justification = "Unity issue URL length > 100")] private float GetTextAreaWidth() { // Use reflection to determine contextWidth, to workaround the following Unity issue: // https://issuetracker.unity3d.com/issues/decoratordrawers-ongui-rect-has-a-different-width-compared-to-editorguiutility-dot-currentviewwidth float contextWidth = (float)typeof(EditorGUIUtility) .GetProperty("contextWidth", BindingFlags.NonPublic | BindingFlags.Static) .GetValue(null, null); float textAreaWidth = contextWidth - EditorStyles.inspectorDefaultMargins.padding.horizontal; // In Unity 2019.1 and later context width must be further reduced by up to 4px when the inspector // window is docked inside the main editor: // - 2px border when docked inside the editor with an adjacent window to the left // - 2px border when docked inside the editor with an adjacent window to the right #if UNITY_2019_1_OR_NEWER textAreaWidth -= 4; #endif return textAreaWidth; } private float GetHelpAttributeHeight() { float attributeHeight = 0; if (IsHelpBoxEmpty()) { return attributeHeight; } var content = new GUIContent(GetHelpAttribute().HelpMessage); var iconOffset = IsIconVisible() ? _iconOffset : 0; float textAreaWidth = GetTextAreaWidth(); // When HelpBox icon is visble, part of the width is occupied by the icon. attributeHeight = EditorStyles.helpBox.CalcHeight(content, textAreaWidth - iconOffset); // When HelpBox icon is visble, HelpAttributeHeight should as least // be the icon offset to prevent icon shrinking. attributeHeight = Mathf.Max(attributeHeight, iconOffset); return attributeHeight; } private string GetIncompatibleAttributeWarning(SerializedProperty property) { // Based on Unity default behavior, potential incompatible attributes have // following priorities: TextAreaAttribute > MultilineAttribute > RangeAttribute. // If higher priority exists, lower one will be ignored. if (GetPropertyAttribute<TextAreaAttribute>() != null) { return property.propertyType == SerializedPropertyType.String ? null : "Use TextArea with string."; } if (GetPropertyAttribute<MultilineAttribute>() != null) { return property.propertyType == SerializedPropertyType.String ? null : "Use Multiline with string."; } if (GetPropertyAttribute<RangeAttribute>() != null) { return property.propertyType == SerializedPropertyType.Float || property.propertyType == SerializedPropertyType.Integer ? null : "Use Range with float or int."; } return null; } } }
42.848708
154
0.602566
[ "Apache-2.0" ]
jiyu-park/arcore-unity-sdk
Assets/GoogleARCore/SDK/Scripts/Editor/HelpAttributeDrawer.cs
11,612
C#
using Newtonsoft.Json.Linq; using System; namespace SonarRepros { public class FalsePositiveSwitchNull { public bool IsEmpty(JToken token) { switch (token?.Type) { case JTokenType.Array: return !token.HasValues; case JTokenType.Integer: case JTokenType.Float: return 0 == (int) token; case JTokenType.String: return bool.FalseString.Equals((string) token, StringComparison.OrdinalIgnoreCase); case JTokenType.Boolean: return !(bool)token; case JTokenType.Null: case JTokenType.Undefined: case null: return true; default: return false; } } public bool NullOrEmpty(JToken token) { return token == null || token.Type == JTokenType.Null || (token.Type == JTokenType.Array && !token.HasValues) || (token.Type == JTokenType.Object && !token.HasValues) || (token.Type == JTokenType.String && string.IsNullOrWhiteSpace((string)token)); } } }
30.707317
103
0.505163
[ "MIT" ]
dotJEM/SonarQube-CSharp-Repros
SonarRepros/SonarRepros/FalsePositiveSwitchNull.cs
1,261
C#
using Newtonsoft.Json; namespace ArgentPonyWarcraftClient { /// <summary> /// A reference to a dungeon or raid. /// </summary> public class InstanceReference { /// <summary> /// Gets the key for the instance. /// </summary> [JsonProperty("key")] public Self Key { get; set; } /// <summary> /// Gets the name of the instance. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Gets the ID of the instance. /// </summary> [JsonProperty("id")] public long Id { get; set; } } }
22.758621
42
0.509091
[ "MIT" ]
willwolfram18/ArgentPonyWarcraftClient
src/ArgentPonyWarcraftClient/Models/GameDataApi/Journal/InstanceReference.cs
662
C#
using Prism.Mvvm; using X4_ComplexCalculator.DB; using X4_ComplexCalculator.DB.X4DB.Interfaces; namespace X4_ComplexCalculator.Main.WorkArea.UI.StationSummary.WorkForce.NeedWareInfo { /// <summary> /// 必要ウェア詳細情報1レコード分 /// </summary> class NeedWareInfoDetailsItem : BindableBase { #region メンバ /// <summary> /// 必要数量 /// </summary> private long _NeedAmount; /// <summary> /// 合計必要数量 /// </summary> private long _TotalNeedAmount; /// <summary> /// 生産数量 /// </summary> private long _ProductionAmount; #endregion #region プロパティ /// <summary> /// 種族 /// </summary> public IRace Race { get; } /// <summary> /// 労働方式 /// </summary> public string Method { get; } /// <summary> /// ウェアID /// </summary> public string WareID { get; } /// <summary> /// 必要ウェア名 /// </summary> public string WareName { get; } /// <summary> /// 必要数量 /// </summary> public long NeedAmount { get => _NeedAmount; set { if (SetProperty(ref _NeedAmount, value)) { RaisePropertyChanged(nameof(Diff)); } } } /// <summary> /// 合計必要数量 /// </summary> public long TotalNeedAmount { get => _TotalNeedAmount; set => SetProperty(ref _TotalNeedAmount, value); } /// <summary> /// 生産数量 /// </summary> public long ProductionAmount { get => _ProductionAmount; set { if (SetProperty(ref _ProductionAmount, value)) { RaisePropertyChanged(nameof(Diff)); } } } /// <summary> /// 差 /// </summary> public long Diff => ProductionAmount - NeedAmount; #endregion /// <summary> /// コンストラクタ /// </summary> /// <param name="race">種族</param> /// <param name="method">労働方式</param> /// <param name="wareID">ウェアID</param> /// <param name="needAmount">必要数量</param> /// <param name="productionAmount">生産数量</param> public NeedWareInfoDetailsItem(IRace race, string method, string wareID, long needAmount = 0, long productionAmount = 0) { Race = race; Method = method; WareID = wareID; WareName = X4Database.Instance.Ware.Get(wareID).Name; NeedAmount = needAmount; ProductionAmount = productionAmount; } } }
23.032
128
0.466134
[ "Apache-2.0" ]
Ocelot1210/X4_ComplexCalculator
X4_ComplexCalculator/Main/WorkArea/UI/StationSummary/WorkForce/NeedWareInfo/NeedWareInfoDetailsItem.cs
3,061
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ds.V20180523.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class SendVcodeRequest : AbstractModel { /// <summary> /// 模块名VerifyCode /// </summary> [JsonProperty("Module")] public string Module{ get; set; } /// <summary> /// 操作名SendVcode /// </summary> [JsonProperty("Operation")] public string Operation{ get; set; } /// <summary> /// 合同ID /// </summary> [JsonProperty("ContractResId")] public string ContractResId{ get; set; } /// <summary> /// 帐号ID /// </summary> [JsonProperty("AccountResId")] public string AccountResId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Module", this.Module); this.SetParamSimple(map, prefix + "Operation", this.Operation); this.SetParamSimple(map, prefix + "ContractResId", this.ContractResId); this.SetParamSimple(map, prefix + "AccountResId", this.AccountResId); } } }
30.430769
83
0.61729
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Ds/V20180523/Models/SendVcodeRequest.cs
1,998
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("10.SequenceOfGivenSum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10.SequenceOfGivenSum")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("82bcc0fb-8515-49ea-b5a4-e3d1bc67ef00")] // 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.243243
84
0.746996
[ "MIT" ]
niki-funky/Telerik_Academy
Programming/02.Csharp/02. Arrays/10.SequenceOfGivenSum/Properties/AssemblyInfo.cs
1,418
C#
using System; namespace DataAccess.Models { public class Employee : BaseMasterData { public Employee() { } } }
13.454545
42
0.560811
[ "MIT" ]
nattawutAmsri/DotnetCore-Docker-starter
DataAccess/Models/Employee.cs
150
C#
using System; using System.Collections.Generic; using System.Linq; namespace DocumentManager.DAL.Repositories.Contracts { public interface IGenericRepository<T> { IQueryable<T> All(); T GetById(Guid id); T GetById(long id); T GetById(int id); T GetById(string id); void Add(T entity); void AddRange(IEnumerable<T> entities); void Update(T entity); void Delete(T entity); void SaveChanges(); } }
16.6
52
0.608434
[ "MIT" ]
encounter12/DocumentManagementSystem
DocumentManager.DAL/Repositories/Contracts/IGenericRepository.cs
500
C#
using System.Threading.Tasks; using Elastic.Xunit.XunitPlumbing; using Nest; using Tests.Framework; using static Tests.Framework.UrlTester; namespace Tests.XPack.Watcher.StopWatcher { public class StopWatcherUrlTests : UrlTestsBase { [U] public override async Task Urls() { await POST("/_xpack/watcher/_stop") .Fluent(c => c.StopWatcher()) .Request(c => c.StopWatcher(new StopWatcherRequest())) .FluentAsync(c => c.StopWatcherAsync()) .RequestAsync(c => c.StopWatcherAsync(new StopWatcherRequest())) ; } } }
24.636364
68
0.721402
[ "Apache-2.0" ]
msarilar/elasticsearch-net
src/Tests/Tests/XPack/Watcher/StopWatcher/StopWatcherUrlTests.cs
544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Wollo.Entities.ViewModels; using Wollo.Base.LocalResource; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Wollo.Base.Entity; namespace Wollo.Entities.ViewModels { [DataContract] public class AdminIsuuePointsViewModel { [DataMember] public List<Issue_Points_Transfer_Master> IssuePointsTransferMaster { get; set; } [DataMember] public List<Topup_Status_Master> TopupStatusMaster { get; set; } [DataMember] public List<Issue_Withdrawel_Permission_Master> IssueWithdrawelPermissionMaster { get; set; } [DataMember] public CommonWordsViewModel CommonWordsViewModel { get; set; } [Display(Name = "AdminName", ResourceType = typeof(Resource))] public string admin_name { get; set; } [Display(Name = "Actions", ResourceType = typeof(Resource))] public string actions { get; set; } [Display(Name = "ChangeStatus", ResourceType = typeof(Resource))] public string change_status { get; set; } [Display(Name = "Cancel", ResourceType = typeof(Resource))] public string cancel { get; set; } [Display(Name = "Confirm", ResourceType = typeof(Resource))] public string confirm { get; set; } [Display(Name = "UserName", ResourceType = typeof(Resource))] public string user_name { get; set; } public AdminIsuuePointsViewModel() { IssuePointsTransferMaster = new List<Issue_Points_Transfer_Master>(); TopupStatusMaster = new List<Topup_Status_Master>(); } //******************************Label for properties*************************// [Display(Name = "DashboardPointIssueRequest", ResourceType = typeof(Resource))] public string dashboard_point_issue_request { get; set; } //******************************end of properties***************************// } }
38.054545
101
0.644052
[ "MIT" ]
umangsunarc/OTH
Wollo.Entities/ViewModels/AdminIsuuePointsViewModel.cs
2,095
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("MusicPlayer_WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MusicPlayer_WinForms")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("39078278-cdc5-437b-b263-1b057c06c159")] // 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")]
39.162162
85
0.729469
[ "MIT" ]
PhilShishov/MusicPlayer
MusicPlayer/Properties/AssemblyInfo.cs
1,452
C#
namespace EstimatorX.Core.Comparison; public class Delta<T> { public IReadOnlyCollection<T> Matched { get; set; } public IReadOnlyCollection<T> Created { get; set; } public IReadOnlyCollection<T> Deleted { get; set; } }
26
55
0.713675
[ "MIT" ]
loresoft/Estimatorx
src/EstimatorX.Core/Comparison/Delta.cs
236
C#
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; public class IKSandbox : ModuleRules { public IKSandbox(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay" }); } }
26.5
124
0.760108
[ "MIT" ]
monguri/IKSandbox
Source/IKSandbox/IKSandbox.Build.cs
371
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> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client { [JsonConverter(typeof(ClassNameDtoTypeConverter))] public class JobExecutionTrigger : IClassNameConvertible, IPropagatePropertyAccessPath { [JsonPropertyName("className")] public virtual string? ClassName => "JobExecutionTrigger"; public static JobExecutionTriggerCodeReviewClosed CodeReviewClosed(string reviewId) => new JobExecutionTriggerCodeReviewClosed(reviewId: reviewId); public static JobExecutionTriggerCodeReviewOpened CodeReviewOpened(string reviewId) => new JobExecutionTriggerCodeReviewOpened(reviewId: reviewId); public static JobExecutionTriggerGitBranchDeleted GitBranchDeleted(List<string> branches) => new JobExecutionTriggerGitBranchDeleted(branches: branches); public static JobExecutionTriggerGitPush GitPush(string commit) => new JobExecutionTriggerGitPush(commit: commit); public static JobExecutionTriggerManual Manual(CPrincipal principal) => new JobExecutionTriggerManual(principal: principal); public static JobExecutionTriggerSchedule Schedule() => new JobExecutionTriggerSchedule(); public JobExecutionTrigger() { } public virtual void SetAccessPath(string path, bool validateHasBeenSet) { } } }
36.181818
97
0.678811
[ "Apache-2.0" ]
PatrickRatzow/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Dtos/JobExecutionTrigger.generated.cs
2,388
C#
using System; using System.IO; using Cuemon.Text; namespace Cuemon.IO { /// <summary> /// Configuration options for <see cref="StreamReader"/>. /// </summary> public class AsyncStreamReaderOptions : AsyncStreamEncodingOptions { private int _bufferSize; /// <summary> /// Initializes a new instance of the <see cref="AsyncStreamReaderOptions"/> class. /// </summary> /// <remarks> /// The following table shows the initial property values for an instance of <see cref="AsyncStreamReaderOptions"/>. /// <list type="table"> /// <listheader> /// <term>Property</term> /// <description>Initial Value</description> /// </listheader> /// <item> /// <term><see cref="AsyncStreamEncodingOptions.Preamble"/></term> /// <description><see cref="EncodingOptions.DefaultPreambleSequence"/></description> /// </item> /// <item> /// <term><see cref="AsyncStreamEncodingOptions.Encoding"/></term> /// <description><see cref="EncodingOptions.DefaultEncoding"/></description> /// </item> /// <item> /// <term><see cref="BufferSize"/></term> /// <description><c>81920</c></description> /// </item> /// </list> /// </remarks> public AsyncStreamReaderOptions() { BufferSize = 81920; } /// <summary> /// Gets or sets the size of the buffer. /// </summary> /// <value>The size of the buffer.</value> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="value" /> is lower than or equal to 0. /// </exception> public int BufferSize { get => _bufferSize; set { Validator.ThrowIfLowerThanOrEqual(value, 0, nameof(value)); _bufferSize = value; } } } }
34.35
124
0.519165
[ "MIT" ]
gimlichael/Cuemon
src/Cuemon.IO/AsyncStreamReaderOptions.cs
2,063
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace WebViewDemo.WinPhone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new WebViewDemo.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
34.411765
94
0.680342
[ "Apache-2.0" ]
aliozgur/xamarin-forms-book-samples
Chapter16/WebViewDemo/WebViewDemo/WebViewDemo.WinPhone/MainPage.xaml.cs
1,755
C#
using System.Threading; using System.Threading.Tasks; namespace OzonEdu.MerchandiseApi.Domain.Contracts { public interface IUnitOfWork { ValueTask StartTransaction(CancellationToken token); Task SaveChangesAsync(CancellationToken cancellationToken); } }
24.333333
67
0.743151
[ "MIT" ]
Pyotr23/MerchApi
src/OzonEdu.MerchandiseApi.Domain/Contracts/IUnitOfWork.cs
294
C#
using System.Reflection; [assembly: AssemblyProduct("DonkerPONG")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © Wesley Donker 2016")] [assembly: AssemblyTrademark("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
24.625
63
0.751269
[ "MIT" ]
DonkerNET/pong
Source/GlobalAssemblyInfo.cs
397
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace RiskOfShame { public class ParticipatingPlayers : MonoBehaviour { void OnEnable() { var o = new GameObject(); var n = o.AddComponent<RoR2.PlayerCharacterMasterController>(); var m = o.AddComponent<RoR2.CharacterMaster>(); //m.alive = true; n.SetField("master", m); } void FixedUpdate() { //RoR2.Run.instance.SetField("participatingPlayerCount", 4); } } }
24.826087
75
0.577933
[ "MIT" ]
shalzuth/RiskOfShame
RiskOfShame/ParticipatingPlayers.cs
573
C#
using CompanyName.MyMeetings.Modules.Meetings.Application.Configuration.Commands; using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingCommentingConfigurations.GetMeetingCommentingConfiguration; using CompanyName.MyMeetings.Modules.Meetings.Domain.MeetingCommentingConfigurations; using CompanyName.MyMeetings.Modules.Meetings.Domain.MeetingGroups; using CompanyName.MyMeetings.Modules.Meetings.Domain.Meetings; using CompanyName.MyMeetings.Modules.Meetings.Domain.Members; namespace CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.AddCommentReply { internal class AddReplyToMeetingCommentCommandHandler : ICommandHandler<AddReplyToMeetingCommentCommand, Guid> { private readonly IMeetingCommentRepository _meetingCommentRepository; private readonly IMeetingRepository _meetingRepository; private readonly IMeetingGroupRepository _meetingGroupRepository; private readonly IMeetingCommentingConfigurationRepository _meetingCommentingConfigurationRepository; private readonly IMemberContext _memberContext; internal AddReplyToMeetingCommentCommandHandler(IMeetingCommentRepository meetingCommentRepository, IMeetingRepository meetingRepository, IMeetingGroupRepository meetingGroupRepository, IMeetingCommentingConfigurationRepository meetingCommentingConfigurationRepository, IMemberContext memberContext) { _meetingCommentRepository = meetingCommentRepository; _meetingRepository = meetingRepository; _meetingGroupRepository = meetingGroupRepository; _meetingCommentingConfigurationRepository = meetingCommentingConfigurationRepository; _memberContext = memberContext; } public async Task<Guid> Handle(AddReplyToMeetingCommentCommand command, CancellationToken cancellationToken) { var meetingComment = await _meetingCommentRepository.GetByIdAsync(command.InReplyToCommentId); if (meetingComment == null) { throw new InvalidCommandException(new List<string> { "To create reply the comment must exist." }); } var meeting = await _meetingRepository.GetByIdAsync(meetingComment.GetMeetingId()); var meetingGroup = await _meetingGroupRepository.GetByIdAsync(meeting.GetMeetingGroupId()); var meetingCommentingConfiguration = await _meetingCommentingConfigurationRepository.GetByMeetingIdAsync(meetingComment.GetMeetingId()); var replyToComment = meetingComment.Reply(_memberContext.MemberId, command.Reply, meetingGroup, meetingCommentingConfiguration); await _meetingCommentRepository.AddAsync(replyToComment); return replyToComment.Id; } } }
59.06383
307
0.791427
[ "MIT" ]
GamilYassin/modular-monolith-with-ddd
src/Modules/Meetings/Application/MeetingComments/AddMeetingCommentReply/AddReplyToMeetingCommentCommandHandler.cs
2,778
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Bindings; using osu.Framework.MathUtils; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Judgements; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Objects.Drawable; using osu.Game.Rulesets.Catch.Replays; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.UI { public class CatcherArea : Container { public const float CATCHER_SIZE = 106.75f; protected internal readonly Catcher MovableCatcher; public Func<CatchHitObject, DrawableHitObject<CatchHitObject>> CreateDrawableRepresentation; public Container ExplodingFruitTarget { set => MovableCatcher.ExplodingFruitTarget = value; } public CatcherArea(BeatmapDifficulty difficulty = null) { RelativeSizeAxes = Axes.X; Height = CATCHER_SIZE; Child = MovableCatcher = new Catcher(difficulty) { AdditiveTarget = this, }; } private DrawableCatchHitObject lastPlateableFruit; public void OnResult(DrawableCatchHitObject fruit, JudgementResult result) { void runAfterLoaded(Action action) { if (lastPlateableFruit == null) return; // this is required to make this run after the last caught fruit runs updateState() at least once. // TODO: find a better alternative if (lastPlateableFruit.IsLoaded) action(); else lastPlateableFruit.OnLoadComplete += _ => action(); } if (result.IsHit && fruit.CanBePlated) { var caughtFruit = (DrawableCatchHitObject)CreateDrawableRepresentation?.Invoke(fruit.HitObject); if (caughtFruit == null) return; caughtFruit.RelativePositionAxes = Axes.None; caughtFruit.Position = new Vector2(MovableCatcher.ToLocalSpace(fruit.ScreenSpaceDrawQuad.Centre).X - MovableCatcher.DrawSize.X / 2, 0); caughtFruit.IsOnPlate = true; caughtFruit.Anchor = Anchor.TopCentre; caughtFruit.Origin = Anchor.Centre; caughtFruit.Scale *= 0.7f; caughtFruit.LifetimeStart = caughtFruit.HitObject.StartTime; caughtFruit.LifetimeEnd = double.MaxValue; MovableCatcher.Add(caughtFruit); lastPlateableFruit = caughtFruit; if (!fruit.StaysOnPlate) runAfterLoaded(() => MovableCatcher.Explode(caughtFruit)); } if (fruit.HitObject.LastInCombo) { if (((CatchJudgement)result.Judgement).ShouldExplodeFor(result)) runAfterLoaded(() => MovableCatcher.Explode()); else MovableCatcher.Drop(); } } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); var state = (GetContainingInputManager().CurrentState as RulesetInputManagerInputState<CatchAction>)?.LastReplayState as CatchFramedReplayInputHandler.CatchReplayState; if (state?.CatcherX != null) MovableCatcher.X = state.CatcherX.Value; } public bool OnReleased(CatchAction action) => false; public bool AttemptCatch(CatchHitObject obj) => MovableCatcher.AttemptCatch(obj); public static float GetCatcherSize(BeatmapDifficulty difficulty) { return CATCHER_SIZE / CatchPlayfield.BASE_WIDTH * (1.0f - 0.7f * (difficulty.CircleSize - 5) / 5); } public class Catcher : Container, IKeyBindingHandler<CatchAction> { /// <summary> /// Width of the area that can be used to attempt catches during gameplay. /// </summary> internal float CatchWidth => CATCHER_SIZE * Math.Abs(Scale.X); private Container<DrawableHitObject> caughtFruit; public Container ExplodingFruitTarget; public Container AdditiveTarget; public Catcher(BeatmapDifficulty difficulty = null) { RelativePositionAxes = Axes.X; X = 0.5f; Origin = Anchor.TopCentre; Anchor = Anchor.TopLeft; Size = new Vector2(CATCHER_SIZE); if (difficulty != null) Scale = new Vector2(1.0f - 0.7f * (difficulty.CircleSize - 5) / 5); } [BackgroundDependencyLoader] private void load() { Children = new[] { caughtFruit = new Container<DrawableHitObject> { Anchor = Anchor.TopCentre, Origin = Anchor.BottomCentre, }, createCatcherSprite(), }; } private int currentDirection; private bool dashing; protected bool Dashing { get => dashing; set { if (value == dashing) return; dashing = value; Trail |= dashing; } } private bool trail; /// <summary> /// Activate or deactive the trail. Will be automatically deactivated when conditions to keep the trail displayed are no longer met. /// </summary> protected bool Trail { get => trail; set { if (value == trail) return; trail = value; if (Trail) beginTrail(); } } private void beginTrail() { Trail &= dashing || HyperDashing; Trail &= AdditiveTarget != null; if (!Trail) return; var additive = createCatcherSprite(); additive.Anchor = Anchor; additive.OriginPosition += new Vector2(DrawWidth / 2, 0); // also temporary to align sprite correctly. additive.Position = Position; additive.Scale = Scale; additive.Colour = HyperDashing ? Color4.Red : Color4.White; additive.RelativePositionAxes = RelativePositionAxes; additive.Blending = BlendingParameters.Additive; AdditiveTarget.Add(additive); additive.FadeTo(0.4f).FadeOut(800, Easing.OutQuint); additive.Expire(true); Scheduler.AddDelayed(beginTrail, HyperDashing ? 25 : 50); } private Drawable createCatcherSprite() => new CatcherSprite(); /// <summary> /// Add a caught fruit to the catcher's stack. /// </summary> /// <param name="fruit">The fruit that was caught.</param> public void Add(DrawableHitObject fruit) { float ourRadius = fruit.DrawSize.X / 2 * fruit.Scale.X; float theirRadius = 0; const float allowance = 6; while (caughtFruit.Any(f => f.LifetimeEnd == double.MaxValue && Vector2Extensions.Distance(f.Position, fruit.Position) < (ourRadius + (theirRadius = f.DrawSize.X / 2 * f.Scale.X)) / (allowance / 2))) { float diff = (ourRadius + theirRadius) / allowance; fruit.X += (RNG.NextSingle() - 0.5f) * 2 * diff; fruit.Y -= RNG.NextSingle() * diff; } fruit.X = Math.Clamp(fruit.X, -CATCHER_SIZE / 2, CATCHER_SIZE / 2); caughtFruit.Add(fruit); } /// <summary> /// Let the catcher attempt to catch a fruit. /// </summary> /// <param name="fruit">The fruit to catch.</param> /// <returns>Whether the catch is possible.</returns> public bool AttemptCatch(CatchHitObject fruit) { float halfCatchWidth = CatchWidth * 0.5f; // this stuff wil disappear once we move fruit to non-relative coordinate space in the future. var catchObjectPosition = fruit.X * CatchPlayfield.BASE_WIDTH; var catcherPosition = Position.X * CatchPlayfield.BASE_WIDTH; var validCatch = catchObjectPosition >= catcherPosition - halfCatchWidth && catchObjectPosition <= catcherPosition + halfCatchWidth; if (validCatch && fruit.HyperDash) { var target = fruit.HyperDashTarget; double timeDifference = target.StartTime - fruit.StartTime; double positionDifference = target.X * CatchPlayfield.BASE_WIDTH - catcherPosition; double velocity = positionDifference / Math.Max(1.0, timeDifference - 1000.0 / 60.0); SetHyperDashState(Math.Abs(velocity), target.X); } else { SetHyperDashState(); } return validCatch; } private double hyperDashModifier = 1; private int hyperDashDirection; private float hyperDashTargetPosition; /// <summary> /// Whether we are hyper-dashing or not. /// </summary> public bool HyperDashing => hyperDashModifier != 1; /// <summary> /// Set hyper-dash state. /// </summary> /// <param name="modifier">The speed multiplier. If this is less or equals to 1, this catcher will be non-hyper-dashing state.</param> /// <param name="targetPosition">When this catcher crosses this position, this catcher ends hyper-dashing.</param> public void SetHyperDashState(double modifier = 1, float targetPosition = -1) { const float hyper_dash_transition_length = 180; bool previouslyHyperDashing = HyperDashing; if (modifier <= 1 || X == targetPosition) { hyperDashModifier = 1; hyperDashDirection = 0; if (previouslyHyperDashing) { this.FadeColour(Color4.White, hyper_dash_transition_length, Easing.OutQuint); this.FadeTo(1, hyper_dash_transition_length, Easing.OutQuint); Trail &= Dashing; } } else { hyperDashModifier = modifier; hyperDashDirection = Math.Sign(targetPosition - X); hyperDashTargetPosition = targetPosition; if (!previouslyHyperDashing) { this.FadeColour(Color4.OrangeRed, hyper_dash_transition_length, Easing.OutQuint); this.FadeTo(0.2f, hyper_dash_transition_length, Easing.OutQuint); Trail = true; } } } public bool OnPressed(CatchAction action) { switch (action) { case CatchAction.MoveLeft: currentDirection--; return true; case CatchAction.MoveRight: currentDirection++; return true; case CatchAction.Dash: Dashing = true; return true; } return false; } public bool OnReleased(CatchAction action) { switch (action) { case CatchAction.MoveLeft: currentDirection++; return true; case CatchAction.MoveRight: currentDirection--; return true; case CatchAction.Dash: Dashing = false; return true; } return false; } /// <summary> /// The relative space to cover in 1 millisecond. based on 1 game pixel per millisecond as in osu-stable. /// </summary> public const double BASE_SPEED = 1.0 / 512; protected override void Update() { base.Update(); if (currentDirection == 0) return; var direction = Math.Sign(currentDirection); double dashModifier = Dashing ? 1 : 0.5; double speed = BASE_SPEED * dashModifier * hyperDashModifier; Scale = new Vector2(Math.Abs(Scale.X) * direction, Scale.Y); X = (float)Math.Clamp(X + direction * Clock.ElapsedFrameTime * speed, 0, 1); // Correct overshooting. if ((hyperDashDirection > 0 && hyperDashTargetPosition < X) || (hyperDashDirection < 0 && hyperDashTargetPosition > X)) { X = hyperDashTargetPosition; SetHyperDashState(); } } /// <summary> /// Drop any fruit off the plate. /// </summary> public void Drop() { var fruit = caughtFruit.ToArray(); foreach (var f in fruit) { if (ExplodingFruitTarget != null) { f.Anchor = Anchor.TopLeft; f.Position = caughtFruit.ToSpaceOfOtherDrawable(f.DrawPosition, ExplodingFruitTarget); caughtFruit.Remove(f); ExplodingFruitTarget.Add(f); } f.MoveToY(f.Y + 75, 750, Easing.InSine); f.FadeOut(750); // todo: this shouldn't exist once DrawableHitObject's ClearTransformsAfter overrides are repaired. f.LifetimeStart = Time.Current; f.Expire(); } } /// <summary> /// Explode any fruit off the plate. /// </summary> public void Explode() { foreach (var f in caughtFruit.ToArray()) Explode(f); } public void Explode(DrawableHitObject fruit) { var originalX = fruit.X * Scale.X; if (ExplodingFruitTarget != null) { fruit.Anchor = Anchor.TopLeft; fruit.Position = caughtFruit.ToSpaceOfOtherDrawable(fruit.DrawPosition, ExplodingFruitTarget); if (!caughtFruit.Remove(fruit)) // we may have already been removed by a previous operation (due to the weird OnLoadComplete scheduling). // this avoids a crash on potentially attempting to Add a fruit to ExplodingFruitTarget twice. return; ExplodingFruitTarget.Add(fruit); } fruit.ClearTransforms(); fruit.MoveToY(fruit.Y - 50, 250, Easing.OutSine).Then().MoveToY(fruit.Y + 50, 500, Easing.InSine); fruit.MoveToX(fruit.X + originalX * 6, 1000); fruit.FadeOut(750); // todo: this shouldn't exist once DrawableHitObject's ClearTransformsAfter overrides are repaired. fruit.LifetimeStart = Time.Current; fruit.Expire(); } } } }
37.100437
181
0.504061
[ "MIT" ]
Luxiono/osu
osu.Game.Rulesets.Catch/UI/CatcherArea.cs
16,537
C#
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using HousingTenant.Data.Service.Controllers; using HousingTenant.Data.Service.Models; using System.Net.Http; using Newtonsoft.Json; namespace HousingTenant.Data.Tests.Service.Controllers { [TestFixture] public class RequestCtrlTest { HttpClient client = new HttpClient { BaseAddress = new Uri ("https://housingtenantdata.azurewebsites.net/api/") }; [Test] public async void GetAllTest() { var requests = await client.GetAsync ("request", HttpCompletionOption.ResponseContentRead); var actual = JsonConvert.DeserializeObject<List<RequestDAO>> (requests.Content.ReadAsStringAsync ().Result); var expected = 0; Assert.IsTrue (actual.Count > expected); } } }
30.5
122
0.697892
[ "MIT" ]
revaturelabs/housing-tenant
HousingTenant.Data/HousingTenant.Data.Tests/Service/Controllers/RequestCtrlTest.cs
856
C#
/******************************************************************************* * * Copyright (c) 2014 Carlos Campo <carlos@campo.com.co> * * 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.Linq; using System.Net.Mime; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using StompNet; using StompNet.Models; using StompNet.Models.Frames; namespace Stomp.Net.Examples { partial class Program { /// <summary> /// This example shows the basic usage of the high level API of the library. /// /// Four messages are going to be sent to a queue and they will be read from the same queue. /// /// High level API features. /// - High level interfaces to ease the flow of the application: IStompConnector, /// IStompConnection, IStompMessage, IStompTransaction and IObserver&lt;IStompMessage&gt;. /// - Built upon an observer pattern. It can be used for reactive application approaches. /// - Message receipt confirmations and sequence number generation for frames are /// automatically handled by the library. /// - Thread-safety. /// - You would rarely have to interact with STOMP frames directly. /// /// </summary> public static async Task ExampleConnector() { //A connection to the TCP server socket is created. using (TcpClient tcpClient = new TcpClient(serverHostname, serverPort)) // IStompConnector is an IDisposable. A Stomp12Connector parametrized using the constructor. // Stomp12Connector receives as parameters: a stream, the name of the virtual host, // a username (optional) and a password (optional). // Stomp12Connector may also receive a parameter 'retryTimeout' (TimeSpan, by default: 30 seconds) // which is the time before a command is re-send if it does not receive a response. using (IStompConnector stompConnector = new Stomp12Connector(tcpClient.GetStream(), virtualHost, login, passcode)) { //Connect to the STOMP service. IStompConnection connection = await stompConnector.ConnectAsync(heartbeat: new Heartbeat(30000, 30000)); // Send a couple of messages with string content. for (int i = 1; i <= 2; i++) await connection.SendAsync( aQueueName, // Queue/Topic to send messages to. messageContent + " #" + i, // The message content. String (by default UTF-8 encoding is used). false, // Optional - Does a receipt confirmation is used in SEND command?. Default: false. null, // Optional - Collection of key-value pairs to include as non-standard headers. CancellationToken.None); // Optional - A CancellationToken. // Subscribe to receive messages. // Calling 'SubscribeAsync' returns an IDisposable which can be called to unsubscribe. // It is not mandatory to dispose the subscription manually. It will be disposed when // the stompConnector is disposed or if an exception in the stream occurs. IDisposable subscription = await connection.SubscribeAsync( new ExampleObserver(), // An observer. A class implementing IObserver<IStompMessage>. aQueueName, // Queue/Topic to observe from. StompAckValues.AckAutoValue, // Optional - Ack mode: "auto", "client", "client-individual". Default: "auto". false, // Optional - Does a receipt confirmation is used in SUBSCRIBE command?. Default: false. null, // Optional - Collection of key-value pairs to include as non-standard headers. CancellationToken.None); // Optional - A CancellationToken. // Messages with byte content can also be send. byte[] aByteMessageContent = new byte [] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Send two more messages using SendAsync byte version. for (int i = 0; i < 2; i++ ) await connection.SendAsync( aQueueName, // Queue/Topic to send messages to. aByteMessageContent, // The message content. MediaTypeNames.Application.Octet, // Message content type. true, // Optional - Does a receipt confirmation is used in SEND command?. Default: false. // In this case, a confirmation receipt will be awaited before the task is completed. null, // Optional - Collection of key-value pairs to include as non-standard headers. CancellationToken.None); // Optional - A CancellationToken. // Wait some time for the messages to be received. await Task.Delay(500); // Unsubscribe. subscription.Dispose(); // Disconnect. await connection.DisconnectAsync(); } } /// <summary> /// Class observer of STOMP incoming messages. /// </summary> class ExampleObserver : IObserver<IStompMessage> { private string _name; public ExampleObserver(string name = null) { _name = name ?? "OBSERVER"; } /// <summary> /// Each message from the subscription is processed on this method. /// </summary> public void OnNext(IStompMessage message) { Console.WriteLine("RECEIVED ON '{0}'", _name); if(message.ContentType == MediaTypeNames.Application.Octet) Console.WriteLine("Message Content (HEX): " + string.Join(" ", message.Content.Select(b => b.ToString("X2")))); else Console.WriteLine("Message Content: " + message.GetContentAsString()); Console.WriteLine(); // If the message is acknowledgeable then acknowledge. if (message.IsAcknowledgeable) message.Acknowledge(); // This command may receive as parameters: a receipt flag, extra-headers and/or a cancellation token. // There is also message.AcknowledgeNegative(); } /// <summary> /// Any error on the input stream will come through this method. /// If an ERROR frame is received, this method will also be called /// with a ErrorFrameException as parameter. /// /// If this method is invoked, no more messages will be received in /// this subscriptions. /// </summary> public void OnError(Exception error) { Console.WriteLine("EXCEPTION ON '{0}'", _name); Console.WriteLine(error.Message); Console.WriteLine(); } /// <summary> /// This method is invoked when unsubscribing. /// /// If this method is invoked, no more messages will be received in /// this subscriptions. /// </summary> public void OnCompleted() { Console.WriteLine("OBSERVING ON '{0}' IS COMPLETED.", _name); Console.WriteLine(); } } } }
50.374269
145
0.54899
[ "Apache-2.0" ]
Sbou/StompNet
StompNet.Examples/1.ExampleConnector.cs
8,616
C#
// <copyright file="RemoteTouchScreen.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2011 Software Freedom Conservancy // // 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> using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium.Interactions.Internal; namespace OpenQA.Selenium.Remote { /// <summary> /// Defines the interface through which the user can execute advanced touch screen interactions. /// </summary> public class RemoteTouchScreen : ITouchScreen { private RemoteWebDriver driver; /// <summary> /// Initializes a new instance of the <see cref="RemoteTouchScreen"/> class. /// </summary> /// <param name="driver">The <see cref="RemoteWebDriver"/> for which the touch screen will be managed.</param> public RemoteTouchScreen(RemoteWebDriver driver) { this.driver = driver; } /// <summary> /// Allows the execution of single tap on the screen, analogous to click using a Mouse. /// </summary> /// <param name="where">The <see cref="ICoordinates"/> object representing the location on the screen, /// usually an <see cref="IWebElement"/>.</param> public void SingleTap(ICoordinates where) { if (where == null) { throw new ArgumentNullException("where", "where coordinates cannot be null"); } string elementId = where.AuxiliaryLocator.ToString(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("element", elementId); this.driver.InternalExecute(DriverCommand.TouchSingleTap, parameters); } /// <summary> /// Allows the execution of the gesture 'down' on the screen. It is typically the first of a /// sequence of touch gestures. /// </summary> /// <param name="locationX">The x coordinate relative to the view port.</param> /// <param name="locationY">The y coordinate relative to the view port.</param> public void Down(int locationX, int locationY) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("x", locationX); parameters.Add("y", locationY); this.driver.InternalExecute(DriverCommand.TouchPress, parameters); } /// <summary> /// Allows the execution of the gesture 'up' on the screen. It is typically the last of a /// sequence of touch gestures. /// </summary> /// <param name="locationX">The x coordinate relative to the view port.</param> /// <param name="locationY">The y coordinate relative to the view port.</param> public void Up(int locationX, int locationY) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("x", locationX); parameters.Add("y", locationY); this.driver.InternalExecute(DriverCommand.TouchRelease, parameters); } /// <summary> /// Allows the execution of the gesture 'move' on the screen. /// </summary> /// <param name="locationX">The x coordinate relative to the view port.</param> /// <param name="locationY">The y coordinate relative to the view port.</param> public void Move(int locationX, int locationY) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("x", locationX); parameters.Add("y", locationY); this.driver.InternalExecute(DriverCommand.TouchMove, parameters); } /// <summary> /// Creates a scroll gesture that starts on a particular screen location. /// </summary> /// <param name="where">The <see cref="ICoordinates"/> object representing the location on the screen /// where the scroll starts, usually an <see cref="IWebElement"/>.</param> /// <param name="offsetX">The x coordinate relative to the view port.</param> /// <param name="offsetY">The y coordinate relative to the view port.</param> public void Scroll(ICoordinates where, int offsetX, int offsetY) { if (where == null) { throw new ArgumentNullException("where", "where coordinates cannot be null"); } string elementId = where.AuxiliaryLocator.ToString(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("element", elementId); parameters.Add("xoffset", offsetX); parameters.Add("yoffset", offsetY); this.driver.InternalExecute(DriverCommand.TouchScroll, parameters); } /// <summary> /// Creates a scroll gesture for a particular x and y offset. /// </summary> /// <param name="offsetX">The horizontal offset relative to the view port.</param> /// <param name="offsetY">The vertical offset relative to the view port.</param> public void Scroll(int offsetX, int offsetY) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("xoffset", offsetX); parameters.Add("yoffset", offsetY); this.driver.InternalExecute(DriverCommand.TouchScroll, parameters); } /// <summary> /// Allows the execution of double tap on the screen, analogous to click using a Mouse. /// </summary> /// <param name="where">The <see cref="ICoordinates"/> object representing the location on the screen, /// usually an <see cref="IWebElement"/>.</param> public void DoubleTap(ICoordinates where) { if (where == null) { throw new ArgumentNullException("where", "where coordinates cannot be null"); } string elementId = where.AuxiliaryLocator.ToString(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("element", elementId); this.driver.InternalExecute(DriverCommand.TouchDoubleTap, parameters); } /// <summary> /// Allows the execution of a long press gesture on the screen. /// </summary> /// <param name="where">The <see cref="ICoordinates"/> object representing the location on the screen, /// usually an <see cref="IWebElement"/>.</param> public void LongPress(ICoordinates where) { if (where == null) { throw new ArgumentNullException("where", "where coordinates cannot be null"); } string elementId = where.AuxiliaryLocator.ToString(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("element", elementId); this.driver.InternalExecute(DriverCommand.TouchLongPress, parameters); } /// <summary> /// Creates a flick gesture for the current view. /// </summary> /// <param name="speedX">The horizontal speed in pixels per second.</param> /// <param name="speedY">The vertical speed in pixels per second.</param> public void Flick(int speedX, int speedY) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("xSpeed", speedX); parameters.Add("ySpeed", speedY); this.driver.InternalExecute(DriverCommand.TouchFlick, parameters); } /// <summary> /// Creates a flick gesture for the current view starting at a specific location. /// </summary> /// <param name="where">The <see cref="ICoordinates"/> object representing the location on the screen /// where the scroll starts, usually an <see cref="IWebElement"/>.</param> /// <param name="offsetX">The x offset relative to the viewport.</param> /// <param name="offsetY">The y offset relative to the viewport.</param> /// <param name="speed">The speed in pixels per second.</param> public void Flick(Interactions.Internal.ICoordinates where, int offsetX, int offsetY, int speed) { if (where == null) { throw new ArgumentNullException("where", "where coordinates cannot be null"); } string elementId = where.AuxiliaryLocator.ToString(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("element", elementId); parameters.Add("xoffset", offsetX); parameters.Add("yoffset", offsetY); parameters.Add("speed", speed); this.driver.InternalExecute(DriverCommand.TouchFlick, parameters); } } }
45.614286
118
0.620733
[ "Apache-2.0" ]
aoluwase-ford/lummyare-lummy
dotnet/src/WebDriver/Remote/RemoteTouchScreen.cs
9,581
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("DayOfWeek")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DayOfWeek")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("94ff3a16-5df0-4089-9362-846c4a72b364")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.459459
84
0.746753
[ "MIT" ]
dragobaltov/Programming-Basics-And-Fundamentals
DayOfWeek/DayOfWeek/Properties/AssemblyInfo.cs
1,389
C#
using NUnit.Framework; namespace java.util { [TestFixture] public class ListTest { [Test] public void EqualsTestLinkedList() { List<ListItemForTest> list_1 = new LinkedList<ListItemForTest>(); List<ListItemForTest> list_2 = new LinkedList<ListItemForTest>(); EqualsTestHelper(list_1, list_2); } private void EqualsTestHelper(List<ListItemForTest> list_1, List<ListItemForTest> list_2) { list_1.add(new ListItemForTest("A")); list_1.add(new ListItemForTest("B")); list_1.add(new ListItemForTest("C")); list_2.add(new ListItemForTest("A")); list_2.add(new ListItemForTest("B")); list_2.add(new ListItemForTest("C")); Assert.AreEqual(list_1, list_2); } } public class ListItemForTest { private readonly string str; public ListItemForTest(string str) { this.str = str; } public override bool Equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (obj is ListItemForTest) { ListItemForTest other = (ListItemForTest) obj; return this.str == other.str; } return false; } public override int GetHashCode() { return str.GetHashCode(); } } }
26.472727
97
0.554258
[ "MIT" ]
TomasJohansson/adapters-shortest-paths-dotnet
Programmerare.ShortestPaths.Adaptees.Common.Test/java.util/ListTest.cs
1,458
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NBitcoin.BuilderExtensions; using NBitcoin.Crypto; using NBitcoin.OpenAsset; using NBitcoin.Policy; using NBitcoin.Stealth; using Builder = System.Func<NBitcoin.TransactionBuilder.TransactionBuildingContext, NBitcoin.IMoney>; namespace NBitcoin { [Flags] public enum ChangeType : int { All = 3, Colored = 1, Uncolored = 2 } public interface ICoinSelector { IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target); } /// <summary> /// A coin selector that selects all the coins passed by default. /// Useful when a user wants a specific set of coins to be spent. /// </summary> public class AllCoinsSelector : ICoinSelector { public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target) { return coins; } } /// <summary> /// Algorithm implemented by bitcoin core https://github.com/bitcoin/bitcoin/blob/master/src/wallet.cpp#L1276 /// Minimize the change /// </summary> public class DefaultCoinSelector : ICoinSelector { public DefaultCoinSelector() { } private Random _Rand = new Random(); public DefaultCoinSelector(int seed) { this._Rand = new Random(seed); } /// <summary> /// Select all coins belonging to same scriptPubKey together to protect privacy. (Default: true) /// </summary> public bool GroupByScriptPubKey { get; set; } = true; #region ICoinSelector Members public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target) { IMoney zero = target.Sub(target); var result = new List<ICoin>(); IMoney total = zero; if (target.CompareTo(zero) == 0) return result; var orderedCoinGroups = coins.GroupBy(c => this.GroupByScriptPubKey ? c.TxOut.ScriptPubKey : new Key().ScriptPubKey) .Select(scriptPubKeyCoins => new { Amount = scriptPubKeyCoins.Select(c => c.Amount).Sum(zero), Coins = scriptPubKeyCoins.ToList() }).OrderBy(c => c.Amount); var targetCoin = orderedCoinGroups .FirstOrDefault(c => c.Amount.CompareTo(target) == 0); //If any of your UTXO² matches the Target¹ it will be used. if (targetCoin != null) return targetCoin.Coins; foreach (var coinGroup in orderedCoinGroups) { if (coinGroup.Amount.CompareTo(target) == -1 && total.CompareTo(target) == -1) { total = total.Add(coinGroup.Amount); result.AddRange(coinGroup.Coins); //If the "sum of all your UTXO smaller than the Target" happens to match the Target, they will be used. (This is the case if you sweep a complete wallet.) if (total.CompareTo(target) == 0) return result; } else { if (total.CompareTo(target) == -1 && coinGroup.Amount.CompareTo(target) == 1) { //If the "sum of all your UTXO smaller than the Target" doesn't surpass the target, the smallest UTXO greater than your Target will be used. return coinGroup.Coins; } else { // Else Bitcoin Core does 1000 rounds of randomly combining unspent transaction outputs until their sum is greater than or equal to the Target. If it happens to find an exact match, it stops early and uses that. // Otherwise it finally settles for the minimum of // the smallest UTXO greater than the Target // the smallest combination of UTXO it discovered in Step 4. var allCoins = orderedCoinGroups.ToArray(); IMoney minTotal = null; for (int _ = 0; _ < 1000; _++) { var selection = new List<ICoin>(); Utils.Shuffle(allCoins, this._Rand); total = zero; for (int i = 0; i < allCoins.Length; i++) { selection.AddRange(allCoins[i].Coins); total = total.Add(allCoins[i].Amount); if (total.CompareTo(target) == 0) return selection; if (total.CompareTo(target) == 1) break; } if (total.CompareTo(target) == -1) { return null; } if (minTotal == null || total.CompareTo(minTotal) == -1) { minTotal = total; result = selection; } } if (minTotal != null) { total = minTotal; } break; } } } if (total.CompareTo(target) == -1) return null; // optimize the set of used coins, removing unnecessary small inputs List<ICoin> sortedUsedCoins = result.OrderBy(c => c.Amount).ToList(); IMoney excess = total.Sub(target); for (int i = 0; i < sortedUsedCoins.Count; i++) { // if the smallest coin in the set is smaller or equal to the difference between the excess of // the total and its amount, we can safely remove it ICoin coin = sortedUsedCoins[i]; if (coin.Amount.CompareTo(excess) <= 0) { result.Remove(coin); excess = excess.Sub(coin.Amount); } if (excess.CompareTo(zero) <= 0) break; } return result; } #endregion } /// <summary> /// Exception thrown when not enough funds are present for verifying or building a transaction /// </summary> public class NotEnoughFundsException : Exception { public NotEnoughFundsException(string message, string group, IMoney missing) : base(BuildMessage(message, group, missing)) { this.Missing = missing; this.Group = group; } private static string BuildMessage(string message, string group, IMoney missing) { var builder = new StringBuilder(); builder.Append(message); if (group != null) builder.Append(" in group " + group); if (missing != null) builder.Append(" with missing amount " + missing); return builder.ToString(); } public NotEnoughFundsException(string message, Exception inner) : base(message, inner) { } /// <summary> /// The group name who is missing the funds /// </summary> public string Group { get; set; } /// <summary> /// Amount of Money missing /// </summary> public IMoney Missing { get; set; } } /// <summary> /// A class for building and signing all sort of transactions easily (http://www.codeproject.com/Articles/835098/NBitcoin-Build-Them-All) /// </summary> public class TransactionBuilder { internal class TransactionBuilderSigner : ISigner { private ICoin coin; private SigHash sigHash; private IndexedTxIn txIn; private TransactionBuilder builder; public TransactionBuilderSigner(TransactionBuilder builder, ICoin coin, SigHash sigHash, IndexedTxIn txIn) { this.builder = builder; this.coin = coin; this.sigHash = sigHash; this.txIn = txIn; } #region ISigner Members public TransactionSignature Sign(Key key) { return this.txIn.Sign(this.builder.Network, key, this.coin, this.sigHash); } #endregion } internal class TransactionBuilderKeyRepository : IKeyRepository { private TransactionSigningContext _Ctx; private TransactionBuilder _TxBuilder; public TransactionBuilderKeyRepository(TransactionBuilder txBuilder, TransactionSigningContext ctx) { this._Ctx = ctx; this._TxBuilder = txBuilder; } #region IKeyRepository Members public Key FindKey(Script scriptPubkey) { return this._TxBuilder.FindKey(this._Ctx, scriptPubkey); } #endregion } private class KnownSignatureSigner : ISigner, IKeyRepository { private ICoin coin; private SigHash sigHash; private IndexedTxIn txIn; private List<Tuple<PubKey, ECDSASignature>> _KnownSignatures; private Dictionary<KeyId, ECDSASignature> _VerifiedSignatures = new Dictionary<KeyId, ECDSASignature>(); private Dictionary<uint256, PubKey> _DummyToRealKey = new Dictionary<uint256, PubKey>(); private TransactionBuilder builder; public KnownSignatureSigner(TransactionBuilder builder, List<Tuple<PubKey, ECDSASignature>> _KnownSignatures, ICoin coin, SigHash sigHash, IndexedTxIn txIn) { this.builder = builder; this._KnownSignatures = _KnownSignatures; this.coin = coin; this.sigHash = sigHash; this.txIn = txIn; } public Key FindKey(Script scriptPubKey) { foreach (Tuple<PubKey, ECDSASignature> tv in this._KnownSignatures.Where(tv => IsCompatibleKey(tv.Item1, scriptPubKey))) { uint256 hash = this.txIn.GetSignatureHash(this.builder.Network, this.coin, this.sigHash); if (tv.Item1.Verify(hash, tv.Item2)) { var key = new Key(); this._DummyToRealKey.Add(Hashes.Hash256(key.PubKey.ToBytes()), tv.Item1); this._VerifiedSignatures.AddOrReplace(key.PubKey.Hash, tv.Item2); return key; } } return null; } public Script ReplaceDummyKeys(Script script) { List<Op> ops = script.ToOps().ToList(); var result = new List<Op>(); foreach (Op op in ops) { uint256 h = Hashes.Hash256(op.PushData); PubKey real; if (this._DummyToRealKey.TryGetValue(h, out real)) result.Add(Op.GetPushOp(real.ToBytes())); else result.Add(op); } return new Script(result.ToArray()); } public TransactionSignature Sign(Key key) { return new TransactionSignature(this._VerifiedSignatures[key.PubKey.Hash], this.sigHash); } } internal class TransactionSigningContext { public TransactionSigningContext(TransactionBuilder builder, Transaction transaction) { this.Builder = builder; this.Transaction = transaction; } public Transaction Transaction { get; set; } public TransactionBuilder Builder { get; set; } private readonly List<Key> _AdditionalKeys = new List<Key>(); public List<Key> AdditionalKeys { get { return this._AdditionalKeys; } } public SigHash SigHash { get; set; } } internal class TransactionBuildingContext { public TransactionBuildingContext(TransactionBuilder builder) { this.Builder = builder; this.Transaction = builder.Network.CreateTransaction(); this.AdditionalFees = Money.Zero; } public BuilderGroup Group { get; set; } private readonly List<ICoin> _ConsumedCoins = new List<ICoin>(); public List<ICoin> ConsumedCoins { get { return this._ConsumedCoins; } } public TransactionBuilder Builder { get; set; } public Transaction Transaction { get; set; } public Money AdditionalFees { get; set; } private readonly List<Builder> _AdditionalBuilders = new List<Builder>(); public List<Builder> AdditionalBuilders { get { return this._AdditionalBuilders; } } private ColorMarker _Marker; public ColorMarker GetColorMarker(bool issuance) { if (this._Marker == null) this._Marker = new ColorMarker(); if (!issuance) EnsureMarkerInserted(); return this._Marker; } private TxOut EnsureMarkerInserted() { uint position; TxIn dummy = this.Transaction.AddInput(new TxIn(new OutPoint(new uint256(1), 0))); //Since a transaction without input will be considered without marker, insert a dummy try { if (ColorMarker.Get(this.Transaction, out position) != null) return this.Transaction.Outputs[position]; } finally { this.Transaction.Inputs.Remove(dummy); } TxOut txout = this.Transaction.AddOutput(new TxOut() { ScriptPubKey = new ColorMarker().GetScript() }); txout.Value = Money.Zero; return txout; } public void Finish() { if (this._Marker != null) { TxOut txout = EnsureMarkerInserted(); txout.ScriptPubKey = this._Marker.GetScript(); } } public IssuanceCoin IssuanceCoin { get; set; } public IMoney ChangeAmount { get; set; } public TransactionBuildingContext CreateMemento() { var memento = new TransactionBuildingContext(this.Builder); memento.RestoreMemento(this); return memento; } public void RestoreMemento(TransactionBuildingContext memento) { this._Marker = memento._Marker == null ? null : new ColorMarker(memento._Marker.GetScript()); this.Transaction = memento.Builder.Network.CreateTransaction(memento.Transaction.ToBytes()); this.AdditionalFees = memento.AdditionalFees; } public bool NonFinalSequenceSet { get; set; } public IMoney CoverOnly { get; set; } public IMoney Dust { get; set; } public ChangeType ChangeType { get; set; } } internal class BuilderGroup { private TransactionBuilder _Parent; public BuilderGroup(TransactionBuilder parent) { this._Parent = parent; this.FeeWeight = 1.0m; this.Builders.Add(SetChange); } private IMoney SetChange(TransactionBuildingContext ctx) { var changeAmount = (Money)ctx.ChangeAmount; if (changeAmount.Satoshi == 0) return Money.Zero; ctx.Transaction.AddOutput(new TxOut(changeAmount, ctx.Group.ChangeScript[(int)ChangeType.Uncolored])); return changeAmount; } internal List<Builder> Builders = new List<Builder>(); internal Dictionary<OutPoint, ICoin> Coins = new Dictionary<OutPoint, ICoin>(); internal List<Builder> IssuanceBuilders = new List<Builder>(); internal Dictionary<AssetId, List<Builder>> BuildersByAsset = new Dictionary<AssetId, List<Builder>>(); internal Script[] ChangeScript = new Script[3]; internal void Shuffle() { Shuffle(this.Builders); foreach (KeyValuePair<AssetId, List<Builder>> builders in this.BuildersByAsset) Shuffle(builders.Value); Shuffle(this.IssuanceBuilders); } private void Shuffle(List<Builder> builders) { Utils.Shuffle(builders, this._Parent._Rand); } public Money CoverOnly { get; set; } public string Name { get; set; } public decimal FeeWeight { get; set; } } private List<BuilderGroup> _BuilderGroups = new List<BuilderGroup>(); private BuilderGroup _CurrentGroup = null; internal BuilderGroup CurrentGroup { get { if (this._CurrentGroup == null) { this._CurrentGroup = new BuilderGroup(this); this._BuilderGroups.Add(this._CurrentGroup); } return this._CurrentGroup; } } public TransactionBuilder(Network network) { this.Network = network; this._Rand = new Random(); this.CoinSelector = new DefaultCoinSelector(); this.StandardTransactionPolicy = new StandardTransactionPolicy(this.Network); this.DustPrevention = true; InitExtensions(); } private void InitExtensions() { this.Extensions.Add(new P2PKHBuilderExtension()); this.Extensions.Add(new P2MultiSigBuilderExtension()); this.Extensions.Add(new P2PKBuilderExtension()); this.Extensions.Add(new OPTrueExtension()); } internal Random _Rand; public TransactionBuilder(int seed, Network network) { this.Network = network; this._Rand = new Random(seed); this.CoinSelector = new DefaultCoinSelector(seed); this.StandardTransactionPolicy = new StandardTransactionPolicy(this.Network); this.DustPrevention = true; InitExtensions(); } public ICoinSelector CoinSelector { get; set; } /// <summary> /// This field should be mandatory in the constructor. /// </summary> public Network Network { get; private set; } /// <summary> /// Will transform transfers below Dust, so the transaction get correctly relayed by the network. /// If true, it will remove any TxOut below Dust, so the transaction get correctly relayed by the network. (Default: true) /// </summary> public bool DustPrevention { get; set; } /// <summary> /// If true, the TransactionBuilder will not select coins whose fee to spend is higher than its value. (Default: true) /// The cost of spending a coin is based on the <see cref="FilterUneconomicalCoinsRate"/>. /// </summary> public bool FilterUneconomicalCoins { get; set; } = true; /// <summary> /// If <see cref="FilterUneconomicalCoins"/> is true, this rate is used to know if an output is economical. /// This property is set automatically when calling <see cref="SendEstimatedFees(FeeRate)"/> or <see cref="SendEstimatedFeesSplit(FeeRate)"/>. /// </summary> public FeeRate FilterUneconomicalCoinsRate { get; set; } /// <summary> /// A callback used by the TransactionBuilder when it does not find the coin for an input /// </summary> public Func<OutPoint, ICoin> CoinFinder { get; set; } /// <summary> /// A callback used by the TransactionBuilder when it does not find the key for a scriptPubKey /// </summary> public Func<Script, Key> KeyFinder { get; set; } private LockTime? _LockTime; public TransactionBuilder SetLockTime(LockTime lockTime) { this._LockTime = lockTime; return this; } private uint? _TimeStamp; public TransactionBuilder SetTimeStamp(uint timeStamp) { this._TimeStamp = timeStamp; return this; } private List<Key> _Keys = new List<Key>(); public TransactionBuilder AddKeys(params ISecret[] keys) { AddKeys(keys.Select(k => k.PrivateKey).ToArray()); return this; } public TransactionBuilder AddKeys(params Key[] keys) { this._Keys.AddRange(keys); foreach (Key k in keys) { AddKnownRedeems(k.PubKey.ScriptPubKey); AddKnownRedeems(k.PubKey.WitHash.ScriptPubKey); AddKnownRedeems(k.PubKey.Hash.ScriptPubKey); } return this; } public TransactionBuilder AddKnownSignature(PubKey pubKey, TransactionSignature signature) { if (pubKey == null) throw new ArgumentNullException("pubKey"); if (signature == null) throw new ArgumentNullException("signature"); this._KnownSignatures.Add(Tuple.Create(pubKey, signature.Signature)); return this; } public TransactionBuilder AddKnownSignature(PubKey pubKey, ECDSASignature signature) { if (pubKey == null) throw new ArgumentNullException("pubKey"); if (signature == null) throw new ArgumentNullException("signature"); this._KnownSignatures.Add(Tuple.Create(pubKey, signature)); return this; } public TransactionBuilder AddCoins(params ICoin[] coins) { return AddCoins((IEnumerable<ICoin>)coins); } public TransactionBuilder AddCoins(IEnumerable<ICoin> coins) { foreach (ICoin coin in coins) { this.CurrentGroup.Coins.AddOrReplace(coin.Outpoint, coin); } return this; } /// <summary> /// Set the name of this group (group are separated by call to Then()) /// </summary> /// <param name="groupName">Name of the group</param> /// <returns></returns> public TransactionBuilder SetGroupName(string groupName) { this.CurrentGroup.Name = groupName; return this; } /// <summary> /// Send bitcoins to a destination /// </summary> /// <param name="destination">The destination</param> /// <param name="amount">The amount</param> /// <returns></returns> public TransactionBuilder Send(IDestination destination, Money amount) { return Send(destination.ScriptPubKey, amount); } private readonly static TxNullDataTemplate _OpReturnTemplate = new TxNullDataTemplate(1024 * 1024); /// <summary> /// Send bitcoins to a destination /// </summary> /// <param name="scriptPubKey">The destination</param> /// <param name="amount">The amount</param> /// <returns></returns> public TransactionBuilder Send(Script scriptPubKey, Money amount) { if (amount < Money.Zero) throw new ArgumentOutOfRangeException("amount", "amount can't be negative"); this._LastSendBuilder = null; //If the amount is dust, we don't want the fee to be paid by the previous Send if (this.DustPrevention && amount < GetDust(scriptPubKey) && !_OpReturnTemplate.CheckScriptPubKey(scriptPubKey)) { SendFees(amount); return this; } var builder = new SendBuilder(new TxOut(amount, scriptPubKey)); this.CurrentGroup.Builders.Add(builder.Build); this._LastSendBuilder = builder; return this; } private SendBuilder _LastSendBuilder; private SendBuilder _SubstractFeeBuilder; private class SendBuilder { internal TxOut _TxOut; public SendBuilder(TxOut txout) { this._TxOut = txout; } public Money Build(TransactionBuildingContext ctx) { ctx.Transaction.Outputs.Add(this._TxOut); return this._TxOut.Value; } } /// <summary> /// Will subtract fees from the previous TxOut added by the last TransactionBuidler.Send() call /// </summary> /// <returns></returns> public TransactionBuilder SubtractFees() { if (this._LastSendBuilder == null) throw new InvalidOperationException("No call to TransactionBuilder.Send has been done which can support the fees"); this._SubstractFeeBuilder = this._LastSendBuilder; return this; } /// <summary> /// Send a money amount to the destination /// </summary> /// <param name="destination">The destination</param> /// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param> /// <returns></returns> /// <exception cref="System.NotSupportedException">The coin type is not supported</exception> public TransactionBuilder Send(IDestination destination, IMoney amount) { return Send(destination.ScriptPubKey, amount); } /// <summary> /// Send a money amount to the destination /// </summary> /// <param name="destination">The destination</param> /// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param> /// <returns></returns> /// <exception cref="NotSupportedException">The coin type is not supported</exception> public TransactionBuilder Send(Script scriptPubKey, IMoney amount) { var bag = amount as MoneyBag; if (bag != null) { foreach (IMoney money in bag) Send(scriptPubKey, amount); return this; } var coinAmount = amount as Money; if (coinAmount != null) return Send(scriptPubKey, coinAmount); var assetAmount = amount as AssetMoney; if (assetAmount != null) return SendAsset(scriptPubKey, assetAmount); throw new NotSupportedException("Type of Money not supported"); } /// <summary> /// Send assets (Open Asset) to a destination /// </summary> /// <param name="destination">The destination</param> /// <param name="asset">The asset and amount</param> /// <returns></returns> public TransactionBuilder SendAsset(IDestination destination, AssetMoney asset) { return SendAsset(destination.ScriptPubKey, asset); } /// <summary> /// Send assets (Open Asset) to a destination /// </summary> /// <param name="destination">The destination</param> /// <param name="asset">The asset and amount</param> /// <returns></returns> public TransactionBuilder SendAsset(IDestination destination, AssetId assetId, ulong quantity) { return SendAsset(destination, new AssetMoney(assetId, quantity)); } public TransactionBuilder Shuffle() { Utils.Shuffle(this._BuilderGroups, this._Rand); foreach (BuilderGroup group in this._BuilderGroups) group.Shuffle(); return this; } private IMoney SetColoredChange(TransactionBuildingContext ctx) { var changeAmount = (AssetMoney)ctx.ChangeAmount; if (changeAmount.Quantity == 0) return changeAmount; ColorMarker marker = ctx.GetColorMarker(false); Script script = ctx.Group.ChangeScript[(int)ChangeType.Colored]; TxOut txout = ctx.Transaction.AddOutput(new TxOut(GetDust(script), script)); marker.SetQuantity(ctx.Transaction.Outputs.Count - 2, changeAmount.Quantity); ctx.AdditionalFees += txout.Value; return changeAmount; } public TransactionBuilder SendAsset(Script scriptPubKey, AssetId assetId, ulong assetQuantity) { return SendAsset(scriptPubKey, new AssetMoney(assetId, assetQuantity)); } public TransactionBuilder SendAsset(Script scriptPubKey, AssetMoney asset) { if (asset.Quantity < 0) throw new ArgumentOutOfRangeException("asset", "Asset amount can't be negative"); if (asset.Quantity == 0) return this; AssertOpReturn("Colored Coin"); List<Builder> builders = this.CurrentGroup.BuildersByAsset.TryGet(asset.Id); if (builders == null) { builders = new List<Builder>(); this.CurrentGroup.BuildersByAsset.Add(asset.Id, builders); builders.Add(SetColoredChange); } builders.Add(ctx => { ColorMarker marker = ctx.GetColorMarker(false); TxOut txout = ctx.Transaction.AddOutput(new TxOut(GetDust(scriptPubKey), scriptPubKey)); marker.SetQuantity(ctx.Transaction.Outputs.Count - 2, asset.Quantity); ctx.AdditionalFees += txout.Value; return asset; }); return this; } private Money GetDust() { return GetDust(new Script(new byte[25])); } private Money GetDust(Script script) { if (this.StandardTransactionPolicy == null || this.StandardTransactionPolicy.MinRelayTxFee == null) return Money.Zero; return new TxOut(Money.Zero, script).GetDustThreshold(this.StandardTransactionPolicy.MinRelayTxFee); } /// <summary> /// Set transaction policy fluently /// </summary> /// <param name="policy">The policy</param> /// <returns>this</returns> public TransactionBuilder SetTransactionPolicy(StandardTransactionPolicy policy) { this.StandardTransactionPolicy = policy; return this; } public StandardTransactionPolicy StandardTransactionPolicy { get; set; } private string _OpReturnUser; private void AssertOpReturn(string name) { if (this._OpReturnUser == null) { this._OpReturnUser = name; } else { if (this._OpReturnUser != name) throw new InvalidOperationException("Op return already used for " + this._OpReturnUser); } } public TransactionBuilder Send(BitcoinStealthAddress address, Money amount, Key ephemKey = null) { if (amount < Money.Zero) throw new ArgumentOutOfRangeException("amount", "amount can't be negative"); if (this._OpReturnUser == null) this._OpReturnUser = "Stealth Payment"; else throw new InvalidOperationException("Op return already used for " + this._OpReturnUser); this.CurrentGroup.Builders.Add(ctx => { StealthPayment payment = address.CreatePayment(ephemKey); payment.AddToTransaction(ctx.Transaction, amount); return amount; }); return this; } public TransactionBuilder IssueAsset(IDestination destination, AssetMoney asset) { return IssueAsset(destination.ScriptPubKey, asset); } private AssetId _IssuedAsset; public TransactionBuilder IssueAsset(Script scriptPubKey, AssetMoney asset) { AssertOpReturn("Colored Coin"); if (this._IssuedAsset == null) this._IssuedAsset = asset.Id; else if (this._IssuedAsset != asset.Id) throw new InvalidOperationException("You can issue only one asset type in a transaction"); this.CurrentGroup.IssuanceBuilders.Add(ctx => { ColorMarker marker = ctx.GetColorMarker(true); if (ctx.IssuanceCoin == null) { IssuanceCoin issuance = ctx.Group.Coins.Values.OfType<IssuanceCoin>().Where(i => i.AssetId == asset.Id).FirstOrDefault(); if (issuance == null) throw new InvalidOperationException("No issuance coin for emitting asset found"); ctx.IssuanceCoin = issuance; ctx.Transaction.Inputs.Insert(0, new TxIn(issuance.Outpoint)); ctx.AdditionalFees -= issuance.Bearer.Amount; if (issuance.DefinitionUrl != null) { marker.SetMetadataUrl(issuance.DefinitionUrl); } } ctx.Transaction.Outputs.Insert(0, new TxOut(GetDust(scriptPubKey), scriptPubKey)); marker.Quantities = new[] { checked((ulong)asset.Quantity) }.Concat(marker.Quantities).ToArray(); ctx.AdditionalFees += ctx.Transaction.Outputs[0].Value; return asset; }); return this; } public TransactionBuilder SendFees(Money fees) { if (fees == null) throw new ArgumentNullException("fees"); this.CurrentGroup.Builders.Add(ctx => fees); this._TotalFee += fees; return this; } private Money _TotalFee = Money.Zero; /// <summary> /// Split the estimated fees across the several groups (separated by Then()) /// </summary> /// <param name="feeRate"></param> /// <returns></returns> public TransactionBuilder SendEstimatedFees(FeeRate feeRate) { this.FilterUneconomicalCoinsRate = feeRate; Money fee = EstimateFees(feeRate); SendFees(fee); return this; } /// <summary> /// Estimate the fee needed for the transaction, and split among groups according to their fee weight /// </summary> /// <param name="feeRate"></param> /// <returns></returns> public TransactionBuilder SendEstimatedFeesSplit(FeeRate feeRate) { this.FilterUneconomicalCoinsRate = feeRate; Money fee = EstimateFees(feeRate); SendFeesSplit(fee); return this; } /// <summary> /// Send the fee splitted among groups according to their fee weight /// </summary> /// <param name="fees"></param> /// <returns></returns> public TransactionBuilder SendFeesSplit(Money fees) { if (fees == null) throw new ArgumentNullException("fees"); BuilderGroup lastGroup = this.CurrentGroup; //Make sure at least one group exists decimal totalWeight = this._BuilderGroups.Select(b => b.FeeWeight).Sum(); Money totalSent = Money.Zero; foreach (BuilderGroup group in this._BuilderGroups) { Money groupFee = Money.Satoshis((group.FeeWeight / totalWeight) * fees.Satoshi); totalSent += groupFee; if (this._BuilderGroups.Last() == group) { Money leftOver = fees - totalSent; groupFee += leftOver; } group.Builders.Add(ctx => groupFee); } return this; } /// <summary> /// If using SendFeesSplit or SendEstimatedFeesSplit, determine the weight this group participate in paying the fees /// </summary> /// <param name="feeWeight">The weight of fee participation</param> /// <returns></returns> public TransactionBuilder SetFeeWeight(decimal feeWeight) { this.CurrentGroup.FeeWeight = feeWeight; return this; } public TransactionBuilder SetChange(IDestination destination, ChangeType changeType = ChangeType.All) { return SetChange(destination.ScriptPubKey, changeType); } public TransactionBuilder SetChange(Script scriptPubKey, ChangeType changeType = ChangeType.All) { if ((changeType & ChangeType.Colored) != 0) { this.CurrentGroup.ChangeScript[(int)ChangeType.Colored] = scriptPubKey; } if ((changeType & ChangeType.Uncolored) != 0) { this.CurrentGroup.ChangeScript[(int)ChangeType.Uncolored] = scriptPubKey; } return this; } public TransactionBuilder SetCoinSelector(ICoinSelector selector) { if (selector == null) throw new ArgumentNullException("selector"); this.CoinSelector = selector; return this; } /// <summary> /// Build the transaction /// </summary> /// <param name="sign">True if signs all inputs with the available keys</param> /// <returns>The transaction</returns> /// <exception cref="NBitcoin.NotEnoughFundsException">Not enough funds are available</exception> public Transaction BuildTransaction(bool sign) { return BuildTransaction(sign, SigHash.All); } /// <summary> /// Build the transaction /// </summary> /// <param name="sign">True if signs all inputs with the available keys</param> /// <param name="sigHash">The type of signature</param> /// <returns>The transaction</returns> /// <exception cref="NBitcoin.NotEnoughFundsException">Not enough funds are available</exception> public Transaction BuildTransaction(bool sign, SigHash sigHash) { var ctx = new TransactionBuildingContext(this); if (this._CompletedTransaction != null) ctx.Transaction = this.Network.CreateTransaction(this._CompletedTransaction.ToBytes()); if (this._LockTime != null) ctx.Transaction.LockTime = this._LockTime.Value; foreach (BuilderGroup group in this._BuilderGroups) { ctx.Group = group; ctx.AdditionalBuilders.Clear(); ctx.AdditionalFees = Money.Zero; ctx.ChangeType = ChangeType.Colored; foreach (Builder builder in group.IssuanceBuilders) builder(ctx); List<KeyValuePair<AssetId, List<Builder>>> buildersByAsset = group.BuildersByAsset.ToList(); foreach (KeyValuePair<AssetId, List<Builder>> builders in buildersByAsset) { IEnumerable<ColoredCoin> coins = group.Coins.Values.OfType<ColoredCoin>().Where(c => c.Amount.Id == builders.Key); ctx.Dust = new AssetMoney(builders.Key); ctx.CoverOnly = null; ctx.ChangeAmount = new AssetMoney(builders.Key); Money btcSpent = BuildTransaction(ctx, group, builders.Value, coins, new AssetMoney(builders.Key)) .OfType<IColoredCoin>().Select(c => c.Bearer.Amount).Sum(); ctx.AdditionalFees -= btcSpent; } ctx.AdditionalBuilders.Add(_ => _.AdditionalFees); ctx.Dust = GetDust(); ctx.ChangeAmount = Money.Zero; ctx.CoverOnly = group.CoverOnly; ctx.ChangeType = ChangeType.Uncolored; BuildTransaction(ctx, group, group.Builders, group.Coins.Values.OfType<Coin>().Where(IsEconomical), Money.Zero); } ctx.Finish(); if (sign) { SignTransactionInPlace(ctx.Transaction, sigHash); } return ctx.Transaction; } private bool IsEconomical(Coin c) { if (!this.FilterUneconomicalCoins || this.FilterUneconomicalCoinsRate == null) return true; int witSize = 0; int baseSize = 0; EstimateScriptSigSize(c, ref witSize, ref baseSize); var vSize = witSize / this.Network.Consensus.Options.WitnessScaleFactor + baseSize; return c.Amount >= this.FilterUneconomicalCoinsRate.GetFee(vSize); } private IEnumerable<ICoin> BuildTransaction( TransactionBuildingContext ctx, BuilderGroup group, IEnumerable<Builder> builders, IEnumerable<ICoin> coins, IMoney zero) { TransactionBuildingContext originalCtx = ctx.CreateMemento(); Money fees = this._TotalFee + ctx.AdditionalFees; // Replace the _SubstractFeeBuilder by another one with the fees substracts List<Builder> builderList = builders.ToList(); for (int i = 0; i < builderList.Count; i++) { if (builderList[i].Target == this._SubstractFeeBuilder) { builderList.Remove(builderList[i]); TxOut newTxOut = this._SubstractFeeBuilder._TxOut.Clone(); newTxOut.Value -= fees; builderList.Insert(i, new SendBuilder(newTxOut).Build); } } //////////////////////////////////////////////////////// IMoney target = builderList.Concat(ctx.AdditionalBuilders).Select(b => b(ctx)).Sum(zero); if (ctx.CoverOnly != null) { target = ctx.CoverOnly.Add(ctx.ChangeAmount); } IEnumerable<ICoin> unconsumed = coins.Where(c => ctx.ConsumedCoins.All(cc => cc.Outpoint != c.Outpoint)); IEnumerable<ICoin> selection = this.CoinSelector.Select(unconsumed, target); if (selection == null) { throw new NotEnoughFundsException("Not enough funds to cover the target", group.Name, target.Sub(unconsumed.Select(u => u.Amount).Sum(zero)) ); } IMoney total = selection.Select(s => s.Amount).Sum(zero); IMoney change = total.Sub(target); if (change.CompareTo(zero) == -1) { throw new NotEnoughFundsException("Not enough funds to cover the target", group.Name, change.Negate() ); } if (change.CompareTo(ctx.Dust) == 1) { Script changeScript = group.ChangeScript[(int)ctx.ChangeType]; if (changeScript == null) throw new InvalidOperationException("A change address should be specified (" + ctx.ChangeType + ")"); if (!(ctx.Dust is Money) || change.CompareTo(GetDust(changeScript)) == 1) { ctx.RestoreMemento(originalCtx); ctx.ChangeAmount = change; try { return BuildTransaction(ctx, group, builders, coins, zero); } finally { ctx.ChangeAmount = zero; } } } foreach (ICoin coin in selection) { ctx.ConsumedCoins.Add(coin); TxIn input = ctx.Transaction.Inputs.FirstOrDefault(i => i.PrevOut == coin.Outpoint); if (input == null) input = ctx.Transaction.AddInput(new TxIn(coin.Outpoint)); if (this._LockTime != null && !ctx.NonFinalSequenceSet) { input.Sequence = 0; ctx.NonFinalSequenceSet = true; } } return selection; } public Transaction SignTransaction(Transaction transaction, SigHash sigHash) { Transaction tx = this.Network.CreateTransaction(transaction.ToBytes()); SignTransactionInPlace(tx, sigHash); return tx; } public Transaction SignTransaction(Transaction transaction) { return SignTransaction(transaction, SigHash.All); } public Transaction SignTransactionInPlace(Transaction transaction) { return SignTransactionInPlace(transaction, SigHash.All); } public Transaction SignTransactionInPlace(Transaction transaction, SigHash sigHash) { var ctx = new TransactionSigningContext(this, transaction) { SigHash = sigHash }; foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs()) { ICoin coin = FindSignableCoin(input); if (coin != null) { Sign(ctx, coin, input); } } return transaction; } public ICoin FindSignableCoin(IndexedTxIn txIn) { ICoin coin = FindCoin(txIn.PrevOut); if (coin is IColoredCoin) coin = ((IColoredCoin)coin).Bearer; if (coin == null || coin is ScriptCoin || coin is StealthCoin) return coin; TxDestination hash = ScriptCoin.GetRedeemHash(this.Network, coin.TxOut.ScriptPubKey); if (hash != null) { Script redeem = this._ScriptPubKeyToRedeem.TryGet(coin.TxOut.ScriptPubKey); if (redeem != null && PayToWitScriptHashTemplate.Instance.CheckScriptPubKey(redeem)) redeem = this._ScriptPubKeyToRedeem.TryGet(redeem); if (redeem == null) { if (hash is WitScriptId) redeem = PayToWitScriptHashTemplate.Instance.ExtractWitScriptParameters(txIn.WitScript, (WitScriptId)hash); if (hash is ScriptId) { PayToScriptHashSigParameters parameters = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(this.Network, txIn.ScriptSig, (ScriptId)hash); if (parameters != null) redeem = parameters.RedeemScript; } } if (redeem != null) return new ScriptCoin(coin, redeem); } return coin; } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">The transaction to check</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx) { TransactionPolicyError[] errors; return Verify(tx, null as Money, out errors); } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">The transaction to check</param> /// <param name="expectedFees">The expected fees (more or less 10%)</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx, Money expectedFees) { TransactionPolicyError[] errors; return Verify(tx, expectedFees, out errors); } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">The transaction to check</param> /// <param name="expectedFeeRate">The expected fee rate</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx, FeeRate expectedFeeRate) { TransactionPolicyError[] errors; return Verify(tx, expectedFeeRate, out errors); } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">The transaction to check</param> /// <param name="errors">Detected errors</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx, out TransactionPolicyError[] errors) { return Verify(tx, null as Money, out errors); } /// <summary> /// Verify that a transaction is fully signed, have enough fees, and follow the Standard and Miner Transaction Policy rules /// </summary> /// <param name="tx">The transaction to check</param> /// <param name="expectedFees">The expected fees (more or less 10%)</param> /// <param name="errors">Detected errors</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx, Money expectedFees, out TransactionPolicyError[] errors) { if (tx == null) throw new ArgumentNullException("tx"); ICoin[] coins = tx.Inputs.Select(i => FindCoin(i.PrevOut)).Where(c => c != null).ToArray(); var exceptions = new List<TransactionPolicyError>(); TransactionPolicyError[] policyErrors = MinerTransactionPolicy.Instance.Check(tx, coins); exceptions.AddRange(policyErrors); policyErrors = this.StandardTransactionPolicy.Check(tx, coins); exceptions.AddRange(policyErrors); if (expectedFees != null) { Money fees = tx.GetFee(coins); if (fees != null) { Money margin = Money.Zero; if (this.DustPrevention) margin = GetDust() * 2; if (!fees.Almost(expectedFees, margin)) exceptions.Add(new NotEnoughFundsPolicyError("Fees different than expected", expectedFees - fees)); } } errors = exceptions.ToArray(); return errors.Length == 0; } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">The transaction to check</param> /// <param name="expectedFeeRate">The expected fee rate</param> /// <param name="errors">Detected errors</param> /// <returns>True if no error</returns> public bool Verify(Transaction tx, FeeRate expectedFeeRate, out TransactionPolicyError[] errors) { if (tx == null) throw new ArgumentNullException("tx"); return Verify(tx, expectedFeeRate == null ? null : expectedFeeRate.GetFee(tx, this.Network.Consensus.Options.WitnessScaleFactor), out errors); } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">he transaction to check</param> /// <param name="expectedFeeRate">The expected fee rate</param> /// <returns>Detected errors</returns> public TransactionPolicyError[] Check(Transaction tx, FeeRate expectedFeeRate) { return Check(tx, expectedFeeRate == null ? null : expectedFeeRate.GetFee(tx, this.Network.Consensus.Options.WitnessScaleFactor)); } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">he transaction to check</param> /// <param name="expectedFee">The expected fee</param> /// <returns>Detected errors</returns> public TransactionPolicyError[] Check(Transaction tx, Money expectedFee) { TransactionPolicyError[] errors; Verify(tx, expectedFee, out errors); return errors; } /// <summary> /// Verify that a transaction is fully signed and have enough fees /// </summary> /// <param name="tx">he transaction to check</param> /// <returns>Detected errors</returns> public TransactionPolicyError[] Check(Transaction tx) { return Check(tx, null as Money); } private CoinNotFoundException CoinNotFound(IndexedTxIn txIn) { return new CoinNotFoundException(txIn); } public ICoin FindCoin(OutPoint outPoint) { ICoin result = this._BuilderGroups.Select(c => c.Coins.TryGet(outPoint)).FirstOrDefault(r => r != null); if (result == null && this.CoinFinder != null) result = this.CoinFinder(outPoint); return result; } /// <summary> /// Find spent coins of a transaction /// </summary> /// <param name="tx">The transaction</param> /// <returns>Array of size tx.Input.Count, if a coin is not fund, a null coin is returned.</returns> public ICoin[] FindSpentCoins(Transaction tx) { return tx .Inputs .Select(i => FindCoin(i.PrevOut)) .ToArray(); } /// <summary> /// Estimate the physical size of the transaction /// </summary> /// <param name="tx">The transaction to be estimated</param> /// <returns></returns> public int EstimateSize(Transaction tx) { return EstimateSize(tx, false); } /// <summary> /// Estimate the size of the transaction /// </summary> /// <param name="tx">The transaction to be estimated</param> /// <param name="virtualSize">If true, returns the size on which fee calculation are based, else returns the physical byte size</param> /// <returns></returns> public int EstimateSize(Transaction tx, bool virtualSize) { if (tx == null) throw new ArgumentNullException("tx"); Transaction clone = this.Network.CreateTransaction(tx.ToHex()); clone.Inputs.Clear(); int baseSize = clone.GetSerializedSize(); int witSize = 0; if (tx.HasWitness) witSize += 2; foreach (var txin in tx.Inputs.AsIndexedInputs()) { ICoin coin = FindSignableCoin(txin) ?? FindCoin(txin.PrevOut); if (coin == null) throw CoinNotFound(txin); EstimateScriptSigSize(coin, ref witSize, ref baseSize); baseSize += 41; } return (virtualSize ? witSize / this.Network.Consensus.Options.WitnessScaleFactor + baseSize : witSize + baseSize); } private void EstimateScriptSigSize(ICoin coin, ref int witSize, ref int baseSize) { if (coin is IColoredCoin) coin = ((IColoredCoin)coin).Bearer; if (coin is ScriptCoin scriptCoin) { Script p2sh = scriptCoin.GetP2SHRedeem(); if (p2sh != null) { coin = new Coin(scriptCoin.Outpoint, new TxOut(scriptCoin.Amount, p2sh)); baseSize += new Script(Op.GetPushOp(p2sh.ToBytes(true))).Length; if (scriptCoin.RedeemType == RedeemType.WitnessV0) { coin = new ScriptCoin(coin, scriptCoin.Redeem); } } if (scriptCoin.RedeemType == RedeemType.WitnessV0) { witSize += new Script(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true))).Length; } } Script scriptPubkey = coin.GetScriptCode(this.Network); int scriptSigSize = -1; foreach (BuilderExtension extension in this.Extensions) { if (extension.CanEstimateScriptSigSize(this.Network, scriptPubkey)) { scriptSigSize = extension.EstimateScriptSigSize(this.Network, scriptPubkey); break; } } if (scriptSigSize == -1) scriptSigSize += coin.TxOut.ScriptPubKey.Length; //Using heurestic to approximate size of unknown scriptPubKey if (coin.GetHashVersion(this.Network) == HashVersion.Witness) witSize += scriptSigSize + 1; //Account for the push if (coin.GetHashVersion(this.Network) == HashVersion.Original) baseSize += scriptSigSize; } /// <summary> /// Estimate fees of the built transaction /// </summary> /// <param name="feeRate">Fee rate</param> /// <returns></returns> public Money EstimateFees(FeeRate feeRate) { if (feeRate == null) throw new ArgumentNullException("feeRate"); int builderCount = this.CurrentGroup.Builders.Count; Money feeSent = Money.Zero; try { while (true) { Transaction tx = BuildTransaction(false); Money shouldSend = EstimateFees(tx, feeRate); Money delta = shouldSend - feeSent; if (delta <= Money.Zero) break; SendFees(delta); feeSent += delta; } } finally { while (this.CurrentGroup.Builders.Count != builderCount) { this.CurrentGroup.Builders.RemoveAt(this.CurrentGroup.Builders.Count - 1); } this._TotalFee -= feeSent; } return feeSent; } /// <summary> /// Estimate fees of an unsigned transaction /// </summary> /// <param name="tx"></param> /// <param name="feeRate">Fee rate</param> /// <returns></returns> public Money EstimateFees(Transaction tx, FeeRate feeRate) { if (tx == null) throw new ArgumentNullException("tx"); if (feeRate == null) throw new ArgumentNullException("feeRate"); int estimation = EstimateSize(tx, true); return feeRate.GetFee(estimation); } private void Sign(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn) { TxIn input = txIn.TxIn; if (coin is StealthCoin) { var stealthCoin = (StealthCoin)coin; Key scanKey = FindKey(ctx, stealthCoin.Address.ScanPubKey.ScriptPubKey); if (scanKey == null) throw new KeyNotFoundException("Scan key for decrypting StealthCoin not found"); Key[] spendKeys = stealthCoin.Address.SpendPubKeys.Select(p => FindKey(ctx, p.ScriptPubKey)).Where(p => p != null).ToArray(); ctx.AdditionalKeys.AddRange(stealthCoin.Uncover(spendKeys, scanKey)); var normalCoin = new Coin(coin.Outpoint, coin.TxOut); if (stealthCoin.Redeem != null) normalCoin = normalCoin.ToScriptCoin(stealthCoin.Redeem); coin = normalCoin; } Script scriptSig = CreateScriptSig(ctx, coin, txIn); if (scriptSig == null) return; var scriptCoin = coin as ScriptCoin; Script signatures = null; if (coin.GetHashVersion(this.Network) == HashVersion.Witness) { signatures = txIn.WitScript; if (scriptCoin != null) { if (scriptCoin.IsP2SH) txIn.ScriptSig = Script.Empty; if (scriptCoin.RedeemType == RedeemType.WitnessV0) signatures = RemoveRedeem(signatures); } } else { signatures = txIn.ScriptSig; if (scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH) signatures = RemoveRedeem(signatures); } signatures = CombineScriptSigs(coin, scriptSig, signatures); if (coin.GetHashVersion(this.Network) == HashVersion.Witness) { txIn.WitScript = signatures; if (scriptCoin != null) { if (scriptCoin.IsP2SH) txIn.ScriptSig = new Script(Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true))); if (scriptCoin.RedeemType == RedeemType.WitnessV0) txIn.WitScript = txIn.WitScript + new WitScript(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true))); } } else { txIn.ScriptSig = signatures; if (scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH) { txIn.ScriptSig = input.ScriptSig + Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true)); } } } private static Script RemoveRedeem(Script script) { if (script == Script.Empty) return script; Op[] ops = script.ToOps().ToArray(); return new Script(ops.Take(ops.Length - 1)); } private Script CombineScriptSigs(ICoin coin, Script a, Script b) { Script scriptPubkey = coin.GetScriptCode(this.Network); if (Script.IsNullOrEmpty(a)) return b ?? Script.Empty; if (Script.IsNullOrEmpty(b)) return a ?? Script.Empty; foreach (BuilderExtension extension in this.Extensions) { if (extension.CanCombineScriptSig(this.Network, scriptPubkey, a, b)) { return extension.CombineScriptSig(this.Network, scriptPubkey, a, b); } } return a.Length > b.Length ? a : b; //Heurestic } private Script CreateScriptSig(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn) { Script scriptPubKey = coin.GetScriptCode(this.Network); var keyRepo = new TransactionBuilderKeyRepository(this, ctx); var signer = new TransactionBuilderSigner(this, coin, ctx.SigHash, txIn); var signer2 = new KnownSignatureSigner(this, this._KnownSignatures, coin, ctx.SigHash, txIn); foreach (BuilderExtension extension in this.Extensions) { if (extension.CanGenerateScriptSig(this.Network, scriptPubKey)) { Script scriptSig1 = extension.GenerateScriptSig(this.Network, scriptPubKey, keyRepo, signer); Script scriptSig2 = extension.GenerateScriptSig(this.Network, scriptPubKey, signer2, signer2); if (scriptSig2 != null) { scriptSig2 = signer2.ReplaceDummyKeys(scriptSig2); } if (scriptSig1 != null && scriptSig2 != null && extension.CanCombineScriptSig(this.Network, scriptPubKey, scriptSig1, scriptSig2)) { Script combined = extension.CombineScriptSig(this.Network, scriptPubKey, scriptSig1, scriptSig2); return combined; } return scriptSig1 ?? scriptSig2; } } throw new NotSupportedException("Unsupported scriptPubKey"); } private List<Tuple<PubKey, ECDSASignature>> _KnownSignatures = new List<Tuple<PubKey, ECDSASignature>>(); private Key FindKey(TransactionSigningContext ctx, Script scriptPubKey) { Key key = this._Keys .Concat(ctx.AdditionalKeys) .FirstOrDefault(k => IsCompatibleKey(k.PubKey, scriptPubKey)); if (key == null && this.KeyFinder != null) { key = this.KeyFinder(scriptPubKey); } return key; } private static bool IsCompatibleKey(PubKey k, Script scriptPubKey) { return k.ScriptPubKey == scriptPubKey || //P2PK k.Hash.ScriptPubKey == scriptPubKey || //P2PKH k.ScriptPubKey.Hash.ScriptPubKey == scriptPubKey || //P2PK P2SH k.Hash.ScriptPubKey.Hash.ScriptPubKey == scriptPubKey; //P2PKH P2SH } /// <summary> /// Create a new participant in the transaction with its own set of coins and keys /// </summary> /// <returns></returns> public TransactionBuilder Then() { this._CurrentGroup = null; return this; } /// <summary> /// Switch to another participant in the transaction, or create a new one if it is not found. /// </summary> /// <returns></returns> public TransactionBuilder Then(string groupName) { BuilderGroup group = this._BuilderGroups.FirstOrDefault(g => g.Name == groupName); if (group == null) { group = new BuilderGroup(this); this._BuilderGroups.Add(group); group.Name = groupName; } this._CurrentGroup = group; return this; } /// <summary> /// Specify the amount of money to cover txouts, if not specified all txout will be covered /// </summary> /// <param name="amount"></param> /// <returns></returns> public TransactionBuilder CoverOnly(Money amount) { this.CurrentGroup.CoverOnly = amount; return this; } private Transaction _CompletedTransaction; /// <summary> /// Allows to keep building on the top of a partially built transaction /// </summary> /// <param name="transaction">Transaction to complete</param> /// <returns></returns> public TransactionBuilder ContinueToBuild(Transaction transaction) { if (this._CompletedTransaction != null) throw new InvalidOperationException("Transaction to complete already set"); this._CompletedTransaction = this.Network.CreateTransaction(transaction.ToHex()); return this; } /// <summary> /// Will cover the remaining amount of TxOut of a partially built transaction (to call after ContinueToBuild) /// </summary> /// <returns></returns> public TransactionBuilder CoverTheRest() { if (this._CompletedTransaction == null) throw new InvalidOperationException("A partially built transaction should be specified by calling ContinueToBuild"); Money spent = this._CompletedTransaction.Inputs.AsIndexedInputs().Select(txin => { ICoin c = FindCoin(txin.PrevOut); if (c == null) throw CoinNotFound(txin); if (!(c is Coin)) return null; return (Coin)c; }) .Where(c => c != null) .Select(c => c.Amount) .Sum(); Money toComplete = this._CompletedTransaction.TotalOut - spent; this.CurrentGroup.Builders.Add(ctx => { if (toComplete < Money.Zero) return Money.Zero; return toComplete; }); return this; } public TransactionBuilder AddCoins(Transaction transaction) { uint256 txId = transaction.GetHash(); AddCoins(transaction.Outputs.Select((o, i) => new Coin(txId, (uint)i, o.Value, o.ScriptPubKey)).ToArray()); return this; } private Dictionary<Script, Script> _ScriptPubKeyToRedeem = new Dictionary<Script, Script>(); public TransactionBuilder AddKnownRedeems(params Script[] knownRedeems) { foreach (Script redeem in knownRedeems) { this._ScriptPubKeyToRedeem.AddOrReplace(redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey, redeem); //Might be P2SH(PWSH) this._ScriptPubKeyToRedeem.AddOrReplace(redeem.Hash.ScriptPubKey, redeem); //Might be P2SH this._ScriptPubKeyToRedeem.AddOrReplace(redeem.WitHash.ScriptPubKey, redeem); //Might be PWSH } return this; } public Transaction CombineSignatures(params Transaction[] transactions) { // Necessary because we can't use params and default parameters together return this.CombineSignatures(false, transactions); } /// <summary> /// Combine transactions by merging their signatures. /// </summary> /// <param name="requireFirstSigned"> /// An optional optimisation to exit early. If set and the merging of the first input doesn't change the transaction, the method will exit. /// </param> /// <param name="transactions">The transactions to merge signatures for.</param> /// <returns>The merged transaction.</returns> public Transaction CombineSignatures(bool requireFirstSigned, params Transaction[] transactions) { if (transactions.Length == 1) return transactions[0]; if (transactions.Length == 0) return null; Transaction tx = this.Network.CreateTransaction(transactions[0].ToHex()); for (int i = 1; i < transactions.Length; i++) { Transaction signed = transactions[i]; tx = this.CombineSignaturesCore(tx, signed, requireFirstSigned); } return tx; } private readonly List<BuilderExtension> _Extensions = new List<BuilderExtension>(); public List<BuilderExtension> Extensions { get { return this._Extensions; } } /// <summary> /// Combine multiple transactions into one, merging signatures for all of their inputs. /// </summary> /// <param name="signed1">First transaction to sign.</param> /// <param name="signed2">Second transaction to sign.</param> /// <param name="requireFirstSigned"> /// An optional optimisation to exit early. If set and the merging of the first input doesn't change the transaction, the method will exit. /// </param> /// <returns>The combined transaction.</returns> private Transaction CombineSignaturesCore(Transaction signed1, Transaction signed2, bool requireFirstSigned) { if (signed1 == null) return signed2; if (signed2 == null) return signed1; Transaction tx = this.Network.CreateTransaction(signed1.ToHex()); IndexedTxIn[] signed1Inputs = signed1.Inputs.AsIndexedInputs().ToArray(); IndexedTxIn[] signed2Inputs = signed2.Inputs.AsIndexedInputs().ToArray(); for (int i = 0; i < tx.Inputs.Count; i++) { if (i >= signed2.Inputs.Count) break; TxIn txIn = tx.Inputs[i]; ICoin coin = FindCoin(txIn.PrevOut); Script scriptPubKey = coin == null ? (DeduceScriptPubKey(txIn.ScriptSig) ?? DeduceScriptPubKey(signed2.Inputs[i].ScriptSig)) : coin.TxOut.ScriptPubKey; Money amount = null; if (coin != null) amount = coin is IColoredCoin ? ((IColoredCoin)coin).Bearer.Amount : ((Coin)coin).Amount; ScriptSigs result = Script.CombineSignatures( this.Network, scriptPubKey, new TransactionChecker(tx, i, amount), GetScriptSigs(signed1Inputs[i]), GetScriptSigs(signed2Inputs[i])); IndexedTxIn input = tx.Inputs.AsIndexedInputs().Skip(i).First(); input.WitScript = result.WitSig; input.ScriptSig = result.ScriptSig; // In certain cases we're expecting every input to be signed. // If merging the first input doesn't affect the transaction, exit early. if (i == 0 && requireFirstSigned && tx.GetHash() == signed1.GetHash()) { return tx; } } return tx; } private ScriptSigs GetScriptSigs(IndexedTxIn indexedTxIn) { return new ScriptSigs() { ScriptSig = indexedTxIn.ScriptSig, WitSig = indexedTxIn.WitScript }; } private Script DeduceScriptPubKey(Script scriptSig) { PayToScriptHashSigParameters p2sh = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(this.Network, scriptSig); if (p2sh != null && p2sh.RedeemScript != null) { return p2sh.RedeemScript.Hash.ScriptPubKey; } foreach (BuilderExtension extension in this.Extensions) { if (extension.CanDeduceScriptPubKey(this.Network, scriptSig)) { return extension.DeduceScriptPubKey(this.Network, scriptSig); } } return null; } } public class CoinNotFoundException : KeyNotFoundException { public CoinNotFoundException(IndexedTxIn txIn) : base("No coin matching " + txIn.PrevOut + " was found") { this._OutPoint = txIn.PrevOut; this._InputIndex = txIn.Index; } private readonly OutPoint _OutPoint; public OutPoint OutPoint { get { return this._OutPoint; } } private readonly uint _InputIndex; public uint InputIndex { get { return this._InputIndex; } } } }
37.496852
235
0.537098
[ "MIT" ]
zeptin/StratisFullNode
src/NBitcoin/TransactionBuilder.cs
77,435
C#
using IAValidator.Core.Interfaces; using MediatR; using System; using System.Collections.Generic; using System.CommandLine; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IAValidator.CLI { public class App { private readonly IAppLogger<App> _logger; private readonly IMediator _mediator; public App(IAppLogger<App> logger, IMediator mediator) { _logger = logger; _mediator = mediator; } public async Task Run(string iaXmlPath, string templateXmlPath) { _logger.LogInformation("Validating Import Agent XML from {iaXmlPath} using template XML from {templateXmlPath}", iaXmlPath, templateXmlPath); } } }
22.147059
153
0.677291
[ "MIT" ]
devingoble/IAValidator
src/IAValidator.CLI/App.cs
755
C#
#nullable disable namespace PasPasPas.Globals.Options.DataTypes { /// <summary> /// flag to required scoped enumerations /// </summary> public enum RequireScopedEnumMode { /// <summary> /// undefined flag state /// </summary> Undefined = 0, /// <summary> /// scope qualifier not required /// </summary> Disable = 1, /// <summary> /// scope qualifier required /// </summary> Enable = 2, } }
21.08
48
0.502846
[ "Apache-2.0" ]
prjm/paspaspas
PasPasPas.Global/src/Options/DataTypes/RequireScopedEnums.cs
529
C#
using Microsoft.AspNetCore.Identity; using System.ComponentModel.DataAnnotations; namespace Tchaps.Impotquebec.Models { public class Declaration { public Declaration() { Details = new List<DeclarationDetail>(); } public int DeclarationId { get; set; } [Display(Name = "Fiscal Year")] public short FiscalYear { get; set; } [DataType(DataType.Currency)] [Display(Name = "Total Income")] public decimal TotalIncome { get; set; } [Display(Name = "Total Deductions")] [DataType(DataType.Currency)] public decimal TotalDeductions { get; set; } [Display(Name = "Net Income")] [DataType(DataType.Currency)] public decimal NetIncome { get; set; } [Display(Name = "Taxable Income")] [DataType(DataType.Currency)] public decimal TaxableIncome { get; set; } [Display(Name = "Non Refundable Tax Credits")] [DataType(DataType.Currency)] public decimal NonRefundableTaxCredits { get; set; } [Display(Name = "Income Tax And Contributions")] [DataType(DataType.Currency)] public decimal IncomeTaxAndContributions { get; set; } [DataType(DataType.Currency)] public decimal Refund { get; set; } [Display(Name = "Balance Due")] [DataType(DataType.Currency)] public decimal BalanceDue { get; set; } public int TaxFormId { get; set; } [System.Text.Json.Serialization.JsonIgnore] public TaxForm? TaxForm { get; set; } public Guid UserId { get; set; } [System.Text.Json.Serialization.JsonIgnore] public AppUser? User { get; set; } public string History { get; set; } = ""; public DateTime? Created { get; set; } public DateTime? Modified { get; set; } public IList<DeclarationDetail> Details { get; set; } #region Methods public DeclarationDetail GetTaxLine( float lineNumber) { return Details.FirstOrDefault(d => d.LineNumber == lineNumber)?? new DeclarationDetail(); } public void SetTaxLine(float lineNumber, decimal value) { var taxLine = GetTaxLine(lineNumber); if (taxLine == null) return; taxLine.Value = $"{value}"; } public decimal GetSumLines(float[] lineNumbers) { return Details.Where(d => lineNumbers .Contains(d.LineNumber) && !string.IsNullOrWhiteSpace(d.Value)) .Sum(x => GetValueFromLine(x.LineNumber)); } public decimal GetValueFromLine(float lineNumber) { var taxLine = GetTaxLine(lineNumber); if (taxLine == null || string.IsNullOrWhiteSpace(taxLine.Value)) return 0; decimal.TryParse(taxLine.Value, out var result); return result; } public decimal GetDiffLines(float lineNumber1, float lineNumber2) { return GetValueFromLine(lineNumber1) - GetValueFromLine(lineNumber2); } #endregion } }
30.375
101
0.594808
[ "MIT" ]
tchapsdev/impotquebec
src/impotquebec/impotquebec.Web/Models/Declaration.cs
3,161
C#
using System.Threading.Tasks; using Examples.ExampleDomain; using Xunit; using Xunit.ScenarioReporting; namespace Examples { [Collection("ExampleScenarioRunner")] public class CollectionFixtureScenarioExample : IAsyncLifetime { private readonly ExampleScenarioCollection.InstanceCountingExampleScenarioRunner _scenarioRunner; public CollectionFixtureScenarioExample(ExampleScenarioCollection.InstanceCountingExampleScenarioRunner scenarioRunner) { _scenarioRunner = scenarioRunner; } [Fact] public void ShouldBe1() { Assert.Equal(1, _scenarioRunner.InstanceCount); } [Fact] public void ShouldStillBe1() { Assert.Equal(1, _scenarioRunner.InstanceCount); } public Task InitializeAsync() { return _scenarioRunner.Run(def => def.Given(new Number(10), new Number(30), new Number(2)).When(new Operation(OperationType.Add)) .Then(new ComputedResult(42))); } public Task DisposeAsync() { return Task.CompletedTask; } } }
28.142857
127
0.635364
[ "MIT" ]
Aardware-Ltd/Xunit.ScenarioReporting
Examples/CollectionFixtureScenarioExample.cs
1,182
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using DocMAH.Dependencies; using DocMAH.Web; using DocMAH.Web.Authorization; using DocMAH.Web.Requests; using Moq; using NUnit.Framework; using System.Net; namespace DocMAH.UnitTests.Web { [TestFixture] public class HttpHandlerTestFixture : BaseTestFixture { #region Private Fields private const string MethodName = "TestMethodName"; private const string ItemId = "25"; #endregion #region Protected Properties protected Mock<IContainer> Container; protected Mock<IEditAuthorizer> EditAuthorizer; protected Mock<HttpContextBase> HttpContext; protected Mock<HttpResponseBase> Response; protected Mock<IRequestProcessorFactory> RequestProcessorFactory; #endregion #region SetUp / TearDown [SetUp] public void SetUp() { RequestProcessorFactory = Mocks.Create<IRequestProcessorFactory>(); EditAuthorizer = Mocks.Create<IEditAuthorizer>(); Container = Mocks.Create<IContainer>(); Container.Setup(c => c.Resolve<IRequestProcessorFactory>()).Returns(RequestProcessorFactory.Object); Container.Setup(c => c.Resolve<IEditAuthorizer>()).Returns(EditAuthorizer.Object); // The response writing code would be too cumbersome to setup for every test. // We'll stub this one out and verify in a dedicated test. Response = new Mock<HttpResponseBase>(); Response.Setup(r => r.Cache).Returns(new Mock<HttpCachePolicyBase>().Object); // Likewise, a lot goes on under the hood with the request that is not worth verifying. HttpContext = new Mock<HttpContextBase>(); HttpContext.Setup(c => c.Request.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes(string.Empty))); HttpContext.Setup(c => c.Request["m"]).Returns(MethodName); HttpContext.Setup(c => c.Request["id"]).Returns(ItemId); HttpContext.Setup(c => c.Response).Returns(Response.Object); } #endregion #region Tests [Test] [Description("Request processor cannot find content.")] public void ProcessRequestInternal_ContentNotFound() { // Arrange var requestProcessor = Mocks.Create<IRequestProcessor>(); requestProcessor.Setup(p => p.Process(ItemId)).Returns(new ResponseState { StatusCode = HttpStatusCode.NotFound }); var notFoundProcessor = Mocks.Create<IRequestProcessor>(); notFoundProcessor.Setup(p => p.Process(null)).Returns(new ResponseState { StatusCode = HttpStatusCode.NotFound, Content = "404" }); RequestProcessorFactory.Setup(f => f.Create(MethodName)).Returns(requestProcessor.Object); RequestProcessorFactory.Setup(f => f.Create(RequestTypes.NotFound)).Returns(notFoundProcessor.Object); var handler = new HttpHandler(Container.Object); // Act handler.ProcessRequestInternal(HttpContext.Object); // Assert Mocks.VerifyAll(); } [Test] [Description("Authorization fails on required edit authorization.")] public void ProcessRequestInternal_EditAuthorizationFails() { // Arrange var processor = new EditAuthorizedProcessor(); var unauthorizedProcessor = Mocks.Create<IRequestProcessor>(); unauthorizedProcessor.Setup(p => p.Process(ItemId)).Returns(new ResponseState()); RequestProcessorFactory.Setup(f => f.Create(MethodName)).Returns(processor); RequestProcessorFactory.Setup(c => c.Create(RequestTypes.Unauthorized)).Returns(unauthorizedProcessor.Object); EditAuthorizer.Setup(a => a.Authorize()).Returns(false); var handler = new HttpHandler(Container.Object); // Act handler.ProcessRequestInternal(HttpContext.Object); // Assert Mocks.VerifyAll(); } [Test] [Description("Handles invalid request types.")] public void ProcessRequestInternal_InvalidRequestType() { // Arrange var requestProcessor = Mocks.Create<IRequestProcessor>(); requestProcessor.Setup(p => p.Process(ItemId)).Returns(new ResponseState()); RequestProcessorFactory.Setup(f => f.Create(MethodName)).Throws(new InvalidOperationException("Dependency creator not registered")); RequestProcessorFactory.Setup(f => f.Create(RequestTypes.NotFound)).Returns(requestProcessor.Object); var handler = new HttpHandler(Container.Object); // Act handler.ProcessRequestInternal(HttpContext.Object); // Assert Mocks.VerifyAll(); } [Test] [Description("Successfully processes a request that does not require authorization.")] public void ProcessRequestInternal_NoAuthorization() { // Arrange var requestProcessor = Mocks.Create<IRequestProcessor>(); requestProcessor.Setup(p => p.Process(ItemId)).Returns(new ResponseState()); RequestProcessorFactory.Setup(f => f.Create(MethodName)).Returns(requestProcessor.Object); var handler = new HttpHandler(Container.Object); // Act handler.ProcessRequestInternal(HttpContext.Object); // Assert Mocks.VerifyAll(); } #endregion [EditAuthorization] private class EditAuthorizedProcessor : IRequestProcessor { #region IRequestProcessor Members public ResponseState Process(string data) { return new ResponseState() { Content = "Success", ContentType = ContentTypes.Html, }; } #endregion } } }
31.44186
136
0.722263
[ "MIT" ]
Milyli/DocMAH
DocMAH.UnitTests/Web/HttpHandlerTestFixture.cs
5,410
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; // Image 36: Newtonsoft.Json.dll - Assembly: Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed - Types 5284-5564 namespace Newtonsoft.Json { [Serializable] [Nullable] // 0x00000001800155A0-0x00000001800155E0 [NullableContext] // 0x00000001800155A0-0x00000001800155E0 public class JsonReaderException : JsonException // TypeDefIndex: 5323 { // Fields [CompilerGenerated] // 0x0000000180014D50-0x0000000180014D60 private readonly int _LineNumber_k__BackingField; // 0x88 [CompilerGenerated] // 0x0000000180014D50-0x0000000180014D60 private readonly int _LinePosition_k__BackingField; // 0x8C [CompilerGenerated] // 0x0000000180015E50-0x0000000180015E80 [Nullable] // 0x0000000180015E50-0x0000000180015E80 private readonly string _Path_k__BackingField; // 0x90 // Constructors public JsonReaderException(); // 0x0000000180501E80-0x0000000180501E90 public JsonReaderException(SerializationInfo info, StreamingContext context); // 0x0000000180501E60-0x0000000180501E80 public JsonReaderException(string message, string path, int lineNumber, int linePosition, [Nullable] /* 0x00000001800155E0-0x0000000180015600 */ Exception innerException); // 0x0000000180501E10-0x0000000180501E60 // Methods internal static JsonReaderException Create(JsonReader reader, string message); // 0x0000000180501CD0-0x0000000180501CE0 internal static JsonReaderException Create(JsonReader reader, string message, [Nullable] /* 0x00000001800155E0-0x0000000180015600 */ Exception ex); // 0x0000000180501B50-0x0000000180501CD0 internal static JsonReaderException Create([Nullable] /* 0x00000001800155E0-0x0000000180015600 */ IJsonLineInfo lineInfo, string path, string message, [Nullable] /* 0x00000001800155E0-0x0000000180015600 */ Exception ex); // 0x0000000180501CE0-0x0000000180501E10 } }
50.674419
263
0.814135
[ "MIT" ]
TotalJTM/PrimitierModdingFramework
Dumps/PrimitierDumpV1.0.1/Newtonsoft/Json/JsonReaderException.cs
2,181
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Communication.Administration.Models { public partial class PhoneNumberEntities { internal static PhoneNumberEntities DeserializePhoneNumberEntities(JsonElement element) { Optional<IReadOnlyList<PhoneNumberEntity>> entities = default; Optional<string> nextLink = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("entities")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<PhoneNumberEntity> array = new List<PhoneNumberEntity>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(PhoneNumberEntity.DeserializePhoneNumberEntity(item)); } entities = array; continue; } if (property.NameEquals("nextLink")) { nextLink = property.Value.GetString(); continue; } } return new PhoneNumberEntities(Optional.ToList(entities), nextLink.Value); } } }
33.808511
95
0.545626
[ "MIT" ]
AWESOME-S-MINDSET/azure-sdk-for-net
sdk/communication/Azure.Communication.Administration/src/Generated/Models/PhoneNumberEntities.Serialization.cs
1,589
C#
namespace System.GCs { using Microsoft.Bartok.Runtime; using System.Runtime.CompilerServices; using System.Threading; // this class contains all of the things from the generational GC that // is accessed by the greater runtime in a non-virtual fashion. putting // it here is necessary to allow devirtualization of critical // non-generational GC methods. [NoCCtor] internal class GenerationalGCData { [TrustedNonNull] internal static RememberedSet installedRemSet; // PageType.Owner0 is not 0 now. One side effect is that the following arrays // have unused entries. internal static short[] gcCountTable; internal static short[] gcFrequencyTable; internal static UIntPtr[] gcPromotedTable; internal static UIntPtr[] gcPromotedLimitTable; internal static int[] fromSpacePageCounts; internal static UIntPtr nurserySize; internal static UIntPtr pretenuredSinceLastFullGC; internal const PageType nurseryGeneration = PageType.Owner0; internal const PageType largeObjectGeneration = PageType.Owner1; internal static PageType defaultGeneration; internal static PageType MIN_GENERATION { get { return PageType.Owner0; } } internal static PageType MAX_GENERATION { get { return PageType.Owner1; } } // These two arrays contain the range of pages each generation is within internal static UIntPtr[] MinGenPage; internal static UIntPtr[] MaxGenPage; [Inline] internal static bool IsLargeObjectSize(UIntPtr size) { UIntPtr largeObjectSize = (UIntPtr) (1 << Constants.LargeObjectBits); return size >= largeObjectSize; } } }
34.464286
86
0.636788
[ "MIT" ]
sphinxlogic/Singularity-RDK-2.0
base/Imported/Bartok/runtime/shared/GCs/GenerationalGCData.cs
1,930
C#
using JSC_LMS.Application.Features.Subject.Commands.CreateSubject; using JSC_LMS.Application.Features.Subject.Commands.UpdateSubject; using JSC_LSM.UI.ResponseModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JSC_LSM.UI.Services.IRepositories { public interface ISubjectRepository { Task<SubjectResponseModel> AddNewSubject(string baseurl, CreateSubjectDto createSubjectDto); Task<GetSubjectByIdResponseModel> GetSubjectById(string baseurl, int Id); Task<GetAllSubjectListResponseModel> GetAllSubjectDetails(string baseurl); Task<GetAllSubjectByFiltersResponseModel> GetSubjectByFilters(string baseurl, string SchoolName, string ClassName, string SectionName, string SubjectName, DateTime CreatedDate, bool IsActive); Task<GetAllSubjectByPaginationResponseModel> GetSubjectByPagination(string baseurl, int page, int size); Task<UpdateSubjectResponseModel> UpdateSubject(string baseurl, UpdateSubjectDto updateSubjectDto); } }
42.24
200
0.810606
[ "Apache-2.0" ]
ashishneosoftmail/JSC_LMS
src/UI/JSC_LSM.UI/Services/IRepositories/ISubjectRepository.cs
1,058
C#
using System; using Sora.Interfaces; namespace Sora.Entities.Info.InternalDataInfo; /// <summary> /// 用于存储链接信息和心跳时间的结构体 /// </summary> internal struct SoraConnectionInfo { internal readonly Guid ServiceId; private readonly Guid ConnectionId; internal readonly ISoraSocket Connection; internal DateTime LastHeartBeatTime; internal long SelfId; internal readonly TimeSpan ApiTimeout; internal SoraConnectionInfo(Guid serviceId, Guid connectionId, ISoraSocket connection, DateTime lastHeartBeatTime, long selfId, TimeSpan apiTimeout) { ServiceId = serviceId; Connection = connection; LastHeartBeatTime = lastHeartBeatTime; SelfId = selfId; ApiTimeout = apiTimeout; ConnectionId = connectionId; } public override int GetHashCode() { return HashCode.Combine(ServiceId, ConnectionId); } }
30.558824
90
0.618864
[ "Apache-2.0" ]
cc004/Sora
Sora/Entities/Info/InternalDataInfo/SoraConnectionInfo.cs
1,075
C#
namespace Sidekick.Business.Trades.Results { public class Extended { public string Text { get; set; } } }
15.75
42
0.626984
[ "MIT" ]
cmos12345/Sidekick
src/Sidekick.Business/Trades/Results/Extended.cs
126
C#
namespace More_Modifiers.Modifiers.Notes { interface INoteModifier { void Cleanup(); bool Enabled { get; set; } } }
14.6
41
0.59589
[ "MIT" ]
DeadlyKitten/Not-Enough-Modifiers
More Modifiers/Modifiers/Notes/INoteModifier.cs
148
C#
using System; using System.Collections.Generic; using EmailSkill.Dialogs.Shared.Resources.Strings; using EmailSkill.Extensions; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Solutions.Extensions; using Microsoft.Bot.Builder.Solutions.Resources; using Microsoft.Graph; namespace EmailSkill.Util { public class SpeakHelper { public static string ToSpeechEmailListString(List<Message> messages, TimeZoneInfo timeZone, int maxReadSize = 1) { string speakString = string.Empty; if (messages == null || messages.Count == 0) { return speakString; } var emailDetail = string.Empty; int readSize = Math.Min(messages.Count, maxReadSize); if (readSize >= 1) { emailDetail = ToSpeechEmailDetailOverallString(messages[0], timeZone); } speakString = emailDetail; return speakString; } public static string ToSpeechEmailDetailOverallString(Message message, TimeZoneInfo timeZone) { string speakString = string.Empty; if (message != null) { string time = message.ReceivedDateTime == null ? CommonStrings.NotAvailable : message.ReceivedDateTime.Value.UtcDateTime.ToRelativeString(timeZone); string sender = (message.Sender?.EmailAddress?.Name != null) ? message.Sender.EmailAddress.Name : EmailCommonStrings.UnknownSender; string subject = (message.Subject != null) ? message.Subject : EmailCommonStrings.EmptySubject; speakString = string.Format(EmailCommonStrings.FromDetailsFormatAll, sender, time, subject); } return speakString; } public static string ToSpeechEmailDetailString(Message message, TimeZoneInfo timeZone, bool isNeedContent = false) { string speakString = string.Empty; if (message != null) { string time = message.ReceivedDateTime == null ? CommonStrings.NotAvailable : message.ReceivedDateTime.Value.UtcDateTime.ToRelativeString(timeZone); string subject = message.Subject ?? EmailCommonStrings.EmptySubject; string sender = (message.Sender?.EmailAddress?.Name != null) ? message.Sender.EmailAddress.Name : EmailCommonStrings.UnknownSender; string content = message.Body.Content ?? EmailCommonStrings.EmptyContent; var stringFormat = isNeedContent ? EmailCommonStrings.FromDetailsWithContentFormat : EmailCommonStrings.FromDetailsFormatAll; speakString = string.Format(stringFormat, sender, time, subject, content); } return speakString; } public static string ToSpeechEmailSendDetailString(string detailSubject, string detailToRecipient, string detailContent) { string speakString = string.Empty; string subject = (detailSubject != string.Empty) ? detailSubject : EmailCommonStrings.EmptySubject; string toRecipient = (detailToRecipient != string.Empty) ? detailToRecipient : EmailCommonStrings.UnknownRecipient; string content = (detailContent != string.Empty) ? detailContent : EmailCommonStrings.EmptyContent; speakString = string.Format(EmailCommonStrings.ToDetailsFormat, subject, toRecipient, content); return speakString; } } }
41.616279
147
0.649623
[ "MIT" ]
garypretty/AI
solutions/Virtual-Assistant/src/csharp/skills/emailskill/emailskill/Util/SpeakHelper.cs
3,581
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InformedProteomics.Backend.MathAndStats { /// <summary> /// Static class with array handling utilities /// </summary> public static class ArrayUtil { // Ignore Spelling: Kadane's, subarray /// <summary> /// Create a string to display the array values. /// </summary> /// <param name="array">The array</param> /// <param name="delimiter">Delimiter character</param> /// <param name="format">Optional. A string to use to format each value. Must contain the colon, so something like ':0.000'</param> public static string ToString<T>(T[] array, string delimiter = "\t", string format = "") { var s = new StringBuilder(); var formatString = "{0" + format + "}"; for (var i = 0; i < array.Length; i++) { if (i < array.Length - 1) { s.AppendFormat(formatString + delimiter, array[i]); } else { s.AppendFormat(formatString, array[i]); } } return s.ToString(); } /// <summary> /// Create a string to display the array values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <param name="delimiter"></param> /// <param name="format"></param> /// <returns>Human-readable list of values</returns> public static string ToString<T>(T[][] array, string delimiter = "\t", string format = "") { var s = new StringBuilder(); var formatString = "{0" + format + "}"; foreach (var item in array) { for (var i = 0; i < item.Length; i++) { if (i < item.Length - 1) { s.AppendFormat(formatString + delimiter, item[i]); } else { s.AppendFormat(formatString, item[i]); } } s.Append("\n"); } return s.ToString(); } /// <summary> /// Return an array ranking every value in <paramref name="values"/>, highest value 1 and lowest value n /// </summary> /// <param name="values"></param> /// <param name="lowerBoundValue"></param> /// <returns>Array of rankings</returns> public static int[] GetRankings(IEnumerable<double> values, double lowerBoundValue = 0.0d) { var temp = new List<KeyValuePair<double, int>>(); var i = 0; foreach (var v in values) { if (v > lowerBoundValue) { temp.Add(new KeyValuePair<double, int>(v, i)); } i++; } var ranking = 1; var rankingList = new int[i]; foreach (var t in temp.OrderByDescending(x => x.Key)) { rankingList[t.Value] = ranking++; } return rankingList; } /// <summary> /// Return an array ranking every value in <paramref name="values"/>, highest value 1 and lowest value n /// </summary> /// <param name="values"></param> /// <param name="median"></param> /// <param name="lowerBoundValue"></param> /// <returns>Array of rankings</returns> public static int[] GetRankings(IEnumerable<double> values, out double median, double lowerBoundValue = 0.0d) { var temp = new List<KeyValuePair<double, int>>(); var i = 0; foreach (var v in values) { if (v > lowerBoundValue) { temp.Add(new KeyValuePair<double, int>(v, i)); } i++; } var ranking = 1; var rankingList = new int[i]; var medianRanking = (int)Math.Max(Math.Round(0.5 * i), 1); median = 0; foreach (var t in temp.OrderByDescending(x => x.Key)) { if (ranking == medianRanking) { median = t.Key; } rankingList[t.Value] = ranking++; } return rankingList; } /// <summary> /// Kadane's algorithm /// https://en.wikipedia.org/wiki/Maximum_subarray_problem /// </summary> /// <param name="a"></param> /// <param name="start"></param> /// <param name="len"></param> /// <returns>Maximum sum of a contiguous subarray</returns> public static int MaxSumSubarray(IList<int> a, out int start, out int len) { start = 0; len = 1; var sum = a[0]; var curStart = 0; var curLen = 1; var curSum = a[0]; for (var i = 1; i < a.Count; i++) { if (a[i] >= curSum + a[i]) { curStart = i; curLen = 1; curSum = a[i]; } else { curLen++; curSum += a[i]; } if ((curSum <= sum) && (curSum != sum || curLen >= len) && (curSum != sum || curLen != len || curStart >= start)) { continue; } start = curStart; len = curLen; sum = curSum; } return sum; } /// <summary> /// Kadane's algorithm /// </summary> /// <param name="a"></param> /// <param name="start"></param> /// <param name="len"></param> /// <returns>Maximum sum of a contiguous subarray</returns> public static double MaxSumSubarray(IList<double> a, out int start, out int len) { start = 0; len = 1; var sum = a[0]; var curStart = 0; var curLen = 1; var curSum = a[0]; for (var i = 1; i < a.Count; i++) { if (a[i] >= curSum + a[i]) { curStart = i; curLen = 1; curSum = a[i]; } else { curLen++; curSum += a[i]; } if ((curSum <= sum) && (Math.Abs(curSum - sum) > 1E-10 || curLen >= len) && (Math.Abs(curSum - sum) > 1E-10 || curLen != len || curStart >= start)) { continue; } start = curStart; len = curLen; sum = curSum; } return sum; } } }
32.064935
140
0.410153
[ "Apache-2.0" ]
PNNL-Comp-Mass-Spec/Informed-Proteomics
InformedProteomics.Backend/MathAndStats/ArrayUtil.cs
7,409
C#
using SilveR.Models; using SilveR.Validators; using System.Collections.Generic; namespace SilveR.StatsModels { public abstract class AnalysisModelBase { public string ScriptFileName { get; private set; } protected AnalysisModelBase(string scriptFileName) { this.ScriptFileName = scriptFileName; } public string CustomRCode { get; set; } public abstract ValidationInfo Validate(); public abstract IEnumerable<Argument> GetArguments(); public abstract void LoadArguments(IEnumerable<Argument> arguments); public abstract string GetCommandLineArguments(); } }
25.384615
76
0.693939
[ "MIT" ]
robalexclark/SilveR
SilveR/StatsModels/AnalysisModelBase.cs
662
C#
namespace RollbarDotNet.Tests.Builder { using System.Security.Claims; using Microsoft.AspNetCore.Http; using Moq; using Payloads; using RollbarDotNet.Builder; using Xunit; public class PersonBuilderTests { public PersonBuilderTests() { this._contextAccessor = new Mock<IHttpContextAccessor>(); this._sut = new PersonBuilder(this._contextAccessor.Object); this._payload = new Payload(); } private readonly Mock<IHttpContextAccessor> _contextAccessor; private readonly Payload _payload; private readonly PersonBuilder _sut; [Fact] public void Execute_NoPrincipal_ShouldSetEmptyPerson() { this._contextAccessor.Setup(accessor => accessor.HttpContext.User).Returns((ClaimsPrincipal) null); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(true, string.IsNullOrEmpty(person.Id)); Assert.Equal(true, string.IsNullOrEmpty(person.Email)); Assert.Equal(true, string.IsNullOrEmpty(person.Username)); } [Fact] public void Execute_PrincipalWithEmail_ShouldSetEmail() { const string expected = "email"; this._contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, expected) }))); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(expected, person.Email); } [Fact] public void Execute_PrincipalWithId_ShouldSetId() { const string expected = "id"; this._contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, expected) }))); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(expected, person.Id); } [Fact] public void Execute_PrincipalWithName_ShouldSetName() { const string expected = "name"; this._contextAccessor.Setup(accessor => accessor.HttpContext.User.Identity.Name).Returns(expected); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(expected, person.Username); } [Fact] public void Execute_PrincipalWithoutEmail_ShouldSetEmailToEmpty() { this._contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity())); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(true, string.IsNullOrEmpty(person.Email)); } [Fact] public void Execute_PrincipalWithoutId_ShouldSetIdToEmpty() { this._contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity())); this._sut.Execute(this._payload); var person = this._payload.Data.Person; Assert.Equal(true, string.IsNullOrEmpty(person.Id)); } } }
33.596154
111
0.60933
[ "MIT" ]
RoushTech/RollbarDotNet
test/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs
3,496
C#
using System.Collections.ObjectModel; using GalaSoft.MvvmLight; using Luminous.Code.VisualStudio.Packages; namespace StartPagePlus.UI.ViewModels { using Options.Models; public class MainViewModel : ViewModelBase { public MainViewModel() { Company = "Luminous Software Solutions"; IsVisible = false; Tabs = new ObservableCollection<TabViewModel> { new StartViewModel(), new FavoritesViewModel(), new CreateViewModel(), new NewsViewModel() }; } public string Company { get; } public bool IsVisible { get; } public static AsyncPackageBase Package { get; set; } public ObservableCollection<TabViewModel> Tabs { get; } public int MaxWidth => GeneralOptions.Instance.MaxWidth; } }
23.710526
63
0.592675
[ "MIT" ]
MagicAndre1981/start-page-plus
src/ui/ViewModels/MainViewModel.cs
903
C#
using System; namespace EF.Tests.Model; public class Document { public int Id { get; init; } public int ItemId { get; init; } public Guid? Signature { get; set; } public string Test { get; set; } public Item Item { get; set; } }
16.9375
40
0.583026
[ "MIT" ]
Gotcha7770/EF.Edu
EF.Tests/Model/Document.cs
273
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace DemoTech.Droid { [Activity(Label = "DemoTech", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
38.393939
183
0.713496
[ "MIT" ]
juucustodio/DemoTech
DemoTech.Android/MainActivity.cs
1,269
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host.Executors; using Microsoft.Azure.WebJobs.Host.Indexers; using Microsoft.Azure.WebJobs.Host.Listeners; using Microsoft.Azure.WebJobs.Host.Storage; using Microsoft.Azure.WebJobs.Host.TestCommon; using Microsoft.Azure.WebJobs.Host.Timers; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Queue; using Moq; using Xunit; namespace Microsoft.Azure.WebJobs.Host.UnitTests { public class JobHostTests { // Checks that we write the marker file when we call the host public void TestSdkMarkerIsWrittenWhenInAzureWebSites() { // Arrange string tempDir = Path.GetTempPath(); const string filename = "WebJobsSdk.marker"; var path = Path.Combine(tempDir, filename); File.Delete(path); var configuration = CreateConfiguration(); using (JobHost host = new JobHost(configuration)) { try { Environment.SetEnvironmentVariable(WebSitesKnownKeyNames.JobDataPath, tempDir); // Act host.Start(); // Assert Assert.True(File.Exists(path), "SDK marker file should have been written"); } finally { Environment.SetEnvironmentVariable(WebSitesKnownKeyNames.JobDataPath, null); File.Delete(path); } } } public void StartAsync_WhenNotStarted_DoesNotThrow() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { // Act & Assert host.StartAsync().GetAwaiter().GetResult(); } } public void StartAsync_WhenStarted_Throws() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called."); } } public void StartAsync_WhenStopped_Throws() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); host.Stop(); // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called."); } } public void StartAsync_WhenStarting_Throws() { // Arrange TaskCompletionSource<IStorageAccount> getAccountTaskSource = new TaskCompletionSource<IStorageAccount>(); JobHostConfiguration configuration = CreateConfiguration(new LambdaStorageAccountProvider( (i1, i2) => getAccountTaskSource.Task)); using (JobHost host = new JobHost(configuration)) { Task starting = host.StartAsync(); Assert.False(starting.IsCompleted); // Guard // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called."); // Cleanup getAccountTaskSource.SetResult(null); starting.GetAwaiter().GetResult(); } } public void StartAsync_WhenStopping_Throws() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); // Replace (and cleanup) the exsiting runner to hook StopAsync. IListener oldListener = host.Listener; oldListener.StopAsync(CancellationToken.None).GetAwaiter().GetResult(); TaskCompletionSource<object> stopTaskSource = new TaskCompletionSource<object>(); Mock<IListener> listenerMock = new Mock<IListener>(MockBehavior.Strict); listenerMock.Setup(r => r.StopAsync(It.IsAny<CancellationToken>())).Returns(stopTaskSource.Task); listenerMock.Setup(r => r.Dispose()); host.Listener = listenerMock.Object; Task stopping = host.StopAsync(); // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called."); // Cleanup stopTaskSource.SetResult(null); stopping.GetAwaiter().GetResult(); } } public void StopAsync_WhenStarted_DoesNotThrow() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); // Act & Assert host.StopAsync().GetAwaiter().GetResult(); } } public void StopAsync_WhenStopped_DoesNotThrow() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); host.Stop(); // Act & Assert host.StopAsync().GetAwaiter().GetResult(); } } public void StopAsync_WhenNotStarted_Throws() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StopAsync(), "The host has not yet started."); } } public void StopAsync_WhenStarting_Throws() { // Arrange TaskCompletionSource<IStorageAccount> getAccountTaskSource = new TaskCompletionSource<IStorageAccount>(); JobHostConfiguration configuration = CreateConfiguration(new LambdaStorageAccountProvider( (i1, i2) => getAccountTaskSource.Task)); using (JobHost host = new JobHost(configuration)) { Task starting = host.StartAsync(); Assert.False(starting.IsCompleted); // Guard // Act & Assert ExceptionAssert.ThrowsInvalidOperation(() => host.StopAsync(), "The host has not yet started."); // Cleanup getAccountTaskSource.SetResult(null); starting.GetAwaiter().GetResult(); } } public void StopAsync_WhenWaiting_ReturnsIncompleteTask() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); // Replace (and cleanup) the existing listener to hook StopAsync. IListener oldListener = host.Listener; oldListener.StopAsync(CancellationToken.None).GetAwaiter().GetResult(); TaskCompletionSource<object> stopTaskSource = new TaskCompletionSource<object>(); Mock<IListener> listenerMock = new Mock<IListener>(MockBehavior.Strict); listenerMock.Setup(r => r.StopAsync(It.IsAny<CancellationToken>())).Returns(stopTaskSource.Task); listenerMock.Setup(r => r.Dispose()); host.Listener = listenerMock.Object; // Act Task stopping = host.StopAsync(); // Assert Assert.False(stopping.IsCompleted); // Cleanup stopTaskSource.SetResult(null); stopping.GetAwaiter().GetResult(); } } public void StopAsync_WhenAlreadyStopping_ReturnsSameTask() { // Arrange using (JobHost host = new JobHost(CreateConfiguration())) { host.Start(); // Replace (and cleanup) the existing listener to hook StopAsync. IListener oldRunner = host.Listener; oldRunner.StopAsync(CancellationToken.None).GetAwaiter().GetResult(); TaskCompletionSource<object> stopTaskSource = new TaskCompletionSource<object>(); Mock<IListener> listenerMock = new Mock<IListener>(MockBehavior.Strict); listenerMock.Setup(r => r.StopAsync(It.IsAny<CancellationToken>())).Returns(stopTaskSource.Task); listenerMock.Setup(r => r.Dispose()); host.Listener = listenerMock.Object; Task alreadyStopping = host.StopAsync(); // Act Task stoppingAgain = host.StopAsync(); // Assert Assert.Same(alreadyStopping, stoppingAgain); // Cleanup stopTaskSource.SetResult(null); alreadyStopping.GetAwaiter().GetResult(); stoppingAgain.GetAwaiter().GetResult(); } } public void SimpleInvoke_WithDictionary() { var host = JobHostFactory.Create<ProgramSimple>(null); var x = "abc"; ProgramSimple._value = null; host.Call("Test", new Dictionary<string, object> { { "value", x } }); // Ensure test method was invoked properly. Assert.Equal(x, ProgramSimple._value); } public void SimpleInvoke_WithObject() { var host = JobHostFactory.Create<ProgramSimple>(null); var x = "abc"; ProgramSimple._value = null; host.Call("Test", new { value = x }); // Ensure test method was invoked properly. Assert.Equal(x, ProgramSimple._value); } public void CallAsyncWithCancellationToken_PassesCancellationTokenToMethod() { // Arrange ProgramWithCancellationToken.Cleanup(); var host = JobHostFactory.Create<ProgramWithCancellationToken>(null); using (CancellationTokenSource source = new CancellationTokenSource()) { ProgramWithCancellationToken.CancellationTokenSource = source; // Act host.CallAsync("BindCancellationToken", null, source.Token).GetAwaiter().GetResult(); // Assert Assert.True(ProgramWithCancellationToken.IsCancellationRequested); } } public void Call_WhenMethodThrows_PreservesStackTrace() { try { // Arrange InvalidOperationException expectedException = new InvalidOperationException(); ExceptionDispatchInfo expectedExceptionInfo = CreateExceptionInfo(expectedException); string expectedStackTrace = expectedExceptionInfo.SourceException.StackTrace; ThrowingProgram.ExceptionInfo = expectedExceptionInfo; var host = JobHostFactory.Create<ThrowingProgram>(null); MethodInfo methodInfo = typeof(ThrowingProgram).GetMethod("Throw"); // Act & Assert FunctionInvocationException exception = Assert.Throws<FunctionInvocationException>( () => host.Call(methodInfo)); Assert.Same(exception.InnerException, expectedException); Assert.NotNull(exception.InnerException.StackTrace); Assert.True(exception.InnerException.StackTrace.StartsWith(expectedStackTrace)); } finally { ThrowingProgram.ExceptionInfo = null; } } public void BlobTrigger_ProvidesBlobTriggerBindingData() { try { // Arrange CloudStorageAccount account = CloudStorageAccount.DevelopmentStorageAccount; var host = JobHostFactory.Create<BlobTriggerBindingDataProgram>(account); MethodInfo methodInfo = typeof(BlobTriggerBindingDataProgram).GetMethod("OnBlob"); string containerName = "a"; string blobName = "b"; string expectedPath = containerName + "/" + blobName; CloudBlobContainer container = account.CreateCloudBlobClient().GetContainerReference(containerName); ICloudBlob blob = container.GetBlockBlobReference(blobName); // Act host.Call(methodInfo, new { blob = blob }); // Assert Assert.Equal(expectedPath, BlobTriggerBindingDataProgram.BlobTrigger); } finally { BlobTriggerBindingDataProgram.BlobTrigger = null; } } public void QueueTrigger_ProvidesQueueTriggerBindingData() { try { // Arrange var host = JobHostFactory.Create<QueueTriggerBindingDataProgram>( CloudStorageAccount.DevelopmentStorageAccount); MethodInfo methodInfo = typeof(QueueTriggerBindingDataProgram).GetMethod("OnQueue"); string expectedMessage = "a"; // Act host.Call(methodInfo, new { message = expectedMessage }); // Assert Assert.Equal(expectedMessage, QueueTriggerBindingDataProgram.QueueTrigger); } finally { QueueTriggerBindingDataProgram.QueueTrigger = null; } } public void QueueTrigger_WithTextualByteArrayMessage_ProvidesQueueTriggerBindingData() { try { // Arrange var host = JobHostFactory.Create<QueueTriggerBindingDataProgram>( CloudStorageAccount.DevelopmentStorageAccount); MethodInfo methodInfo = typeof(QueueTriggerBindingDataProgram).GetMethod("OnQueue"); string expectedMessage = "abc"; CloudQueueMessage message = new CloudQueueMessage(expectedMessage); Assert.Equal(expectedMessage, message.AsString); // Guard // Act host.Call(methodInfo, new { message = message }); // Assert Assert.Equal(expectedMessage, QueueTriggerBindingDataProgram.QueueTrigger); } finally { QueueTriggerBindingDataProgram.QueueTrigger = null; } } public void QueueTrigger_WithNonTextualByteArrayMessageUsingQueueTriggerBindingData_Throws() { try { // Arrange var host = JobHostFactory.Create<QueueTriggerBindingDataProgram>( CloudStorageAccount.DevelopmentStorageAccount); MethodInfo methodInfo = typeof(QueueTriggerBindingDataProgram).GetMethod("OnQueue"); byte[] contents = new byte[] { 0x00, 0xFF }; // Not valid UTF-8 CloudQueueMessage message = CloudQueueMessage.CreateCloudQueueMessageFromByteArray(contents); // Act & Assert FunctionInvocationException exception = Assert.Throws<FunctionInvocationException>( () => host.Call(methodInfo, new { message = message })); // This exeption shape/message could be better, but it's meets a minimum acceptibility threshold. Assert.Equal("Exception binding parameter 'queueTrigger'", exception.InnerException.Message); Exception innerException = exception.InnerException.InnerException; Assert.IsType<InvalidOperationException>(innerException); Assert.Equal("Binding data does not contain expected value 'queueTrigger'.", innerException.Message); } finally { QueueTriggerBindingDataProgram.QueueTrigger = null; } } public void QueueTrigger_WithNonTextualByteArrayMessageNotUsingQueueTriggerBindingData_DoesNotThrow() { try { // Arrange var host = JobHostFactory.Create<QueueTriggerBindingDataProgram>( CloudStorageAccount.DevelopmentStorageAccount); MethodInfo methodInfo = typeof(QueueTriggerBindingDataProgram).GetMethod("ProcessQueueAsBytes"); byte[] expectedBytes = new byte[] { 0x00, 0xFF }; // Not valid UTF-8 CloudQueueMessage message = CloudQueueMessage.CreateCloudQueueMessageFromByteArray(expectedBytes); // Act host.Call(methodInfo, new { message = message }); // Assert Assert.Equal(QueueTriggerBindingDataProgram.Bytes, expectedBytes); } finally { QueueTriggerBindingDataProgram.QueueTrigger = null; } } [Fact] [Trait("Category", "secretsrequired")] public void IndexingExceptions_CanBeHandledByLogger() { JobHostConfiguration config = new JobHostConfiguration(); config.TypeLocator = new FakeTypeLocator(typeof(BindingErrorsProgram)); FunctionErrorLogger errorLogger = new FunctionErrorLogger("TestCategory"); config.AddService<IWebJobsExceptionHandler>(new TestExceptionHandler()); Mock<ILoggerProvider> mockProvider = new Mock<ILoggerProvider>(MockBehavior.Strict); mockProvider .Setup(m => m.CreateLogger(It.IsAny<string>())) .Returns(errorLogger); ILoggerFactory factory = new LoggerFactory(); factory.AddProvider(mockProvider.Object); config.LoggerFactory = factory; JobHost host = new JobHost(config); host.Start(); // verify the handled binding error FunctionIndexingException fex = errorLogger.Errors.SingleOrDefault() as FunctionIndexingException; Assert.True(fex.Handled); Assert.Equal("BindingErrorsProgram.Invalid", fex.MethodName); // verify that the binding error was logged Assert.Equal(4, errorLogger.LogMessages.Count); LogMessage logMessage = errorLogger.LogMessages.ElementAt(0); Assert.Equal("Error indexing method 'BindingErrorsProgram.Invalid'", logMessage.FormattedMessage); Assert.Same(fex, logMessage.Exception); Assert.Equal("Invalid container name: invalid$=+1", logMessage.Exception.InnerException.Message); // verify that the valid function was still indexed logMessage = errorLogger.LogMessages.ElementAt(1); Assert.True(logMessage.FormattedMessage.Contains("Found the following functions")); Assert.True(logMessage.FormattedMessage.Contains("BindingErrorsProgram.Valid")); // verify that the job host was started successfully logMessage = errorLogger.LogMessages.ElementAt(3); Assert.Equal("Job host started", logMessage.FormattedMessage); host.Stop(); host.Dispose(); } private static JobHostConfiguration CreateConfiguration() { Mock<IServiceProvider> services = new Mock<IServiceProvider>(MockBehavior.Strict); StorageClientFactory clientFactory = new StorageClientFactory(); services.Setup(p => p.GetService(typeof(StorageClientFactory))).Returns(clientFactory); IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider(services.Object) { // Use null connection strings since unit tests shouldn't make wire requests. StorageAccount = null, DashboardAccount = null }; return CreateConfiguration(storageAccountProvider); } private static JobHostConfiguration CreateConfiguration(IStorageAccountProvider storageAccountProvider) { var singletonManager = new SingletonManager(); return TestHelpers.NewConfig( storageAccountProvider, singletonManager, new NullConsoleProvider(), new FixedHostIdProvider(Guid.NewGuid().ToString("N")), new EmptyFunctionIndexProvider() ); } private static ExceptionDispatchInfo CreateExceptionInfo(Exception exception) { try { throw exception; } catch (Exception caught) { return ExceptionDispatchInfo.Capture(caught); } } private class ProgramSimple { public static string _value; // evidence of execution [NoAutomaticTrigger] public static void Test(string value) { _value = value; } } private class LambdaStorageAccountProvider : IStorageAccountProvider { private readonly Func<string, CancellationToken, Task<IStorageAccount>> _getAccountAsync; public LambdaStorageAccountProvider(Func<string, CancellationToken, Task<IStorageAccount>> getAccountAsync) { _getAccountAsync = getAccountAsync; } public Task<IStorageAccount> TryGetAccountAsync(string connectionStringName, CancellationToken cancellationToken) { return _getAccountAsync.Invoke(connectionStringName, cancellationToken); } } private class ProgramWithCancellationToken { public static CancellationTokenSource CancellationTokenSource { get; set; } public static bool IsCancellationRequested { get; private set; } public static void Cleanup() { CancellationTokenSource = null; IsCancellationRequested = false; } [NoAutomaticTrigger] public static void BindCancellationToken(CancellationToken cancellationToken) { CancellationTokenSource.Cancel(); IsCancellationRequested = cancellationToken.IsCancellationRequested; } } private class ThrowingProgram { public static ExceptionDispatchInfo ExceptionInfo { get; set; } [NoAutomaticTrigger] public static void Throw() { ExceptionInfo.Throw(); } } private class BlobTriggerBindingDataProgram { public static string BlobTrigger { get; set; } public static void OnBlob([BlobTrigger("ignore/{name}")] ICloudBlob blob, string blobTrigger) { BlobTrigger = blobTrigger; } } private class QueueTriggerBindingDataProgram { public static string QueueTrigger { get; set; } public static byte[] Bytes { get; set; } public static void OnQueue([QueueTrigger("ignore")] CloudQueueMessage message, string queueTrigger) { QueueTrigger = queueTrigger; } public static void ProcessQueueAsBytes([QueueTrigger("ignore")] byte[] message) { Bytes = message; } } private class BindingErrorsProgram { // Invalid function public static void Invalid([BlobTrigger("invalid$=+1")] string blob) { } // Valid function public static void Valid([BlobTrigger("test")] string blob) { } } private class FunctionErrorLogger : TestLogger { public Collection<Exception> Errors = new Collection<Exception>(); public FunctionErrorLogger(string category) : base(category, null) { } public override void Log<TState>(Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { FunctionIndexingException fex = exception as FunctionIndexingException; if (fex != null) { fex.Handled = true; Errors.Add(fex); } base.Log(logLevel, eventId, state, exception, formatter); } } } }
37.854766
177
0.583087
[ "MIT" ]
Azure-App-Service/azure-webjobs-sdk
test/Microsoft.Azure.WebJobs.Host.UnitTests/JobHostTests.cs
25,024
C#
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ using Xamarin.Forms; using Tizen; using Tizen.System; using Tizen.Tapi; namespace XamarinForTizen.Tizen { internal class Globals { internal static string LogTag = "Tapitest"; internal static TapiHandle handleModem0 = null; internal static TapiHandle handleModem1 = null; } public class App : Application { private static bool s_isTapiSupported = false; public App() { SystemInfo.TryGetValue("http://tizen.org/feature/network.telephony", out s_isTapiSupported); if (s_isTapiSupported) { Log.Debug(Globals.LogTag, "tapi feature check = " + s_isTapiSupported); MainPage = new NavigationPage(new MainPage()); } else { Log.Debug(Globals.LogTag, "tapi feature is not supported"); } } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } class Program : global::Xamarin.Forms.Platform.Tizen.FormsApplication { private static App _app; protected override void OnCreate() { base.OnCreate(); Log.Debug(Globals.LogTag, "OnCreate()"); _app = new App(); LoadApplication(_app); } public static App getApp() { return _app; } static void Main(string[] args) { Log.Debug(Globals.LogTag, "inside main"); var app = new Program(); global::Xamarin.Forms.Platform.Tizen.Forms.Init(app); app.Run(args); } } }
28.292135
104
0.590151
[ "Apache-2.0" ]
EwoutH/TizenFX
test/Tizen.Tapitest/Program.cs
2,518
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using PersonalWebsite.Models; namespace PersonalWebsite.Migrations { [DbContext(typeof(DataDbContext))] partial class DataDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("WebsiteContent.Models.Content", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("InternalCaption") .IsRequired() .HasMaxLength(255); b.HasKey("Id"); b.ToTable("Content"); }); modelBuilder.Entity("WebsiteContent.Models.Translation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ContentId"); b.Property<string>("ContentMarkup") .IsRequired(); b.Property<string>("CustomHeaderMarkup"); b.Property<string>("Description") .IsRequired(); b.Property<int>("State"); b.Property<string>("Title") .IsRequired(); b.Property<DateTime>("UpdatedAt"); b.Property<string>("UrlName") .IsRequired() .HasMaxLength(200); b.Property<int>("Version") .HasMaxLength(10); b.HasKey("Id"); b.HasIndex("ContentId"); b.HasIndex("Version", "ContentId") .IsUnique(); b.HasIndex("Version", "UrlName") .IsUnique(); b.ToTable("Translation"); }); modelBuilder.Entity("WebsiteContent.Models.Translation", b => { b.HasOne("WebsiteContent.Models.Content", "Content") .WithMany("Translations") .HasForeignKey("ContentId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.833333
126
0.495375
[ "MIT" ]
nettsundere/PersonalWebsite
src/PersonalWebsite/Migrations/DataDbContextModelSnapshot.cs
3,137
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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class ReadOnlyStructsTests : CompilingTestBase { [Fact()] public void WriteableInstanceAutoPropsInRoStructs() { var text = @" public readonly struct A { // ok - no state int ro => 5; // ok - ro state int ro1 {get;} // error int rw {get; set;} // ok - static static int rws {get; set;} } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // int rw {get; set;} Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "rw").WithLocation(11, 9) ); } [Fact()] public void WriteableInstanceFieldsInRoStructs() { var text = @" public readonly struct A { // ok public static int s; // ok public readonly int ro; // error int x; void AssignField() { // error this.x = 1; A a = default; // OK a.x = 2; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS8340: Instance fields of readonly structs must be readonly. // int x; Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "x").WithLocation(11, 9), // (16,9): error CS1604: Cannot assign to 'this' because it is read-only // this.x = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this.x").WithArguments("this").WithLocation(16, 9) ); } [Fact()] public void EventsInRoStructs() { var text = @" using System; public readonly struct A : I1 { //error public event System.Action e; //error public event Action ei1; //ok public static event Action es; A(int arg) { // ok e = () => { }; ei1 = () => { }; es = () => { }; // ok M1(ref e); } //ok event Action I1.ei2 { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } void AssignEvent() { // error e = () => { }; // error M1(ref e); } static void M1(ref System.Action arg) { } } interface I1 { event System.Action ei1; event System.Action ei2; } "; CreateCompilation(text).VerifyDiagnostics( // (7,32): error CS8342: Field-like events are not allowed in readonly structs. // public event System.Action e; Diagnostic(ErrorCode.ERR_FieldlikeEventsInRoStruct, "e").WithLocation(7, 32), // (10,25): error CS8342: Field-like events are not allowed in readonly structs. // public event Action ei1; Diagnostic(ErrorCode.ERR_FieldlikeEventsInRoStruct, "ei1").WithLocation(10, 25), // (43,9): error CS1604: Cannot assign to 'this' because it is read-only // e = () => { }; Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "e").WithArguments("this").WithLocation(43, 9), // (46,16): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // M1(ref e); Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "e").WithArguments("this").WithLocation(46, 16) ); } private static string ilreadonlyStructWithWriteableFieldIL = @" .class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method EmbeddedAttribute::.ctor } // end of class Microsoft.CodeAnalysis.EmbeddedAttribute .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method IsReadOnlyAttribute::.ctor } // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute .class public sequential ansi sealed beforefieldinit S1 extends [mscorlib]System.ValueType { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // WRITEABLE FIELD!!! .field public int32 'field' } // end of class S1 "; [Fact()] public void UseWriteableInstanceFieldsInRoStructs() { var csharp = @" public class Program { public static void Main() { S1 s = new S1(); s.field = 123; System.Console.WriteLine(s.field); } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, ilreadonlyStructWithWriteableFieldIL, options:TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput:"123"); } [Fact()] public void UseWriteableInstanceFieldsInRoStructsErr() { var csharp = @" public class Program { static readonly S1 s = new S1(); public static void Main() { s.field = 123; System.Console.WriteLine(s.field); } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, ilreadonlyStructWithWriteableFieldIL, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (8,9): error CS1650: Fields of static readonly field 'Program.s' cannot be assigned to (except in a static constructor or a variable initializer) // s.field = 123; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "s.field").WithArguments("Program.s").WithLocation(8, 9) ); } } }
28.933071
164
0.602395
[ "Apache-2.0" ]
AdamSpeight2008/roslyn-1
src/Compilers/CSharp/Test/Semantic/Semantics/ReadOnlyStructsTests.cs
7,351
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace RemuWeb.controladores { public partial class eliminarEstado : System.Web.UI.Page { RemuWebEntities rwe = new RemuWebEntities(); protected void Page_Load(object sender, EventArgs e) { int eliminar = Convert.ToInt32(Request["estadoT"]); try { estadoTrabajador s = (from s1 in rwe.estadoTrabajador where s1.id == eliminar select s1).First(); rwe.DeleteObject(s); rwe.SaveChanges(); Session["mensaje"] = "Estado de trabajador eliminado"; Response.Redirect("../vistas/registrarTrabajador.aspx"); } catch (InvalidOperationException) { Session["mensaje"] = "No se puede eliminar este estado de trabajador porque esta siendo utilizado."; Response.Redirect("../vistas/registrarTrabajador.aspx"); } } } }
34.90625
117
0.584602
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Sn0wW0lf/RemuWeb
RemuWeb/controladores/eliminarEstado.aspx.cs
1,119
C#
/* * Copyright 2012 ZXing.Net 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.DrawingCore.Imaging; using System.DrawingCore; using System.Runtime.InteropServices; namespace ZXing.ZKWeb { /// <summary> /// class which represents the luminance values for a bitmap object /// </summary> public partial class BitmapLuminanceSource : BaseLuminanceSource { /// <summary> /// Initializes a new instance of the <see cref="BitmapLuminanceSource"/> class. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> protected BitmapLuminanceSource(int width, int height) : base(width, height) { } /// <summary> /// Initializes a new instance of the <see cref="BitmapLuminanceSource"/> class /// with the image of a Bitmap instance /// </summary> /// <param name="bitmap">The bitmap.</param> public BitmapLuminanceSource(Bitmap bitmap) : base(bitmap.Width, bitmap.Height) { var height = bitmap.Height; var width = bitmap.Width; // In order to measure pure decoding speed, we convert the entire image to a greyscale array // The underlying raster of image consists of bytes with the luminance values var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { var stride = Math.Abs(data.Stride); var pixelWidth = stride / width; if (pixelWidth > 4) { // old slow way for unsupported bit depth Color c; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { c = bitmap.GetPixel(x, y); luminances[offset + x] = (byte)((RChannelWeight * c.R + GChannelWeight * c.G + BChannelWeight * c.B) >> ChannelWeight); } } } else { var strideStep = data.Stride; var buffer = new byte[stride]; var ptrInBitmap = data.Scan0; #if !WindowsCE // prepare palette for 1, 4 and 8 bit indexed bitmaps var luminancePalette = new byte[bitmap.Palette.Entries.Length]; for (var index = 0; index < bitmap.Palette.Entries.Length; index++) { var color = bitmap.Palette.Entries[index]; luminancePalette[index] = (byte)((RChannelWeight * color.R + GChannelWeight * color.G + BChannelWeight * color.B) >> ChannelWeight); } if (bitmap.PixelFormat == PixelFormat.Format32bppArgb || bitmap.PixelFormat == PixelFormat.Format32bppPArgb) { pixelWidth = 40; } if ((int)bitmap.PixelFormat == 8207 || (bitmap.Flags & (int)ImageFlags.ColorSpaceCmyk) == (int)ImageFlags.ColorSpaceCmyk) { pixelWidth = 41; } #endif for (int y = 0; y < height; y++) { // copy a scanline not the whole bitmap because of memory usage Marshal.Copy(ptrInBitmap, buffer, 0, stride); #if NET40 || NET45 ptrInBitmap = IntPtr.Add(ptrInBitmap, strideStep); #else ptrInBitmap = new IntPtr(ptrInBitmap.ToInt64() + strideStep); #endif var offset = y * width; switch (pixelWidth) { #if !WindowsCE case 0: if (bitmap.PixelFormat == PixelFormat.Format4bppIndexed) { for (int sourceX = 0, destX = 0; destX < width; sourceX++, destX += 2) { var sourceValue = buffer[sourceX]; var index = sourceValue & 15; luminances[offset + destX + 1] = luminancePalette[index]; index = (sourceValue >> 4) & 15; luminances[offset + destX] = luminancePalette[index]; } } else { for (int x = 0; x * 8 < width; x++) { for (int subX = 0; subX < 8 && 8 * x + subX < width; subX++) { var index = (buffer[x] >> (7 - subX)) & 1; luminances[offset + 8 * x + subX] = luminancePalette[index]; } } } break; case 1: for (int x = 0; x < width; x++) { luminances[offset + x] = luminancePalette[buffer[x]]; } break; #endif case 2: // should be RGB565 or RGB555, assume RGB565 { var maxIndex = 2 * width; for (int index = 0; index < maxIndex; index += 2) { var byte1 = buffer[index]; var byte2 = buffer[index + 1]; var b5 = byte1 & 0x1F; var g5 = (((byte1 & 0xE0) >> 5) | ((byte2 & 0x03) << 3)) & 0x1F; var r5 = (byte2 >> 2) & 0x1F; var r8 = (r5 * 527 + 23) >> 6; var g8 = (g5 * 527 + 23) >> 6; var b8 = (b5 * 527 + 23) >> 6; luminances[offset] = (byte)((RChannelWeight * r8 + GChannelWeight * g8 + BChannelWeight * b8) >> ChannelWeight); offset++; } } break; case 3: { var maxIndex = width * 3; for (int x = 0; x < maxIndex; x += 3) { var luminance = (byte)((BChannelWeight * buffer[x] + GChannelWeight * buffer[x + 1] + RChannelWeight * buffer[x + 2]) >> ChannelWeight); luminances[offset] = luminance; offset++; } } break; case 4: // 4 bytes without alpha channel value { var maxIndex = 4 * width; for (int x = 0; x < maxIndex; x += 4) { var luminance = (byte)((BChannelWeight * buffer[x] + GChannelWeight * buffer[x + 1] + RChannelWeight * buffer[x + 2]) >> ChannelWeight); luminances[offset] = luminance; offset++; } } break; case 40: // with alpha channel; some barcodes are completely black if you // only look at the r, g and b channel but the alpha channel controls // the view { var maxIndex = 4 * width; for (int x = 0; x < maxIndex; x += 4) { var luminance = (byte)((BChannelWeight * buffer[x] + GChannelWeight * buffer[x + 1] + RChannelWeight * buffer[x + 2]) >> ChannelWeight); // calculating the resulting luminance based upon a white background // var alpha = buffer[x * pixelWidth + 3] / 255.0; // luminance = (byte)(luminance * alpha + 255 * (1 - alpha)); var alpha = buffer[x + 3]; luminance = (byte)(((luminance * alpha) >> 8) + (255 * (255 - alpha) >> 8) + 1); luminances[offset] = luminance; offset++; } } break; case 41: // CMYK color space { var maxIndex = 4 * width; for (int x = 0; x < maxIndex; x += 4) { var luminance = (byte)(255 - ((BChannelWeight * buffer[x] + GChannelWeight * buffer[x + 1] + RChannelWeight * buffer[x + 2]) >> ChannelWeight)); // Ignore value of k at the moment luminances[offset] = luminance; offset++; } } break; default: throw new NotSupportedException(); } } } } finally { bitmap.UnlockBits(data); } } /// <summary> /// Should create a new luminance source with the right class type. /// The method is used in methods crop and rotate. /// </summary> /// <param name="newLuminances">The new luminances.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns></returns> protected override LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height) { return new BitmapLuminanceSource(width, height) { luminances = newLuminances }; } } }
50.521569
153
0.359466
[ "Apache-2.0" ]
1255225613/ZXing.Net
Source/Bindings/ZXing.ZKWeb.System.Drawing/BitmapLuminanceSource.cs
12,885
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace NakedObjects.Rest.Model { public class PersistArgumentMapBinder : IModelBinder { #region IModelBinder Members public Task BindModelAsync(ModelBindingContext bindingContext) => ModelBinderUtils.BindModelOnSuccessOrFail(bindingContext, async () => ModelBinderUtils.CreatePersistArgMap(await ModelBinderUtils.DeserializeJsonContent(bindingContext), true), ModelBinderUtils.CreateMalformedArguments<PersistArgumentMap>); #endregion } }
55.227273
136
0.761317
[ "Apache-2.0" ]
e-manual-goldstein/NakedObjectsFramework
NakedFramework/NakedFramework.Rest/Model/PersistArgumentMapBinder.cs
1,215
C#
using UnityEditor; using UnityEngine; namespace UnityEssentials.Spline.PropertyAttribute.DrawIf { [CustomPropertyDrawer(typeof(DrawIfAttribute))] public class DrawIfPropertyDrawer : PropertyDrawer { // Reference to the attribute on the property. private DrawIfAttribute drawIf; // Field that is being compared. private SerializedProperty comparedField; // Height of the property. private float propertyHeight; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return propertyHeight; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // Set the global variables. drawIf = attribute as DrawIfAttribute; comparedField = property.serializedObject.FindProperty(drawIf.comparedPropertyName); // Get the value of the compared field. object comparedFieldValue = comparedField.GetValue<object>(); // References to the values as numeric types. NumericType numericComparedFieldValue = null; NumericType numericComparedValue = null; try { // Try to set the numeric types. numericComparedFieldValue = new NumericType(comparedFieldValue); numericComparedValue = new NumericType(drawIf.comparedValue); } catch (NumericTypeExpectedException) { // This place will only be reached if the type is not a numeric one. If the comparison type is not valid for the compared field type, log an error. if (drawIf.comparisonType != ComparisonType.Equals && drawIf.comparisonType != ComparisonType.NotEqual) { Debug.LogError("The only comparsion types available to type '" + comparedFieldValue.GetType() + "' are Equals and NotEqual. (On object '" + property.serializedObject.targetObject.name + "')"); return; } } // Is the condition met? Should the field be drawn? bool conditionMet = false; // Compare the values to see if the condition is met. switch (drawIf.comparisonType) { case ComparisonType.Equals: if (comparedFieldValue.Equals(drawIf.comparedValue)) conditionMet = true; break; case ComparisonType.NotEqual: if (!comparedFieldValue.Equals(drawIf.comparedValue)) conditionMet = true; break; case ComparisonType.GreaterThan: if (numericComparedFieldValue > numericComparedValue) conditionMet = true; break; case ComparisonType.SmallerThan: if (numericComparedFieldValue < numericComparedValue) conditionMet = true; break; case ComparisonType.SmallerOrEqual: if (numericComparedFieldValue <= numericComparedValue) conditionMet = true; break; case ComparisonType.GreaterOrEqual: if (numericComparedFieldValue >= numericComparedValue) conditionMet = true; break; } // The height of the property should be defaulted to the default height. propertyHeight = base.GetPropertyHeight(property, label); // If the condition is met, simply draw the field. Else... if (conditionMet) { EditorGUI.PropertyField(position, property); } else { //...check if the disabling type is read only. If it is, draw it disabled, else, set the height to zero. if (drawIf.disablingType == DisablingType.ReadOnly) { GUI.enabled = false; EditorGUI.PropertyField(position, property); GUI.enabled = true; } else { propertyHeight = 0f; } } } } }
38.973451
212
0.557448
[ "MIT" ]
usernameHed/Philae-Lander
Assets/Plugins/Unity Essentials - Spline/PropertyAttribute/DrawIf/Editor/DrawIfDrawer.cs
4,406
C#
using System.Collections.Generic; namespace SharpIpp.Model { public class NewJobAttributes { /// <summary> /// The client OPTIONALLY supplies this attribute. The Printer /// object MUST support this attribute. It contains the client /// supplied Job name. If this attribute is supplied by the /// client, its value is used for the "job-name" attribute of the /// newly created Job object. The client MAY automatically include /// any information that will help the end-user distinguish amongst /// his/her jobs, such as the name of the application program along /// with information from the document, such as the document name, /// document subject, or source file name. If this attribute is /// not supplied by the client, the Printer generates a name to use /// in the "job-name" attribute of the newly created Job object /// </summary> public string? JobName { get; set; } /// <summary> /// The client OPTIONALLY supplies this attribute. The Printer /// object MUST support this attribute. The value 'true' indicates /// that total fidelity to client supplied Job Template attributes /// and values is required, else the Printer object MUST reject the /// Print-Job request. The value 'false' indicates that a /// reasonable attempt to print the Job object is acceptable and /// the Printer object MUST accept the Print-Job request. If not /// supplied, the Printer object assumes the value is 'false'. All /// Printer objects MUST support both types of job processing. See /// section 15 for a full description of "ipp-attribute-fidelity" /// and its relationship to other attributes, especially the /// Printer object's "pdl-override-supported" attribute. /// </summary> public bool? IppAttributeFidelity { get; set; } /// <summary> /// This attribute specifies a priority for scheduling the Job. A higher /// value specifies a higher priority. The value 1 indicates the lowest /// possible priority. The value 100 indicates the highest possible /// priority. Among those jobs that are ready to print, a Printer MUST /// print all jobs with a priority value of n before printing those with /// a priority value of n-1 for all n. /// If the Printer object supports this attribute, it MUST always support /// the full range from 1 to 100. No administrative restrictions are /// permitted. This way an end-user can always make full use of the /// entire range with any Printer object. If privileged jobs are /// implemented outside IPP/1.1, they MUST have priorities higher than /// 100, rather than restricting the range available to end-users. /// If the client does not supply this attribute and this attribute is /// supported by the Printer object, the Printer object MUST use the /// value of the Printer object's "job-priority-default" at job /// submission time (unlike most Job Template attributes that are used if /// necessary at job processing time). /// </summary> public int? JobPriority { get; set; } /// <summary> /// This attribute specifies the named time period during which the Job /// MUST become a candidate for printing. /// </summary> public JobHoldUntil? JobHoldUntil { get; set; } public MultipleDocumentHandling? MultipleDocumentHandling { get; set; } /// <summary> /// This attribute specifies the number of copies to be printed. /// On many devices the supported number of collated copies will be /// limited by the number of physical output bins on the device, and may /// be different from the number of uncollated copies which can be /// supported. /// </summary> public int? Copies { get; set; } /// <summary> /// This attribute identifies the finishing operations that the Printer /// uses for each copy of each printed document in the Job. For Jobs with /// multiple documents, the "multiple-document-handling" attribute /// determines what constitutes a "copy" for purposes of finishing. /// </summary> public Finishings? Finishings { get; set; } /// <summary> /// This attribute identifies the range(s) of print-stream pages that the /// Printer object uses for each copy of each document which are to be /// printed. Nothing is printed for any pages identified that do not /// exist in the document(s). Ranges MUST be in ascending order, for /// example: 1-3, 5-7, 15-19 and MUST NOT overlap, so that a non-spooling /// Printer object can process the job in a single pass. If the ranges /// are not ascending or are overlapping, the IPP object MUST reject the /// request and return the 'client-error-bad-request' status code. The /// attribute is associated with print-stream pages not application- /// numbered pages (for example, the page numbers found in the headers /// and or footers for certain word processing applications). /// For Jobs with multiple documents, the "multiple-document-handling" /// attribute determines what constitutes a "copy" for purposes of the /// specified page range(s). When "multiple-document-handling" is /// 'single-document', the Printer object MUST apply each supplied page /// range once to the concatenation of the print-stream pages. For /// example, if there are 8 documents of 10 pages each, the page-range /// '41:60' prints the pages in the 5th and 6th documents as a single /// document and none of the pages of the other documents are printed. /// When "multiple-document- handling" is 'separate-documents- /// uncollated-copies' or 'separate-documents-collated-copies', the /// Printer object MUST apply each supplied page range repeatedly to each /// document copy. For the same job, the page-range '1:3, 10:10' would /// print the first 3 pages and the 10th page of each of the 8 documents /// in the Job, as 8 separate documents. /// In most cases, the exact pages to be printed will be generated by a /// device driver and this attribute would not be required. However, /// when printing an archived document which has already been formatted, /// the end user may elect to print just a subset of the pages contained /// in the document. In this case, if page-range = n.m is specified, the /// first page to be printed will be page n. All subsequent pages of the /// document will be printed through and including page m. /// "page-ranges-supported" is a boolean value indicating whether or not /// the printer is capable of supporting the printing of page ranges. /// This capability may differ from one PDL to another. There is no /// "page-ranges-default" attribute. If the "page-ranges" attribute is /// not supplied by the client, all pages of the document will be /// printed. /// </summary> public Range[]? PageRanges { get; set; } /// <summary> /// This attribute specifies how print-stream pages are to be imposed /// upon the sides of an instance of a selected medium, i.e., an /// impression. /// </summary> public Sides? Sides { get; set; } /// <summary> /// This attribute specifies the number of print-stream pages to impose /// upon a single side of an instance of a selected medium. For example, /// if the value is: /// '1' the Printer MUST place one print-stream page on a single side /// of an instance of the selected medium (MAY add some sort /// of translation, scaling, or rotation). /// '2' the Printer MUST place two print-stream pages on a single side /// of an instance of the selected medium (MAY add some sort /// of translation, scaling, or rotation). /// '4' the Printer MUST place four print-stream pages on a single /// side of an instance of the selected medium (MAY add some /// sort of translation, scaling, or rotation). /// This attribute primarily controls the translation, scaling and /// rotation of print-stream pages. /// </summary> public int? NumberUp { get; set; } /// <summary> /// This attribute indicates the desired orientation for printed print- /// stream pages; it does not describe the orientation of the client- /// supplied print-stream pages. /// For some document formats (such as 'application/postscript'), the /// desired orientation of the print-stream pages is specified within the /// document data. This information is generated by a device driver /// prior to the submission of the print job. Other document formats /// (such as 'text/plain') do not include the notion of desired /// orientation within the document data. In the latter case it is /// possible for the Printer object to bind the desired orientation to /// the document data after it has been submitted. It is expected that a /// Printer object would only support "orientations-requested" for some /// document formats (e.g., 'text/plain' or 'text/html') but not others /// (e.g., 'application/postscript'). This is no different than any /// other Job Template attribute since section 4.2, item 1, points out /// that a Printer object may support or not support any Job Template /// attribute based on the document format supplied by the client. /// However, a special mention is made here since it is very likely that /// a Printer object will support "orientation-requested" for only a /// subset of the supported document formats. /// </summary> public Orientation? OrientationRequested { get; set; } /// <summary> /// This attribute identifies the medium that the Printer uses for all /// impressions of the Job. /// The values for "media" include medium-names, medium-sizes, input- /// trays and electronic forms so that one attribute specifies the media. /// If a Printer object supports a medium name as a value of this /// attribute, such a medium name implicitly selects an input-tray that /// contains the specified medium. If a Printer object supports a medium /// size as a value of this attribute, such a medium size implicitly /// selects a medium name that in turn implicitly selects an input-tray /// that contains the medium with the specified size. If a Printer /// object supports an input-tray as the value of this attribute, such an /// input-tray implicitly selects the medium that is in that input-tray /// at the time the job prints. This case includes manual-feed input- /// trays. If a Printer object supports an electronic form as the value /// of this attribute, such an electronic form implicitly selects a /// medium-name that in turn implicitly selects an input-tray that /// contains the medium specified by the electronic form. The electronic /// form also implicitly selects an image that the Printer MUST merge /// with the document data as its prints each page. /// </summary> public string? Media { get; set; } /// <summary> /// This attribute identifies the resolution that Printer uses for the /// Job. /// </summary> public Resolution? PrinterResolution { get; set; } /// <summary> /// This attribute specifies the print quality that the Printer uses for /// the Job. /// </summary> public PrintQuality? PrintQuality { get; set; } public PrintScaling? PrintScaling { get; set; } public IEnumerable<IppAttribute>? AdditionalOperationAttributes { get; set; } public IEnumerable<IppAttribute>? AdditionalJobAttributes { get; set; } } }
60.652778
85
0.620487
[ "MIT" ]
KittyDotNet/SharpIpp
SharpIpp/Model/NewJobAttributes.cs
13,103
C#
using System; using System.Drawing; using System.Runtime.InteropServices; namespace mpvnet { public class Native { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern void ReleaseCapture(); [DllImport("user32.dll")] public static extern bool AdjustWindowRect(ref RECT lpRect, uint dwStyle, bool bMenu); [DllImport("user32.dll", SetLastError = true)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); [DllImport("user32.dll", EntryPoint = "GetWindowLong")] private static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")] private static extern IntPtr GetWindowLong64(IntPtr hWnd, int nIndex); public static IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex) { if (IntPtr.Size == 8) return GetWindowLong64(hWnd, nIndex); else return GetWindowLong32(hWnd, nIndex); } [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; public RECT(Rectangle r) { Left = r.Left; Top = r.Top; Right = r.Right; Bottom = r.Bottom; } public RECT(int left, int top, int right, int bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } public Rectangle ToRectangle() { return Rectangle.FromLTRB(Left, Top, Right, Bottom); } public Size Size => new Size(Right - Left, Bottom - Top); public int Width => Right - Left; public int Height => Bottom - Top; } } }
35.135135
128
0.594231
[ "MIT" ]
Revan654/mpv.net
mpv.net/Native/Native.cs
2,602
C#
using System; using System.IO; using System.Threading.Tasks; using Etg.Yams.Application; using Etg.Yams.Storage; using Etg.Yams.Storage.Config; using Etg.Yams.Storage.Status; using Etg.Yams.Utils; namespace Etg.Yams.Test.Storage { public class LocalDeploymentRepository : IDeploymentRepository, IDeploymentStatusReader, IDeploymentStatusWriter { private readonly string _path; private readonly string _deploymentConfigPath; private readonly IDeploymentConfigSerializer _deploymentConfigSerializer; private readonly IDeploymentStatusSerializer _deploymentStatusSerializer; public LocalDeploymentRepository(string path, IDeploymentConfigSerializer deploymentConfigSerializer, IDeploymentStatusSerializer deploymentStatusSerializer) { _path = path; _deploymentConfigPath = Path.Combine(_path, Constants.DeploymentConfigFileName); _deploymentConfigSerializer = deploymentConfigSerializer; _deploymentStatusSerializer = deploymentStatusSerializer; } public Task<DeploymentConfig> FetchDeploymentConfig() { string data = File.ReadAllText(_deploymentConfigPath); return Task.FromResult(_deploymentConfigSerializer.Deserialize(data)); } public Task PublishDeploymentConfig(DeploymentConfig deploymentConfig) { File.WriteAllText(_deploymentConfigPath, _deploymentConfigSerializer.Serialize(deploymentConfig)); return Task.CompletedTask; } public Task UploadApplicationBinaries(AppIdentity appIdentity, string localPath, ConflictResolutionMode conflictResolutionMode) { if (FileUtils.DirectoryDoesntExistOrEmpty(localPath)) { throw new BinariesNotFoundException( $"Binaries were not be uploaded because they were not found at the given path {localPath}"); } string destPath = GetBinariesPath(appIdentity); bool binariesExist = FileUtils.DirectoryDoesntExistOrEmpty(destPath); if (binariesExist) { if (conflictResolutionMode == ConflictResolutionMode.DoNothingIfBinariesExist) { return Task.CompletedTask; } if (conflictResolutionMode == ConflictResolutionMode.FailIfBinariesExist) { throw new DuplicateBinariesException(); } } return FileUtils.CopyDir(_path, localPath, true); } private string GetBinariesPath(AppIdentity appIdentity) { return Path.Combine(_path, GetDeploymentRelativePath(appIdentity)); } private static string GetDeploymentRelativePath(AppIdentity appIdentity) { return Path.Combine(appIdentity.Id, appIdentity.Version.ToString()); } public Task DeleteApplicationBinaries(AppIdentity appIdentity) { string path = GetBinariesPath(appIdentity); if (FileUtils.DirectoryDoesntExistOrEmpty(path)) { throw new BinariesNotFoundException( $"Cannot delete binaries for application {appIdentity} because they were not found"); } Directory.Delete(path, true); return Task.CompletedTask; } public Task<bool> HasApplicationBinaries(AppIdentity appIdentity) { string path = GetBinariesPath(appIdentity); return Task.FromResult(!FileUtils.DirectoryDoesntExistOrEmpty(path)); } public async Task DownloadApplicationBinaries(AppIdentity appIdentity, string localPath, ConflictResolutionMode conflictResolutionMode) { bool exists = !FileUtils.DirectoryDoesntExistOrEmpty(localPath); if (exists) { if (conflictResolutionMode == ConflictResolutionMode.DoNothingIfBinariesExist) { return; } if (conflictResolutionMode == ConflictResolutionMode.FailIfBinariesExist) { throw new DuplicateBinariesException( $"Cannot download the binaries because the destination directory {localPath} contains files"); } } string path = GetBinariesPath(appIdentity); if (FileUtils.DirectoryDoesntExistOrEmpty(path)) { throw new BinariesNotFoundException($"The binaries were not found in the Yams repository"); } await FileUtils.CopyDir(path, localPath, true); } public Task<InstanceDeploymentStatus> FetchInstanceDeploymentStatus(string clusterId, string instanceId) { string path = GetInstanceDeploymentStatusPath(clusterId, instanceId); string data = File.ReadAllText(path); return Task.FromResult(_deploymentStatusSerializer.Deserialize(data)); } public Task PublishInstanceDeploymentStatus(string clusterId, string instanceId, InstanceDeploymentStatus instanceDeploymentStatus) { string path = GetInstanceDeploymentStatusPath(clusterId, instanceId); string parentDirPath = Path.GetDirectoryName(path); if (!Directory.Exists(parentDirPath)) { Directory.CreateDirectory(parentDirPath); } File.WriteAllText(path, _deploymentStatusSerializer.Serialize(instanceDeploymentStatus)); return Task.CompletedTask; } private string GetInstanceDeploymentStatusPath(string clusterId, string instanceId) { return $"{_path}/clusters/{clusterId}/instances/{instanceId}"; } } }
41.624113
143
0.652241
[ "MIT" ]
Bhaskers-Blu-Org2/Yams
test/Etg.Yams.Core.Test/Storage/LocalDeploymentRepository.cs
5,871
C#
using Sanakan.DAL.Models.Configuration; namespace Sanakan.DAL.MySql.Migrator.TableEnumerators { public class ReportsEnumerator : TableEnumerator<Report> { public ReportsEnumerator(IDbConnection connection) : base(connection) { } public override Report Current => new() { Id = _reader.GetUInt64(0), UserId = _reader.GetUInt64(1), MessageId = _reader.GetUInt64(2), GuildOptionsId = _reader.GetUInt64(3), }; public override string TableName => nameof(SanakanDbContext.Raports); } }
26.608696
77
0.617647
[ "MPL-2.0" ]
Jozpod/sanakan
DAL.MySql.Migrator/TableEnumerators/ReportsEnumerator.cs
614
C#
using System; struct MyStruct { public void Sub() => Console.WriteLine("Hello in MyStruct"); } class Program { static unsafe void Main() { MyStruct theValue; MyStruct* p = &theValue; p->Sub(); } }
14.117647
64
0.575
[ "MIT" ]
autumn009/CSharpSourceDance
Answers/SymbolOperators/address/address/Program.cs
242
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetCoreWebApi.Model; using DotNetCoreWebApi.Repository; using Microsoft.AspNetCore.Mvc; namespace DotNetCoreWebApi.Controllers { [Route("api/measurement")] [ApiController] public class MeasurementController : Controller { public IMeasurementRepository<Measurement> _measurementRepository { get; } public MeasurementController(IMeasurementRepository<Measurement> measurementRepository) { this._measurementRepository = measurementRepository; } [HttpGet] public async Task<IActionResult> GetAll() { var measurements = await _measurementRepository.GetAll(); return Ok(measurements); } [HttpGet("{id}", Name = "Get")] public async Task<IActionResult> Get(long id) { var measurements = await _measurementRepository.Get(id); return Ok(measurements); } [HttpPost] public async Task<IActionResult> Add(Measurement measurement) { await _measurementRepository.Add(measurement); return CreatedAtAction(nameof(Get), new { id = measurement.Id }, measurement); } [HttpPut("{id}")] public async Task<IActionResult> Update(long id, Measurement measurement) { var measurementsToUpdate = await _measurementRepository.Get(id); await _measurementRepository.Update(measurementsToUpdate, measurement); return NoContent(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(long id) { var measurementToDelete = await _measurementRepository.Get(id); await _measurementRepository.Delete(measurementToDelete); return NoContent(); } } }
34.509091
95
0.650158
[ "MIT" ]
Badyl96/DotNetCoreCrc
DotNetCoreCrc/src/DotNetCoreWebApi/Controllers/MeasurementController.cs
1,900
C#
using System; namespace EventBus.Core { public interface IConsumer: IDisposable { void Start(); } }
12.2
43
0.622951
[ "MIT" ]
FeiniuBus/EventBus
src/EventBus.Core/IConsumer.cs
124
C#
// Copyright 2012-2018 Chris Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace GreenPipes.Partitioning { /// <summary> /// Generates a hash of the input data for partitioning purposes /// </summary> public interface IHashGenerator { uint Hash(byte[] data); } }
37.590909
82
0.711004
[ "Apache-2.0" ]
fivec/GreenPipes
src/GreenPipes/Partitioning/IHashGenerator.cs
829
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("Small shop")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Small shop")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("37e902d2-6316-411f-bbc3-40c8dd7d8b36")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.648649
84
0.743001
[ "MIT" ]
kostadinlambov/C-Programming-Basics
03. Complex Conditions/02. Small-Shop/Properties/AssemblyInfo.cs
1,396
C#
using System; using System.Net.Http.Headers; using System.Threading; using OpenLibSys; namespace KTest { class Program { static void Main(string[] args) { Ols ols = new Ols(); // Check support library status switch (ols.GetStatus()) { case (uint)Ols.Status.NO_ERROR: Console.WriteLine("WinRing Dll_NO_ERROR"); break; case (uint)Ols.Status.DLL_NOT_FOUND: throw new ApplicationException("WinRing DLL_NOT_FOUND"); case (uint)Ols.Status.DLL_INCORRECT_VERSION: throw new ApplicationException("WinRing DLL_INCORRECT_VERSION"); case (uint)Ols.Status.DLL_INITIALIZE_ERROR: throw new ApplicationException("WinRing DLL_INITIALIZE_ERROR"); } // Check WinRing0 status switch (ols.GetDllStatus()) { case (uint)Ols.OlsDllStatus.OLS_DLL_NO_ERROR: Console.WriteLine("WinRing OLS_Dll_NO_ERROR"); break; case (uint)Ols.OlsDllStatus.OLS_DLL_DRIVER_NOT_LOADED: throw new ApplicationException("WinRing OLS_DRIVER_NOT_LOADED"); case (uint)Ols.OlsDllStatus.OLS_DLL_UNSUPPORTED_PLATFORM: throw new ApplicationException("WinRing OLS_UNSUPPORTED_PLATFORM"); case (uint)Ols.OlsDllStatus.OLS_DLL_DRIVER_NOT_FOUND: throw new ApplicationException("WinRing OLS_DLL_DRIVER_NOT_FOUND"); case (uint)Ols.OlsDllStatus.OLS_DLL_DRIVER_UNLOADED: throw new ApplicationException("WinRing OLS_DLL_DRIVER_UNLOADED"); case (uint)Ols.OlsDllStatus.OLS_DLL_DRIVER_NOT_LOADED_ON_NETWORK: throw new ApplicationException("WinRing DRIVER_NOT_LOADED_ON_NETWORK"); case (uint)Ols.OlsDllStatus.OLS_DLL_UNKNOWN_ERROR: throw new ApplicationException("WinRing OLS_DLL_UNKNOWN_ERROR"); } Console.WriteLine("---------------------------------"); uint eax = default, edx = default; Console.WriteLine("Test starting in 3: "); Thread.Sleep(1000); Console.WriteLine("Test starting in 2: "); Thread.Sleep(1000); Console.WriteLine("Test starting in 1: "); Thread.Sleep(1000); Console.WriteLine("Test starting..."); uint voltage = 0x90000000; bool result; for(int i = 0; i<100; i++) { edx = 0x80000011; eax = voltage; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; edx = 0x80000111; eax = voltage; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; edx = 0x80000211; eax = voltage; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; edx = 0x80000311; eax = voltage; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; edx = 0x80000411; eax = voltage; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; edx = 0x80000010; eax = 0x00000000; result = ols.WrmsrTx(0X150, eax, edx, (UIntPtr)(1)) == 1; } Console.WriteLine("Not Vulnerable. Please report your system info to sbski. Thank you."); } } }
35.990099
101
0.536726
[ "MIT" ]
sbski/KTest
KTest/Program.cs
3,637
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-09-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Container for the parameters to the ResetDBParameterGroup operation. /// Modifies the parameters of a DB parameter group to the engine/system default value. /// To reset specific parameters submit a list of the following: <code>ParameterName</code> /// and <code>ApplyMethod</code>. To reset the entire DB parameter group, specify the /// <code>DBParameterGroup</code> name and <code>ResetAllParameters</code> parameters. /// When resetting the entire group, dynamic parameters are updated immediately and static /// parameters are set to <code>pending-reboot</code> to take effect on the next DB instance /// restart or <code>RebootDBInstance</code> request. /// </summary> public partial class ResetDBParameterGroupRequest : AmazonRDSRequest { private string _dBParameterGroupName; private List<Parameter> _parameters = new List<Parameter>(); private bool? _resetAllParameters; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public ResetDBParameterGroupRequest() { } /// <summary> /// Instantiates ResetDBParameterGroupRequest with the parameterized properties /// </summary> /// <param name="dbParameterGroupName"> The name of the DB parameter group. Constraints: <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> </ul></param> public ResetDBParameterGroupRequest(string dbParameterGroupName) { _dBParameterGroupName = dbParameterGroupName; } /// <summary> /// Gets and sets the property DBParameterGroupName. /// <para> /// The name of the DB parameter group. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be /// a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> /// </ul> /// </summary> public string DBParameterGroupName { get { return this._dBParameterGroupName; } set { this._dBParameterGroupName = value; } } // Check to see if DBParameterGroupName property is set internal bool IsSetDBParameterGroupName() { return this._dBParameterGroupName != null; } /// <summary> /// Gets and sets the property Parameters. /// <para> /// An array of parameter names, values, and the apply method for the parameter update. /// At least one parameter name, value, and apply method must be supplied; subsequent /// arguments are optional. A maximum of 20 parameters may be modified in a single request. /// /// </para> /// /// <para> /// <b>MySQL</b> /// </para> /// /// <para> /// Valid Values (for Apply method): <code>immediate</code> | <code>pending-reboot</code> /// </para> /// /// <para> /// You can use the immediate value with dynamic parameters only. You can use the <code>pending-reboot</code> /// value for both dynamic and static parameters, and changes are applied when DB instance /// reboots. /// </para> /// /// <para> /// <b>Oracle</b> /// </para> /// /// <para> /// Valid Values (for Apply method): <code>pending-reboot</code> /// </para> /// </summary> public List<Parameter> Parameters { get { return this._parameters; } set { this._parameters = value; } } // Check to see if Parameters property is set internal bool IsSetParameters() { return this._parameters != null && this._parameters.Count > 0; } /// <summary> /// Gets and sets the property ResetAllParameters. /// <para> /// Specifies whether (<code>true</code>) or not (<code>false</code>) to reset all parameters /// in the DB parameter group to default values. /// </para> /// /// <para> /// Default: <code>true</code> /// </para> /// </summary> public bool ResetAllParameters { get { return this._resetAllParameters.GetValueOrDefault(); } set { this._resetAllParameters = value; } } // Check to see if ResetAllParameters property is set internal bool IsSetResetAllParameters() { return this._resetAllParameters.HasValue; } } }
37.993421
277
0.610563
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.RDS/Model/ResetDBParameterGroupRequest.cs
5,775
C#
namespace ZazasCleaningService.Data { using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ZazasCleaningService.Data.Common; public class DbQueryRunner : IDbQueryRunner { public DbQueryRunner(ApplicationDbContext context) { this.Context = context ?? throw new ArgumentNullException(nameof(context)); } public ApplicationDbContext Context { get; set; } public Task RunQueryAsync(string query, params object[] parameters) { return this.Context.Database.ExecuteSqlRawAsync(query, parameters); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.Context?.Dispose(); } } } }
24.657895
87
0.59445
[ "MIT" ]
TihomirIvanovIvanov/ZazasCleaningService
ZazasCleaningService/Data/ZazasCleaningService.Data/DbQueryRunner.cs
939
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 dynamodb-2012-08-10.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.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CancellationReason Object /// </summary> public class CancellationReasonUnmarshaller : IUnmarshaller<CancellationReason, XmlUnmarshallerContext>, IUnmarshaller<CancellationReason, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> CancellationReason IUnmarshaller<CancellationReason, 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 CancellationReason Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; CancellationReason unmarshalledObject = new CancellationReason(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Code", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Code = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Item", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, AttributeValue, StringUnmarshaller, AttributeValueUnmarshaller>(StringUnmarshaller.Instance, AttributeValueUnmarshaller.Instance); unmarshalledObject.Item = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Message", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Message = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static CancellationReasonUnmarshaller _instance = new CancellationReasonUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static CancellationReasonUnmarshaller Instance { get { return _instance; } } } }
37.692308
205
0.615816
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DynamoDBv2/Generated/Model/Internal/MarshallTransformations/CancellationReasonUnmarshaller.cs
3,920
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 apigatewayv2-2018-11-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ApiGatewayV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ApiGatewayV2.Model.Internal.MarshallTransformations { /// <summary> /// UpdateAuthorizer Request Marshaller /// </summary> public class UpdateAuthorizerRequestMarshaller : IMarshaller<IRequest, UpdateAuthorizerRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateAuthorizerRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateAuthorizerRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ApiGatewayV2"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-11-29"; request.HttpMethod = "PATCH"; if (!publicRequest.IsSetApiId()) throw new AmazonApiGatewayV2Exception("Request object does not have required field ApiId set"); request.AddPathResource("{apiId}", StringUtils.FromString(publicRequest.ApiId)); if (!publicRequest.IsSetAuthorizerId()) throw new AmazonApiGatewayV2Exception("Request object does not have required field AuthorizerId set"); request.AddPathResource("{authorizerId}", StringUtils.FromString(publicRequest.AuthorizerId)); request.ResourcePath = "/v2/apis/{apiId}/authorizers/{authorizerId}"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAuthorizerCredentialsArn()) { context.Writer.WritePropertyName("authorizerCredentialsArn"); context.Writer.Write(publicRequest.AuthorizerCredentialsArn); } if(publicRequest.IsSetAuthorizerPayloadFormatVersion()) { context.Writer.WritePropertyName("authorizerPayloadFormatVersion"); context.Writer.Write(publicRequest.AuthorizerPayloadFormatVersion); } if(publicRequest.IsSetAuthorizerResultTtlInSeconds()) { context.Writer.WritePropertyName("authorizerResultTtlInSeconds"); context.Writer.Write(publicRequest.AuthorizerResultTtlInSeconds); } if(publicRequest.IsSetAuthorizerType()) { context.Writer.WritePropertyName("authorizerType"); context.Writer.Write(publicRequest.AuthorizerType); } if(publicRequest.IsSetAuthorizerUri()) { context.Writer.WritePropertyName("authorizerUri"); context.Writer.Write(publicRequest.AuthorizerUri); } if(publicRequest.IsSetEnableSimpleResponses()) { context.Writer.WritePropertyName("enableSimpleResponses"); context.Writer.Write(publicRequest.EnableSimpleResponses); } if(publicRequest.IsSetIdentitySource()) { context.Writer.WritePropertyName("identitySource"); context.Writer.WriteArrayStart(); foreach(var publicRequestIdentitySourceListValue in publicRequest.IdentitySource) { context.Writer.Write(publicRequestIdentitySourceListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetIdentityValidationExpression()) { context.Writer.WritePropertyName("identityValidationExpression"); context.Writer.Write(publicRequest.IdentityValidationExpression); } if(publicRequest.IsSetJwtConfiguration()) { context.Writer.WritePropertyName("jwtConfiguration"); context.Writer.WriteObjectStart(); var marshaller = JWTConfigurationMarshaller.Instance; marshaller.Marshall(publicRequest.JwtConfiguration, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("name"); context.Writer.Write(publicRequest.Name); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateAuthorizerRequestMarshaller _instance = new UpdateAuthorizerRequestMarshaller(); internal static UpdateAuthorizerRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateAuthorizerRequestMarshaller Instance { get { return _instance; } } } }
39.947674
147
0.606753
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ApiGatewayV2/Generated/Model/Internal/MarshallTransformations/UpdateAuthorizerRequestMarshaller.cs
6,871
C#
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. using System; using JetBrains.Annotations; using MessagePack; namespace Lykke.MarginTrading.Activities.Contracts.Models { [MessagePackObject] public class ActivityContract { public ActivityContract(string id, string accountId, string instrument, string eventSourceId, DateTime timestamp, ActivityCategoryContract category, ActivityTypeContract @event, string[] descriptionAttributes, string[] relatedIds) { Id = id; AccountId = accountId; Instrument = instrument; Timestamp = timestamp; Event = @event; DescriptionAttributes = descriptionAttributes; RelatedIds = relatedIds; EventSourceId = eventSourceId; Category = category; } [Key(0)] public string Id { get; } [Key(1)] public string AccountId { get; } [Key(2)] public string Instrument { get; } [Key(3)] public string EventSourceId { get; } [Key(4)] public DateTime Timestamp { get; } [Key(5)] public ActivityCategoryContract Category { get; } [Key(6)] public ActivityTypeContract Event { get; } [Key(7)] public string[] DescriptionAttributes { get; } [Key(8)] public string[] RelatedIds { get; } } }
28.090909
101
0.572816
[ "MIT-0" ]
LykkeBusiness/MarginTrading.Activities
src/MarginTrading.Activities.Contracts/Models/ActivityContract.cs
1,545
C#
using System; using System.Collections.Generic; namespace DidacticalEnigma.Mem.DatabaseModels { public class Category { public Guid Id { get; set; } public string Name { get; set; } public Project Parent { get; set; } public int ParentId { get; set; } public IReadOnlyCollection<Translation> Translations { get; set; } } }
22.833333
74
0.591241
[ "MIT" ]
DidacticalEnigma/DidacticalEnigma.Mem
DidacticalEnigma.Mem/DatabaseModels/Category.cs
411
C#
// DraggingManager.cs // Copyright Karel Kroeze, 2018-2018 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; using Verse.Steam; using static ModManager.Constants; namespace ModManager { public static class DraggingManager { public static ModButton Dragged; public static bool Dragging => Dragged != null; public static bool Dropped; public static void Update() { if ( Dropped ) { Dragged = null; Dropped = false; SoundDefOf.Tick_Low.PlayOneShotOnCamera(); } if ( Dragging && Event.current.type == EventType.MouseUp ) { Dropped = true; } } public static bool ContainerUpdate<T>( IEnumerable<T> mods, Rect rect ) where T: ModButton { int temp; return ContainerUpdate( mods, rect, out temp ); } public static bool ContainerUpdate<T>( IEnumerable<T> mods, Rect rect, out int index ) where T: ModButton { index = -1; if ( !Mouse.IsOver( rect ) ) return false; // get index of mousePosition var position = ( Event.current.mousePosition.y - rect.yMin ) / ModButtonHeight; // start drag var dragIndex = Mathf.FloorToInt( position ); var clampedDragIndex = Mathf.Clamp( dragIndex, 0, mods.Count() - 1 ); if ( !Dragging && Event.current.type == EventType.MouseDrag && dragIndex == clampedDragIndex ) { SoundDefOf.Tick_High.PlayOneShotOnCamera(); Dragged = mods.ElementAt( clampedDragIndex ); } if ( Dragging ) { var dropIndex = Mathf.RoundToInt( position ); var clampedDropIndex = Mathf.Clamp( dropIndex, 0, mods.Count() ); index = clampedDropIndex; // drop element into place if ( Dropped ) return true; } return false; } public static void OnGUI() { if ( !Dragging ) return; // draw as mouse attachment var rect = new Rect( 0, 0, ModButtonWidth, ModButtonHeight ); var pos = Event.current.mousePosition; rect.position = pos + new Vector2( 6f, 6f ); // because it's my favourite number. Find.WindowStack.ImmediateWindow(24, rect, WindowLayer.Super, () => { Dragged?.DoModButton( rect.AtZero(), true ); }, false ); } } }
30.258065
113
0.535537
[ "MIT" ]
CandyFiend/ModManager
Source/ModManager/Utilities/DraggingManager.cs
2,816
C#
#region Using directives using System.Reflection; using System.Runtime.CompilerServices; using System.Resources; using System.Globalization; using System.Windows; using System.Runtime.InteropServices; #endregion // 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("NNMFClustering")] [assembly: AssemblyDescription("Non Negative Matrix Factorisation applied to document clustering")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("NNMFClustering")] [assembly: AssemblyCopyright("Copyright @ Jack Dermody 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [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)] // Specifies the location in which theme dictionaries are stored for types in an assembly. [assembly: ThemeInfo( // Specifies the location of system theme-specific resource dictionaries for this project. // The default setting in this project is "None" since this default project does not // include these user-defined theme files: // Themes\Aero.NormalColor.xaml // Themes\Classic.xaml // Themes\Luna.Homestead.xaml // Themes\Luna.Metallic.xaml // Themes\Luna.NormalColor.xaml // Themes\Royale.NormalColor.xaml ResourceDictionaryLocation.None, // Specifies the location of the system non-theme specific resource dictionary: // Themes\generic.xaml ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")]
38
99
0.765705
[ "MIT" ]
jdermody/icbld
CodeProject/NNMF/Properties/AssemblyInfo.cs
2,356
C#
using System.Reflection; [assembly: AssemblyTitle("Headquarter")] [assembly: AssemblyProduct("Headquarter")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.428571
43
0.728643
[ "Apache-2.0", "MIT" ]
ianbattersby/NServiceBus
Samples/Gateway/Headquarter/Properties/AssemblyInfo.cs
195
C#
// SPDX-License-Identifier: MIT // Copyright (C) 2018-present iced project and contributors using System; namespace Generator { static class NumberFormatter { static string AddNumberSeparator32(string prefix, string number) { if (number.Length != 8) throw new InvalidOperationException(); return prefix + number[0..4] + "_" + number[4..]; } static string AddNumberSeparator64(string prefix, string number) { if (number.Length != 16) throw new InvalidOperationException(); return prefix + number[0..4] + "_" + number[4..8] + "_" + number[8..12] + "_" + number[12..16]; } public static string FormatHexUInt32WithSep(uint value) => AddNumberSeparator32("0x", value.ToString("X8")); public static string FormatHexUInt64WithSep(ulong value) => AddNumberSeparator64("0x", value.ToString("X16")); } }
34.666667
112
0.705529
[ "MIT" ]
0xd4d/iced
src/csharp/Intel/Generator/NumberFormatter.cs
832
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GradeBook { public class Statistics { public double Average { get { return Sum / Count; } } public double High; public double Low; public char Letter { get { switch (Average) { case var d when d >= 90.0: return 'A'; case var d when d >= 80.0: return 'B'; case var d when d >= 70.0: return 'C'; case var d when d >= 60.0: return 'D'; default: return 'F'; } } } public double Sum; public int Count; public void Add(double number) { Sum += number; Count += 1; High = Math.Max(number, High); Low = Math.Min(number, Low); } public Statistics() { Count = 0; Sum = 0.0; High = double.MinValue; Low = double.MaxValue; } } }
20.984375
46
0.379747
[ "MIT" ]
SuSandarLinSolidCAD/GradeBook-C--Fundamentals
GradeBook/Statistics.cs
1,345
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Text; using Silk.NET.Core.Native; using Ultz.SuperInvoke; namespace Silk.NET.Vulkan { public unsafe struct AccelerationStructureBuildOffsetInfoKHR { public AccelerationStructureBuildOffsetInfoKHR ( uint primitiveCount = default, uint primitiveOffset = default, uint firstVertex = default, uint transformOffset = default ) { PrimitiveCount = primitiveCount; PrimitiveOffset = primitiveOffset; FirstVertex = firstVertex; TransformOffset = transformOffset; } /// <summary></summary> public uint PrimitiveCount; /// <summary></summary> public uint PrimitiveOffset; /// <summary></summary> public uint FirstVertex; /// <summary></summary> public uint TransformOffset; } }
25.97561
64
0.652582
[ "MIT" ]
mcavanagh/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/AccelerationStructureBuildOffsetInfoKHR.gen.cs
1,065
C#
using Com.Moonlay.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace EWorkplaceAbsensiService.Lib.Models { public class Report : StandardEntity, IValidatableObject { public int ProjectId { get; set; } public int TimesheetId { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { List<ValidationResult> validationResult = new List<ValidationResult>(); return validationResult; } } }
26.590909
90
0.705983
[ "MIT" ]
Martinus123S/id.co.moonlay-eworkplace-attendance-service
EWorkplaceAbsensiService.Lib/Models/Report.cs
587
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ecm.V20190719.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeMonthPeakNetworkRequest : AbstractModel { /// <summary> /// 月份时间(xxxx-xx) 如2021-03,默认取当前时间的上一个月份 /// </summary> [JsonProperty("Month")] public string Month{ get; set; } /// <summary> /// 过滤条件 /// </summary> [JsonProperty("Filters")] public Filter[] Filters{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Month", this.Month); this.SetParamArrayObj(map, prefix + "Filters.", this.Filters); } } }
30.078431
81
0.637549
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Ecm/V20190719/Models/DescribeMonthPeakNetworkRequest.cs
1,578
C#
namespace MassTransit.Metadata { using Contracts; using Internals.Reflection; public interface IObjectInfoContractCache { Contract GetOrAddObjectInfo(ObjectInfo objectInfo); void AddContracts(params ObjectInfo[] objectInfos); } }
19.214286
59
0.72119
[ "ECL-2.0", "Apache-2.0" ]
ArmyMedalMei/MassTransit
src/MassTransit/Configuration/Metadata/IObjectInfoContractCache.cs
269
C#
using System; namespace Orleans.Streams { /// <summary> /// Mark a subscriptionId as either an implicit subscription Id, or an explicit subscription Id. /// high bit of last byte in guild is the subscription type flag. /// 1: implicit subscription /// 0: explicit subscription /// </summary> internal static class SubscriptionMarker { internal static Guid MarkAsExplicitSubscriptionId(Guid subscriptionGuid) { return MarkSubscriptionGuid(subscriptionGuid, false); } internal static Guid MarkAsImplictSubscriptionId(Guid subscriptionGuid) { return MarkSubscriptionGuid(subscriptionGuid, true); } internal static bool IsImplicitSubscription(Guid subscriptionGuid) { byte[] guidBytes = subscriptionGuid.ToByteArray(); // return true if high bit of last byte is set return guidBytes[guidBytes.Length - 1] == (byte)(guidBytes[guidBytes.Length - 1] | 0x80); } private static Guid MarkSubscriptionGuid(Guid subscriptionGuid, bool isImplicitSubscription) { byte[] guidBytes = subscriptionGuid.ToByteArray(); if (isImplicitSubscription) { // set high bit of last byte guidBytes[guidBytes.Length - 1] = (byte)(guidBytes[guidBytes.Length - 1] | 0x80); } else { // clear high bit of last byte guidBytes[guidBytes.Length - 1] = (byte)(guidBytes[guidBytes.Length - 1] & 0x7f); } return new Guid(guidBytes); } } }
34.5
101
0.607488
[ "MIT" ]
1007lu/orleans
src/Orleans.Core/Streams/PubSub/SubscriptionMarker.cs
1,656
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataFactory.Models { /// <summary> /// Defines values for IntegrationRuntimeInternalChannelEncryptionMode. /// </summary> public static class IntegrationRuntimeInternalChannelEncryptionMode { public const string NotSet = "NotSet"; public const string SslEncrypted = "SslEncrypted"; public const string NotEncrypted = "NotEncrypted"; } }
32.333333
75
0.726804
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/datafactory/Microsoft.Azure.Management.DataFactory/src/Generated/Models/IntegrationRuntimeInternalChannelEncryptionMode.cs
776
C#