content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; /// <summary> /// Copyright 2010 Neuroph Project http://neuroph.sourceforge.net /// /// 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. /// </summary> namespace org.neuroph.samples { using org.neuroph.core; using DataSet = org.neuroph.core.data.DataSet; using DataSetRow = org.neuroph.core.data.DataSetRow; using Perceptron = org.neuroph.nnet.Perceptron; /// <summary> /// This sample shows how to create, train, save and load simple Perceptron neural network /// @author Zoran Sevarac <sevarac@gmail.com> /// </summary> public class PerceptronSample { /// <summary> /// Runs this sample /// </summary> public static void Main(string[] args) { // create training set (logical AND function) DataSet trainingSet = new DataSet(2, 1); trainingSet.addRow(new DataSetRow(new double[]{0, 0}, new double[]{0})); trainingSet.addRow(new DataSetRow(new double[]{0, 1}, new double[]{0})); trainingSet.addRow(new DataSetRow(new double[]{1, 0}, new double[]{0})); trainingSet.addRow(new DataSetRow(new double[]{1, 1}, new double[]{1})); // create perceptron neural network NeuralNetwork myPerceptron = new Perceptron(2, 1); // learn the training set myPerceptron.learn(trainingSet); // test perceptron Console.WriteLine("Testing trained perceptron"); testNeuralNetwork(myPerceptron, trainingSet); // save trained perceptron myPerceptron.save("mySamplePerceptron.nnet"); // load saved neural network NeuralNetwork loadedPerceptron = NeuralNetwork.load("mySamplePerceptron.nnet"); // test loaded neural network Console.WriteLine("Testing loaded perceptron"); testNeuralNetwork(loadedPerceptron, trainingSet); } /// <summary> /// Prints network output for the each element from the specified training set. </summary> /// <param name="neuralNet"> neural network </param> /// <param name="testSet"> data set used for testing </param> public static void testNeuralNetwork(NeuralNetwork neuralNet, DataSet testSet) { foreach (DataSetRow trainingElement in testSet.Rows) { neuralNet.Input = trainingElement.Input; neuralNet.calculate(); double[] networkOutput = neuralNet.Output; Console.Write("Input: " + Arrays.ToString(trainingElement.Input)); Console.WriteLine(" Output: " + Arrays.ToString(networkOutput)); } } } }
35.182927
92
0.710225
[ "Apache-2.0" ]
starhash/Neuroph.NET
Neuroph/samples/PerceptronSample.cs
2,887
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; using Moq; using Xunit; namespace Curiosity.Migrations.UnitTests { public class DbMigratorTests { [Fact] public async Task MigrateAsync_SkipMigration_Ok() { var initialDbVersion = new DbVersion(1,0); var provider = new Mock<IDbProvider>(); provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(new []{initialDbVersion} as IReadOnlyCollection<DbVersion>)); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var migrations = new List<IMigration>(0); var migrator = new DbMigrator( provider.Object, migrations, MigrationPolicy.Allowed, MigrationPolicy.Forbidden, null, initialDbVersion); var result = await migrator.MigrateSafeAsync(); provider .Verify(x => x.SaveAppliedMigrationVersionAsync(It.IsAny<string>(), It.IsAny<DbVersion>(), It.IsAny<CancellationToken>()), Times.Never); provider .Verify(x => x.CreateDatabaseIfNotExistsAsync(It.IsAny<CancellationToken>()), Times.Never); provider .Verify(x => x.CreateAppliedMigrationsTableIfNotExistsAsync(It.IsAny<CancellationToken>()), Times.Never); Assert.True(result.IsSuccessfully); } [Fact] public async Task MigrateAsync_UpgradeOnSpecifiedTarget_Ok() { var initialDbVersion = new DbVersion(1,0); var targetDbVersion = new DbVersion(1,1); var policy = MigrationPolicy.Allowed; var actualAppliedMigrations = new HashSet<DbVersion>(); var provider = new Mock<IDbProvider>(); provider .Setup(x => x.SaveAppliedMigrationVersionAsync(It.IsAny<string>(), It.IsAny<DbVersion>(), It.IsAny<CancellationToken>())) .Callback<string, DbVersion, CancellationToken>((name, version, token) => actualAppliedMigrations.Add(version)) .Returns(() => Task.CompletedTask); provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(new []{initialDbVersion} as IReadOnlyCollection<DbVersion>)); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock<IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object }; var expectedAppliedMigrations = new HashSet<DbVersion> { migrations[1].Version }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.True(result.IsSuccessfully); Assert.Equal(expectedAppliedMigrations, actualAppliedMigrations); } [Fact] public async Task MigrateAsync_UpgradeOnNotSpecifiedTarget_Ok() { var initialDbVersion = new DbVersion(1,0); var policy = MigrationPolicy.Allowed; var actualAppliedMigrations = new HashSet<DbVersion>(); var provider = new Mock<IDbProvider>(); provider .Setup(x => x.SaveAppliedMigrationVersionAsync(It.IsAny<string>(), It.IsAny<DbVersion>(), It.IsAny<CancellationToken>())) .Callback<string, DbVersion, CancellationToken>((name, version, token) => actualAppliedMigrations.Add(version)) .Returns(() => Task.CompletedTask); provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(new []{initialDbVersion} as IReadOnlyCollection<DbVersion>)); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock<IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object }; var expectedAppliedMigrations = new HashSet<DbVersion> { migrations[1].Version, migrations[2].Version }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy); var result = await migrator.MigrateSafeAsync(); Assert.True(result.IsSuccessfully); Assert.Equal(expectedAppliedMigrations, actualAppliedMigrations); } [Fact] public async Task MigrateAsync_UpgradeForbidden_Error() { var initialDbVersion = new DbVersion(1,0); var targetDbVersion = new DbVersion(2,0); var policy = MigrationPolicy.Forbidden; var provider = new Mock<IDbProvider>(); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(new []{initialDbVersion} as IReadOnlyCollection<DbVersion>)); var firstMigration = new Mock<IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock<IMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.False(result.IsSuccessfully); Assert.True(result.Error.HasValue); Assert.Equal(MigrationError.PolicyError, result.Error.Value); } [Fact] public void MigrateAsync_NotEnoughMigrations_Error() { var targetDbVersion = new DbVersion(3,0); var policy = MigrationPolicy.Allowed; var provider = new Mock<IDbProvider>(); var firstMigration = new Mock<IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock<IMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; try { var _ = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); Assert.True(false); } catch (Exception) { Assert.True(true); } } [Fact] public async Task MigrateAsync_Downgrade_Ok() { var targetDbVersion = new DbVersion(1,0); var policy = MigrationPolicy.Allowed; var actualAppliedMigrations = new HashSet<DbVersion>(); var provider = new Mock<IDbProvider>(); provider .Setup(x => x.DeleteAppliedMigrationVersionAsync(It.IsAny<DbVersion>(), It.IsAny<CancellationToken>())) .Callback<DbVersion, CancellationToken>((version, token) => actualAppliedMigrations.Add(version)) .Returns(() => Task.CompletedTask); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock<IDowngradeMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IDowngradeMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IDowngradeMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object }; provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(migrations.Select(x => x.Version).ToArray() as IReadOnlyCollection<DbVersion>)); var expectedAppliedMigrations = new HashSet<DbVersion> { migrations[1].Version, migrations[2].Version }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.True(result.IsSuccessfully); Assert.Equal(expectedAppliedMigrations, actualAppliedMigrations); firstMigration.Verify(x => x.DowngradeAsync(It.IsAny<DbTransaction>(), It.IsAny<CancellationToken>()), Times.Never); secondMigration.Verify(x => x.DowngradeAsync(It.IsAny<DbTransaction>(), It.IsAny<CancellationToken>()), Times.Once); thirdMigration.Verify(x => x.DowngradeAsync(It.IsAny<DbTransaction>(), It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task MigrateAsync_DowngradeForbidden_Error() { var targetDbVersion = new DbVersion(1,0); var policy = MigrationPolicy.Forbidden; var provider = new Mock<IDbProvider>(); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock<IDowngradeMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock<IDowngradeMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock<IDowngradeMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock<IDowngradeMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List<IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(migrations.Select(x => x.Version).ToArray() as IReadOnlyCollection<DbVersion>)); var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.False(result.IsSuccessfully); Assert.True(result.Error.HasValue); Assert.Equal(MigrationError.PolicyError, result.Error.Value); } private class MockTransaction : DbTransaction { public override void Commit() { } public override void Rollback() { } protected override DbConnection DbConnection { get; } public override IsolationLevel IsolationLevel { get; } } } }
37.087678
152
0.512236
[ "MIT" ]
siisltd/Curiosity.Migrations
tests/UnitTests/Curiosity.Migrations.UnitTests/DbMigratorTests.cs
15,651
C#
using System.IO; using ProtoBuf; namespace DynStack.DataModel.Common { public static class SerializableExtensions { public static byte[] Serialize(this ISerializable obj) { using (var stream = new MemoryStream()) { Serializer.Serialize(stream, obj); return stream.ToArray(); } } public static T Parse<T>(this byte[] data) where T : ISerializable { using (var stream = new MemoryStream(data)) { return Serializer.Deserialize<T>(stream); } } } }
27.052632
72
0.651751
[ "MIT" ]
dybalabak/GECCO_2021_Competition
simulation/DynStack.DataModel/Common/SerializableExtensions.cs
516
C#
#pragma warning disable 1634, 1691 /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 #pragma warning disable 56523 using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Management.Automation.Internal; using System.Runtime.ConstrainedExecution; using DWORD = System.UInt32; using BOOL = System.UInt32; namespace System.Management.Automation.Security { // Crypto API native constants internal partial class NativeConstants { internal const int CRYPT_OID_INFO_OID_KEY = 1; internal const int CRYPT_OID_INFO_NAME_KEY = 2; internal const int CRYPT_OID_INFO_CNG_ALGID_KEY = 5; } // Safer native constants internal partial class NativeConstants { /// SAFER_TOKEN_NULL_IF_EQUAL -> 0x00000001 public const int SAFER_TOKEN_NULL_IF_EQUAL = 1; /// SAFER_TOKEN_COMPARE_ONLY -> 0x00000002 public const int SAFER_TOKEN_COMPARE_ONLY = 2; /// SAFER_TOKEN_MAKE_INERT -> 0x00000004 public const int SAFER_TOKEN_MAKE_INERT = 4; /// SAFER_CRITERIA_IMAGEPATH -> 0x00001 public const int SAFER_CRITERIA_IMAGEPATH = 1; /// SAFER_CRITERIA_NOSIGNEDHASH -> 0x00002 public const int SAFER_CRITERIA_NOSIGNEDHASH = 2; /// SAFER_CRITERIA_IMAGEHASH -> 0x00004 public const int SAFER_CRITERIA_IMAGEHASH = 4; /// SAFER_CRITERIA_AUTHENTICODE -> 0x00008 public const int SAFER_CRITERIA_AUTHENTICODE = 8; /// SAFER_CRITERIA_URLZONE -> 0x00010 public const int SAFER_CRITERIA_URLZONE = 16; /// SAFER_CRITERIA_IMAGEPATH_NT -> 0x01000 public const int SAFER_CRITERIA_IMAGEPATH_NT = 4096; /// WTD_UI_NONE -> 0x00002 public const int WTD_UI_NONE = 2; /// S_OK -> ((HRESULT)0L) public const int S_OK = 0; /// S_FALSE -> ((HRESULT)1L) public const int S_FALSE = 1; /// ERROR_MORE_DATA -> 234L public const int ERROR_MORE_DATA = 234; /// ERROR_ACCESS_DISABLED_BY_POLICY -> 1260L public const int ERROR_ACCESS_DISABLED_BY_POLICY = 1260; /// ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY -> 786L public const int ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786; /// SAFER_MAX_HASH_SIZE -> 64 public const int SAFER_MAX_HASH_SIZE = 64; /// SRP_POLICY_SCRIPT -> L"SCRIPT" public const string SRP_POLICY_SCRIPT = "SCRIPT"; /// SIGNATURE_DISPLAYNAME_LENGTH -> MAX_PATH internal const int SIGNATURE_DISPLAYNAME_LENGTH = NativeConstants.MAX_PATH; /// SIGNATURE_PUBLISHER_LENGTH -> 128 internal const int SIGNATURE_PUBLISHER_LENGTH = 128; /// SIGNATURE_HASH_LENGTH -> 64 internal const int SIGNATURE_HASH_LENGTH = 64; /// MAX_PATH -> 260 internal const int MAX_PATH = 260; } /// <summary> /// pinvoke methods from crypt32.dll /// </summary> internal static partial class NativeMethods { // ------------------------------------------------------------------- // crypt32.dll stuff // [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertEnumSystemStore(CertStoreFlags Flags, IntPtr notUsed1, IntPtr notUsed2, CertEnumSystemStoreCallBackProto fn); /// <summary> /// signature of call back function used by CertEnumSystemStore /// </summary> internal delegate bool CertEnumSystemStoreCallBackProto([MarshalAs(UnmanagedType.LPWStr)] string storeName, DWORD dwFlagsNotUsed, IntPtr notUsed1, IntPtr notUsed2, IntPtr notUsed3); /// <summary> /// signature of cert enumeration function /// </summary> [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CertEnumCertificatesInStore(IntPtr storeHandle, IntPtr certContext); /// <summary> /// signature of cert find function /// </summary> [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CertFindCertificateInStore( IntPtr hCertStore, Security.NativeMethods.CertOpenStoreEncodingType dwEncodingType, DWORD dwFindFlags, // 0 Security.NativeMethods.CertFindType dwFindType, [MarshalAs(UnmanagedType.LPWStr)] string pvFindPara, IntPtr notUsed1); // pPrevCertContext [Flags] internal enum CertFindType { // pvFindPara: CERT_COMPARE_ANY = 0 << 16, // null CERT_FIND_ISSUER_STR = (8 << 16) | 4, // substring CERT_FIND_SUBJECT_STR = (8 << 16) | 7, // substring CERT_FIND_CROSS_CERT_DIST_POINTS = 17 << 16, // null CERT_FIND_SUBJECT_INFO_ACCESS = 19 << 16, // null CERT_FIND_HASH_STR = 20 << 16, // thumbprint } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags); [Flags] internal enum CertStoreFlags { CERT_SYSTEM_STORE_CURRENT_USER = 1 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE = 2 << 16, CERT_SYSTEM_STORE_CURRENT_SERVICE = 4 << 16, CERT_SYSTEM_STORE_SERVICES = 5 << 16, CERT_SYSTEM_STORE_USERS = 6 << 16, CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = 7 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = 8 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = 9 << 16, } [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertGetEnhancedKeyUsage(IntPtr pCertContext, // PCCERT_CONTEXT DWORD dwFlags, IntPtr pUsage, // PCERT_ENHKEY_USAGE out int pcbUsage); // DWORD* [DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CertOpenStore(CertOpenStoreProvider storeProvider, CertOpenStoreEncodingType dwEncodingType, IntPtr notUsed1, // hCryptProv CertOpenStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string storeName); [Flags] internal enum CertOpenStoreFlags { CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001, CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004, CERT_STORE_DELETE_FLAG = 0x00000010, CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020, CERT_STORE_SHARE_STORE_FLAG = 0x00000040, CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080, CERT_STORE_MANIFOLD_FLAG = 0x00000100, CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200, CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400, CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800, CERT_STORE_READONLY_FLAG = 0x00008000, CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000, CERT_STORE_CREATE_NEW_FLAG = 0x00002000, CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000, CERT_SYSTEM_STORE_CURRENT_USER = 1 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE = 2 << 16, CERT_SYSTEM_STORE_CURRENT_SERVICE = 4 << 16, CERT_SYSTEM_STORE_SERVICES = 5 << 16, CERT_SYSTEM_STORE_USERS = 6 << 16, CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = 7 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = 8 << 16, CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = 9 << 16, } [Flags] internal enum CertOpenStoreProvider { CERT_STORE_PROV_MEMORY = 2, CERT_STORE_PROV_SYSTEM = 10, CERT_STORE_PROV_SYSTEM_REGISTRY = 13, } [Flags] internal enum CertOpenStoreEncodingType { X509_ASN_ENCODING = 0x00000001, } [DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertControlStore( IntPtr hCertStore, DWORD dwFlags, CertControlStoreType dwCtrlType, IntPtr pvCtrlPara); [Flags] internal enum CertControlStoreType : uint { CERT_STORE_CTRL_RESYNC = 1, CERT_STORE_CTRL_COMMIT = 3, CERT_STORE_CTRL_AUTO_RESYNC = 4, } [Flags] internal enum AddCertificateContext : uint { CERT_STORE_ADD_NEW = 1, CERT_STORE_ADD_USE_EXISTING = 2, CERT_STORE_ADD_REPLACE_EXISTING = 3, CERT_STORE_ADD_ALWAYS = 4, CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5, CERT_STORE_ADD_NEWER = 6, CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7 } [Flags] internal enum CertPropertyId { CERT_KEY_PROV_HANDLE_PROP_ID = 1, CERT_KEY_PROV_INFO_PROP_ID = 2, // CRYPT_KEY_PROV_INFO CERT_SHA1_HASH_PROP_ID = 3, CERT_MD5_HASH_PROP_ID = 4, CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID = 102, } [Flags] internal enum NCryptDeletKeyFlag { NCRYPT_MACHINE_KEY_FLAG = 0x00000020, // same as CAPI CRYPT_MACHINE_KEYSET NCRYPT_SILENT_FLAG = 0x00000040, // same as CAPI CRYPT_SILENT } [Flags] internal enum ProviderFlagsEnum : uint { CRYPT_VERIFYCONTEXT = 0xF0000000, CRYPT_NEWKEYSET = 0x00000008, CRYPT_DELETEKEYSET = 0x00000010, CRYPT_MACHINE_KEYSET = 0x00000020, CRYPT_SILENT = 0x00000040, } internal enum ProviderParam : int { PP_CLIENT_HWND = 1, } internal enum PROV : uint { /// <summary> /// The PROV_RSA_FULL type. /// </summary> RSA_FULL = 1, /// <summary> /// The PROV_RSA_SIG type. /// </summary> RSA_SIG = 2, /// <summary> /// The PROV_RSA_DSS type. /// </summary> DSS = 3, /// <summary> /// The PROV_FORTEZZA type. /// </summary> FORTEZZA = 4, /// <summary> /// The PROV_MS_EXCHANGE type. /// </summary> MS_EXCHANGE = 5, /// <summary> /// The PROV_SSL type. /// </summary> SSL = 6, /// <summary> /// The PROV_RSA_SCHANNEL type. SSL certificates are generated with these providers. /// </summary> RSA_SCHANNEL = 12, /// <summary> /// The PROV_DSS_DH type. /// </summary> DSS_DH = 13, /// <summary> /// The PROV_EC_ECDSA type. /// </summary> EC_ECDSA_SIG = 14, /// <summary> /// The PROV_EC_ECNRA_SIG type. /// </summary> EC_ECNRA_SIG = 15, /// <summary> /// The PROV_EC_ECDSA_FULL type. /// </summary> EC_ECDSA_FULL = 16, /// <summary> /// The PROV_EC_ECNRA_FULL type. /// </summary> EC_ECNRA_FULL = 17, /// <summary> /// The PROV_DH_SCHANNEL type. /// </summary> DH_SCHANNEL = 18, /// <summary> /// The PROV_SPYRUS_LYNKS type. /// </summary> SPYRUS_LYNKS = 20, /// <summary> /// The PROV_RNG type. /// </summary> RNG = 21, /// <summary> /// The PROV_INTEL_SEC type. /// </summary> INTEL_SEC = 22 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CRYPT_KEY_PROV_INFO { /// <summary> /// String naming a key container within a particular CSP. /// </summary> public string pwszContainerName; /// <summary> /// String that names a CSP. /// </summary> public string pwszProvName; /// <summary> /// CSP type. /// </summary> public PROV dwProvType; /// <summary> /// Flags value indicating whether a key container is to be created or destroyed, and /// whether an application is allowed access to a key container. /// </summary> public uint dwFlags; /// <summary> /// Number of elements in the rgProvParam array. /// </summary> public uint cProvParam; /// <summary> /// Array of pointers to CRYPT_KEY_PROV_PARAM structures. /// </summary> public IntPtr rgProvParam; /// <summary> /// The specification of the private key to retrieve. AT_KEYEXCHANGE and AT_SIGNATURE /// are defined for the default provider. /// </summary> public uint dwKeySpec; } internal const string NCRYPT_WINDOW_HANDLE_PROPERTY = "HWND Handle"; [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertDeleteCertificateFromStore(IntPtr pCertContext); [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CertDuplicateCertificateContext(IntPtr pCertContext); [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertAddCertificateContextToStore(IntPtr hCertStore, IntPtr pCertContext, DWORD dwAddDisposition, ref IntPtr ppStoreContext); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertFreeCertificateContext(IntPtr certContext); [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertGetCertificateContextProperty(IntPtr pCertContext, CertPropertyId dwPropId, IntPtr pvData, ref int pcbData); [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertSetCertificateContextProperty(IntPtr pCertContext, CertPropertyId dwPropId, DWORD dwFlags, IntPtr pvData); [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CryptFindLocalizedName(string pwszCryptName); [DllImport(PinvokeDllNames.CryptAcquireContextDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CryptAcquireContext(ref IntPtr hProv, String strContainerName, String strProviderName, int nProviderType, uint uiProviderFlags); [DllImport(PinvokeDllNames.CryptReleaseContextDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags); [DllImport(PinvokeDllNames.CryptSetProvParamDllName, SetLastError = true)] internal static extern unsafe bool CryptSetProvParam(IntPtr hProv, ProviderParam dwParam, void* pbData, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern int NCryptOpenStorageProvider(ref IntPtr hProv, String strProviderName, uint dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern int NCryptOpenKey(IntPtr hProv, ref IntPtr hKey, String strKeyName, uint dwLegacySpec, uint dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern unsafe int NCryptSetProperty(IntPtr hProv, String pszProperty, void* pbInput, int cbInput, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern int NCryptDeleteKey(IntPtr hKey, uint dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern int NCryptFreeObject(IntPtr hObject); // ----------------------------------------------------------------- // cryptUI.dll stuff // // // CryptUIWizDigitalSign() function and associated structures/enums // [DllImport("cryptUI.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CryptUIWizDigitalSign(DWORD dwFlags, IntPtr hwndParentNotUsed, IntPtr pwszWizardTitleNotUsed, IntPtr pDigitalSignInfo, IntPtr ppSignContextNotUsed); [Flags] internal enum CryptUIFlags { CRYPTUI_WIZ_NO_UI = 0x0001 // other flags not used }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO { internal DWORD dwSize; internal DWORD dwSubjectChoice; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszFileName; internal DWORD dwSigningCertChoice; internal IntPtr pSigningCertContext; // PCCERT_CONTEXT [MarshalAs(UnmanagedType.LPWStr)] internal string pwszTimestampURL; internal DWORD dwAdditionalCertChoice; internal IntPtr pSignExtInfo; // PCCRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO }; [Flags] internal enum SignInfoSubjectChoice { CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = 0x01 //CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_BLOB = 0x02 NotUsed }; [Flags] internal enum SignInfoCertChoice { CRYPTUI_WIZ_DIGITAL_SIGN_CERT = 0x01 //CRYPTUI_WIZ_DIGITAL_SIGN_STORE = 0x02, NotUsed //CRYPTUI_WIZ_DIGITAL_SIGN_PVK = 0x03, NotUsed }; [Flags] internal enum SignInfoAdditionalCertChoice { CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN = 1, CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT = 2 }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO { internal DWORD dwSize; internal DWORD dwAttrFlagsNotUsed; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszMoreInfoLocation; [MarshalAs(UnmanagedType.LPStr)] internal string pszHashAlg; internal IntPtr pwszSigningCertDisplayStringNotUsed; // LPCWSTR internal IntPtr hAdditionalCertStoreNotUsed; // HCERTSTORE internal IntPtr psAuthenticatedNotUsed; // PCRYPT_ATTRIBUTES internal IntPtr psUnauthenticatedNotUsed; // PCRYPT_ATTRIBUTES }; [ArchitectureSensitive] internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO InitSignInfoExtendedStruct(string description, string moreInfoUrl, string hashAlgorithm) { CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO siex = new CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO(); siex.dwSize = (DWORD)Marshal.SizeOf(siex); siex.dwAttrFlagsNotUsed = 0; siex.pwszDescription = description; siex.pwszMoreInfoLocation = moreInfoUrl; siex.pszHashAlg = null; siex.pwszSigningCertDisplayStringNotUsed = IntPtr.Zero; siex.hAdditionalCertStoreNotUsed = IntPtr.Zero; siex.psAuthenticatedNotUsed = IntPtr.Zero; siex.psUnauthenticatedNotUsed = IntPtr.Zero; if (hashAlgorithm != null) { siex.pszHashAlg = hashAlgorithm; } return siex; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_OID_INFO { /// DWORD->unsigned int public uint cbSize; /// LPCSTR->CHAR* [MarshalAsAttribute(UnmanagedType.LPStr)] public string pszOID; /// LPCWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] public string pwszName; /// DWORD->unsigned int public uint dwGroupId; /// Anonymous_a3ae7823_8a1d_432c_bc07_a72b6fc6c7d8 public Anonymous_a3ae7823_8a1d_432c_bc07_a72b6fc6c7d8 Union1; /// CRYPT_DATA_BLOB->_CRYPTOAPI_BLOB public CRYPT_ATTR_BLOB ExtraInfo; } [StructLayout(LayoutKind.Explicit)] internal struct Anonymous_a3ae7823_8a1d_432c_bc07_a72b6fc6c7d8 { /// DWORD->unsigned int [FieldOffset(0)] public uint dwValue; /// ALG_ID->unsigned int [FieldOffset(0)] public uint Algid; /// DWORD->unsigned int [FieldOffset(0)] public uint dwLength; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ATTR_BLOB { /// DWORD->unsigned int public uint cbData; /// BYTE* public System.IntPtr pbData; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_DATA_BLOB { /// DWORD->unsigned int public uint cbData; /// BYTE* public System.IntPtr pbData; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CONTEXT { public int dwCertEncodingType; public IntPtr pbCertEncoded; public int cbCertEncoded; public IntPtr pCertInfo; public IntPtr hCertStore; } // Return the OID info for a given algorithm [DllImport("crypt32.dll", EntryPoint = "CryptFindOIDInfo")] internal static extern IntPtr CryptFindOIDInfo( uint dwKeyType, System.IntPtr pvKey, uint dwGroupId); [ArchitectureSensitive] internal static DWORD GetCertChoiceFromSigningOption( SigningOption option) { DWORD cc = 0; switch (option) { case SigningOption.AddOnlyCertificate: cc = 0; break; case SigningOption.AddFullCertificateChain: cc = (DWORD)SignInfoAdditionalCertChoice.CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN; break; case SigningOption.AddFullCertificateChainExceptRoot: cc = (DWORD)SignInfoAdditionalCertChoice.CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT; break; default: cc = (DWORD)SignInfoAdditionalCertChoice.CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT; break; } return cc; } [ArchitectureSensitive] internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO InitSignInfoStruct(string fileName, X509Certificate2 signingCert, string timeStampServerUrl, string hashAlgorithm, SigningOption option) { CRYPTUI_WIZ_DIGITAL_SIGN_INFO si = new CRYPTUI_WIZ_DIGITAL_SIGN_INFO(); si.dwSize = (DWORD)Marshal.SizeOf(si); si.dwSubjectChoice = (DWORD)SignInfoSubjectChoice.CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE; si.pwszFileName = fileName; si.dwSigningCertChoice = (DWORD)SignInfoCertChoice.CRYPTUI_WIZ_DIGITAL_SIGN_CERT; si.pSigningCertContext = signingCert.Handle; si.pwszTimestampURL = timeStampServerUrl; si.dwAdditionalCertChoice = GetCertChoiceFromSigningOption(option); CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO siex = InitSignInfoExtendedStruct("", "", hashAlgorithm); IntPtr pSiexBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(siex)); Marshal.StructureToPtr(siex, pSiexBuffer, false); si.pSignExtInfo = pSiexBuffer; return si; } // ----------------------------------------------------------------- // wintrust.dll stuff // // // WinVerifyTrust() function and associated structures/enums // [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern DWORD WinVerifyTrust( IntPtr hWndNotUsed, // HWND IntPtr pgActionID, // GUID* IntPtr pWinTrustData // WINTRUST_DATA* ); [StructLayout(LayoutKind.Sequential)] internal struct WINTRUST_FILE_INFO { internal DWORD cbStruct; // = sizeof(WINTRUST_FILE_INFO) [MarshalAs(UnmanagedType.LPWStr)] internal string pcwszFilePath; // LPCWSTR internal IntPtr hFileNotUsed; // optional, HANDLE to pcwszFilePath internal IntPtr pgKnownSubjectNotUsed; // optional: GUID* : fill if the // subject type is known }; [StructLayoutAttribute(LayoutKind.Sequential)] internal struct WINTRUST_BLOB_INFO { /// DWORD->unsigned int internal uint cbStruct; /// GUID->_GUID internal GUID gSubject; /// LPCWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] internal string pcwszDisplayName; /// DWORD->unsigned int internal uint cbMemObject; /// BYTE* internal System.IntPtr pbMemObject; /// DWORD->unsigned int internal uint cbMemSignedMsg; /// BYTE* internal System.IntPtr pbMemSignedMsg; } [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct GUID { /// unsigned int internal uint Data1; /// unsigned short internal ushort Data2; /// unsigned short internal ushort Data3; /// unsigned char[8] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] internal byte[] Data4; } [ArchitectureSensitive] internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName) { WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO(); fi.cbStruct = (DWORD)Marshal.SizeOf(fi); fi.pcwszFilePath = fileName; fi.hFileNotUsed = IntPtr.Zero; fi.pgKnownSubjectNotUsed = IntPtr.Zero; return fi; } [ArchitectureSensitive] internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content) { WINTRUST_BLOB_INFO bi = new WINTRUST_BLOB_INFO(); byte[] contentBytes = System.Text.Encoding.Unicode.GetBytes(content); // The GUID of the PowerShell SIP bi.gSubject.Data1 = 0x603bcc1f; bi.gSubject.Data2 = 0x4b59; bi.gSubject.Data3 = 0x4e08; bi.gSubject.Data4 = new byte[] { 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51 }; bi.cbStruct = (DWORD)Marshal.SizeOf(bi); bi.pcwszDisplayName = fileName; bi.cbMemObject = (uint)contentBytes.Length; bi.pbMemObject = Marshal.AllocCoTaskMem(contentBytes.Length); Marshal.Copy(contentBytes, 0, bi.pbMemObject, contentBytes.Length); return bi; } [Flags] internal enum WintrustUIChoice { WTD_UI_ALL = 1, WTD_UI_NONE = 2, WTD_UI_NOBAD = 3, WTD_UI_NOGOOD = 4 }; [Flags] internal enum WintrustUnionChoice { WTD_CHOICE_FILE = 1, //WTD_CHOICE_CATALOG = 2, WTD_CHOICE_BLOB = 3, //WTD_CHOICE_SIGNER = 4, //WTD_CHOICE_CERT = 5, }; [Flags] internal enum WintrustProviderFlags { WTD_PROV_FLAGS_MASK = 0x0000FFFF, WTD_USE_IE4_TRUST_FLAG = 0x00000001, WTD_NO_IE4_CHAIN_FLAG = 0x00000002, WTD_NO_POLICY_USAGE_FLAG = 0x00000004, WTD_REVOCATION_CHECK_NONE = 0x00000010, WTD_REVOCATION_CHECK_END_CERT = 0x00000020, WTD_REVOCATION_CHECK_CHAIN = 0x00000040, WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x00000080, WTD_SAFER_FLAG = 0x00000100, WTD_HASH_ONLY_FLAG = 0x00000200, WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, WTD_LIFETIME_SIGNING_FLAG = 0x00000800, WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 }; [Flags] internal enum WintrustAction { WTD_STATEACTION_IGNORE = 0x00000000, WTD_STATEACTION_VERIFY = 0x00000001, WTD_STATEACTION_CLOSE = 0x00000002, WTD_STATEACTION_AUTO_CACHE = 0x00000003, WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 }; [StructLayoutAttribute(LayoutKind.Explicit)] internal struct WinTrust_Choice { /// WINTRUST_FILE_INFO_* [FieldOffsetAttribute(0)] internal System.IntPtr pFile; /// WINTRUST_CATALOG_INFO_* [FieldOffsetAttribute(0)] internal System.IntPtr pCatalog; /// WINTRUST_BLOB_INFO_* [FieldOffsetAttribute(0)] internal System.IntPtr pBlob; /// WINTRUST_SGNR_INFO_* [FieldOffsetAttribute(0)] internal System.IntPtr pSgnr; /// WINTRUST_CERT_INFO_* [FieldOffsetAttribute(0)] internal System.IntPtr pCert; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct WINTRUST_DATA { /// DWORD->unsigned int internal uint cbStruct; /// LPVOID->void* internal System.IntPtr pPolicyCallbackData; /// LPVOID->void* internal System.IntPtr pSIPClientData; /// DWORD->unsigned int internal uint dwUIChoice; /// DWORD->unsigned int internal uint fdwRevocationChecks; /// DWORD->unsigned int internal uint dwUnionChoice; /// WinTrust_Choice struct internal WinTrust_Choice Choice; /// DWORD->unsigned int internal uint dwStateAction; /// HANDLE->void* internal System.IntPtr hWVTStateData; /// WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] internal string pwszURLReference; /// DWORD->unsigned int internal uint dwProvFlags; /// DWORD->unsigned int internal uint dwUIContext; } [ArchitectureSensitive] internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi) { WINTRUST_DATA wtd = new WINTRUST_DATA(); wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd); wtd.pPolicyCallbackData = IntPtr.Zero; wtd.pSIPClientData = IntPtr.Zero; wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; wtd.fdwRevocationChecks = 0; wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_FILE; IntPtr pFileBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi)); Marshal.StructureToPtr(wfi, pFileBuffer, false); wtd.Choice.pFile = pFileBuffer; wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; wtd.hWVTStateData = IntPtr.Zero; wtd.pwszURLReference = null; wtd.dwProvFlags = 0; return wtd; } [ArchitectureSensitive] internal static WINTRUST_DATA InitWintrustDataStructFromBlob(WINTRUST_BLOB_INFO wbi) { WINTRUST_DATA wtd = new WINTRUST_DATA(); wtd.cbStruct = (DWORD)Marshal.SizeOf(wbi); wtd.pPolicyCallbackData = IntPtr.Zero; wtd.pSIPClientData = IntPtr.Zero; wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; wtd.fdwRevocationChecks = 0; wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB; IntPtr pBlob = Marshal.AllocCoTaskMem(Marshal.SizeOf(wbi)); Marshal.StructureToPtr(wbi, pBlob, false); wtd.Choice.pBlob = pBlob; wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; wtd.hWVTStateData = IntPtr.Zero; wtd.pwszURLReference = null; wtd.dwProvFlags = 0; return wtd; } [ArchitectureSensitive] internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd) { DWORD dwResult = Win32Errors.E_FAIL; IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; IntPtr wtdBuffer = IntPtr.Zero; Guid actionVerify = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); try { WINTRUST_ACTION_GENERIC_VERIFY_V2 = Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); Marshal.StructureToPtr(actionVerify, WINTRUST_ACTION_GENERIC_VERIFY_V2, false); wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_CLOSE; wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); Marshal.StructureToPtr(wtd, wtdBuffer, false); // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. #pragma warning disable 56523 dwResult = WinVerifyTrust( IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, wtdBuffer); #pragma warning enable 56523 wtd = Marshal.PtrToStructure<WINTRUST_DATA>(wtdBuffer); } finally { Marshal.DestroyStructure<WINTRUST_DATA>(wtdBuffer); Marshal.FreeCoTaskMem(wtdBuffer); Marshal.DestroyStructure<Guid>(WINTRUST_ACTION_GENERIC_VERIFY_V2); Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); } // Clear the blob or file info, depending on the type of // verification that was done. if (wtd.dwUnionChoice == (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB) { WINTRUST_BLOB_INFO originalBlob = (WINTRUST_BLOB_INFO)Marshal.PtrToStructure<WINTRUST_BLOB_INFO>(wtd.Choice.pBlob); Marshal.FreeCoTaskMem(originalBlob.pbMemObject); Marshal.DestroyStructure<WINTRUST_BLOB_INFO>(wtd.Choice.pBlob); Marshal.FreeCoTaskMem(wtd.Choice.pBlob); } else { Marshal.DestroyStructure<WINTRUST_FILE_INFO>(wtd.Choice.pFile); Marshal.FreeCoTaskMem(wtd.Choice.pFile); } return dwResult; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_CERT { private DWORD _cbStruct; internal IntPtr pCert; // PCCERT_CONTEXT private BOOL _fCommercial; private BOOL _fTrustedRoot; private BOOL _fSelfSigned; private BOOL _fTestCert; private DWORD _dwRevokedReason; private DWORD _dwConfidence; private DWORD _dwError; private IntPtr _pTrustListContext; // CTL_CONTEXT* private BOOL _fTrustListSignerCert; private IntPtr _pCtlContext; // PCCTL_CONTEXT private DWORD _dwCtlError; private BOOL _fIsCyclic; private IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_SGNR { private DWORD _cbStruct; private FILETIME _sftVerifyAsOf; private DWORD _csCertChain; private IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* private DWORD _dwSignerType; private IntPtr _psSigner; // CMSG_SIGNER_INFO* private DWORD _dwError; internal DWORD csCounterSigners; internal IntPtr pasCounterSigners; // CRYPT_PROVIDER_SGNR* private IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT }; [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr // CRYPT_PROVIDER_DATA* WTHelperProvDataFromStateData(IntPtr hStateData); [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr // CRYPT_PROVIDER_SGNR* WTHelperGetProvSignerFromChain( IntPtr pProvData, // CRYPT_PROVIDER_DATA* DWORD idxSigner, BOOL fCounterSigner, DWORD idxCounterSigner ); [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr // CRYPT_PROVIDER_CERT* WTHelperGetProvCertFromChain( IntPtr pSgnr, // CRYPT_PROVIDER_SGNR* DWORD idxCert ); /// Return Type: HRESULT->LONG->int ///pszFile: PCWSTR->WCHAR* ///hFile: HANDLE->void* ///sigInfoFlags: SIGNATURE_INFO_FLAGS->Anonymous_5157c654_2076_48e7_9241_84ac648615e9 ///psiginfo: SIGNATURE_INFO* ///ppCertContext: void** ///phWVTStateData: HANDLE* [DllImportAttribute("wintrust.dll", EntryPoint = "WTGetSignatureInfo", CallingConvention = CallingConvention.StdCall)] internal static extern int WTGetSignatureInfo([InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string pszFile, [InAttribute()] System.IntPtr hFile, SIGNATURE_INFO_FLAGS sigInfoFlags, ref SIGNATURE_INFO psiginfo, ref System.IntPtr ppCertContext, ref System.IntPtr phWVTStateData); internal static void FreeWVTStateData(System.IntPtr phWVTStateData) { WINTRUST_DATA wtd = new WINTRUST_DATA(); DWORD dwResult = Win32Errors.E_FAIL; IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; IntPtr wtdBuffer = IntPtr.Zero; Guid actionVerify = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); try { WINTRUST_ACTION_GENERIC_VERIFY_V2 = Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); Marshal.StructureToPtr(actionVerify, WINTRUST_ACTION_GENERIC_VERIFY_V2, false); wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd); wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; wtd.fdwRevocationChecks = 0; wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB; wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_CLOSE; wtd.hWVTStateData = phWVTStateData; wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); Marshal.StructureToPtr(wtd, wtdBuffer, false); // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. #pragma warning disable 56523 dwResult = WinVerifyTrust( IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, wtdBuffer); #pragma warning enable 56523 } finally { Marshal.DestroyStructure<WINTRUST_DATA>(wtdBuffer); Marshal.FreeCoTaskMem(wtdBuffer); Marshal.DestroyStructure<Guid>(WINTRUST_ACTION_GENERIC_VERIFY_V2); Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); } } // // stuff required for getting cert extensions // [StructLayout(LayoutKind.Sequential)] internal struct CERT_ENHKEY_USAGE { internal DWORD cUsageIdentifier; //[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=0)] //internal string[] rgpszUsageIdentifier; // LPSTR* internal IntPtr rgpszUsageIdentifier; }; internal enum SIGNATURE_STATE { /// SIGNATURE_STATE_UNSIGNED_MISSING -> 0 SIGNATURE_STATE_UNSIGNED_MISSING = 0, SIGNATURE_STATE_UNSIGNED_UNSUPPORTED, SIGNATURE_STATE_UNSIGNED_POLICY, SIGNATURE_STATE_INVALID_CORRUPT, SIGNATURE_STATE_INVALID_POLICY, SIGNATURE_STATE_VALID, SIGNATURE_STATE_TRUSTED, SIGNATURE_STATE_UNTRUSTED, } internal enum SIGNATURE_INFO_FLAGS { /// SIF_NONE -> 0x0000 SIF_NONE = 0, /// SIF_AUTHENTICODE_SIGNED -> 0x0001 SIF_AUTHENTICODE_SIGNED = 1, /// SIF_CATALOG_SIGNED -> 0x0002 SIF_CATALOG_SIGNED = 2, /// SIF_VERSION_INFO -> 0x0004 SIF_VERSION_INFO = 4, /// SIF_CHECK_OS_BINARY -> 0x0800 SIF_CHECK_OS_BINARY = 2048, /// SIF_BASE_VERIFICATION -> 0x1000 SIF_BASE_VERIFICATION = 4096, /// SIF_CATALOG_FIRST -> 0x2000 SIF_CATALOG_FIRST = 8192, /// SIF_MOTW -> 0x4000 SIF_MOTW = 16384, } internal enum SIGNATURE_INFO_AVAILABILITY { /// SIA_DISPLAYNAME -> 0x0001 SIA_DISPLAYNAME = 1, /// SIA_PUBLISHERNAME -> 0x0002 SIA_PUBLISHERNAME = 2, /// SIA_MOREINFOURL -> 0x0004 SIA_MOREINFOURL = 4, /// SIA_HASH -> 0x0008 SIA_HASH = 8, } internal enum SIGNATURE_INFO_TYPE { /// SIT_UNKNOWN -> 0 SIT_UNKNOWN = 0, SIT_AUTHENTICODE, SIT_CATALOG, } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct SIGNATURE_INFO { /// DWORD->unsigned int internal uint cbSize; /// SIGNATURE_STATE->Anonymous_7e0526d8_af30_47f9_9233_a77658d0f1e5 internal SIGNATURE_STATE nSignatureState; /// SIGNATURE_INFO_TYPE->Anonymous_27075e4b_faa5_4e57_ada0_6d49fae74187 internal SIGNATURE_INFO_TYPE nSignatureType; /// DWORD->unsigned int internal uint dwSignatureInfoAvailability; /// DWORD->unsigned int internal uint dwInfoAvailability; /// PWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] internal string pszDisplayName; /// DWORD->unsigned int internal uint cchDisplayName; /// PWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] internal string pszPublisherName; /// DWORD->unsigned int internal uint cchPublisherName; /// PWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] internal string pszMoreInfoURL; /// DWORD->unsigned int internal uint cchMoreInfoURL; /// LPBYTE->BYTE* internal System.IntPtr prgbHash; /// DWORD->unsigned int internal uint cbHash; /// BOOL->int internal int fOSBinary; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_INFO { /// DWORD->unsigned int internal uint dwVersion; /// CRYPT_INTEGER_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB SerialNumber; /// CRYPT_ALGORITHM_IDENTIFIER->_CRYPT_ALGORITHM_IDENTIFIER internal CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; /// CERT_NAME_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB Issuer; /// FILETIME->_FILETIME internal FILETIME NotBefore; /// FILETIME->_FILETIME internal FILETIME NotAfter; /// CERT_NAME_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB Subject; /// CERT_PUBLIC_KEY_INFO->_CERT_PUBLIC_KEY_INFO internal CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; /// CRYPT_BIT_BLOB->_CRYPT_BIT_BLOB internal CRYPT_BIT_BLOB IssuerUniqueId; /// CRYPT_BIT_BLOB->_CRYPT_BIT_BLOB internal CRYPT_BIT_BLOB SubjectUniqueId; /// DWORD->unsigned int internal uint cExtension; /// PCERT_EXTENSION->_CERT_EXTENSION* internal System.IntPtr rgExtension; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { /// LPSTR->CHAR* [MarshalAsAttribute(UnmanagedType.LPStr)] internal string pszObjId; /// CRYPT_OBJID_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB Parameters; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct FILETIME { /// DWORD->unsigned int internal uint dwLowDateTime; /// DWORD->unsigned int internal uint dwHighDateTime; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { /// CRYPT_ALGORITHM_IDENTIFIER->_CRYPT_ALGORITHM_IDENTIFIER internal CRYPT_ALGORITHM_IDENTIFIER Algorithm; /// CRYPT_BIT_BLOB->_CRYPT_BIT_BLOB internal CRYPT_BIT_BLOB PublicKey; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CRYPT_BIT_BLOB { /// DWORD->unsigned int internal uint cbData; /// BYTE* internal System.IntPtr pbData; /// DWORD->unsigned int internal uint cUnusedBits; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_EXTENSION { /// LPSTR->CHAR* [MarshalAsAttribute(UnmanagedType.LPStr)] internal string pszObjId; /// BOOL->int internal int fCritical; /// CRYPT_OBJID_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB Value; } } /// <summary> /// pinvoke methods from certca.dll /// </summary> internal static partial class NativeMethods { internal const int CRYPT_E_NOT_FOUND = unchecked((int)0x80092004); internal const int E_INVALID_DATA = unchecked((int)0x8007000d); internal const int NTE_NOT_SUPPORTED = unchecked((int)0x80090029); internal enum AltNameType : uint { CERT_ALT_NAME_OTHER_NAME = 1, CERT_ALT_NAME_RFC822_NAME = 2, CERT_ALT_NAME_DNS_NAME = 3, CERT_ALT_NAME_X400_ADDRESS = 4, CERT_ALT_NAME_DIRECTORY_NAME = 5, CERT_ALT_NAME_EDI_PARTY_NAME = 6, CERT_ALT_NAME_URL = 7, CERT_ALT_NAME_IP_ADDRESS = 8, CERT_ALT_NAME_REGISTERED_ID = 9, } internal enum CryptDecodeFlags : uint { CRYPT_DECODE_ENABLE_PUNYCODE_FLAG = 0x02000000, CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG = 0x04000000, CRYPT_DECODE_ENABLE_IA5CONVERSION_FLAG = (CRYPT_DECODE_ENABLE_PUNYCODE_FLAG | CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG), } } #region Check_UI_Allowed /// <summary> /// Used in CertificateProvider to detect if UI is allowed. /// </summary> internal static partial class NativeMethods { [DllImport("kernel32.dll")] internal static extern bool ProcessIdToSessionId(uint dwProcessId, out uint pSessionId); [DllImport("kernel32.dll")] internal static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] internal static extern IntPtr GetDesktopWindow(); } #endregion Check_UI_Allowed #region SAFER_APIs // SAFER native methods internal static partial class NativeMethods { /// Return Type: BOOL->int ///dwNumProperties: DWORD->unsigned int ///pCodeProperties: PSAFER_CODE_PROPERTIES->_SAFER_CODE_PROPERTIES* ///pLevelHandle: SAFER_LEVEL_HANDLE* ///lpReserved: LPVOID->void* [DllImportAttribute("advapi32.dll", EntryPoint = "SaferIdentifyLevel", SetLastError = true)] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool SaferIdentifyLevel( uint dwNumProperties, [InAttribute()] ref SAFER_CODE_PROPERTIES pCodeProperties, out IntPtr pLevelHandle, [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string bucket); /// Return Type: BOOL->int ///LevelHandle: SAFER_LEVEL_HANDLE->SAFER_LEVEL_HANDLE__* ///InAccessToken: HANDLE->void* ///OutAccessToken: PHANDLE->HANDLE* ///dwFlags: DWORD->unsigned int ///lpReserved: LPVOID->void* [DllImportAttribute("advapi32.dll", EntryPoint = "SaferComputeTokenFromLevel", SetLastError = true)] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool SaferComputeTokenFromLevel( [InAttribute()] IntPtr LevelHandle, [InAttribute()] System.IntPtr InAccessToken, ref System.IntPtr OutAccessToken, uint dwFlags, System.IntPtr lpReserved); /// Return Type: BOOL->int ///hLevelHandle: SAFER_LEVEL_HANDLE->SAFER_LEVEL_HANDLE__* [DllImportAttribute("advapi32.dll", EntryPoint = "SaferCloseLevel")] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool SaferCloseLevel([InAttribute()] IntPtr hLevelHandle); /// Return Type: BOOL->int ///hObject: HANDLE->void* [DllImportAttribute(PinvokeDllNames.CloseHandleDllName, EntryPoint = "CloseHandle")] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool CloseHandle([InAttribute()] System.IntPtr hObject); } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct SAFER_CODE_PROPERTIES { /// DWORD->unsigned int public uint cbSize; /// DWORD->unsigned int public uint dwCheckFlags; /// LPCWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] public string ImagePath; /// HANDLE->void* public System.IntPtr hImageFileHandle; /// DWORD->unsigned int public uint UrlZoneId; /// BYTE[SAFER_MAX_HASH_SIZE] [MarshalAsAttribute( UnmanagedType.ByValArray, SizeConst = NativeConstants.SAFER_MAX_HASH_SIZE, ArraySubType = UnmanagedType.I1)] public byte[] ImageHash; /// DWORD->unsigned int public uint dwImageHashSize; /// LARGE_INTEGER->_LARGE_INTEGER public LARGE_INTEGER ImageSize; /// ALG_ID->unsigned int public uint HashAlgorithm; /// LPBYTE->BYTE* public System.IntPtr pByteBlock; /// HWND->HWND__* public System.IntPtr hWndParent; /// DWORD->unsigned int public uint dwWVTUIChoice; } [StructLayoutAttribute(LayoutKind.Explicit)] internal struct LARGE_INTEGER { /// Anonymous_9320654f_2227_43bf_a385_74cc8c562686 [FieldOffsetAttribute(0)] public Anonymous_9320654f_2227_43bf_a385_74cc8c562686 Struct1; /// Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 [FieldOffsetAttribute(0)] public Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 u; /// LONGLONG->__int64 [FieldOffsetAttribute(0)] public long QuadPart; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct HWND__ { /// int public int unused; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct Anonymous_9320654f_2227_43bf_a385_74cc8c562686 { /// DWORD->unsigned int public uint LowPart; /// LONG->int public int HighPart; } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 { /// DWORD->unsigned int public uint LowPart; /// LONG->int public int HighPart; } #endregion SAFER_APIs /// <summary> /// pinvoke methods from advapi32.dll /// </summary> internal static partial class NativeMethods { // // This is duplicating some of the effort made in Win32Native.cs, // namespace = Microsoft.PowerShell.Commands.Internal.Win32Native // internal const uint ERROR_SUCCESS = 0; internal const uint ERROR_NO_TOKEN = 0x3f0; internal const uint STATUS_SUCCESS = 0; internal const uint STATUS_INVALID_PARAMETER = 0xC000000D; internal const uint ACL_REVISION = 2; internal const uint SYSTEM_SCOPED_POLICY_ID_ACE_TYPE = 0x13; internal const uint SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3; internal const uint INHERIT_ONLY_ACE = 0x8; internal const uint TOKEN_ASSIGN_PRIMARY = 0x0001; internal const uint TOKEN_DUPLICATE = 0x0002; internal const uint TOKEN_IMPERSONATE = 0x0004; internal const uint TOKEN_QUERY = 0x0008; internal const uint TOKEN_QUERY_SOURCE = 0x0010; internal const uint TOKEN_ADJUST_PRIVILEGES = 0x0020; internal const uint TOKEN_ADJUST_GROUPS = 0x0040; internal const uint TOKEN_ADJUST_DEFAULT = 0x0080; internal const uint TOKEN_ADJUST_SESSIONID = 0x0100; internal const uint SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; internal const uint SE_PRIVILEGE_ENABLED = 0x00000002; internal const uint SE_PRIVILEGE_REMOVED = 0X00000004; internal const uint SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; internal enum SeObjectType : uint { SE_UNKNOWN_OBJECT_TYPE = 0, SE_FILE_OBJECT = 1, SE_SERVICE = 2, SE_PRINTER = 3, SE_REGISTRY_KEY = 4, SE_LMSHARE = 5, SE_KERNEL_OBJECT = 6, SE_WINDOW_OBJECT = 7, SE_DS_OBJECT = 8, SE_DS_OBJECT_ALL = 9, SE_PROVIDER_DEFINED_OBJECT = 10, SE_WMIGUID_OBJECT = 11, SE_REGISTRY_WOW64_32KEY = 12 } internal enum SecurityInformation : uint { OWNER_SECURITY_INFORMATION = 0x00000001, GROUP_SECURITY_INFORMATION = 0x00000002, DACL_SECURITY_INFORMATION = 0x00000004, SACL_SECURITY_INFORMATION = 0x00000008, LABEL_SECURITY_INFORMATION = 0x00000010, ATTRIBUTE_SECURITY_INFORMATION = 0x00000020, SCOPE_SECURITY_INFORMATION = 0x00000040, BACKUP_SECURITY_INFORMATION = 0x00010000, PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000, PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000, UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000, UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LUID { internal uint LowPart; internal uint HighPart; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LUID_AND_ATTRIBUTES { internal LUID Luid; internal uint Attributes; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TOKEN_PRIVILEGE { internal uint PrivilegeCount; internal LUID_AND_ATTRIBUTES Privilege; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct ACL { internal byte AclRevision; internal byte Sbz1; internal ushort AclSize; internal ushort AceCount; internal ushort Sbz2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct ACE_HEADER { internal byte AceType; internal byte AceFlags; internal ushort AceSize; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SYSTEM_AUDIT_ACE { internal ACE_HEADER Header; internal uint Mask; internal uint SidStart; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LSA_UNICODE_STRING { internal ushort Length; internal ushort MaximumLength; internal IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CENTRAL_ACCESS_POLICY { internal IntPtr CAPID; internal LSA_UNICODE_STRING Name; internal LSA_UNICODE_STRING Description; internal LSA_UNICODE_STRING ChangeId; internal uint Flags; internal uint CAPECount; internal IntPtr CAPEs; } [DllImport(PinvokeDllNames.GetNamedSecurityInfoDllName, CharSet = CharSet.Unicode)] internal static extern uint GetNamedSecurityInfo( string pObjectName, SeObjectType ObjectType, SecurityInformation SecurityInfo, out IntPtr ppsidOwner, out IntPtr ppsidGroup, out IntPtr ppDacl, out IntPtr ppSacl, out IntPtr ppSecurityDescriptor ); [DllImport(PinvokeDllNames.SetNamedSecurityInfoDllName, CharSet = CharSet.Unicode)] internal static extern uint SetNamedSecurityInfo( string pObjectName, SeObjectType ObjectType, SecurityInformation SecurityInfo, IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl); [DllImport(PinvokeDllNames.ConvertStringSidToSidDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool ConvertStringSidToSid( string StringSid, out IntPtr Sid); [DllImport(PinvokeDllNames.IsValidSidDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool IsValidSid(IntPtr pSid); [DllImport(PinvokeDllNames.GetLengthSidDllName, CharSet = CharSet.Unicode)] internal static extern uint GetLengthSid(IntPtr pSid); [DllImport("Advapi32.dll", CharSet = CharSet.Unicode)] internal static extern uint LsaQueryCAPs( IntPtr[] CAPIDs, uint CAPIDCount, out IntPtr CAPs, out uint CAPCount); [DllImport(PinvokeDllNames.LsaFreeMemoryDllName, CharSet = CharSet.Unicode)] internal static extern uint LsaFreeMemory(IntPtr Buffer); [DllImport(PinvokeDllNames.InitializeAclDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool InitializeAcl( IntPtr pAcl, uint nAclLength, uint dwAclRevision); [DllImport("api-ms-win-security-base-l1-2-0.dll", CharSet = CharSet.Unicode)] internal static extern uint AddScopedPolicyIDAce( IntPtr Acl, uint AceRevision, uint AceFlags, uint AccessMask, IntPtr Sid); [DllImport(PinvokeDllNames.GetCurrentProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport(PinvokeDllNames.GetCurrentThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr GetCurrentThread(); [DllImport(PinvokeDllNames.OpenProcessTokenDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool OpenProcessToken( IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); [DllImport(PinvokeDllNames.OpenThreadTokenDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool OpenThreadToken( IntPtr ThreadHandle, uint DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle); [DllImport(PinvokeDllNames.LookupPrivilegeValueDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool LookupPrivilegeValue( string lpSystemName, string lpName, ref LUID lpLuid); [DllImport(PinvokeDllNames.AdjustTokenPrivilegesDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool AdjustTokenPrivileges( IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGE NewState, uint BufferLength, ref TOKEN_PRIVILEGE PreviousState, ref uint ReturnLength); [DllImport(PinvokeDllNames.LocalFreeDllName, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr LocalFree(IntPtr hMem); internal const uint DONT_RESOLVE_DLL_REFERENCES = 0x00000001; internal const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; internal const uint LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008; internal const uint LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010; internal const uint LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020; internal const uint LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040; internal const uint LOAD_LIBRARY_REQUIRE_SIGNED_TARGET = 0x00000080; internal const uint LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x00000100; internal const uint LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200; internal const uint LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400; internal const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; internal const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000; [DllImport(PinvokeDllNames.LoadLibraryEx, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr LoadLibraryExW( string DllName, IntPtr reserved, uint Flags); [DllImport(PinvokeDllNames.FreeLibrary, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool FreeLibrary( IntPtr Module); internal static bool IsSystem32DllPresent(string DllName) { bool DllExists = false; try { IntPtr module = LoadLibraryExW( DllName, IntPtr.Zero, NativeMethods.LOAD_LIBRARY_AS_DATAFILE | NativeMethods.LOAD_LIBRARY_AS_IMAGE_RESOURCE | NativeMethods.LOAD_LIBRARY_SEARCH_SYSTEM32); if (IntPtr.Zero != module) { FreeLibrary(module); DllExists = true; } } catch (Exception) { } return DllExists; } } // Constants needed for Catalog Error Handling internal partial class NativeConstants { // CRYPTCAT_E_AREA_HEADER = "0x00000000"; public const int CRYPTCAT_E_AREA_HEADER = 0; // CRYPTCAT_E_AREA_MEMBER = "0x00010000"; public const int CRYPTCAT_E_AREA_MEMBER = 65536; // CRYPTCAT_E_AREA_ATTRIBUTE = "0x00020000"; public const int CRYPTCAT_E_AREA_ATTRIBUTE = 131072; // CRYPTCAT_E_CDF_UNSUPPORTED = "0x00000001"; public const int CRYPTCAT_E_CDF_UNSUPPORTED = 1; // CRYPTCAT_E_CDF_DUPLICATE = "0x00000002"; public const int CRYPTCAT_E_CDF_DUPLICATE = 2; // CRYPTCAT_E_CDF_TAGNOTFOUND = "0x00000004"; public const int CRYPTCAT_E_CDF_TAGNOTFOUND = 4; // CRYPTCAT_E_CDF_MEMBER_FILE_PATH = "0x00010001"; public const int CRYPTCAT_E_CDF_MEMBER_FILE_PATH = 65537; // CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA = "0x00010002"; public const int CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA = 65538; // CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND = "0x00010004"; public const int CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND = 65540; // CRYPTCAT_E_CDF_BAD_GUID_CONV = "0x00020001"; public const int CRYPTCAT_E_CDF_BAD_GUID_CONV = 131073; // CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES = "0x00020002"; public const int CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES = 131074; // CRYPTCAT_E_CDF_ATTR_TYPECOMBO = "0x00020004"; public const int CRYPTCAT_E_CDF_ATTR_TYPECOMBO = 131076; } /// <summary> /// pinvoke methods from wintrust.dll /// These are added to Generate and Validate Window Catalog Files /// </summary> internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ATTRIBUTE_TYPE_VALUE { [MarshalAs(UnmanagedType.LPStr)] internal string pszObjId; internal CRYPT_ATTR_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct SIP_INDIRECT_DATA { internal CRYPT_ATTRIBUTE_TYPE_VALUE Data; internal CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; internal CRYPT_ATTR_BLOB Digest; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATCDF { private DWORD _cbStruct; private IntPtr _hFile; private DWORD _dwCurFilePos; private DWORD _dwLastMemberOffset; private BOOL _fEOF; [MarshalAs(UnmanagedType.LPWStr)] private string _pwszResultDir; private IntPtr _hCATStore; }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATMEMBER { internal DWORD cbStruct; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszFileName; internal GUID gSubjectType; internal DWORD fdwMemberFlags; internal IntPtr pIndirectData; internal DWORD dwCertVersion; internal DWORD dwReserved; internal IntPtr hReserved; internal CRYPT_ATTR_BLOB sEncodedIndirectData; internal CRYPT_ATTR_BLOB sEncodedMemberInfo; }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATATTRIBUTE { private DWORD _cbStruct; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; private DWORD _dwAttrTypeAndAction; internal DWORD cbValue; internal System.IntPtr pbValue; private DWORD _dwReserved; }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATSTORE { private DWORD _cbStruct; internal DWORD dwPublicVersion; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszP7File; private IntPtr _hProv; private DWORD _dwEncodingType; private DWORD _fdwStoreFlags; private IntPtr _hReserved; private IntPtr _hAttrs; private IntPtr _hCryptMsg; private IntPtr _hSorted; }; [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATCDFOpen( [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, CryptCATCDFOpenCallBack pfnParseError ); [DllImport("wintrust.dll")] internal static extern BOOL CryptCATCDFClose( IntPtr pCDF ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATCDFEnumCatAttributes( IntPtr pCDF, IntPtr pPrevAttr, CryptCATCDFOpenCallBack pfnParseError ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATCDFEnumMembersByCDFTagEx( IntPtr pCDF, IntPtr pwszPrevCDFTag, CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn, ref IntPtr ppMember, bool fContinueOnError, IntPtr pvReserved ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATCDFEnumAttributesWithCDFTag( IntPtr pCDF, IntPtr pwszMemberTag, IntPtr pMember, IntPtr pPrevAttr, CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATOpen( [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, DWORD fdwOpenFlags, IntPtr hProv, DWORD dwPublicVersion, DWORD dwEncodingType ); [DllImport("wintrust.dll")] internal static extern BOOL CryptCATClose( IntPtr hCatalog ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATStoreFromHandle( IntPtr hCatalog ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern bool CryptCATAdminAcquireContext2( ref IntPtr phCatAdmin, IntPtr pgSubsystem, [MarshalAs(UnmanagedType.LPWStr)] string pwszHashAlgorithm, IntPtr pStrongHashPolicy, DWORD dwFlags ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern bool CryptCATAdminReleaseContext( IntPtr phCatAdmin, DWORD dwFlags ); [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern unsafe IntPtr CreateFile( string lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, IntPtr hTemplateFile ); [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CryptCATAdminCalcHashFromFileHandle2( IntPtr hCatAdmin, IntPtr hFile, [In, Out] ref DWORD pcbHash, IntPtr pbHash, DWORD dwFlags ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATEnumerateCatAttr( IntPtr hCatalog, IntPtr pPrevAttr ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATEnumerateMember( IntPtr hCatalog, IntPtr pPrevMember ); [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATEnumerateAttr( IntPtr hCatalog, IntPtr pCatMember, IntPtr pPrevAttr ); /// <summary> /// signature of call back function used by CryptCATCDFOpen /// </summary> internal delegate void CryptCATCDFOpenCallBack(DWORD NotUsedDWORD1, DWORD NotUsedDWORD2, [MarshalAs(UnmanagedType.LPWStr)] string NotUsedString); /// <summary> /// signature of call back function used by CryptCATCDFEnumMembersByCDFTagEx /// </summary> internal delegate void CryptCATCDFEnumMembersByCDFTagExErrorCallBack(DWORD NotUsedDWORD1, DWORD NotUsedDWORD2, [MarshalAs(UnmanagedType.LPWStr)] string NotUsedString); } } #pragma warning restore 56523
35.436857
297
0.594016
[ "Apache-2.0", "MIT-0" ]
blindfuzzy/PowerShell-1
src/System.Management.Automation/security/nativeMethods.cs
75,764
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("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test")] [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("C53E324B-221A-4686-9BB1-161C8DA0FDE3")]
37.269231
84
0.77193
[ "MIT" ]
carable/Carable.Swagger.DocumentWithCode
Test/Properties/AssemblyInfo.cs
972
C#
namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public partial class SearchQualifierTypeStatus { private string _status; [System.Xml.Serialization.XmlAttributeAttribute()] public string Status { get { return this._status; } set { this._status = value; } } } }
29.346154
118
0.59633
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/SearchQualifierTypeStatus.cs
763
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; using RavenBOT.Common; using RavenBOT.Modules.Games.Methods; namespace RavenBOT.Modules.Games.Modules { [Group("Games")] public partial class Game : ReactiveBase { public GameService GameService { get; } public HelpService HelpService { get; } public Random Random { get; } public HttpClient HttpClient { get; } public Game(GameService gameService, HelpService helpService, Random random, HttpClient client) { GameService = gameService; HelpService = helpService; Random = random; HttpClient = client; } [Command("Help")] public async Task HelpAsync() { var res = await HelpService.PagedHelpAsync(Context, true, new List<string> { "games" }, "This module contains fun games to play"); if (res != null) { await PagedReplyAsync(res.ToCallBack().WithDefaultPagerCallbacks()); } else { await ReplyAsync("N/A"); } } [Command("DailyReward", RunMode = RunMode.Async)] [Summary("Get 200 free coins")] [RateLimit(2, 23, Measure.Hours)] public async Task DailyRewardAsync() { var guildobj = GameService.GetGameServer(Context.Guild.Id); var guser = GameService.GetGameUser(Context.User.Id, Context.Guild.Id); guser.Points = guser.Points + 200; GameService.SaveGameUser(guser); var embed = new EmbedBuilder { Title = $"Success, you have received 200 Points", Description = $"Balance: {guser.Points} Points", ThumbnailUrl = Context.User.GetAvatarUrl(), Color = Color.Blue, Footer = new EmbedFooterBuilder { Text = $"{Context.User.Username}#{Context.User.Discriminator}" } }; await ReplyAsync("", false, embed.Build()); } [Command("GameStats", RunMode = RunMode.Async)] [Summary("Get a user's game stats")] public async Task GambleStatsAsync(IUser user = null) { var guildobj = GameService.GetGameServer(Context.Guild.Id); if (user == null) { user = Context.User; } var guser = GameService.GetGameUser(user.Id, Context.Guild.Id); var embed = new EmbedBuilder { Title = $"{user.Username} Game Stats", Description = $"Balance: {guser.Points} Points\n" + $"Total Bet: {guser.TotalBet} Points\n" + $"Total Paid Out: {guser.TotalWon} Points\n", ThumbnailUrl = user.GetAvatarUrl(), Color = Color.Blue, Footer = new EmbedFooterBuilder { Text = $"{user.Username}#{user.Discriminator}" } }; await ReplyAsync("", false, embed.Build()); } } }
33.040404
103
0.537145
[ "MIT" ]
PassiveModding/Raven
Games/Modules/Game.cs
3,271
C#
namespace EventTraceKit.EventTracing.Collections { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using EventTraceKit.EventTracing.Support; public abstract class UniqueCollection<T> : Collection<T>, IUniqueList<T> { private readonly List<IUniqueConstraint<T>> uniqueConstraints = new List<IUniqueConstraint<T>>(); public bool IsUnique(T item) { if (default(T) == null && item == null) throw new ArgumentNullException(nameof(item)); return uniqueConstraints.All(c => c.IsSatisfiedBy(this, item)); } public bool IsUnique(T item, IDiagnostics diags) { if (default(T) == null && item == null) throw new ArgumentNullException(nameof(item)); if (diags == null) throw new ArgumentNullException(nameof(diags)); bool unique = true; foreach (var constraint in uniqueConstraints) { if (!constraint.IsSatisfiedBy(this, item, diags)) unique = false; } return unique; } public bool TryAdd(T item) { if (!IsUnique(item)) return false; Add(item); return true; } public bool TryAdd(T item, IDiagnostics diags) { if (!IsUnique(item, diags)) return false; Add(item); return true; } public void AddConstraint(IUniqueConstraint<T> constraint, IDiagnostics diags = null) { if (constraint == null) throw new ArgumentNullException(nameof(constraint)); if (Count != 0 && !Items.All(x => constraint.IsSatisfiedBy(this, x, diags))) { throw new InvalidOperationException( "Cannot add new constraint because it is violated by existing items."); } uniqueConstraints.Add(constraint); } protected override void InsertItem(int index, T item) { foreach (var constraint in uniqueConstraints) { if (!constraint.IsSatisfiedBy(this, item)) throw CreateDuplicateItemException(item, constraint); } foreach (var constraint in uniqueConstraints) constraint.NotifyAdd(item); base.InsertItem(index, item); } protected override void SetItem(int index, T newEntity) { T oldEntity = this[index]; foreach (var constraint in uniqueConstraints) { if (constraint.Changed(oldEntity, newEntity) && !constraint.IsSatisfiedBy(this, newEntity)) throw CreateDuplicateItemException(newEntity, constraint); } foreach (var constraint in uniqueConstraints) constraint.NotifyAdd(newEntity); base.SetItem(index, newEntity); } protected override void RemoveItem(int index) { T entity = this[index]; foreach (var constraint in uniqueConstraints) constraint.NotifyRemove(entity); base.RemoveItem(index); } private Exception CreateDuplicateItemException( T entity, IUniqueConstraint<T> constraint) { string message = constraint.FormatMessage(entity); return new DuplicateItemException(message); } } }
31.787611
93
0.564031
[ "MIT" ]
gix/event-trace-kit
src/EventTraceKit.EventTracing/Collections/UniqueCollection.cs
3,592
C#
using System; namespace _15_FastPrimeChecker { class Program { static void Main(string[] args) { int number = int.Parse(Console.ReadLine()); for (int toCheck = 2; toCheck <= number; toCheck++) { bool isPrime = true; for (int current = 2; current <= Math.Sqrt(toCheck); current++) { if (toCheck % current == 0) { isPrime = false; break; } } Console.WriteLine($"{toCheck} -> {isPrime}"); } } } }
26.153846
79
0.388235
[ "MIT" ]
Knightwalker/KB
02_Programming_Fundamentals/01_Programming_Fundamentals_with_C#/07_Data_Types_and_Variables_Exercise/15_fast_prime_checker.cs
680
C#
using NUnit.Framework; using Autodesk.RefineryToolkits.SpacePlanning.Analyze; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TestServices; using Autodesk.DesignScript.Geometry; namespace Autodesk.RefineryToolkits.SpacePlanning.Analyze.Tests { [TestFixture] public class OpenessTests : GeometricTestBase { private static Polygon obstacle; [SetUp] public void BeforeTest() { obstacle = Rectangle.ByWidthLength(10, 10) as Polygon; } /// <summary> /// Check if the openess score detects a obstacle on the left /// </summary> [Test] public void LeftObstacleTest() { // Create a rectangle object with 4 equal sides to check openess score Point origin = Point.ByCoordinates(-10, 0); Surface surface = Surface.ByPatch(Rectangle.ByWidthLength(CoordinateSystem.ByOrigin(origin), 10, 10)); // Calculate openess score double openessScore = Openess.FromSurface(surface,0,new List<Polygon> { }, new List<Polygon> { obstacle }); // Check of score equals 0.25, as the entire left side is blocked by the obstacle Assert.AreEqual(0.25, openessScore); // Dispose unused geometry obstacle.Dispose(); origin.Dispose(); } /// <summary> /// Check if the openess score detects a obstacle on the right /// </summary> [Test] public void RightObstacleTest() { // Create a rectangle object with 4 equal sides to check openess score Point origin = Point.ByCoordinates(10, 0); Surface surface = Surface.ByPatch(Rectangle.ByWidthLength(CoordinateSystem.ByOrigin(origin), 10, 10)); // Calculate openess score double openessScore = Openess.FromSurface(surface, 0, new List<Polygon> { }, new List<Polygon> { obstacle }); // Check of score equals 0.25, as the entire right side is blocked by the obstacle Assert.AreEqual(0.25, openessScore); // Dispose unused geometry obstacle.Dispose(); origin.Dispose(); } /// <summary> /// Check if the openess score detects a obstacle on the top /// </summary> [Test] public void TopObstacleTest() { // Create a rectangle object with 4 equal sides to check openess score Point origin = Point.ByCoordinates(0, 10); Surface surface = Surface.ByPatch(Rectangle.ByWidthLength(CoordinateSystem.ByOrigin(origin), 10, 10)); // Calculate openess score double openessScore = Openess.FromSurface(surface, 0, new List<Polygon> { }, new List<Polygon> { obstacle }); // Check of score equals 0.25, as the entire top is blocked by the obstacle Assert.AreEqual(0.25, openessScore); // Dispose unused geometry obstacle.Dispose(); origin.Dispose(); } /// <summary> /// Check if the openess score detects a obstacle on the bottom /// </summary> [Test] public void BottomObstacleTest() { // Create a rectangle object with 4 equal sides to check openess score Point origin = Point.ByCoordinates(0, -10); Surface surface = Surface.ByPatch(Rectangle.ByWidthLength(CoordinateSystem.ByOrigin(origin), 10, 10)); // Calculate openess score double openessScore = Openess.FromSurface(surface, 0, new List<Polygon> { }, new List<Polygon> { obstacle }); // Check of score equals 0.25, as the entire bottom is blocked by the obstacle Assert.AreEqual(0.25, openessScore); // Dispose unused geometry obstacle.Dispose(); origin.Dispose(); } /// <summary> /// Check if the openess score detects a obstacle on the left and right /// </summary> [Test] public void ObstacleOnBothSides() { List<Polygon> obstaclePolygons = new List<Polygon>() { obstacle.Translate(-10) as Polygon, obstacle.Translate(10) as Polygon }; // Create a rectangle object with 4 equal sides to check openess score Surface surface = Surface.ByPatch(Rectangle.ByWidthLength(10, 10)); // Calculate openess score double openessScore = Openess.FromSurface(surface, 0, new List<Polygon> { }, obstaclePolygons); // Check if score equals 0.50, as the entire right and left side is blocked by the obstacles Assert.AreEqual(0.50, openessScore); // Dispose unused geometry obstaclePolygons.ForEach(poly => poly.Dispose()); } } }
37.285714
121
0.603952
[ "Apache-2.0" ]
mrahmaniasl/RefineryToolkits
tests/Autodesk.RefineryToolkits.SpacePlanningTests/Analyze/OpenessTests.cs
4,961
C#
//----------------------------------------------------------------------- // <copyright file="TypeNameQualifier.cs"> // Copyright (c) Microsoft Corporation. All rights reserved. // // 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> //----------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.PSharp.LanguageServices.Syntax; namespace Microsoft.PSharp.LanguageServices.Rewriting.PSharp { /// <summary> /// Utility class to qualify type names, for typeof(Type) or Goto&lt;Type&gt;(). /// </summary> class TypeNameQualifier { #region fields /// <summary> /// Set of all qualified state names in the current machine. /// </summary> internal HashSet<string> CurrentAllQualifiedStateNames = new HashSet<string>(); /// <summary> /// Qualified state name corresponding to the procedure /// currently being rewritten. /// </summary> internal List<string> CurrentQualifiedStateName = new List<string>(); /// <summary> /// Set of rewritten qualified methods. /// </summary> internal HashSet<QualifiedMethod> RewrittenQualifiedMethods = new HashSet<QualifiedMethod>(); #endregion #region internal API /// <summary> /// Returns a fully-qualified name for the type inside the syntax node. /// </summary> /// <param name="typeUsed">Identifier of the type to rewrite</param> /// <param name="succeeded">Whether the fully qualified name was found</param> /// <returns>The fully qualified name</returns> internal string GetQualifiedName(TypeSyntax typeUsed, out bool succeeded) { var typeName = typeUsed.ToString(); var fullyQualifiedName = this.GetFullyQualifiedStateName(typeName); succeeded = fullyQualifiedName != typeUsed.ToString(); return fullyQualifiedName; } internal bool InitializeForNode(SyntaxNode node) { this.CurrentAllQualifiedStateNames.Clear(); this.CurrentQualifiedStateName.Clear(); // Gets containing method. var methoddecl = node.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault(); if (methoddecl == null) { return false; } // Gets containing class. var classdecl = methoddecl.Ancestors().OfType<ClassDeclarationSyntax>().FirstOrDefault(); if (classdecl == null) { return false; } // Gets containing namespace. var namespacedecl = classdecl.Ancestors().OfType<NamespaceDeclarationSyntax>().FirstOrDefault(); if (namespacedecl == null) { return false; } var rewrittenMethods = this.RewrittenQualifiedMethods.Where( val => val.Name.Equals(methoddecl.Identifier.ValueText) && val.MachineName.Equals(classdecl.Identifier.ValueText) && val.NamespaceName.Equals(namespacedecl.Name.ToString())).ToList(); // Must be unique. if (rewrittenMethods.Count == 0) { return false; } if (rewrittenMethods.Count > 1) { throw new RewritingException( string.Format("Multiple definitions of the same method {0} in namespace {1}, machine {2}", methoddecl.Identifier.ValueText, namespacedecl.Name.ToString(), classdecl.Identifier.ValueText) ); } var rewrittenMethod = rewrittenMethods.First(); this.CurrentAllQualifiedStateNames.UnionWith(rewrittenMethod.MachineQualifiedStateNames); this.CurrentQualifiedStateName.AddRange(rewrittenMethod.QualifiedStateName); return true; } #endregion #region private methods /// <summary> /// Given a partially-qualified state name, return the /// fully qualified state name. /// </summary> /// <param name="state">Partially qualified state name</param> /// <returns>Fully qualified state name</returns> private string GetFullyQualifiedStateName(string state) { if (this.CurrentQualifiedStateName.Count < 1 || CurrentAllQualifiedStateNames.Count == 0) { return state; } for (int i = this.CurrentQualifiedStateName.Count - 2; i >= 0; i--) { var prefix = this.CurrentQualifiedStateName[0]; for (int j = 1; j <= i; j++) { prefix += "." + this.CurrentQualifiedStateName[j]; } if (this.CurrentAllQualifiedStateNames.Contains(prefix + "." + state)) { return prefix + "." + state; } } return state; } /// <summary> /// Tokenizes a qualified name. /// </summary> /// <param name="state">Qualified name</param> /// <returns>Tokenized name</returns> private List<string> ToTokens(string state) { return state.Split('.').ToList(); } /// <summary> /// Collapses a tokenized qualified name. /// </summary> /// <param name="state">Tokenized qualified name</param> /// <returns>Qualified name</returns> private string FromTokens(List<string> state) { return state.Aggregate("", (acc, name) => acc == "" ? name : acc + "." + name); } #endregion } }
36.146067
110
0.565123
[ "MIT" ]
chandramouleswaran/PSharp
Source/LanguageServices/Rewriting/PSharp/Statements/TypeNameQualifier.cs
6,436
C#
using System; using System.Collections.Generic; using GammaJul.ForTea.Core.Parsing; using GammaJul.ForTea.Core.Psi; using GammaJul.ForTea.Core.Psi.FileType; using GammaJul.ForTea.Core.Services.CodeCompletion; using JetBrains.Annotations; using JetBrains.Application.CommandProcessing; using JetBrains.Application.Settings; using JetBrains.Application.UI.ActionSystem.Text; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.CodeCompletion; using JetBrains.ReSharper.Feature.Services.TypingAssist; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CachingLexers; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.TextControl; namespace GammaJul.ForTea.Core.Services.TypingAssist { [SolutionComponent] public class T4TypingAssist : TypingAssistLanguageBase<T4Language>, ITypingHandler { private static IReadOnlySet<TokenNodeType> AttributeValueTokens { get; } = new JetHashSet<TokenNodeType> { T4TokenNodeTypes.RAW_ATTRIBUTE_VALUE, T4TokenNodeTypes.DOLLAR, T4TokenNodeTypes.LEFT_PARENTHESIS, T4TokenNodeTypes.RIGHT_PARENTHESIS, T4TokenNodeTypes.PERCENT }; [NotNull] private readonly ICodeCompletionSessionManager _codeCompletionSessionManager; protected override bool IsSupported(ITextControl textControl) { IPsiSourceFile psiSourceFile = textControl.Document.GetPsiSourceFile(Solution); return psiSourceFile?.LanguageType.Is<T4ProjectFileType>() == true && psiSourceFile.IsValid(); } public bool QuickCheckAvailability(ITextControl textControl, IPsiSourceFile projectFile) => projectFile.LanguageType.Is<T4ProjectFileType>(); /// <summary>When = is typed, insert "".</summary> private bool OnEqualTyped(ITypingContext context) { ITextControl textControl = context.TextControl; // get the token type before = CachingLexer cachingLexer = GetCachingLexer(textControl); int offset = textControl.Selection.OneDocRangeWithCaret().GetMinOffset(); if (cachingLexer == null || offset <= 0 || !cachingLexer.FindTokenAt(offset - 1)) return false; // do nothing if we're not after an attribute name TokenNodeType tokenType = cachingLexer.TokenType; if (tokenType != T4TokenNodeTypes.TOKEN) return false; // insert = textControl.Selection.Delete(); textControl.FillVirtualSpaceUntilCaret(); textControl.Document.InsertText(offset, "="); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); // insert "" context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting \"\"")) { textControl.Document.InsertText(offset + 1, "\"\""); textControl.Caret.MoveTo(offset + 2, CaretVisualPlacement.DontScrollIfVisible); } // ignore if a subsequent " is typed by the user SkippingTypingAssist.SetCharsToSkip(textControl.Document, "\""); // popup auto completion _codeCompletionSessionManager.ExecuteAutoCompletion<T4AutopopupSettingsKey>(textControl, Solution, key => key.InDirectives); }); return true; } /// <summary>When a " is typed, insert another ".</summary> private bool OnQuoteTyped(ITypingContext context) { ITextControl textControl = context.TextControl; // get the token type after " CachingLexer cachingLexer = GetCachingLexer(textControl); int offset = textControl.Selection.OneDocRangeWithCaret().GetMinOffset(); if (cachingLexer == null || offset <= 0 || !cachingLexer.FindTokenAt(offset)) return false; // there is already another quote after the ", swallow the typing TokenNodeType tokenType = cachingLexer.TokenType; if (tokenType == T4TokenNodeTypes.QUOTE) { textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); return true; } // we're inside or after an attribute value, simply do nothing and let the " be typed if (tokenType == T4TokenNodeTypes.RAW_ATTRIBUTE_VALUE) return false; // insert the first " textControl.Selection.Delete(); textControl.FillVirtualSpaceUntilCaret(); textControl.Document.InsertText(offset, "\""); // insert the second " context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting \"")) { textControl.Document.InsertText(offset + 1, "\""); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); } // ignore if a subsequent " is typed by the user SkippingTypingAssist.SetCharsToSkip(textControl.Document, "\""); // popup auto completion _codeCompletionSessionManager.ExecuteAutoCompletion<T4AutopopupSettingsKey>(textControl, Solution, key => key.InDirectives); }); return true; } /// <summary>When a # is typed, complete code block</summary> private bool OnOctothorpeTyped(ITypingContext context) { if (IsInsertingBlockStart(context)) { InsertBlock(context); return true; } if (IsInsertingBlockEnd(context)) { InsertBlockEnd(context); return true; } return false; } private void InsertBlock([NotNull] ITypingContext context) { var textControl = context.TextControl; int offset = textControl.GetOffset(); InsertOctothorpe(textControl); context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting T4 Code Block")) { textControl.Document.InsertText(offset + 1, "#>"); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); } SkippingTypingAssist.SetCharsToSkip(textControl.Document, ">"); }); } private bool IsInsertingBlockStart([NotNull] ITypingContext context) { var textControl = context.TextControl; var lexer = GetCachingLexer(textControl); if (lexer == null) return false; int offset = textControl.GetOffset(); if (!lexer.FindTokenAt(offset - 1)) return false; string tokenText = lexer.GetTokenText(); return tokenText.EndsWith("<", StringComparison.Ordinal) && !tokenText.EndsWith("\\<", StringComparison.Ordinal); } private void InsertBlockEnd([NotNull] ITypingContext context) { var textControl = context.TextControl; int offset = textControl.GetOffset(); InsertOctothorpe(textControl); context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting >")) { textControl.Document.InsertText(offset + 1, ">"); textControl.Caret.MoveTo(offset + 2, CaretVisualPlacement.DontScrollIfVisible); } SkippingTypingAssist.SetCharsToSkip(textControl.Document, ">"); }); } private bool IsInsertingBlockEnd([NotNull] ITypingContext context) { var textControl = context.TextControl; var lexer = GetCachingLexer(textControl); if (lexer == null) return false; int offset = textControl.GetOffset(); var previousToken = FindPreviousToken(GetCachingLexer(textControl), offset); switch (previousToken) { case null: case T4TokenNodeType _: return false; default: return true; } } private static void InsertOctothorpe(ITextControl textControl) { int offset = textControl.GetOffset(); textControl.Selection.Delete(); textControl.FillVirtualSpaceUntilCaret(); textControl.Document.InsertText(offset, "#"); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); } [CanBeNull] private TokenNodeType FindPreviousToken([CanBeNull] CachingLexer lexer, int initialOffset) { if (lexer == null) return null; for (int offset = initialOffset; offset >= 0; offset -= 1) { if (!lexer.FindTokenAt(offset)) continue; var tokenType = lexer.TokenType; if (tokenType?.IsWhitespace != false) continue; return tokenType; } return null; } private bool OnEnterPressed(IActionContext context) { var textControl = context.TextControl; int charPos; var lexer = GetCachingLexer(textControl); if (lexer == null) return false; if (!CheckAndDeleteSelectionIfNeeded(textControl, selection => { charPos = TextControlToLexer(textControl, selection.StartOffset); if (charPos <= 0) return false; if (!lexer.FindTokenAt(charPos - 1)) return false; if (!IsBlockStart(lexer)) return false; if (!lexer.FindTokenAt(charPos)) return false; if (!IsBlockEnd(lexer)) return false; return true; }) ) return false; int offset = textControl.GetOffset(); var psiSourceFile = textControl.Document.GetPsiSourceFile(Solution); // Only insert one newline, as another gets inserted automatically textControl.Document.InsertText(offset, GetNewLineText(psiSourceFile)); textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible); return false; } private bool IsBlockEnd(CachingLexer lexer) => lexer.TokenType == T4TokenNodeTypes.BLOCK_END; private bool IsBlockStart([NotNull] CachingLexer lexer) => lexer.TokenType == T4TokenNodeTypes.STATEMENT_BLOCK_START || lexer.TokenType == T4TokenNodeTypes.EXPRESSION_BLOCK_START || lexer.TokenType == T4TokenNodeTypes.FEATURE_BLOCK_START; private bool OnDollarTyped(ITypingContext context) { var textControl = context.TextControl; if (!IsInAttributeValue(textControl)) return false; int offset = textControl.GetOffset(); textControl.Selection.Delete(); textControl.Document.InsertText(offset, "$"); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting T4 Macro Parenthesis")) { textControl.Document.InsertText(offset + 1, "()"); textControl.Caret.MoveTo(offset + 2, CaretVisualPlacement.DontScrollIfVisible); } SkippingTypingAssist.SetCharsToSkip(textControl.Document, "("); }); return true; } private bool IsInAttributeValue([NotNull] ITextControl textControl) { var lexer = GetCachingLexer(textControl); int offset = textControl.Selection.OneDocRangeWithCaret().GetMinOffset(); if (lexer == null || offset <= 1) return false; if (!lexer.FindTokenAt(offset - 1)) return false; var tokenType = lexer.TokenType; if (AttributeValueTokens.Contains(tokenType)) return true; if (tokenType != T4TokenNodeTypes.QUOTE) return false; if (!lexer.FindTokenAt(offset)) return false; return tokenType == T4TokenNodeTypes.QUOTE || tokenType == T4TokenNodeTypes.RAW_ATTRIBUTE_VALUE; } // When '%' is typed, insert another private bool OnPercentTyped(ITypingContext context) { var textControl = context.TextControl; if (!IsInAttributeValue(textControl)) return false; // get the token type after % var lexer = GetCachingLexer(textControl); int offset = textControl.Selection.OneDocRangeWithCaret().GetMinOffset(); if (lexer == null || offset <= 0 || !lexer.FindTokenAt(offset)) return false; // If there is already another percent after the %, swallow the typing var tokenType = lexer.TokenType; if (tokenType == T4TokenNodeTypes.PERCENT) { textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); return true; } // insert the first % textControl.Selection.Delete(); textControl.FillVirtualSpaceUntilCaret(); textControl.Document.InsertText(offset, "%"); // insert the second " context.QueueCommand(() => { using (CommandProcessor.UsingCommand("Inserting %")) { textControl.Document.InsertText(offset + 1, "%"); textControl.Caret.MoveTo(offset + 1, CaretVisualPlacement.DontScrollIfVisible); } }); return true; } public T4TypingAssist( Lifetime lifetime, [NotNull] ISolution solution, [NotNull] ISettingsStore settingsStore, [NotNull] CachingLexerService cachingLexerService, [NotNull] ICommandProcessor commandProcessor, [NotNull] IPsiServices psiServices, [NotNull] IExternalIntellisenseHost externalIntellisenseHost, [NotNull] SkippingTypingAssist skippingTypingAssist, [NotNull] ITypingAssistManager typingAssistManager, [NotNull] ICodeCompletionSessionManager codeCompletionSessionManager ) : base(solution, settingsStore, cachingLexerService, commandProcessor, psiServices, externalIntellisenseHost, skippingTypingAssist) { _codeCompletionSessionManager = codeCompletionSessionManager; typingAssistManager.AddTypingHandler(lifetime, '=', this, OnEqualTyped, IsTypingSmartParenthesisHandlerAvailable); typingAssistManager.AddTypingHandler(lifetime, '"', this, OnQuoteTyped, IsTypingSmartParenthesisHandlerAvailable); typingAssistManager.AddTypingHandler(lifetime, '#', this, OnOctothorpeTyped, IsTypingSmartParenthesisHandlerAvailable); typingAssistManager.AddTypingHandler(lifetime, '$', this, OnDollarTyped, IsTypingSmartParenthesisHandlerAvailable); typingAssistManager.AddTypingHandler(lifetime, '%', this, OnPercentTyped, IsTypingSmartParenthesisHandlerAvailable); typingAssistManager.AddActionHandler(lifetime, TextControlActions.ActionIds.Enter, this, OnEnterPressed, IsActionHandlerAvailable); } } }
35.702479
136
0.74213
[ "Apache-2.0" ]
denis417/ForTea
Backend/ForTea.Core/Services/TypingAssist/T4TypingAssist.cs
12,960
C#
using System; using System.Net; using System.Net.Http; using System.Web.Http; using Hangfire.Topshelf.AppServices; using Hangfire.Topshelf.Core; using Hangfire.Samples.Framework.Logging; namespace Hangfire.Topshelf.Apis { /// <summary> /// Restful Apis to process request and add it to background job from apps/micro-services. /// </summary> public class RPCController : ApiController { private static ILog logger = LogProvider.GetLogger(typeof(RPCController)); public IProductService ProductService { get; private set; } public RPCController(IProductService productService) { ProductService = productService; } /// <summary> /// Test apis /// </summary> /// <returns></returns> [Route("api/test")] [HttpGet] public HttpResponseMessage TestSimpleJob() { BackgroundJob.Enqueue<ISampleService>(x => x.SimpleJob(PerformContextToken.Null)); return Request.CreateResponse(HttpStatusCode.OK, "SimpleJob enqueued."); } /// <summary> /// Create order /// </summary> /// <param name="productId">Product Id</param> /// <returns></returns> [Route("api/order/create")] [HttpPost] public HttpResponseMessage CreateOrder(int productId) { if (!(ProductService.Exists(productId))) throw new Exception("Product not exists."); BackgroundJob.Enqueue<IOrderService>(x => x.CreateOrder(productId)); return Request.CreateResponse(HttpStatusCode.OK, "Order Creating..."); } } }
25.714286
91
0.717361
[ "MIT" ]
Fleetingold/Hangfire.Topshelf-myTest
Hangfire.Topshelf/Apis/RPCController.cs
1,442
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V251.Segment; using NHapi.Model.V251.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V251.Group { ///<summary> ///Represents the ORD_O04_TIMING_DIET Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: TQ1 (Timing/Quantity) </li> ///<li>1: TQ2 (Timing/Quantity Relationship) optional repeating</li> ///</ol> ///</summary> [Serializable] public class ORD_O04_TIMING_DIET : AbstractGroup { ///<summary> /// Creates a new ORD_O04_TIMING_DIET Group. ///</summary> public ORD_O04_TIMING_DIET(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(TQ1), true, false); this.add(typeof(TQ2), false, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORD_O04_TIMING_DIET - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns TQ1 (Timing/Quantity) - creates it if necessary ///</summary> public TQ1 TQ1 { get{ TQ1 ret = null; try { ret = (TQ1)this.GetStructure("TQ1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of TQ2 (Timing/Quantity Relationship) - creates it if necessary ///</summary> public TQ2 GetTQ2() { TQ2 ret = null; try { ret = (TQ2)this.GetStructure("TQ2"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of TQ2 /// * (Timing/Quantity Relationship) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public TQ2 GetTQ2(int rep) { return (TQ2)this.GetStructure("TQ2", rep); } /** * Returns the number of existing repetitions of TQ2 */ public int TQ2RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("TQ2").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the TQ2 results */ public IEnumerable<TQ2> TQ2s { get { for (int rep = 0; rep < TQ2RepetitionsUsed; rep++) { yield return (TQ2)this.GetStructure("TQ2", rep); } } } ///<summary> ///Adds a new TQ2 ///</summary> public TQ2 AddTQ2() { return this.AddStructure("TQ2") as TQ2; } ///<summary> ///Removes the given TQ2 ///</summary> public void RemoveTQ2(TQ2 toRemove) { this.RemoveStructure("TQ2", toRemove); } ///<summary> ///Removes the TQ2 at the given index ///</summary> public void RemoveTQ2At(int index) { this.RemoveRepetition("TQ2", index); } } }
27.616541
158
0.64171
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V251/Group/ORD_O04_TIMING_DIET.cs
3,673
C#
// ========================================================================== // IdContentData.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Squidex.Domain.Apps.Core.Schemas; using Squidex.Infrastructure; using Squidex.Infrastructure.Json; namespace Squidex.Domain.Apps.Core.Contents { public sealed class IdContentData : ContentData<long>, IEquatable<IdContentData> { public IdContentData() : base(EqualityComparer<long>.Default) { } public IdContentData(IdContentData copy) : base(copy, EqualityComparer<long>.Default) { } public IdContentData MergeInto(IdContentData target) { return Merge(this, target); } public IdContentData ToCleaned() { return Clean(this, new IdContentData()); } public IdContentData AddField(long id, ContentFieldData data) { Guard.GreaterThan(id, 0, nameof(id)); this[id] = data; return this; } public IdContentData ToCleanedReferences(Schema schema, ISet<Guid> deletedReferencedIds) { var result = new IdContentData(this); foreach (var field in schema.Fields) { if (field is IReferenceField referenceField) { var fieldKey = GetKey(field); var fieldData = this.GetOrDefault(fieldKey); if (fieldData == null) { continue; } foreach (var partitionValue in fieldData.Where(x => !x.Value.IsNull()).ToList()) { var newValue = referenceField.RemoveDeletedReferences(partitionValue.Value, deletedReferencedIds); fieldData[partitionValue.Key] = newValue; } } } return result; } public NamedContentData ToNameModel(Schema schema, bool decodeJsonField) { Guard.NotNull(schema, nameof(schema)); var result = new NamedContentData(); foreach (var fieldValue in this) { if (!schema.FieldsById.TryGetValue(fieldValue.Key, out var field)) { continue; } if (decodeJsonField && field is JsonField) { var encodedValue = new ContentFieldData(); foreach (var partitionValue in fieldValue.Value) { if (partitionValue.Value.IsNull()) { encodedValue[partitionValue.Key] = null; } else { var value = Encoding.UTF8.GetString(Convert.FromBase64String(partitionValue.Value.ToString())); encodedValue[partitionValue.Key] = JToken.Parse(value); } } result[field.Name] = encodedValue; } else { result[field.Name] = fieldValue.Value; } } return result; } public bool Equals(IdContentData other) { return base.Equals(other); } public override long GetKey(Field field) { return field.Id; } } }
29.44697
123
0.472086
[ "MIT" ]
andrewhoi/squidex
src/Squidex.Domain.Apps.Core/Contents/IdContentData.cs
3,889
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20201101 { public static class GetPublicIPPrefix { /// <summary> /// Public IP prefix resource. /// </summary> public static Task<GetPublicIPPrefixResult> InvokeAsync(GetPublicIPPrefixArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPublicIPPrefixResult>("azure-native:network/v20201101:getPublicIPPrefix", args ?? new GetPublicIPPrefixArgs(), options.WithVersion()); } public sealed class GetPublicIPPrefixArgs : Pulumi.InvokeArgs { /// <summary> /// Expands referenced resources. /// </summary> [Input("expand")] public string? Expand { get; set; } /// <summary> /// The name of the public IP prefix. /// </summary> [Input("publicIpPrefixName", required: true)] public string PublicIpPrefixName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetPublicIPPrefixArgs() { } } [OutputType] public sealed class GetPublicIPPrefixResult { /// <summary> /// The customIpPrefix that this prefix is associated with. /// </summary> public readonly Outputs.SubResourceResponse? CustomIPPrefix; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// The extended location of the public ip address. /// </summary> public readonly Outputs.ExtendedLocationResponse? ExtendedLocation; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// The allocated Prefix. /// </summary> public readonly string IpPrefix; /// <summary> /// The list of tags associated with the public IP prefix. /// </summary> public readonly ImmutableArray<Outputs.IpTagResponse> IpTags; /// <summary> /// The reference to load balancer frontend IP configuration associated with the public IP prefix. /// </summary> public readonly Outputs.SubResourceResponse LoadBalancerFrontendIpConfiguration; /// <summary> /// Resource location. /// </summary> public readonly string? Location; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// NatGateway of Public IP Prefix. /// </summary> public readonly Outputs.NatGatewayResponse? NatGateway; /// <summary> /// The Length of the Public IP Prefix. /// </summary> public readonly int? PrefixLength; /// <summary> /// The provisioning state of the public IP prefix resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// The public IP address version. /// </summary> public readonly string? PublicIPAddressVersion; /// <summary> /// The list of all referenced PublicIPAddresses. /// </summary> public readonly ImmutableArray<Outputs.ReferencedPublicIpAddressResponse> PublicIPAddresses; /// <summary> /// The resource GUID property of the public IP prefix resource. /// </summary> public readonly string ResourceGuid; /// <summary> /// The public IP prefix SKU. /// </summary> public readonly Outputs.PublicIPPrefixSkuResponse? Sku; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// A list of availability zones denoting the IP allocated for the resource needs to come from. /// </summary> public readonly ImmutableArray<string> Zones; [OutputConstructor] private GetPublicIPPrefixResult( Outputs.SubResourceResponse? customIPPrefix, string etag, Outputs.ExtendedLocationResponse? extendedLocation, string? id, string ipPrefix, ImmutableArray<Outputs.IpTagResponse> ipTags, Outputs.SubResourceResponse loadBalancerFrontendIpConfiguration, string? location, string name, Outputs.NatGatewayResponse? natGateway, int? prefixLength, string provisioningState, string? publicIPAddressVersion, ImmutableArray<Outputs.ReferencedPublicIpAddressResponse> publicIPAddresses, string resourceGuid, Outputs.PublicIPPrefixSkuResponse? sku, ImmutableDictionary<string, string>? tags, string type, ImmutableArray<string> zones) { CustomIPPrefix = customIPPrefix; Etag = etag; ExtendedLocation = extendedLocation; Id = id; IpPrefix = ipPrefix; IpTags = ipTags; LoadBalancerFrontendIpConfiguration = loadBalancerFrontendIpConfiguration; Location = location; Name = name; NatGateway = natGateway; PrefixLength = prefixLength; ProvisioningState = provisioningState; PublicIPAddressVersion = publicIPAddressVersion; PublicIPAddresses = publicIPAddresses; ResourceGuid = resourceGuid; Sku = sku; Tags = tags; Type = type; Zones = zones; } } }
32.894737
191
0.5984
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20201101/GetPublicIPPrefix.cs
6,250
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; namespace RESTService.WinForm { public class EMICalculatorAppServiceClient : IEMICalculator { public double emi(double amount, int period, double rate) { double result = 0; try { AppServiceConnectionStatus status = AppServiceConnectionStatus.Unknown; AppServiceResponse response = null; var connection = new AppServiceConnection { AppServiceName = "com.ilink-systems.emi", PackageFamilyName = "f39a492b-4169-44ea-95e0-684611551b3b_y1rwc9yf20874" }; Task.Run(async () => { status = await connection.OpenAsync(); }).Wait(); if (status == AppServiceConnectionStatus.Success) { var inputs = new ValueSet { { "amount", amount }, { "period", period }, { "rate", rate } }; MainForm.SetRequestMessage(JsonConvert.SerializeObject(inputs)); Task.Run(async () => { response = await connection.SendMessageAsync(inputs); }).Wait(); if (response != null && response.Status == AppServiceResponseStatus.Success && response.Message.ContainsKey("result")) { result = Math.Ceiling(Convert.ToDouble(response.Message["result"].ToString())); MainForm.SetResponseMessage(result.ToString()); } } } catch (Exception) { result = -2; } MainForm.SetLastServed(DateTime.Now.ToString()); return result; } } }
32.806452
138
0.529007
[ "Apache-2.0" ]
ilinkmobility/WCFAndAppServiceHosting
EMICalculator/RESTService.WinForm/EMICalculatorAppServiceClient.cs
2,036
C#
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license.txt */ using System.Collections.Generic; using System.ComponentModel.Composition; using System.IdentityModel.Protocols.WSTrust; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Web.Http; using Thinktecture.IdentityModel; using Thinktecture.IdentityModel.Constants; using Thinktecture.IdentityServer.Repositories; using Thinktecture.IdentityServer.TokenService; namespace Thinktecture.IdentityServer.Protocols.OpenIdConnect { [Authorize] public class OidcUserInfoController : ApiController { [Import] public IClaimsRepository ClaimsRepository { get; set; } public OidcUserInfoController() { Container.Current.SatisfyImportsOnce(this); } public OidcUserInfoController(IClaimsRepository claimsRepository) { ClaimsRepository = claimsRepository; } public HttpResponseMessage Get() { Tracing.Start("OIDC UserInfo endpoint"); var details = new RequestDetails { IsOpenIdRequest = true }; var scopeClaims = ClaimsPrincipal.Current.FindAll(OAuth2Constants.Scope).ToList(); var requestedClaims = ClaimsPrincipal.Current.FindAll("requestclaim").ToList(); if (scopeClaims.Count > 0) { var scopes = new List<string>(scopeClaims.Select(sc => sc.Value)); details.OpenIdScopes = scopes; } if (requestedClaims.Count > 0) { var requestClaims = new RequestClaimCollection(); requestedClaims.ForEach(rc => requestClaims.Add(new RequestClaim(rc.Value))); details.ClaimsRequested = true; details.RequestClaims = requestClaims; } var principal = Principal.Create("OpenIdConnect", new Claim(ClaimTypes.Name, ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value)); var claims = ClaimsRepository.GetClaims(principal, details); var dictionary = new Dictionary<string, string>(); foreach (var claim in claims) { if (!dictionary.ContainsKey(claim.Type)) { dictionary.Add(claim.Type, claim.Value); } else { var currentValue = dictionary[claim.Type]; dictionary[claim.Type] = currentValue += ("," + claim.Value); } } return Request.CreateResponse<Dictionary<string, string>>(HttpStatusCode.OK, dictionary, "application/json"); } } }
33.963415
121
0.616876
[ "BSD-3-Clause" ]
AllenBrook/IdentityServer2
src/Libraries/Thinktecture.IdentityServer.Protocols/OpenIdConnect/Endpoints/UserInfoController.cs
2,787
C#
using System; using System.Runtime.Serialization; using Elders.Cronus; namespace Playground.AtomTracker { [DataContract(Namespace = "atom", Name = "c5b43828-b6da-47c1-961e-17ed433159ef")] public class AggregateComittedEvent : IEvent { private AggregateComittedEvent() { } public AggregateComittedEvent(AtomTrackerId id) { Id = id ?? throw new ArgumentNullException(nameof(id)); } [DataMember(Order = 1)] public AtomTrackerId Id { get; private set; } } }
25.428571
85
0.659176
[ "Apache-2.0" ]
Elders/Cronus.AtomicAction.Consul
src/Playground/AtomTracker/Events/AggregateComittedEvent.cs
536
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Sections; namespace Microsoft.AspNetCore.Components; /// <summary> /// Dispatches external actions to be executed on the context of a <see cref="Renderer"/>. /// </summary> public abstract class Dispatcher { private SectionRegistry? _sectionRegistry; /// <summary> /// Creates a default instance of <see cref="Dispatcher"/>. /// </summary> /// <returns>A <see cref="Dispatcher"/> instance.</returns> public static Dispatcher CreateDefault() => new RendererSynchronizationContextDispatcher(); /// <summary> /// Provides notifications of unhandled exceptions that occur within the dispatcher. /// </summary> internal event UnhandledExceptionEventHandler? UnhandledException; /// <summary> /// Gets the <see cref="Sections.SectionRegistry"/> associated with the dispatcher. /// </summary> internal SectionRegistry SectionRegistry => _sectionRegistry ??= new(); /// <summary> /// Validates that the currently executing code is running inside the dispatcher. /// </summary> public void AssertAccess() { if (!CheckAccess()) { throw new InvalidOperationException( "The current thread is not associated with the Dispatcher. " + "Use InvokeAsync() to switch execution to the Dispatcher when " + "triggering rendering or component state."); } } /// <summary> /// Returns a value that determines whether using the dispatcher to invoke a work item is required /// from the current context. /// </summary> /// <returns><c>true</c> if invoking is required, otherwise <c>false</c>.</returns> public abstract bool CheckAccess(); /// <summary> /// Invokes the given <see cref="Action"/> in the context of the associated <see cref="Renderer"/>. /// </summary> /// <param name="workItem">The action to execute.</param> /// <returns>A <see cref="Task"/> that will be completed when the action has finished executing.</returns> public abstract Task InvokeAsync(Action workItem); /// <summary> /// Invokes the given <see cref="Func{TResult}"/> in the context of the associated <see cref="Renderer"/>. /// </summary> /// <param name="workItem">The asynchronous action to execute.</param> /// <returns>A <see cref="Task"/> that will be completed when the action has finished executing.</returns> public abstract Task InvokeAsync(Func<Task> workItem); /// <summary> /// Invokes the given <see cref="Func{TResult}"/> in the context of the associated <see cref="Renderer"/>. /// </summary> /// <param name="workItem">The function to execute.</param> /// <returns>A <see cref="Task{TResult}"/> that will be completed when the function has finished executing.</returns> public abstract Task<TResult> InvokeAsync<TResult>(Func<TResult> workItem); /// <summary> /// Invokes the given <see cref="Func{TResult}"/> in the context of the associated <see cref="Renderer"/>. /// </summary> /// <param name="workItem">The asynchronous function to execute.</param> /// <returns>A <see cref="Task{TResult}"/> that will be completed when the function has finished executing.</returns> public abstract Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> workItem); /// <summary> /// Called to notify listeners of an unhandled exception. /// </summary> /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/>.</param> protected void OnUnhandledException(UnhandledExceptionEventArgs e) { if (e is null) { throw new ArgumentNullException(nameof(e)); } UnhandledException?.Invoke(this, e); } }
41.316327
121
0.672018
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Components/Components/src/Dispatcher.cs
4,049
C#
using Discord; using DiscordBotFramework.Utilities; using System.Collections.Generic; namespace DiscordBotFramework.DefaultModules { public class HelpBuilder { public Dictionary<string, string> HelpValues { get; set; } = new Dictionary<string, string>(); public HelpBuilder() { } public Embed BuildHelpEmbed() { EmbedBuilder embed = new EmbedBuilder { Title = "Valid commands:", Color = new Color(ColorUtil.RandomColorGenerate()) }; foreach(KeyValuePair<string, string> kvp in HelpValues) { embed.AddField(kvp.Key, kvp.Value); } return embed.Build(); } } }
24.9
102
0.574297
[ "MIT" ]
Esherymack/DiscordBotFramework
DefaultModules/HelpBuilder.cs
749
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="COCD_TP146025UK04.Support", Namespace="urn:hl7-org:v3")] public partial class COCD_TP146025UK04Support { private TemplateContent contentIdField; private COCD_TP146025UK04SupportSeperatableInd seperatableIndField; private COCD_TP146025UK04SupportTemplateId templateIdField; private object itemField; private string nullFlavorField; private cs_UpdateMode updateModeField; private bool updateModeFieldSpecified; private string typeCodeField; private bool contextConductionIndField; private static System.Xml.Serialization.XmlSerializer serializer; public COCD_TP146025UK04Support() { this.typeCodeField = "SPRT"; this.contextConductionIndField = false; } [System.Xml.Serialization.XmlElementAttribute(Namespace="NPFIT:HL7:Localisation")] public TemplateContent contentId { get { return this.contentIdField; } set { this.contentIdField = value; } } public COCD_TP146025UK04SupportSeperatableInd seperatableInd { get { return this.seperatableIndField; } set { this.seperatableIndField = value; } } public COCD_TP146025UK04SupportTemplateId templateId { get { return this.templateIdField; } set { this.templateIdField = value; } } [System.Xml.Serialization.XmlElementAttribute("COCD_TP147012UK03.FindingRef", typeof(COCD_TP147012UK03FindingRef))] [System.Xml.Serialization.XmlElementAttribute("COCD_TP147017UK03.FindingOrganizerRef", typeof(COCD_TP147017UK03FindingOrganizerRef))] [System.Xml.Serialization.XmlElementAttribute("COCD_TP147022UK03.AllergicOrAdverseReactionEventRef", typeof(COCD_TP147022UK03AllergicOrAdverseReactionEventRef))] public object Item { get { return this.itemField; } set { this.itemField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public cs_UpdateMode updateMode { get { return this.updateModeField; } set { this.updateModeField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool updateModeSpecified { get { return this.updateModeFieldSpecified; } set { this.updateModeFieldSpecified = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool contextConductionInd { get { return this.contextConductionIndField; } set { this.contextConductionIndField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(COCD_TP146025UK04Support)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current COCD_TP146025UK04Support object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an COCD_TP146025UK04Support object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output COCD_TP146025UK04Support object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out COCD_TP146025UK04Support obj, out System.Exception exception) { exception = null; obj = default(COCD_TP146025UK04Support); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out COCD_TP146025UK04Support obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static COCD_TP146025UK04Support Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((COCD_TP146025UK04Support)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current COCD_TP146025UK04Support object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an COCD_TP146025UK04Support object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output COCD_TP146025UK04Support object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out COCD_TP146025UK04Support obj, out System.Exception exception) { exception = null; obj = default(COCD_TP146025UK04Support); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out COCD_TP146025UK04Support obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static COCD_TP146025UK04Support LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this COCD_TP146025UK04Support object /// </summary> public virtual COCD_TP146025UK04Support Clone() { return ((COCD_TP146025UK04Support)(this.MemberwiseClone())); } #endregion } }
40.864238
1,368
0.578721
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/COCD_TP146025UK04Support.cs
12,341
C#
using System.Collections.Generic; namespace MilitaryElite.Contracts { public interface ICommando:ISpecialisedSoldier { IReadOnlyCollection<IMission> Missions { get; } void AddMission(IMission mission); } }
19.666667
55
0.720339
[ "MIT" ]
tonchevaAleksandra/C-Sharp-OOP
InterfacesAndAbstraction/MilitaryElite/Contracts/ICommando.cs
238
C#
#region License // // Author: Nate Kohari <nate@enkari.com> // Copyright (c) 2007-2010, Enkari, Ltd. // // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). // See the file LICENSE.txt for details. // #endregion #region Using Directives using System; using System.Collections; using System.Linq; #endregion namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { internal static class ExtensionsForIEnumerable { public static IEnumerable CastSlow(this IEnumerable series, Type elementType) { var method = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as IEnumerable; } public static Array ToArraySlow(this IEnumerable series, Type elementType) { var method = typeof(Enumerable).GetMethod("ToArray").MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as Array; } public static IList ToListSlow(this IEnumerable series, Type elementType) { var method = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as IList; } } }
34.131579
97
0.67926
[ "Apache-2.0" ]
tailsu/JustMockLite
Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerable.cs
1,297
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("VirtoCommerce.Mobile.Windows.Windows")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VirtoCommerce.Mobile.Windows.Windows")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
37.551724
84
0.747475
[ "MIT" ]
VirtoCommerce/mobile-agent-xamarin
VirtoCommerce.Mobile/VirtoCommerce.Mobile/VirtoCommerce.Mobile.Windows/Properties/AssemblyInfo.cs
1,092
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq.Modules; using OwinFramework.Pages.Core.Debug; using OwinFramework.Pages.Core.Interfaces.DataModel; using OwinFramework.Pages.Core.Interfaces.Runtime; namespace OwinFramework.Pages.Mocks.DataModel { public class MockDataSupplier: ConcreteImplementationProvider<IDataSupplier> { protected override IDataSupplier GetImplementation(IMockProducer mockProducer) { return new DataSupplier(); } public class DataSupplier : IDataSupplier, IDataSupply { public IList<Type> SuppliedTypes { get; private set; } public IDataDependency DefaultDependency { get { return _dependency; } } public bool IsStatic { get { return true; } set { } } private readonly List<Action<IRenderContext>> _dependentSupplies = new List<Action<IRenderContext>>(); private IDataDependency _dependency; private Action<IRenderContext, IDataContext, IDataDependency> _action; public void Add( IDataDependency dependency, Action<IRenderContext, IDataContext, IDataDependency> action) { _dependency = dependency; _action = action; SuppliedTypes = new List<Type> { dependency.DataType }; } bool IDataSupplier.CanSupplyScoped(Type type) { return !string.IsNullOrEmpty(_dependency.ScopeName); } bool IDataSupplier.CanSupplyUnscoped(Type type) { return string.IsNullOrEmpty(_dependency.ScopeName); } public bool IsSupplierOf(IDataDependency dependency) { return _dependency == null || _dependency.DataType == dependency.DataType; } public IDataSupply GetSupply(IDataDependency dependency) { return this; } void IDataSupply.AddOnSupplyAction(Action<IRenderContext> renderAction) { _dependentSupplies.Add(renderAction); } public void Supply(IRenderContext renderContext, IDataContext dataContext) { _action(renderContext, dataContext, _dependency); foreach (var dependent in _dependentSupplies) dependent(renderContext); } } } }
34.708333
114
0.616246
[ "Apache-2.0" ]
forki/OwinFramework.Pages
OwinFramework.Pages.Mocks/DataModel/MockDataSupplier.cs
2,501
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.IO; using System.Text; namespace Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Json { public abstract partial class JsonNode { internal abstract JsonType Type { get; } public virtual JsonNode this[int index] => throw new NotImplementedException(); public virtual JsonNode this[string name] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } #region Type Helpers internal bool IsArray => Type == JsonType.Array; internal bool IsDate => Type == JsonType.Date; internal bool IsObject => Type == JsonType.Object; internal bool IsNumber => Type == JsonType.Number; internal bool IsNull => Type == JsonType.Null; #endregion internal void WriteTo(TextWriter textWriter, bool pretty = true) { var writer = new JsonWriter(textWriter, pretty); writer.WriteNode(this); } internal T As<T>() where T : new() => new JsonSerializer().Deseralize<T>((JsonObject)this); internal T[] ToArrayOf<T>() { return (T[])new JsonSerializer().DeserializeArray(typeof(T[]), (JsonArray)this); } #region ToString Overrides public override string ToString() => ToString(pretty: true); internal string ToString(bool pretty) { var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { WriteTo(writer, pretty); return sb.ToString(); } } #endregion #region Static Constructors internal static JsonNode Parse(string text) { return Parse(new SourceReader(new StringReader(text))); } internal static JsonNode Parse(TextReader textReader) => Parse(new SourceReader(textReader)); private static JsonNode Parse(SourceReader sourceReader) { using (var parser = new JsonParser(sourceReader)) { return parser.ReadNode(); } } internal static JsonNode FromObject(object instance) => new JsonSerializer().Serialize(instance); #endregion #region Implict Casts public static implicit operator string(JsonNode node) => node.ToString(); #endregion #region Explict Casts public static explicit operator DateTime(JsonNode node) { switch (node.Type) { case JsonType.Date: return ((JsonDate)node).ToDateTime(); case JsonType.String: return JsonDate.Parse(node.ToString()).ToDateTime(); case JsonType.Number: var num = (JsonNumber)node; if (num.IsInteger) { return DateTimeOffset.FromUnixTimeSeconds(num).UtcDateTime; } else { return DateTimeOffset.FromUnixTimeMilliseconds((long)((double)num * 1000)).UtcDateTime; } } throw new ConversionException(node, typeof(DateTime)); } public static explicit operator DateTimeOffset(JsonNode node) { switch (node.Type) { case JsonType.Date : return ((JsonDate)node).ToDateTimeOffset(); case JsonType.String : return JsonDate.Parse(node.ToString()).ToDateTimeOffset(); case JsonType.Number: var num = (JsonNumber)node; if (num.IsInteger) { return DateTimeOffset.FromUnixTimeSeconds(num); } else { return DateTimeOffset.FromUnixTimeMilliseconds((long)((double)num * 1000)); } } throw new ConversionException(node, typeof(DateTimeOffset)); } public static explicit operator float(JsonNode node) { switch (node.Type) { case JsonType.Number : return (JsonNumber)node; case JsonType.String : return float.Parse(node.ToString()); } throw new ConversionException(node, typeof(float)); } public static explicit operator double(JsonNode node) { switch (node.Type) { case JsonType.Number : return (JsonNumber)node; case JsonType.String : return double.Parse(node.ToString()); } throw new ConversionException(node, typeof(double)); } public static explicit operator decimal(JsonNode node) { switch (node.Type) { case JsonType.Number: return (JsonNumber)node; case JsonType.String: return decimal.Parse(node.ToString()); } throw new ConversionException(node, typeof(decimal)); } public static explicit operator Guid(JsonNode node) => new Guid(node.ToString()); public static explicit operator short(JsonNode node) { switch (node.Type) { case JsonType.Number : return (JsonNumber)node; case JsonType.String : return short.Parse(node.ToString()); } throw new ConversionException(node, typeof(short)); } public static explicit operator int(JsonNode node) { switch (node.Type) { case JsonType.Number : return (JsonNumber)node; case JsonType.String : return int.Parse(node.ToString()); } throw new ConversionException(node, typeof(int)); } public static explicit operator long(JsonNode node) { switch (node.Type) { case JsonType.Number: return (JsonNumber)node; case JsonType.String: return long.Parse(node.ToString()); } throw new ConversionException(node, typeof(long)); } public static explicit operator bool(JsonNode node) => ((JsonBoolean)node).Value; public static explicit operator ushort(JsonNode node) => (JsonNumber)node; public static explicit operator uint(JsonNode node) => (JsonNumber)node; public static explicit operator ulong(JsonNode node) => (JsonNumber)node; public static explicit operator TimeSpan(JsonNode node) => TimeSpan.Parse(node.ToString()); public static explicit operator Uri(JsonNode node) { if (node.Type == JsonType.String) { return new Uri(node.ToString()); } throw new ConversionException(node, typeof(Uri)); } #endregion } }
31.152
112
0.51451
[ "MIT" ]
3quanfeng/azure-powershell
src/ImageBuilder/generated/runtime/Nodes/JsonNode.cs
7,541
C#
using FluxorBlazorWeb.ReduxDevToolsTutorial.Shared; using Fluxor; using Microsoft.AspNetCore.Components; using System.Net.Http; using System.Threading.Tasks; namespace FluxorBlazorWeb.ReduxDevToolsTutorial.Client.Store.WeatherUseCase { public class Effects { private readonly HttpClient Http; public Effects(HttpClient http) { Http = http; } [EffectMethod] public async Task HandleFetchDataAction(FetchDataAction action, IDispatcher dispatcher) { var forecasts = await Http.GetJsonAsync<WeatherForecast[]>("WeatherForecast"); dispatcher.Dispatch(new FetchDataResultAction(forecasts)); } } }
23.961538
89
0.788122
[ "MIT" ]
BlazorHub/Fluxor
Tutorials/02-Blazor/02D-ReduxDevToolsTutorial/ReduxDevToolsTutorial/Client/Store/WeatherUseCase/Effects.cs
625
C#
using System; using UnityEngine.UI; namespace Phedg1Studios { namespace StartingItemsGUI { public class CanvasScalerFixed : CanvasScaler { public void ForcedUpdate() { Update(); } } } }
20.307692
56
0.545455
[ "Apache-2.0" ]
Grizzski/StartingItemsGUI
Development/Scripts/CanvasScalerFixed.cs
266
C#
using AutoMapper; using AutoMapper.QueryableExtensions; using CleanArchitecture.Application.Common.Extensions; using CleanArchitecture.Application.Common.Interfaces; using CleanArchitecture.Application.Common.Mappings; using CleanArchitecture.Application.Common.Models; using CleanArchitecture.Application.TodoLists.Queries.GetTodos; using MediatR; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination { public class GetTodoItemsWithPaginationQuery : IRequest<PaginatedList<TodoItemDto>> { public int ListId { get; set; } public int PageNumber { get; set; } = 1; public int PageSize { get; set; } = 10; } public class GetTodoItemsWithPaginationQueryHandler : IRequestHandler<GetTodoItemsWithPaginationQuery, PaginatedList<TodoItemDto>> { private readonly IApplicationDbContext _context; private readonly IMapper _mapper; private readonly IApplicationCacheService _applicationCacheService; public GetTodoItemsWithPaginationQueryHandler(IApplicationDbContext context, IMapper mapper, IApplicationCacheService applicationCacheService) { _context = context; _mapper = mapper; _applicationCacheService = applicationCacheService; } public async Task<PaginatedList<TodoItemDto>> Handle(GetTodoItemsWithPaginationQuery request, CancellationToken cancellationToken) { return await _applicationCacheService.GetAndSetAsync(request.ListId.ToString(), async () => await GetTodoItemAsync(request), TimeSpan.FromMinutes(1)); } private async Task<PaginatedList<TodoItemDto>> GetTodoItemAsync(GetTodoItemsWithPaginationQuery request) { return await _context.TodoItems .Where(x => x.ListId == request.ListId) .OrderBy(x => x.Title) .ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider) .PaginatedListAsync(request.PageNumber, request.PageSize); } } }
41.705882
162
0.736248
[ "MIT" ]
furkandeveloper/CleanArchitecture
src/Application/TodoItems/Queries/GetTodoItemsWithPagination/GetTodoItemsWithPaginationQuery.cs
2,129
C#
using System; using System.IO; using System.Linq; using System.Reflection; namespace Astrum { partial class AstralWorlds { public static class WorldMods { public static AstralWorldTargetAttribute[] worlds = new AstralWorldTargetAttribute[0] { }; public static object[] mods; public static void Initialize() { if (!Directory.Exists(nameof(AstralWorlds))) { Logger.Warn("AstralWorlds folder does not exist. No world mods will be loaded."); return; } worlds = Directory.EnumerateFiles(nameof(AstralWorlds)) .Select(f => (f, File.ReadAllBytes(f))) .Select(f => { try { Assembly asm = Assembly.Load(f.Item2); Logger.Info($"Loaded {f.f.Substring(13):20} ({SHA256(f.Item2)})"); return asm; } catch (Exception ex) { Logger.Error($"Failed to load {f.f}: {ex}"); return null; } }) .Where(f => f != null) .Select(f => f.GetCustomAttributes<AstralWorldTargetAttribute>()) .Aggregate(new AstralWorldTargetAttribute[0], (a, f) => a.Concat(f).ToArray()) .ToArray(); } public static System.Collections.IEnumerator WaitForLocalLoad(string name) { while (VRC.SDKBase.Networking.LocalPlayer == null) yield return null; mods = worlds.Where(f => f.SceneName == name) .Select(f => { try { return Activator.CreateInstance(f.Type); } catch (Exception ex) { Logger.Error($"Failed to load world mod: {ex}"); return null; } }) .Where(f => f != null) .ToArray(); Logger.Info($"Loaded into {name} with {mods.Length} World Mods"); } public static string SHA256(byte[] bytes) { var hash = new System.Text.StringBuilder(); foreach (byte theByte in new System.Security.Cryptography.SHA256Managed().ComputeHash(bytes)) hash.Append(theByte.ToString($"x2")); return hash.ToString(); } } } }
36
109
0.422644
[ "MIT" ]
Astrum-Project/AstralWorlds
WorldMods.cs
2,846
C#
namespace P03_SalesDatabase.Data.Models { using System; public class Sale { public int SaleId { get; set; } public DateTime Date { get; set; } public int ProductId { get; set; } public Product Product { get; set; } public int CustomerId { get; set; } public Customer Customer { get; set; } public int StoreId { get; set; } public Store Store { get; set; } } }
22.25
46
0.570787
[ "MIT" ]
kkaraivanov/CCharpDB
EntityFrameworkCore/CodeFirst/SalesDatabase/P03_SalesDatabase.Data.Models/Sale.cs
447
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasRenderContext.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Implements <see cref="IRenderContext" /> for <see cref="System.Windows.Controls.Canvas" />. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Silverlight { using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using FontWeights = OxyPlot.FontWeights; /// <summary> /// Implements <see cref="IRenderContext" /> for <see cref="System.Windows.Controls.Canvas" />. /// </summary> public class CanvasRenderContext : IRenderContext { /// <summary> /// The brush cache. /// </summary> private readonly Dictionary<OxyColor, Brush> brushCache = new Dictionary<OxyColor, Brush>(); /// <summary> /// The canvas. /// </summary> private readonly Canvas canvas; /// <summary> /// The images in use /// </summary> private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage>(); /// <summary> /// The image cache /// </summary> private readonly Dictionary<OxyImage, BitmapSource> imageCache = new Dictionary<OxyImage, BitmapSource>(); /// <summary> /// The current tool tip /// </summary> private string currentToolTip; /// <summary> /// The clip rectangle. /// </summary> private Rect clipRect; /// <summary> /// The clip flag. /// </summary> private bool clip; /// <summary> /// Initializes a new instance of the <see cref="CanvasRenderContext" /> class. /// </summary> /// <param name="canvas">The canvas.</param> public CanvasRenderContext(Canvas canvas) { this.canvas = canvas; this.Width = canvas.ActualWidth; this.Height = canvas.ActualHeight; this.RendersToScreen = true; } /// <summary> /// Gets the height. /// </summary> /// <value>The height.</value> public double Height { get; private set; } /// <summary> /// Gets a value indicating whether to paint the background. /// </summary> /// <value><c>true</c> if the background should be painted; otherwise, <c>false</c>.</value> public bool PaintBackground { get { return false; } } /// <summary> /// Gets the width. /// </summary> /// <value>The width.</value> public double Width { get; private set; } /// <summary> /// Gets or sets a value indicating whether the context renders to screen. /// </summary> /// <value><c>true</c> if the context renders to screen; otherwise, <c>false</c>.</value> public bool RendersToScreen { get; set; } /// <summary> /// Draws an ellipse. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The thickness.</param> public void DrawEllipse(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness) { var el = new Ellipse(); if (stroke.IsVisible()) { el.Stroke = new SolidColorBrush(stroke.ToColor()); el.StrokeThickness = thickness; } if (fill.IsVisible()) { el.Fill = new SolidColorBrush(fill.ToColor()); } el.Width = rect.Width; el.Height = rect.Height; Canvas.SetLeft(el, rect.Left); Canvas.SetTop(el, rect.Top); this.Add(el, rect.Left, rect.Top); } /// <summary> /// Draws the collection of ellipses, where all have the same stroke and fill. /// This performs better than calling DrawEllipse multiple times. /// </summary> /// <param name="rectangles">The rectangles.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> public void DrawEllipses(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness) { var path = new Path(); this.SetStroke(path, stroke, thickness); if (fill.IsVisible()) { path.Fill = this.GetCachedBrush(fill); } var gg = new GeometryGroup { FillRule = FillRule.Nonzero }; foreach (var rect in rectangles) { gg.Children.Add( new EllipseGeometry { Center = new Point(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)), RadiusX = rect.Width / 2, RadiusY = rect.Height / 2 }); } path.Data = gg; this.Add(path); } /// <summary> /// Draws the polyline from the specified points. /// </summary> /// <param name="points">The points.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawLine( IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var e = new Polyline(); this.SetStroke(e, stroke, thickness, lineJoin, dashArray, aliased); var pc = new PointCollection(); foreach (var p in points) { pc.Add(p.ToPoint(aliased)); } e.Points = pc; this.Add(e); } /// <summary> /// Draws the multiple line segments defined by points (0,1) (2,3) (4,5) etc. /// This should have better performance than calling DrawLine for each segment. /// </summary> /// <param name="points">The points.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawLineSegments( IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var path = new Path(); this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased); var pg = new PathGeometry(); for (int i = 0; i + 1 < points.Count; i += 2) { // if (points[i].Y==points[i+1].Y) // { // var line = new Line(); // line.X1 = 0.5+(int)points[i].X; // line.X2 = 0.5+(int)points[i+1].X; // line.Y1 = 0.5+(int)points[i].Y; // line.Y2 = 0.5+(int)points[i+1].Y; // SetStroke(line, OxyColors.DarkRed, thickness, lineJoin, dashArray, aliased); // Add(line); // continue; // } var figure = new PathFigure { StartPoint = points[i].ToPoint(aliased), IsClosed = false }; figure.Segments.Add(new LineSegment { Point = points[i + 1].ToPoint(aliased) }); pg.Figures.Add(figure); } path.Data = pg; this.Add(path); } /// <summary> /// Draws the polygon from the specified points. The polygon can have stroke and/or fill. /// </summary> /// <param name="points">The points.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawPolygon( IList<ScreenPoint> points, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var po = new Polygon(); this.SetStroke(po, stroke, thickness, lineJoin, dashArray, aliased); if (fill.IsVisible()) { po.Fill = this.GetCachedBrush(fill); } var pc = new PointCollection(); foreach (var p in points) { pc.Add(p.ToPoint(aliased)); } po.Points = pc; this.Add(po); } /// <summary> /// Draws a collection of polygons, where all polygons have the same stroke and fill. /// This performs better than calling DrawPolygon multiple times. /// </summary> /// <param name="polygons">The polygons.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawPolygons( IList<IList<ScreenPoint>> polygons, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var path = new Path(); this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased); if (fill.IsVisible()) { path.Fill = this.GetCachedBrush(fill); } var pg = new PathGeometry { FillRule = FillRule.Nonzero }; foreach (var polygon in polygons) { var figure = new PathFigure { IsClosed = true }; bool first = true; foreach (var p in polygon) { if (first) { figure.StartPoint = p.ToPoint(aliased); first = false; } else { figure.Segments.Add(new LineSegment { Point = p.ToPoint(aliased) }); } } pg.Figures.Add(figure); } path.Data = pg; this.Add(path); } /// <summary> /// Draws the rectangle. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> public void DrawRectangle(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness) { var el = new Rectangle(); if (stroke.IsVisible()) { el.Stroke = new SolidColorBrush(stroke.ToColor()); el.StrokeThickness = thickness; } if (fill.IsVisible()) { el.Fill = new SolidColorBrush(fill.ToColor()); } el.Width = rect.Width; el.Height = rect.Height; Canvas.SetLeft(el, rect.Left); Canvas.SetTop(el, rect.Top); this.Add(el, rect.Left, rect.Top); } /// <summary> /// Draws a collection of rectangles, where all have the same stroke and fill. /// This performs better than calling DrawRectangle multiple times. /// </summary> /// <param name="rectangles">The rectangles.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> public void DrawRectangles(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness) { var path = new Path(); this.SetStroke(path, stroke, thickness); if (fill.IsVisible()) { path.Fill = this.GetCachedBrush(fill); } var gg = new GeometryGroup { FillRule = FillRule.Nonzero }; foreach (var rect in rectangles) { gg.Children.Add(new RectangleGeometry { Rect = rect.ToRect(true) }); } path.Data = gg; this.Add(path); } /// <summary> /// Draws the text. /// </summary> /// <param name="p">The position.</param> /// <param name="text">The text.</param> /// <param name="fill">The fill color.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <param name="rotate">The rotation angle.</param> /// <param name="halign">The horizontal alignment.</param> /// <param name="valign">The vertical alignment.</param> /// <param name="maxSize">The maximum size of the text.</param> public void DrawText( ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, OxyPlot.HorizontalAlignment halign, OxyPlot.VerticalAlignment valign, OxySize? maxSize) { var tb = new TextBlock { Text = text, Foreground = new SolidColorBrush(fill.ToColor()) }; // tb.SetValue(TextOptions.TextHintingModeProperty, TextHintingMode.Animated); if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } tb.FontWeight = GetFontWeight(fontWeight); tb.Measure(new Size(1000, 1000)); var size = new Size(tb.ActualWidth, tb.ActualHeight); if (maxSize != null) { if (size.Width > maxSize.Value.Width) { size.Width = maxSize.Value.Width; } if (size.Height > maxSize.Value.Height) { size.Height = maxSize.Value.Height; } tb.Clip = new RectangleGeometry { Rect = new Rect(0, 0, size.Width, size.Height) }; } double dx = 0; if (halign == OxyPlot.HorizontalAlignment.Center) { dx = -size.Width / 2; } if (halign == OxyPlot.HorizontalAlignment.Right) { dx = -size.Width; } double dy = 0; if (valign == OxyPlot.VerticalAlignment.Middle) { dy = -size.Height / 2; } if (valign == OxyPlot.VerticalAlignment.Bottom) { dy = -size.Height; } var transform = new TransformGroup(); transform.Children.Add(new TranslateTransform { X = (int)dx, Y = (int)dy }); if (!rotate.Equals(0)) { transform.Children.Add(new RotateTransform { Angle = rotate }); } transform.Children.Add(new TranslateTransform { X = (int)p.X, Y = (int)p.Y }); tb.RenderTransform = transform; this.ApplyTooltip(tb); if (this.clip) { // add a clipping container that is not rotated var c = new Canvas(); c.Children.Add(tb); this.Add(c); } else { this.Add(tb); } } /// <summary> /// Measures the text. /// </summary> /// <param name="text">The text.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <returns>The text size.</returns> public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight) { if (string.IsNullOrEmpty(text)) { return OxySize.Empty; } var tb = new TextBlock { Text = text }; if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } tb.FontWeight = GetFontWeight(fontWeight); tb.Measure(new Size(1000, 1000)); return new OxySize(tb.ActualWidth, tb.ActualHeight); } /// <summary> /// Sets the tool tip for the following items. /// </summary> /// <param name="text">The text in the tooltip.</param> public void SetToolTip(string text) { this.currentToolTip = text; } /// <summary> /// Draws the specified portion of the specified <see cref="OxyImage" /> at the specified location and with the specified size. /// </summary> /// <param name="source">The source.</param> /// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param> /// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param> /// <param name="srcWidth">Width of the portion of the source image to draw.</param> /// <param name="srcHeight">Height of the portion of the source image to draw.</param> /// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param> /// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param> /// <param name="destWidth">The width of the drawn image.</param> /// <param name="destHeight">The height of the drawn image.</param> /// <param name="opacity">The opacity.</param> /// <param name="interpolate">interpolate if set to <c>true</c>.</param> public void DrawImage( OxyImage source, double srcX, double srcY, double srcWidth, double srcHeight, double destX, double destY, double destWidth, double destHeight, double opacity, bool interpolate) { if (destWidth <= 0 || destHeight <= 0 || srcWidth <= 0 || srcHeight <= 0) { return; } var image = new Image(); var bmp = this.GetImageSource(source); if (srcX.Equals(0) && srcY.Equals(0) && srcWidth.Equals(bmp.PixelWidth) && srcHeight.Equals(bmp.PixelHeight)) { // do not crop } else { // TODO: cropped image not available in Silverlight?? // bmp = new CroppedBitmap(bmp, new Int32Rect((int)srcX, (int)srcY, (int)srcWidth, (int)srcHeight)); return; } image.Opacity = opacity; image.Width = destWidth; image.Height = destHeight; image.Stretch = Stretch.Fill; // TODO: not available in Silverlight?? // RenderOptions.SetBitmapScalingMode(image, interpolate ? BitmapScalingMode.HighQuality : BitmapScalingMode.NearestNeighbor); // Canvas.SetLeft(image, x); // Canvas.SetTop(image, y); image.RenderTransform = new TranslateTransform { X = destX, Y = destY }; image.Source = bmp; this.ApplyTooltip(image); this.Add(image, destX, destY); } /// <summary> /// Sets the clipping rectangle. /// </summary> /// <param name="clippingRect">The clipping rectangle.</param> /// <returns>True if the clipping rectangle was set.</returns> public bool SetClip(OxyRect clippingRect) { this.clipRect = clippingRect.ToRect(false); this.clip = true; return true; } /// <summary> /// Resets the clipping rectangle. /// </summary> public void ResetClip() { this.clip = false; } /// <summary> /// Cleans up resources not in use. /// </summary> /// <remarks>This method is called at the end of each rendering.</remarks> public void CleanUp() { // Find the images in the cache that has not been used since last call to this method var imagesToRelease = this.imageCache.Keys.Where(i => !this.imagesInUse.Contains(i)).ToList(); // Remove the images from the cache foreach (var i in imagesToRelease) { this.imageCache.Remove(i); } this.imagesInUse.Clear(); } /// <summary> /// Creates the dash array collection. /// </summary> /// <param name="dashArray">The dash array.</param> /// <returns>A DoubleCollection.</returns> private static DoubleCollection CreateDashArrayCollection(IEnumerable<double> dashArray) { var dac = new DoubleCollection(); foreach (double v in dashArray) { dac.Add(v); } return dac; } /// <summary> /// Gets the font weight. /// </summary> /// <param name="fontWeight">The font weight.</param> /// <returns>A <see cref="FontWeight" /></returns> private static FontWeight GetFontWeight(double fontWeight) { return fontWeight > FontWeights.Normal ? System.Windows.FontWeights.Bold : System.Windows.FontWeights.Normal; } /// <summary> /// Adds the specified element to the canvas. /// </summary> /// <param name="element">The element.</param> /// <param name="clipOffsetX">The clip offset X.</param> /// <param name="clipOffsetY">The clip offset Y.</param> private void Add(UIElement element, double clipOffsetX = 0, double clipOffsetY = 0) { if (this.clip) { this.ApplyClip(element, clipOffsetX, clipOffsetY); } this.canvas.Children.Add(element); } /// <summary> /// Applies the tooltip to the specified element. /// </summary> /// <param name="element">The element.</param> private void ApplyTooltip(DependencyObject element) { if (!string.IsNullOrEmpty(this.currentToolTip)) { ToolTipService.SetToolTip(element, this.currentToolTip); } } /// <summary> /// Gets the cached brush. /// </summary> /// <param name="stroke">The stroke.</param> /// <returns>The brush.</returns> private Brush GetCachedBrush(OxyColor stroke) { Brush brush; if (!this.brushCache.TryGetValue(stroke, out brush)) { brush = new SolidColorBrush(stroke.ToColor()); this.brushCache.Add(stroke, brush); } return brush; } /// <summary> /// Sets the stroke of the specified shape. /// </summary> /// <param name="shape">The shape.</param> /// <param name="stroke">The stroke.</param> /// <param name="thickness">The thickness.</param> /// <param name="lineJoin">The line join.</param> /// <param name="dashArray">The dash array.</param> /// <param name="aliased">aliased if set to <c>true</c>.</param> private void SetStroke( Shape shape, OxyColor stroke, double thickness, LineJoin lineJoin = LineJoin.Miter, IEnumerable<double> dashArray = null, bool aliased = false) { if (stroke.IsVisible() && thickness > 0) { shape.Stroke = this.GetCachedBrush(stroke); switch (lineJoin) { case LineJoin.Round: shape.StrokeLineJoin = PenLineJoin.Round; break; case LineJoin.Bevel: shape.StrokeLineJoin = PenLineJoin.Bevel; break; // The default StrokeLineJoin is Miter } shape.StrokeThickness = thickness; if (dashArray != null) { shape.StrokeDashArray = CreateDashArrayCollection(dashArray); } if (aliased) { // shape.UseLayoutRounding = aliased; } } } /// <summary> /// Applies the clip rectangle. /// </summary> /// <param name="image">The image.</param> /// <param name="x">The x offset of the element.</param> /// <param name="y">The y offset of the element.</param> private void ApplyClip(UIElement image, double x, double y) { image.Clip = new RectangleGeometry { Rect = new Rect(this.clipRect.X - x, this.clipRect.Y - y, this.clipRect.Width, this.clipRect.Height) }; } /// <summary> /// Gets the bitmap source. /// </summary> /// <param name="image">The image.</param> /// <returns>The bitmap source.</returns> private BitmapSource GetImageSource(OxyImage image) { if (image == null) { return null; } if (!this.imagesInUse.Contains(image)) { this.imagesInUse.Add(image); } BitmapSource src; if (this.imageCache.TryGetValue(image, out src)) { return src; } using (var ms = new System.IO.MemoryStream(image.GetData())) { var bitmapImage = new BitmapImage(); bitmapImage.SetSource(ms); this.imageCache.Add(image, bitmapImage); return bitmapImage; } } } }
35.390645
152
0.507823
[ "MIT" ]
BRER-TECH/oxyplot
Source/OxyPlot.Silverlight/CanvasRenderContext.cs
27,996
C#
// Write a program that deletes from given text file all odd lines. // The result should be in the same file. using System; using System.IO; using System.Text; class DeleteOddLines { static void DeleteOnlyOddLines() { int row = 1; StringBuilder sb = new StringBuilder(); using (StreamReader str = new StreamReader("Text.txt")) { for (string l; (l = str.ReadLine()) != null; row++) { if (row % 2 == 0) { sb.AppendLine(l); } } } using (StreamWriter write = new StreamWriter("Text.txt")) { write.WriteLine(sb); } } static void Main() { DeleteOnlyOddLines(); } }
21.868421
68
0.468111
[ "MIT" ]
Producenta/TelerikAcademy
C# 2/DomTextFiles/09.DeleteOddLines/DeleteOddLines.cs
833
C#
using System.Text.Json.Serialization; namespace nerderies.TelegramBotApi.DTOS { public class EncryptedCredentials { //complete API as of 2019-01-11 [JsonPropertyName("data")] [JsonInclude] public string Data; [JsonPropertyName("hash")] [JsonInclude] public string Hash; [JsonPropertyName("secret")] [JsonInclude] public string Secret; } }
20.714286
39
0.613793
[ "MIT" ]
devnulli/TelegramBotApi.NET
TelegramBotApi/TelegramBotApi/DTOS/Types/EncryptedCredentials.cs
437
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ExactSync { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "DropboxWebhook", url: "webhook", defaults: new { controller = "Dropbox", action = "Webhook" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{page}", defaults: new { controller = "Home", action = "Index", page = UrlParameter.Optional } ); routes.MapRoute( name: "Detail", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Detail", id = UrlParameter.Optional } ); routes.MapRoute( name: "DropboxConnect", url: "{controller}/{action}", defaults: new { controller = "Dropbox", action = "Connect" } ); routes.MapRoute( name: "DropboxDisconnect", url: "{controller}/{action}", defaults: new { controller = "Dropbox", action = "Disconnect" } ); routes.MapRoute( name: "DropboxAuthorize", url: "{controller}/{action}", defaults: new { controller = "Dropbox", action = "Authorize" } ); routes.MapRoute( name: "ExactOnlineConnect", url: "{controller}/{action}", defaults: new { controller = "ExactOnline", action = "Connect" } ); routes.MapRoute( name: "ExactOnlineDisconnect", url: "{controller}/{action}", defaults: new { controller = "ExactOnline", action = "Disconnect" } ); routes.MapRoute( name: "ExactOnlineAuthorize", url: "{controller}/{action}", defaults: new { controller = "ExactOnline", action = "Authorize" } ); } } }
32.323944
101
0.490196
[ "MIT" ]
exactsync/ExactSync
ExactSync/App_Start/RouteConfig.cs
2,297
C#
using AutoMapper; using Philcosa.Application.Interfaces.Repositories; using Philcosa.Domain.Entities; using Philcosa.Shared.Constants.Application; using Philcosa.Shared.Wrapper; using LazyCache; using MediatR; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Linq; namespace Philcosa.Application.Features.Themes.Queries.GetAll { public class GetAllThemesQuery : IRequest<Result<List<GetAllThemesResponse>>> { public GetAllThemesQuery() { } } public class GetAllThemesCachedQueryHandler : IRequestHandler<GetAllThemesQuery, Result<List<GetAllThemesResponse>>> { private readonly IUnitOfWork _unitOfWork; private readonly IMapper _mapper; private readonly IAppCache _cache; public GetAllThemesCachedQueryHandler(IUnitOfWork unitOfWork, IMapper mapper, IAppCache cache) { _unitOfWork = unitOfWork; _mapper = mapper; _cache = cache; } public async Task<Result<List<GetAllThemesResponse>>> Handle(GetAllThemesQuery request, CancellationToken cancellationToken) { Func<Task<List<Theme>>> getAllThemes = () => _unitOfWork.Repository<Theme>().GetAllAsync(); var themeList = await _cache.GetOrAddAsync(ApplicationConstants.Cache.GetAllThemesCacheKey, getAllThemes); var mappedThemes = new List<GetAllThemesResponse>(); foreach (var theme in themeList) { mappedThemes.Add(new GetAllThemesResponse { Id = theme.Id, Name = theme.Name }); } return await Result<List<GetAllThemesResponse>>.SuccessAsync(mappedThemes.OrderBy(x => x.Name).ToList()); } } }
35.346154
132
0.66975
[ "MIT" ]
HenkVanMilligen/Philcosa
Philcosa.Application/Features/Themes/Queries/GetAll/GetAllThemesQuery.cs
1,840
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ZabbixApi.Entities; using ZabbixApi.Helper; namespace ZabbixApi.Entities { public partial class ItemPrototype : EntityBase { #region Properties /// <summary> /// (readonly) ID of the item prototype. /// </summary> [JsonProperty("itemid")] public override string Id { get; set; } /// <summary> /// Update interval of the item prototype in seconds. /// </summary> public string delay { get; set; } /// <summary> /// ID of the host that the item prototype belongs to. /// </summary> public string hostid { get; set; } /// <summary> /// ID of the LLD rule that the item belongs to. /// /// For update operations this field is readonly. /// </summary> public string ruleid { get; set; } /// <summary> /// ID of the item prototype's host interface. Used only for host item prototypes. /// /// Optional for Zabbix agent (active), Zabbix internal, Zabbix trapper, Zabbix aggregate, database monitor and calculated item prototypes. /// </summary> public string interfaceid { get; set; } /// <summary> /// Item prototype key. /// </summary> public string key_ { get; set; } /// <summary> /// Name of the item prototype. /// </summary> public string name { get; set; } /// <summary> /// Type of the item prototype. /// /// Possible values: /// 0 - Zabbix agent; /// 1 - SNMPv1 agent; /// 2 - Zabbix trapper; /// 3 - simple check; /// 4 - SNMPv2 agent; /// 5 - Zabbix internal; /// 6 - SNMPv3 agent; /// 7 - Zabbix agent (active); /// 8 - Zabbix aggregate; /// 10 - external check; /// 11 - database monitor; /// 12 - IPMI agent; /// 13 - SSH agent; /// 14 - TELNET agent; /// 15 - calculated; /// 16 - JMX agent; /// 17 - SNMP trap. /// </summary> public ItemPrototypeType type { get; set; } /// <summary> /// URL string required only for HTTP agent item prototypes. Supports LLD macros, user macros, {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}. /// </summary> public string url { get; set; } /// <summary> /// Type of information of the item prototype. /// /// Possible values: /// 0 - numeric float; /// 1 - character; /// 2 - log; /// 3 - numeric unsigned; /// 4 - text. /// </summary> public ValueType value_type { get; set; } /// <summary> /// Used only by SSH agent items or HTTP agent items. /// /// SSH agent authentication method possible values: /// 0 - (default) password; /// 1 - public key. /// /// HTTP agent authentication method possible values: /// 0 - (default) none /// 1 - basic /// 2 - NTLM public AuthenticationMethod authtype { get; set; } /// <summary> /// Description of the item prototype. /// </summary> public string description { get; set; } /// <summary> /// (readonly) Error text if there are problems updating the item. /// </summary> public string error { get; set; } /// <summary> /// (readonly) Origin of the item. /// /// Possible values: /// 0 - a plain item; /// 4 - a discovered item. /// </summary> public Flags flags { get; set; } /// <summary> /// HTTP agent item field. Follow respose redirects while pooling data. /// /// 0 - Do not follow redirects. /// 1 - (default) Follow redirects. /// </summary> public FollowRedirects follow_redirects { get; set; } /// <summary> /// HTTP agent item prototype field. Object with HTTP(S) request headers, where header name is used as key and header value as value. /// /// Example: /// { "User-Agent": "Zabbix" } /// </summary> public IList<Dictionary<string, string>> headers { get; set; } /// <summary> /// Number of days to keep item prototype's history data. /// /// Default: 90. /// </summary> public string history { get; set; } /// <summary> /// HTTP agent item field. HTTP(S) proxy connection string. /// </summary> public string http_proxy { get; set; } /// <summary> /// IPMI sensor. Used only by IPMI item prototypes. /// </summary> public string ipmi_sensor { get; set; } /// <summary> /// JMX agent custom connection string. /// /// Default value: /// service:jmx:rmi:///jndi/rmi://{HOST.CONN}:{HOST.PORT}/jmxrmi /// </summary> public string jmx_endpoint { get; set; } /// <summary> /// Format of the time in log entries. Used only by log item prototypes. /// </summary> public string logtimefmt { get; set; } /// <summary> /// Master item ID. /// Recursion up to 3 dependent items and maximum count of dependent items equal to 999 are allowed. /// /// Required by Dependent items. /// </summary> public int master_itemid { get; set; } /// <summary> /// HTTP agent item field. Should response converted to JSON. /// /// 0 - (default) Store raw. /// 1 - Convert to JSON /// </summary> public OutputFormat output_format { get; set; } /// <summary> /// Additional parameters depending on the type of the item prototype: /// - executed script for SSH and Telnet item prototypes; /// - SQL query for database monitor item prototypes; /// - formula for calculated item prototypes. /// </summary> [JsonProperty("params")] public string @params { get; set; } /// <summary> /// Password for authentication. Used by simple check, SSH, Telnet, database monitor and JMX item prototypes. /// </summary> public string password { get; set; } /// <summary> /// Port monitored by the item prototype. Used only by SNMP items prototype. /// </summary> public string port { get; set; } /// <summary> /// HTTP agent item field. Type of post data body stored in posts property. /// /// 0 - (default) Raw data. /// 2 - JSON data. /// 3 - XML data. /// </summary> public PostType post_type { get; set; } /// <summary> /// HTTP agent item field. HTTP(S) request body data. Used with post_type. /// </summary> public string posts { get; set; } /// <summary> /// Name of the private key file. /// </summary> public string privatekey { get; set; } /// <summary> /// Name of the public key file. /// </summary> public string publickey { get; set; } /// <summary> /// HTTP agent item field. Query parameters. Array of objects with 'key':'value' pairs, where value can be empty string. /// </summary> public IList<Dictionary<string, string>> query_fields { get; set; } /// <summary> /// HTTP agent item field. Type of request method. /// /// 0 - (default) GET /// 1 - POST /// 2 - PUT /// 3 - HEAD /// </summary> public RequestMethod request_method { get; set; } /// <summary> /// HTTP agent item field. What part of response should be stored. /// /// 0 - (default) Body. /// 1 - Headers. /// 2 - Both body and headers will be stored. /// /// For request_method HEAD only 1 is allowed value. /// </summary> public RetrieveMode retrieve_mode { get; set; } /// <summary> /// SNMP community. /// /// Used only by SNMPv1 and SNMPv2 item prototypes. /// </summary> public string snmp_community { get; set; } /// <summary> /// SNMP OID. /// </summary> public string snmp_oid { get; set; } /// <summary> /// SNMPv3 auth passphrase. Used only by SNMPv3 item prototypes. /// </summary> public string snmpv3_authpassphrase { get; set; } /// <summary> /// SNMPv3 authentication protocol. Used only by SNMPv3 items. /// /// Possible values: /// 0 - (default) MD5; /// 1 - SHA. /// </summary> public SNMPv3AuthenticationProtocol snmpv3_authprotocol { get; set; } /// <summary> /// SNMPv3 context name. Used only by SNMPv3 item prototypes. /// </summary> public string snmpv3_contextname { get; set; } /// <summary> /// SNMPv3 priv passphrase. Used only by SNMPv3 item prototypes. /// </summary> public string snmpv3_privpassphrase { get; set; } /// <summary> /// SNMPv3 privacy protocol. Used only by SNMPv3 items. /// /// Possible values: /// 0 - (default) DES; /// 1 - AES. /// </summary> public SNMPv3PrivacyProtocol snmpv3_privprotocol { get; set; } /// <summary> /// SNMPv3 security level. Used only by SNMPv3 item prototypes. /// /// Possible values: /// 0 - noAuthNoPriv; /// 1 - authNoPriv; /// 2 - authPriv. /// </summary> public SNMPv3SecurityLevel snmpv3_securitylevel { get; set; } /// <summary> /// SNMPv3 security name. Used only by SNMPv3 item prototypes. /// </summary> public string snmpv3_securityname { get; set; } /// <summary> /// HTTP agent item field. Public SSL Key file path. /// </summary> public string ssl_cert_file { get; set; } /// <summary> /// HTTP agent item field. Private SSL Key file path. /// </summary> public string ssl_key_file { get; set; } /// <summary> /// HTTP agent item field. Password for SSL Key file. /// </summary> public string ssl_key_password { get; set; } /// <summary> /// Status of the item prototype. /// /// Possible values: /// 0 - (default) enabled item prototype; /// 1 - disabled item prototype; /// 3 - unsupported item prototype. /// </summary> public Status status { get; set; } /// <summary> /// HTTP agent item field. Ranges of required HTTP status codes separated by commas. Also supports user macros as part of comma separated list. /// /// Example: 200,200-{$M},{$M},200-400 /// </summary> public string status_codes { get; set; } /// <summary> /// (readonly) ID of the parent template item prototype. /// </summary> public string templateid { get; set; } /// <summary> /// HTTP agent item field. Item data polling request timeout. Support user macros. /// /// default: 3s /// maximum value: 60s /// </summary> public string timeout { get; set; } /// <summary> /// Allowed hosts. Used only by trapper item prototypes. /// </summary> public string trapper_hosts { get; set; } /// <summary> /// Number of days to keep item prototype's trends data. /// /// Default: 365. /// </summary> public string trends { get; set; } /// <summary> /// Value units. /// </summary> public string units { get; set; } /// <summary> /// Username for authentication. Used by simple check, SSH, Telnet, database monitor and JMX item prototypes. /// /// Required by SSH and Telnet item prototypes. /// </summary> public string username { get; set; } /// <summary> /// ID of the associated value map. /// </summary> public string valuemapid { get; set; } /// <summary> /// HTTP agent item field. Validate host name in URL is in Common Name field or a Subject Alternate Name field of host certificate. /// /// 0 - (default) Do not validate. /// 1 - Validate. /// </summary> public Verify verify_host { get; set; } /// <summary> /// HTTP agent item field. Validate is host certificate authentic. /// /// 0 - (default) Do not validate. /// 1 - Validate /// </summary> public Verify verify_peer { get; set; } #endregion #region Associations /// <summary> /// Applications that the item prototype belongs to /// </summary> public IList<Application> applications { get; set; } /// <summary> /// Low-level discovery rule that the graph prototype belongs to /// </summary> [JsonConverter(typeof(SingleObjectConverter<DiscoveryRule>))] public DiscoveryRule discoveryRule { get; set; } /// <summary> /// Graph prototypes that the item prototype is used /// </summary> public IList<Graph> graphs { get; set; } /// <summary> /// Host that the item prototype belongs to as an array /// </summary> public IList<Host> hosts { get; set; } /// <summary> /// Trigger prototypes that the item prototype is used /// </summary> public IList<Trigger> triggers { get; set; } #endregion #region ENUMS public enum ItemPrototypeType { ZabbixAgent = 0, SNMPv1Agent = 1, ZabbixTrapper = 2, SimpleCheck = 3, SNMPv2Agent = 4, ZabbixInternal = 5, SNMPv3Agent = 6, ZabbixAgentActive = 7, ZabbixAggregate = 8, ExternalCheck = 10, DatabaseMonitor = 11, IPMIAgent = 12, SSHAgent = 13, TELNETAgent = 14, Calculated = 15, JMXAgent = 16, SNMPTrap = 17, DependentItem = 18, HTTPAgent = 19, } public enum ValueType { NumericFloat = 0, Character = 1, Log = 2, NumericUnsigned = 3, Text = 4 } public enum DataType { Decimal = 0, Octal = 1, Hexadecimal = 2, Boolean = 3 } public enum SNMPv3AuthenticationProtocol { MD5 = 0, SHA = 1 } public enum SNMPv3PrivacyProtocol { DES = 0, AES = 1 } public enum SNMPv3SecurityLevel { NoAuthNoPriv = 0, AuthNoPriv = 1, AuthPriv = 2 } public enum Status { Enabled = 0, Disabled = 1, Unsupported = 3 } #endregion #region Constructors public ItemPrototype() { authtype = AuthenticationMethod.Password; follow_redirects = FollowRedirects.FollowRedirects; history = "90d"; snmpv3_authprotocol = SNMPv3AuthenticationProtocol.MD5; snmpv3_privprotocol = SNMPv3PrivacyProtocol.DES; status = Status.Enabled; timeout = "3s"; trends = "365d"; } #endregion #region ShouldSerialize public bool ShouldSerializeerror() => false; public bool ShouldSerializeflags() => false; #endregion } }
30.586142
187
0.516623
[ "MIT" ]
HenriqueCaires/ZabbixApi
ZabbixApi/Entities/ItemPrototype.cs
16,335
C#
using DevExpress.ExpressApp; using Xpand.Extensions.XAF.XafApplicationExtensions; using Xpand.TestsLib; using Xpand.TestsLib.Common; using Xpand.XAF.Modules.PositionInListView.Tests.BOModel; namespace Xpand.XAF.Modules.PositionInListView.Tests{ public abstract class PositionInListViewCommonTest:BaseTest{ protected static PositionInListViewModule PositionInListViewModuleModule(params ModuleBase[] modules){ var positionInListViewModule = Platform.Win.NewApplication<PositionInListViewModule>().AddModule<PositionInListViewModule>(typeof(PIL)); var xafApplication = positionInListViewModule.Application; xafApplication.MockPlatformListEditor(); xafApplication.Modules.AddRange(modules); xafApplication.Logon(); xafApplication.CreateObjectSpace(); return positionInListViewModule; } } }
47.157895
148
0.758929
[ "Apache-2.0" ]
aois-dev/Reactive.XAF
src/Tests/PositionInListView/PositionInListViewCommonTest.cs
898
C#
using System; using System.Collections.Generic; namespace TimeTrackingServer.Models { public partial class Staff { public Staff() { ActivityStaff = new HashSet<ActivityStaff>(); StaffToGroup = new HashSet<StaffToGroup>(); } public int Id { get; set; } public DateTime? UpdatedAt { get; set; } public bool? Status { get; set; } public DateTime? ActivityFirst { get; set; } public DateTime? ActivityLast { get; set; } public string Caption { get; set; } public virtual ICollection<ActivityStaff> ActivityStaff { get; set; } public virtual ICollection<StaffToGroup> StaffToGroup { get; set; } } }
28.88
77
0.616343
[ "MIT" ]
nicel3d/TimeTracking
TimeTrackingServer/TimeTrackingServer/Models/Staff.cs
724
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.Apigateway.V20180808.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class UnReleaseServiceResponse : AbstractModel { /// <summary> /// 下线操作是否成功。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Result")] public bool? Result{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Result", this.Result); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.596154
83
0.641106
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Apigateway/V20180808/Models/UnReleaseServiceResponse.cs
1,707
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using TygaSoft.IDAL; using TygaSoft.Model; using TygaSoft.DBUtility; namespace TygaSoft.SqlServerDAL { public partial class ActivityPlayer : IActivityPlayer { #region IActivityPlayer Member public Guid InsertByOutput(ActivityPlayerInfo model) { StringBuilder sb = new StringBuilder(250); sb.Append(@"insert into ActivityPlayer (ActivityId,Named,HeadPicture,DetailInformation,ActualVoteCount,UpdateVoteCount,Remark,IsDisable,LastUpdatedDate) output inserted.Id values (@ActivityId,@Named,@HeadPicture,@DetailInformation,@ActualVoteCount,@UpdateVoteCount,@Remark,@IsDisable,@LastUpdatedDate) "); SqlParameter[] parms = { new SqlParameter("@ActivityId",SqlDbType.UniqueIdentifier), new SqlParameter("@Named",SqlDbType.NVarChar,50), new SqlParameter("@HeadPicture",SqlDbType.VarChar,100), new SqlParameter("@DetailInformation",SqlDbType.NVarChar,4000), new SqlParameter("@ActualVoteCount",SqlDbType.Int), new SqlParameter("@UpdateVoteCount",SqlDbType.Int), new SqlParameter("@Remark",SqlDbType.NVarChar,300), new SqlParameter("@IsDisable",SqlDbType.Bit), new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime) }; parms[0].Value = model.ActivityId; parms[1].Value = model.Named; parms[2].Value = model.HeadPicture; parms[3].Value = model.DetailInformation; parms[4].Value = model.ActualVoteCount; parms[5].Value = model.UpdateVoteCount; parms[6].Value = model.Remark; parms[7].Value = model.IsDisable; parms[8].Value = model.LastUpdatedDate; object obj = SqlHelper.ExecuteScalar(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), parms); if (obj != null) return Guid.Parse(obj.ToString()); return Guid.Empty; } public int UpdateVoteCount(object Id, int count) { StringBuilder sb = new StringBuilder(250); sb.Append("select VoteMultiple from ActivitySubject ASj,ActivityPlayer AP where ASj.Id = AP.ActivityId and AP.Id = @Id"); SqlParameter parm = new SqlParameter("@Id", SqlDbType.UniqueIdentifier); parm.Value = Guid.Parse(Id.ToString()); int voteMultiple = 1; using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), parm)) { if (reader != null && reader.HasRows) { while (reader.Read()) { voteMultiple = reader.GetInt32(0); } } } sb.Clear(); sb.AppendFormat(@"update ActivityPlayer set ActualVoteCount = ActualVoteCount + {0},UpdateVoteCount = UpdateVoteCount + {1} where Id = @Id", count, voteMultiple * count); SqlParameter[] parms = { new SqlParameter("@Id",SqlDbType.UniqueIdentifier), }; parms[0].Value = Guid.Parse(Id.ToString()); return SqlHelper.ExecuteNonQuery(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), parms); } public DataSet GetModelOW(object Id) { StringBuilder sb = new StringBuilder(300); sb.Append(@"select top 1 ASj.MaxVoteCount,ASj.VoteMultiple,AP.Id,AP.ActivityId,Named,HeadPicture,DetailInformation,ActualVoteCount,UpdateVoteCount,AP.Remark,AP.IsDisable,AP.LastUpdatedDate, P.Id as PictureId,FileName,FileSize,FileExtension,FileDirectory,RandomFolder from ActivitySubject ASj,ActivityPlayer AP left join (select AP.PlayerId,CP.* from PlayerPicture AP,ActivityPlayerPhotoPicture CP where AP.PictureId=CP.Id) as P on AP.Id=P.PlayerId where ASj.Id=AP.ActivityId and AP.Id = @Id "); SqlParameter parm = new SqlParameter("@Id", SqlDbType.UniqueIdentifier); parm.Value = Guid.Parse(Id.ToString()); DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), parm); return ds; } public DataSet GetListOW(int pageIndex, int pageSize, out int totalRecords, string sqlWhere, params SqlParameter[] cmdParms) { StringBuilder sb = new StringBuilder(250); sb.Append(@"select count(*) from ActivityPlayer "); if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere); totalRecords = (int)SqlHelper.ExecuteScalar(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), cmdParms); sb.Clear(); int startIndex = (pageIndex - 1) * pageSize + 1; int endIndex = pageIndex * pageSize; sb.Append(@"select * from(select row_number() over(order by AP.LastUpdatedDate desc) as RowNumber, ASj.Title,AP.Id,AP.ActivityId,AP.Named,HeadPicture,DetailInformation,ActualVoteCount,UpdateVoteCount,AP.Remark,AP.IsDisable,AP.LastUpdatedDate, P.Id as PictureId,FileName,FileSize,FileExtension,FileDirectory,RandomFolder from ActivitySubject ASj,ActivityPlayer AP left join (select AP.PlayerId,CP.* from PlayerPicture AP,ActivityPlayerPhotoPicture CP where AP.PictureId=CP.Id) as P on AP.Id=P.PlayerId"); sb.AppendFormat(" where ASj.Id=AP.ActivityId {0} ", sqlWhere); sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex); DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), cmdParms); return ds; } public DataSet GetListOW(int pageIndex, int pageSize, string sqlWhere, params SqlParameter[] cmdParms) { StringBuilder sb = new StringBuilder(250); int startIndex = (pageIndex - 1) * pageSize + 1; int endIndex = pageIndex * pageSize; sb.Append(@"select * from(select row_number() over(order by UpdateVoteCount desc) as RowNumber, AP.Id,AP.ActivityId,Named,HeadPicture,DetailInformation,ActualVoteCount,UpdateVoteCount,Remark,IsDisable,AP.LastUpdatedDate, P.Id as PictureId,FileName,FileSize,FileExtension,FileDirectory,RandomFolder from ActivityPlayer AP left join (select AP.PlayerId,CP.* from PlayerPicture AP,ActivityPlayerPhotoPicture CP where AP.PictureId=CP.Id) as P on AP.Id=P.PlayerId"); if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere); sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex); DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), cmdParms); return ds; } public DataSet GetListOW(string sqlWhere, params SqlParameter[] cmdParms) { StringBuilder sb = new StringBuilder(250); sb.Append(@"select AP.Id,AP.ActivityId,Named,HeadPicture,DetailInformation,ActualVoteCount,UpdateVoteCount,Remark,IsDisable,AP.LastUpdatedDate, P.Id as PictureId,FileName,FileSize,FileExtension,FileDirectory,RandomFolder from ActivityPlayer AP left join (select AP.PlayerId,CP.* from PlayerPicture AP,ActivityPlayerPhotoPicture CP where AP.PictureId=CP.Id) as P on AP.Id=P.PlayerId"); if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} order by UpdateVoteCount desc", sqlWhere); DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.HnztcTeamDbConnString, CommandType.Text, sb.ToString(), cmdParms); return ds; } #endregion } }
51.707006
201
0.649914
[ "MIT" ]
qq283335746/Infoztc
src/Team12/TygaSoft/SqlServerDAL/MyActivityPlayer.cs
8,118
C#
#region License // // CoiniumServ - Crypto Currency Mining Pool Server Software // Copyright (C) 2013 - 2014, CoiniumServ Project - http://www.coinium.org // http://www.coiniumserv.com - https://github.com/CoiniumServ/CoiniumServ // // This software is dual-licensed: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // For the terms of this license, see licenses/gpl_v3.txt. // // Alternatively, you can license this software under a commercial // license or white-label it as set out in licenses/commercial.txt. // #endregion using System; using CoiniumServ.Utils.Commands; namespace CoiniumServ.Server.Commands { [CommandGroup("uptime", "Renders uptime statistics.")] public class UptimeCommand : CommandGroup { [DefaultCommand] public string Uptime(string[] @params) { var uptime = DateTime.Now - Program.StartupTime; return string.Format("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds.", uptime.Days, uptime.Hours, uptime.Minutes, uptime.Seconds); } } }
38.2
150
0.684555
[ "MIT" ]
banura/brasilcoin
src/CoiniumServ/Server/Commands/Uptime.cs
1,530
C#
using System; using System.Globalization; using System.Windows.Data; namespace PowerApps_Theme_Editor.Converters { public class BorderStyleFormatConverter : IValueConverter { public static string borderStyleReservedPrefix = "%BorderStyle.RESERVED%."; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { string paBorderStyleName = value.ToString(); paBorderStyleName = paBorderStyleName.Replace(borderStyleReservedPrefix, ""); paBorderStyleName = paBorderStyleName.Replace("'", ""); return paBorderStyleName; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string paFontWeightName = value.ToString(); string paFontName = string.Format("{0}{1}", borderStyleReservedPrefix, paFontWeightName); return paFontName; } } }
32.333333
103
0.636364
[ "MIT" ]
AzureMentor/powerapps-tools
Tools/Apps/Microsoft.PowerApps.ThemeEditor/Converters/BorderStyleFormatConverter.cs
1,069
C#
namespace iSukces.Translation { public interface IMinimumTextSource { string Text { get; } string Language { get; } string Key { get; } string Hint { get; } } }
21.7
39
0.529954
[ "MIT" ]
isukces/iSukces.Translation
app/iSukces.Translation/_translations/IMinimumTextSource.cs
217
C#
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Our.Umbraco.Ditto.Tests.Mocks; namespace Our.Umbraco.Ditto.Tests { [TestFixture] [Category("Collections"), Category("Processors")] public class EnumerableDetectionTests { public class MyModel { [MyProcessor] public Dictionary<string, string> MyProperty { get; set; } public string EnumerableToSingle { get; set; } public IEnumerable<string> SingleToEnumerable { get; set; } } public class MyProcessorAttribute : DittoProcessorAttribute { public override object ProcessValue() { return new Dictionary<string, string> { { "hello", "world" }, { "foo", "bar" } }; } } [Test] public void GenericDictionaryPropertyIsNotDetectedAsCastableEnumerable() { var content = new MockPublishedContent { Properties = new[] { new MockPublishedContentProperty("myProperty", "myValue") } }; var result = content.As<MyModel>(); Assert.That(result.MyProperty, Is.Not.Null); Assert.That(result.MyProperty.Any(), Is.True); Assert.That(result.MyProperty["hello"], Is.EqualTo("world")); } [Test] public void EnumerablesCast() { var propertyValue = "myVal"; var content = new MockPublishedContent { Properties = new[] { new MockPublishedContentProperty("enumerableToSingle", new[] { propertyValue, "myOtherVal" }), new MockPublishedContentProperty("singleToEnumerable", propertyValue) } }; var result = content.As<MyModel>(); Assert.That(result.EnumerableToSingle, Is.Not.Null); Assert.That(result.EnumerableToSingle, Is.EqualTo(propertyValue)); Assert.That(result.SingleToEnumerable, Is.Not.Null); Assert.That(result.SingleToEnumerable.Any(), Is.True); Assert.That(result.SingleToEnumerable.First(), Is.EqualTo(propertyValue)); } } }
31.69863
114
0.563526
[ "MIT" ]
stevetemple/umbraco-ditto
tests/Our.Umbraco.Ditto.Tests/EnumerableDetectionTests.cs
2,316
C#
using System.Management.Automation; using PwshKeePass.Common; using PwshKeePass.Service; // ReSharper disable MemberCanBePrivate.Global namespace PwshKeePass.Commands.Group { [Cmdlet(VerbsCommon.Remove, "KeePassGroup", SupportsShouldProcess = true)] [OutputType("null")] public class RemoveKeePassGroup : KeePassConnectedCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true)] public PSObject KeePassGroup { get; set; } [Parameter] [ValidateNotNull] public SwitchParameter NoRecycle { get; set; } [Parameter] [ValidateNotNull] public SwitchParameter Force { get; set; } public override void ExecuteCmdlet() { var groupService = new GroupService(KeePassProfile, this, Connection); var keePassPwGroup = ResolveKeePassGroup(KeePassGroup); keePassPwGroup = groupService.GetGroup(keePassPwGroup.GetFullPath("/", true)).KPGroup; if (Force | ShouldProcess(keePassPwGroup.GetFullPath("/", true), "Remove")) { groupService.RemoveGroup(keePassPwGroup, NoRecycle.ToBool()); } } } }
35.181818
98
0.670973
[ "MIT" ]
dimitertodorov/PwshKeePass
PwshKeePass/Commands/Group/RemoveKeePassGroup.cs
1,161
C#
using ASPNETCoreIdentitySample.Common.IdentityToolkit; using ASPNETCoreIdentitySample.Entities.Identity; using ASPNETCoreIdentitySample.Services.Contracts.Identity; using ASPNETCoreIdentitySample.ViewModels.Identity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using ASPNETCoreIdentitySample.Services.Identity; using DNTBreadCrumb.Core; using DNTCommon.Web.Core; using System; namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers { [Authorize(Roles = ConstantRoles.Admin)] [Area(AreaConstants.IdentityArea)] [BreadCrumb(Title = "مدیریت نقش‌ها", UseDefaultRouteUrl = true, Order = 0)] public class RolesManagerController : Controller { private const string RoleNotFound = "نقش درخواستی یافت نشد."; private const int DefaultPageSize = 7; private readonly IApplicationRoleManager _roleManager; public RolesManagerController(IApplicationRoleManager roleManager) { _roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager)); } [BreadCrumb(Title = "ایندکس", Order = 1)] public IActionResult Index() { var roles = _roleManager.GetAllCustomRolesAndUsersCountList(); return View(roles); } [AjaxOnly] public async Task<IActionResult> RenderRole([FromBody] ModelIdViewModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (model == null || model.Id == 0) { return PartialView("_Create", model: new RoleViewModel()); } var role = await _roleManager.FindByIdAsync(model.Id.ToString()); if (role == null) { ModelState.AddModelError("", RoleNotFound); return PartialView("_Create", model: new RoleViewModel()); } return PartialView("_Create", model: new RoleViewModel { Id = role.Id.ToString(), Name = role.Name }); } [AjaxOnly] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EditRole(RoleViewModel model) { if (ModelState.IsValid) { var role = await _roleManager.FindByIdAsync(model.Id); if (role == null) { ModelState.AddModelError("", RoleNotFound); } else { role.Name = model.Name; var result = await _roleManager.UpdateAsync(role); if (result.Succeeded) { return Json(new { success = true }); } ModelState.AddErrorsFromResult(result); } } return PartialView("_Create", model: model); } [AjaxOnly] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddRole(RoleViewModel model) { if (ModelState.IsValid) { var result = await _roleManager.CreateAsync(new Role(model.Name)); if (result.Succeeded) { return Json(new { success = true }); } ModelState.AddErrorsFromResult(result); } return PartialView("_Create", model: model); } [AjaxOnly] public async Task<IActionResult> RenderDeleteRole([FromBody] ModelIdViewModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (model == null) { return BadRequest("model is null."); } var role = await _roleManager.FindByIdAsync(model.Id.ToString()); if (role == null) { ModelState.AddModelError("", RoleNotFound); return PartialView("_Delete", model: new RoleViewModel()); } return PartialView("_Delete", model: new RoleViewModel { Id = role.Id.ToString(), Name = role.Name }); } [AjaxOnly] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(RoleViewModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (string.IsNullOrWhiteSpace(model?.Id)) { return BadRequest("model is null."); } var role = await _roleManager.FindByIdAsync(model.Id); if (role == null) { ModelState.AddModelError("", RoleNotFound); } else { var result = await _roleManager.DeleteAsync(role); if (result.Succeeded) { return Json(new { success = true }); } ModelState.AddErrorsFromResult(result); } return PartialView("_Delete", model: model); } [BreadCrumb(Title = "لیست کاربران دارای نقش", Order = 1)] public async Task<IActionResult> UsersInRole(int? id, int? page = 1, string field = "Id", SortOrder order = SortOrder.Ascending) { if (id == null) { return View("Error"); } var model = await _roleManager.GetPagedApplicationUsersInRoleListAsync( roleId: id.Value, pageNumber: page.Value - 1, recordsPerPage: DefaultPageSize, sortByField: field, sortOrder: order, showAllUsers: true); model.Paging.CurrentPage = page.Value; model.Paging.ItemsPerPage = DefaultPageSize; model.Paging.ShowFirstLast = true; if (HttpContext.Request.IsAjaxRequest()) { return PartialView("~/Areas/Identity/Views/UsersManager/_UsersList.cshtml", model); } return View(model); } } }
34.038251
136
0.54455
[ "Apache-2.0" ]
MohammadGhaedi/DNTIdentity
src/ASPNETCoreIdentitySample/Areas/Identity/Controllers/RolesManagerController.cs
6,287
C#
using System; using System.Diagnostics; using System.Globalization; using System.Text; namespace TweakUIX { public static class WindowsHelper { private static readonly ErrorHelper logger = ErrorHelper.Instance; // Command Prompt (to be replaced with wt.exe) public static void RunCmd(string args) { ProcStart(Helpers.Strings.Paths.ShellCommandPrompt, args); } // Windows Terminal public static void RunWT(string args) { ProcStart(Helpers.Strings.Paths.ShellWT, args); } public static void ProcStart(string name, string args) { try { var proc = new Process { StartInfo = new ProcessStartInfo { FileName = name, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage), CreateNoWindow = true } }; proc.Start(); string line = null; while (!proc.StandardOutput.EndOfStream) { line += Environment.NewLine + proc.StandardOutput.ReadLine(); } proc.WaitForExit(); logger.Log($"{name} {args} {line}"); } catch { logger.Log($"Could not start {name} {args}."); } } public static void IsServiceRunning(string service) { logger.Log($"Check if {service} service is running"); RunCmd($"/c sc query {service} | find \"RUNNING\""); } public static void DisableService(string service) { RunCmd($"/c net stop {service}"); ProcStart(Helpers.Strings.Paths.ShellPS, $"-command \"Set-Service -Name {service} -StartupType disabled\""); logger.Log($"Disable {service} service"); } public static void EnableService(string service) { RunCmd($"/c net start {service}"); ProcStart(Helpers.Strings.Paths.ShellPS, $"-command \"Set-Service -Name {service} -StartupType auto\""); logger.Log($"Enable {service} service"); } } }
33.146667
120
0.51609
[ "MIT" ]
builtbybel/BreakingApp
src/TUIX/Helpers/WindowsHelper.cs
2,488
C#
using System; using R5T.T0093; namespace R5T.T0122 { public interface IFileSpecification : IFilePathed { } }
10.416667
53
0.68
[ "MIT" ]
SafetyCone/R5T.T0122
source/R5T.T0122/Code/Interfaces/IFileSpecification.cs
127
C#
using GamesWiki.Core.ProjectAggregate.Events; using Xunit; namespace GamesWiki.UnitTests.Core.ProjectAggregate { public class ToDoItemMarkComplete { [Fact] public void SetsIsDoneToTrue() { var item = new ToDoItemBuilder() .WithDefaultValues() .Description("") .Build(); item.MarkComplete(); Assert.True(item.IsDone); } [Fact] public void RaisesToDoItemCompletedEvent() { var item = new ToDoItemBuilder().Build(); item.MarkComplete(); Assert.Single(item.Events); Assert.IsType<ToDoItemCompletedEvent>(item.Events.First()); } } }
23.1875
71
0.553908
[ "MIT" ]
Paexp/GamesWiki
tests/GamesWiki.UnitTests/Core/ProjectAggregate/ToDoItemMarkComplete.cs
744
C#
using System; using System.Globalization; namespace NuGet { public class PackageRestoreConsent { private const string EnvironmentVariableName = "EnableNuGetPackageRestore"; private const string PackageRestoreSection = "packageRestore"; private const string PackageRestoreConsentKey = "enabled"; // the key to enable/disable automatic package restore during build. private const string PackageRestoreAutomaticKey = "automatic"; private readonly ISettings _settings; private readonly IEnvironmentVariableReader _environmentReader; private readonly ConfigurationDefaults _configurationDefaults; public PackageRestoreConsent(ISettings settings) : this(settings, new EnvironmentVariableWrapper()) { } public PackageRestoreConsent(ISettings settings, IEnvironmentVariableReader environmentReader) : this(settings, environmentReader, ConfigurationDefaults.Instance) { } public PackageRestoreConsent(ISettings settings, IEnvironmentVariableReader environmentReader, ConfigurationDefaults configurationDefaults) { if (settings == null) { throw new ArgumentNullException("settings"); } if (environmentReader == null) { throw new ArgumentNullException("environmentReader"); } if (configurationDefaults == null) { throw new ArgumentNullException("configurationDefaults"); } _settings = settings; _environmentReader = environmentReader; _configurationDefaults = configurationDefaults; } public bool IsGranted { get { string envValue = _environmentReader.GetEnvironmentVariable(EnvironmentVariableName).SafeTrim(); return IsGrantedInSettings || IsSet(envValue); } } public bool IsGrantedInSettings { get { string settingsValue = _settings.GetValue( PackageRestoreSection, PackageRestoreConsentKey, isPath: false); if (String.IsNullOrWhiteSpace(settingsValue)) { settingsValue = _configurationDefaults.DefaultPackageRestoreConsent; } settingsValue = settingsValue.SafeTrim(); if (String.IsNullOrEmpty(settingsValue)) { // default value of user consent is true. return true; } return IsSet(settingsValue); } set { _settings.SetValue(PackageRestoreSection, PackageRestoreConsentKey, value.ToString()); } } public bool IsAutomatic { get { string settingsValue = _settings.GetValue( PackageRestoreSection, PackageRestoreAutomaticKey, isPath: false); if (String.IsNullOrWhiteSpace(settingsValue)) { return IsGrantedInSettings; } settingsValue = settingsValue.SafeTrim(); return IsSet(settingsValue); } set { _settings.SetValue(PackageRestoreSection, PackageRestoreAutomaticKey, value.ToString()); } } private static bool IsSet(string value) { bool boolResult; int intResult; return ((Boolean.TryParse(value, out boolResult) && boolResult) || (Int32.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out intResult) && (intResult == 1))); } } }
34.803419
148
0.553291
[ "ECL-2.0", "Apache-2.0" ]
Barsonax/NuGet2
src/Core/PackageRestoreConsent.cs
4,074
C#
using Lol_AutoRecorder.Exceptions; using Lol_AutoRecorder.Interfaces; using LolAutoRecorder.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Lol_AutoRecorder.Providers { public class ReplayPlaybackProvider : IReplayPlaybackProvider { public async Task<List<ReplayPlayback>> ProvideAsync(string pathToMedatadaFile) { if (string.IsNullOrEmpty(pathToMedatadaFile)) throw new ReplayPlaybackProviderException($"Argument: {pathToMedatadaFile} not specified."); try { return await Task.Run(() => { List<ReplayPlayback> replayPlaybacks = new List<ReplayPlayback>(); using (StreamReader r = new StreamReader(pathToMedatadaFile)) { string json = r.ReadToEnd(); replayPlaybacks = JsonConvert.DeserializeObject<List<ReplayPlayback>>(json); } return replayPlaybacks; }); } catch (Exception exception) { throw new ReplayPlaybackProviderException($"Error occured while retrieving replay playbacks. See inner exceptions for details.", exception); } } } }
36.026316
156
0.607743
[ "MIT" ]
smmileey/lol-replay-core
Lol AutoRecorder/Providers/ReplayPlaybackProvider.cs
1,371
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProjetoPinturaOO { public partial class frm_projeto_pintura : Form { public frm_projeto_pintura() { InitializeComponent(); } private void btn_calcular_Click(object sender, EventArgs e) { lbl_resultado.Visible = true; ClassCalculo calq = new ClassCalculo(); try { calq.Area = Convert.ToDouble(txt_area.Text); calq.ValorLata = Convert.ToDouble(txt_vLatas.Text); calq.ValorMaodObra = Convert.ToDouble(txt_vMaodobra.Text); } catch { txt_area.Text = "Erro"; txt_vLatas.Text = "Erro"; txt_vMaodobra.Text = "Erro"; lbl_resultado.Visible = false; lbl_resultado.Text = ""; } lbl_resultado.Text = "Área a ser pintada: " + calq.Area + "m² " + "\nDias necessários: " + calq.DiasNecessarios() + "\nQuantidade de latas: " + calq.CalculoLata() + "\nValor total Latas: R$" + calq.CalculoTintas() + "\nPreço da diária: R$" + calq.ValorMaodObra + "\nValor da mão-de-obra: R$" + calq.CalculoMaodObra() + "\nValor total da pintura: R$" + calq.CalculoValorTotal(); } private void btn_sair_Click(object sender, EventArgs e) { Close(); } private void btn_limpar_Click(object sender, EventArgs e) { lbl_resultado.Text = ""; lbl_resultado.Visible = false; txt_area.Text = ""; txt_vLatas.Text = ""; txt_vMaodobra.Text = ""; txt_area.Focus(); } } }
32.457627
147
0.562402
[ "MIT" ]
GuiPiovezan/Atividades
C#/ProjetoPinturaOO/ProjetoPinturaOO/Form1.cs
1,923
C#
using System; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// MybankPaymentTradeAccountSubvirtualcardCreateModel Data Structure. /// </summary> [Serializable] public class MybankPaymentTradeAccountSubvirtualcardCreateModel : AlipayObject { /// <summary> /// 买家标识 /// </summary> [JsonProperty("member_id")] public string MemberId { get; set; } /// <summary> /// 卖家主卡户名 /// </summary> [JsonProperty("prim_card_name")] public string PrimCardName { get; set; } /// <summary> /// 卖家主卡号 /// </summary> [JsonProperty("prim_card_no")] public string PrimCardNo { get; set; } } }
24.83871
82
0.585714
[ "MIT" ]
gebiWangshushu/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/MybankPaymentTradeAccountSubvirtualcardCreateModel.cs
802
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.Sqlserver.V20180328.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeInstanceParamsResponse : AbstractModel { /// <summary> /// 实例的参数总数 /// </summary> [JsonProperty("TotalCount")] public long? TotalCount{ get; set; } /// <summary> /// 参数详情 /// </summary> [JsonProperty("Items")] public ParameterDetail[] Items{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ 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 + "TotalCount", this.TotalCount); this.SetParamArrayObj(map, prefix + "Items.", this.Items); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.827586
81
0.630313
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Sqlserver/V20180328/Models/DescribeInstanceParamsResponse.cs
1,868
C#
using Rollvolet.CRM.APIContracts.JsonApi; namespace Rollvolet.CRM.APIContracts.DTO { public class TelephoneTypeDto : Resource<TelephoneTypeDto.AttributesDto, EmptyRelationshipsDto> { public class AttributesDto { public string Name { get; set; } } } }
26.272727
99
0.702422
[ "MIT" ]
rollvolet/crm-ap
src/Rollvolet.CRM.APIContracts/DTO/TelephoneTypeDto.cs
289
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using System.Web.Routing; using System.Web.UI; using Microsoft.TestCommon; using Moq; namespace System.Web.Mvc.Test { public class ViewMasterPageTest { [Fact] public void GetModelFromViewPage() { // Arrange ViewMasterPage vmp = new ViewMasterPage(); ViewPage vp = new ViewPage(); vmp.Page = vp; object model = new object(); vp.ViewData = new ViewDataDictionary(model); // Assert Assert.Equal(model, vmp.Model); } [Fact] public void GetModelFromViewPageStronglyTyped() { // Arrange ViewMasterPage<FooModel> vmp = new ViewMasterPage<FooModel>(); ViewPage vp = new ViewPage(); vmp.Page = vp; FooModel model = new FooModel(); vp.ViewData = new ViewDataDictionary(model); // Assert Assert.Equal(model, vmp.Model); } [Fact] public void GetViewDataFromViewPage() { // Arrange ViewMasterPage vmp = new ViewMasterPage(); ViewPage vp = new ViewPage(); vmp.Page = vp; vp.ViewData = new ViewDataDictionary { { "a", "123" }, { "b", "456" } }; // Assert Assert.Equal("123", vmp.ViewData.Eval("a")); Assert.Equal("456", vmp.ViewData.Eval("b")); } [Fact] public void GetViewItemFromViewPageTViewData() { // Arrange MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData(); MockViewPageDummyViewData vp = new MockViewPageDummyViewData(); vmp.Page = vp; vp.ViewData.Model = new DummyViewData { MyInt = 123, MyString = "abc" }; // Assert Assert.Equal(123, vmp.ViewData.Model.MyInt); Assert.Equal("abc", vmp.ViewData.Model.MyString); } [Fact] public void GetWriterFromViewPage() { // Arrange bool triggered = false; HtmlTextWriter writer = new HtmlTextWriter(TextWriter.Null); ViewMasterPage vmp = new ViewMasterPage(); MockViewPage vp = new MockViewPage(); vp.RenderCallback = delegate() { triggered = true; Assert.Equal(writer, vmp.Writer); }; vmp.Page = vp; // Act & Assert Assert.Null(vmp.Writer); vp.RenderControl(writer); Assert.Null(vmp.Writer); Assert.True(triggered); } [Fact] public void GetViewDataFromPageThrows() { // Arrange ViewMasterPage vmp = new ViewMasterPage(); vmp.Page = new Page(); // Assert Assert.Throws<InvalidOperationException>( delegate { object foo = vmp.ViewData; }, "A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>." ); } [Fact] public void GetViewItemFromWrongGenericViewPageType() { // Arrange MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData(); MockViewPageBogusViewData vp = new MockViewPageBogusViewData(); vmp.Page = vp; vp.ViewData.Model = new SelectListItem(); // Assert Assert.Throws<InvalidOperationException>( delegate { object foo = vmp.ViewData.Model; }, "The model item passed into the dictionary is of type 'System.Web.Mvc.SelectListItem', but this dictionary requires a model item of type 'System.Web.Mvc.Test.ViewMasterPageTest+DummyViewData'." ); } [Fact] public void GetViewDataFromNullPageThrows() { // Arrange MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData(); // Assert Assert.Throws<InvalidOperationException>( delegate { object foo = vmp.ViewData; }, "A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>." ); } [Fact] public void GetViewDataFromRegularPageThrows() { // Arrange MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData(); vmp.Page = new Page(); // Assert Assert.Throws<InvalidOperationException>( delegate { object foo = vmp.ViewData; }, "A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>." ); } [Fact] public void GetHtmlHelperFromViewPage() { // Arrange ViewMasterPage vmp = new ViewMasterPage(); ViewPage vp = new ViewPage(); vmp.Page = vp; ViewContext vc = new Mock<ViewContext>().Object; HtmlHelper<object> htmlHelper = new HtmlHelper<object>(vc, vp); vp.Html = htmlHelper; // Assert Assert.Equal(vmp.Html, htmlHelper); } [Fact] public void GetUrlHelperFromViewPage() { // Arrange ViewMasterPage vmp = new ViewMasterPage(); ViewPage vp = new ViewPage(); vmp.Page = vp; RequestContext rc = new RequestContext( new Mock<HttpContextBase>().Object, new RouteData() ); UrlHelper urlHelper = new UrlHelper(rc); vp.Url = urlHelper; // Assert Assert.Equal(vmp.Url, urlHelper); } [Fact] public void ViewBagProperty_ReflectsViewData() { // Arrange ViewPage page = new ViewPage(); ViewMasterPage masterPage = new ViewMasterPage(); masterPage.Page = page; masterPage.ViewData["A"] = 1; // Act & Assert Assert.NotNull(masterPage.ViewBag); Assert.Equal(1, masterPage.ViewBag.A); } [Fact] public void ViewBagProperty_PropagatesChangesToViewData() { // Arrange ViewPage page = new ViewPage(); ViewMasterPage masterPage = new ViewMasterPage(); masterPage.Page = page; masterPage.ViewData["A"] = 1; // Act masterPage.ViewBag.A = "foo"; masterPage.ViewBag.B = 2; // Assert Assert.Equal("foo", masterPage.ViewData["A"]); Assert.Equal(2, masterPage.ViewData["B"]); } // Master page types private sealed class MockViewMasterPageDummyViewData : ViewMasterPage<DummyViewData> { } // View data types private sealed class DummyViewData { public int MyInt { get; set; } public string MyString { get; set; } } // Page types private sealed class MockViewPageBogusViewData : ViewPage<SelectListItem> { } private sealed class MockViewPageDummyViewData : ViewPage<DummyViewData> { } private sealed class MockViewPage : ViewPage { public Action RenderCallback { get; set; } protected override void RenderChildren(HtmlTextWriter writer) { if (RenderCallback != null) { RenderCallback(); } base.RenderChildren(writer); } } private sealed class FooModel { } } }
30.70412
209
0.529275
[ "Apache-2.0" ]
belav/AspNetWebStack
test/System.Web.Mvc.Test/Test/ViewMasterPageTest.cs
8,200
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 kinesisanalyticsv2-2018-05-23.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.KinesisAnalyticsV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.KinesisAnalyticsV2.Model.Internal.MarshallTransformations { /// <summary> /// InputParallelismUpdate Marshaller /// </summary> public class InputParallelismUpdateMarshaller : IRequestMarshaller<InputParallelismUpdate, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(InputParallelismUpdate requestObject, JsonMarshallerContext context) { if(requestObject.IsSetCountUpdate()) { context.Writer.WritePropertyName("CountUpdate"); context.Writer.Write(requestObject.CountUpdate); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static InputParallelismUpdateMarshaller Instance = new InputParallelismUpdateMarshaller(); } }
34.306452
118
0.697226
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/Model/Internal/MarshallTransformations/InputParallelismUpdateMarshaller.cs
2,127
C#
using System; using Zen.Base.Common; using Zen.Base.Module.Cache; // ReSharper disable InconsistentNaming // ReSharper disable StaticMemberInGenericType #pragma warning disable 693 namespace Zen.Base.Module.Data { public static class Info<T> where T : Data<T> { private static T _Instance; public static Settings<T> Settings => TypeConfigurationCache<T>.Get().Item1; public static DataConfigAttribute Configuration => TypeConfigurationCache<T>.Get().Item2; public static T Instance { get { if (_Instance != null) return _Instance; _Instance = (T) Activator.CreateInstance(typeof(T), null); return _Instance; } } public static string CacheKey(string key = "") => Data<T>._cacheKeyBase + ":" + key; public static void TryFlushCachedCollection(Mutator mutator = null) { if (!(Configuration?.UseCaching == true && Current.Cache.OperationalStatus == EOperationalStatus.Operational)) return; Current.Cache.RemoveAll(); } internal static void TryFlushCachedModel(T model, Mutator mutator = null) { if (!(Configuration?.UseCaching == true && Current.Cache.OperationalStatus == EOperationalStatus.Operational)) return; var key = mutator?.KeyPrefix + model.GetDataKey(); CacheFactory.FlushModel<T>(key); } } }
31.956522
130
0.629252
[ "MIT" ]
bucknellu/zen
Zen.Base/Module/Data/Info.cs
1,472
C#
using System.Collections.Generic; using System.Collections.Immutable; using DnsTools.Worker; using Reinforced.Typings.Attributes; namespace DnsTools.Web.Models { [TsInterface(AutoI = false)] public class PingRequest { public string Host { get; set; } public Protocol Protocol { get; set; } [TsProperty(Type = "ReadonlyArray<string>", ForceNullable = true)] public ImmutableHashSet<string>? Workers { get; set; } } }
22.736842
68
0.743056
[ "MIT" ]
Daniel15/dnstools
src/DnsTools.Web/Models/PingRequest.cs
434
C#
using AspNetCoreHero.Boilerplate.Application.ApiService; using AspNetCoreHero.Boilerplate.Web.Abstractions; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace AspNetCoreHero.Boilerplate.Web.Areas.Catalog.Controllers; [Area("Catalog")] public class BrandController : BaseController<BrandController, IBrandsClient> { public IActionResult Index() { var model = new BrandDto(); return View(model); } public async Task<IActionResult> LoadAll() { var response = await _service.SearchAsync(new BrandListFilter() { PageSize = 10 }); if (response.Succeeded) { return PartialView("_ViewAll", response.Data); } return PartialView("_ViewAll", new List<BrandDto>()); } public async Task<JsonResult> OnGetCreateOrEdit(Guid? id = null) { if (id == null) { var brand = new BrandDto(); return new JsonResult(new { isValid = true, html = await _viewRenderer.RenderViewToStringAsync("_CreateOrEdit", brand) }); } else { var response = await _service.GetAsync(id ?? Guid.Empty); if (response.Succeeded) { return new JsonResult(new { isValid = true, html = await _viewRenderer.RenderViewToStringAsync("_CreateOrEdit", response.Data) }); } return null; } } [HttpPost] public async Task<JsonResult> OnPostCreateOrEdit(Guid id, CreateBrandRequest createBrandRequest) { if (ModelState.IsValid) { if (id == Guid.Empty) { var result = await _service.CreateAsync(createBrandRequest); if (result.Succeeded) { id = result.Data; _notify.Success($"Brand with ID {result.Data} Created."); } else _notify.Error(string.Join(",", result.Messages)); } else { var result = await _service.UpdateAsync(id, new UpdateBrandRequest() { Description = createBrandRequest.Description, Name = createBrandRequest.Name, }); if (result.Succeeded) _notify.Information($"Brand with ID {result.Data} Updated."); } var response = await _service.SearchAsync(new BrandListFilter() { PageSize = 10 }); if (response.Succeeded) { string html = await _viewRenderer.RenderViewToStringAsync("_ViewAll", response.Data); return new JsonResult(new { isValid = true, html = html }); } else { _notify.Error(string.Join(",", response.Messages)); return null; } } else { string html = await _viewRenderer.RenderViewToStringAsync("_CreateOrEdit", createBrandRequest); return new JsonResult(new { isValid = false, html = html }); } } [HttpPost] public async Task<JsonResult> OnPostDelete(int id) { //var deleteCommand = await _mediator.Send(new DeleteBrandCommand { Id = id }); //if (deleteCommand.Succeeded) //{ // _notify.Information($"Brand with Id {id} Deleted."); // var response = await _mediator.Send(new GetAllBrandsCachedQuery()); // if (response.Succeeded) // { // var viewModel = _mapper.Map<List<BrandDto>>(response.Data); // var html = await _viewRenderer.RenderViewToStringAsync("_ViewAll", viewModel); // return new JsonResult(new { isValid = true, html = html }); // } // else // { // _notify.Error(response.Message); // return null; // } //} //else //{ // _notify.Error(deleteCommand.Message); // return null; //} string html = await _viewRenderer.RenderViewToStringAsync("_ViewAll", new List<BrandDto>()); return new JsonResult(new { isValid = true, html }); } }
35.147541
146
0.563433
[ "MIT" ]
nagurshaik-git/Boilerplate
AspNetCoreHero.Boilerplate.Web/Areas/Catalog/Controllers/BrandController.cs
4,290
C#
using System; using System.Collections.Generic; using System.Text; namespace AzureSearchBackupRestoreIndex { public static class Constants { public const string ValuePropertyName = "value"; } }
17.166667
52
0.76699
[ "MIT" ]
manalotoj/azure-search-dotnet-samples
index-backup-restore/AzureSearchBackupRestoreIndex/Constants.cs
208
C#
using System.Collections.Generic; namespace DETOWN.Domain.Services.Mail { public class MailMessage { public MailAddress From { get; set; } public IEnumerable<MailAddress> To { get; set; } public IEnumerable<MailAddress> Cc { get; set; } public IEnumerable<MailAddress> Bcc { get; set; } public IEnumerable<Attachment> Attachments { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool IsBodyHtml { get; set; } } }
31.294118
64
0.633459
[ "MIT" ]
paulogabrielfs/DETOWN-API
src/DETOWN.Domain/Services/Mail/MailMessage.cs
534
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Threading; using Commands.Storage.ScenarioTest.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; namespace Commands.Storage.ScenarioTest.Functional.Blob { using Common; /// <summary> /// functional test for Get-AzureStorageBlob /// </summary> [TestClass] class GetBlob : TestBase { [ClassInitialize()] public static void GetBlobClassInit(TestContext testContext) { TestBase.TestClassInitialize(testContext); } [ClassCleanup()] public static void GetBlobClassCleanup() { TestBase.TestClassCleanup(); } /// <summary> /// get blobs in specified container /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 3. Get an existing blob using the container name specified by the param /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetMultipleBlobByName() { string containerName = Utility.GenNameString("container"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<string> blobNames = new List<string>(); int count = random.Next(1, 5); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } List<ICloudBlob> blobs = blobUtil.CreateRandomBlob(container, blobNames); Test.Assert(agent.GetAzureStorageBlob(string.Empty, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(blobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get one blob in specified container /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 3. Get an existing blob using the container name specified by the param /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobByName() { string containerName = Utility.GenNameString("container"); try { string pageBlobName = Utility.GenNameString("page"); string blockBlobName = Utility.GenNameString("block"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); List<string> blobNames = new List<string>(); int count = random.Next(1, 5); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } List<ICloudBlob> blobs = blobUtil.CreateRandomBlob(container, blobNames); ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<ICloudBlob>() { pageBlob }); ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<ICloudBlob>() { pageBlob }); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get specified blob by container pipeline /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 4. Get an existing blob using the container object retrieved by Get-AzureContainer /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobByContainerPipeline() { //TODO add string.empty as the blob name //TODO add invalid container pipeline string containerName = Utility.GenNameString("container"); string blobName = Utility.GenNameString("blob"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { ICloudBlob blob = blobUtil.CreatePageBlob(container, blobName); string cmd = String.Format("Get-AzureStorageContainer {0}", containerName); ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(agent.GetAzureStorageBlob(blobName, string.Empty), Utility.GenComparisonData("Get-AzureStorageContainer | Get-AzureStorageBlob", true)); Test.Assert(agent.Output.Count == 1, String.Format("Want to retrieve {0} page blob, but retrieved {1} page blobs", 1, agent.Output.Count)); agent.OutputValidation(new List<ICloudBlob>() { blob }); blobName = Utility.GenNameString("blob"); blob = blobUtil.CreateBlockBlob(container, blobName); ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(agent.GetAzureStorageBlob(blobName, string.Empty), Utility.GenComparisonData("Get-AzureStorageContainer | Get-AzureStorageBlob", true)); Test.Assert(agent.Output.Count == 1, String.Format("Want to retrieve {0} block blob, but retrieved {1} block blobs", 1, agent.Output.Count)); agent.OutputValidation(new List<ICloudBlob>() { blob }); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get specified blob by container pipeline /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 5. Validate that all the blobs in one container can be enumerated /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetAllBlobsInSpecifiedContainer() { string containerName = Utility.GenNameString("container"); string blobName = Utility.GenNameString("blob"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { int count = random.Next(1, 5); List<string> blobNames = new List<string>(); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } List<ICloudBlob> blobs = blobUtil.CreateRandomBlob(container, blobNames); Test.Assert(agent.GetAzureStorageBlob(string.Empty, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with empty blob name", true)); Test.Assert(agent.Output.Count == blobNames.Count, String.Format("Want to retrieve {0} blobs, but retrieved {1} blobs", blobNames.Count, agent.Output.Count)); agent.OutputValidation(blobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blobs by prefix /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 6. Get a list of blobs by using Prefix parameter /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobsByPrefix() { string containerName = Utility.GenNameString("container"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<string> blobNames = new List<string>(); int count = random.Next(2, 4); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blobprefix")); } List<ICloudBlob> blobs = blobUtil.CreateRandomBlob(container, blobNames); Test.Assert(agent.GetAzureStorageBlobByPrefix("blobprefix", containerName), Utility.GenComparisonData("Get-AzureStorageBlob with prefix", true)); Test.Assert(agent.Output.Count == blobs.Count, String.Format("Expect to retrieve {0} blobs, but retrieved {1} blobs", blobs.Count, agent.Output.Count)); agent.OutputValidation(blobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blobs by wildcard /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 7. Get a list of blobs by using wildcards in the name /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobByWildCard() { string containerName = Utility.GenNameString("container"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<string> prefixes = new List<string>(); List<string> noprefixes = new List<string>(); int count = random.Next(2, 4); for (int i = 0; i < count; i++) { prefixes.Add(Utility.GenNameString("prefix")); } count = random.Next(2, 4); for (int i = 0; i < count; i++) { noprefixes.Add(Utility.GenNameString("noprefix")); } List<ICloudBlob> prefixBlobs = blobUtil.CreateRandomBlob(container, prefixes); List<ICloudBlob> noprefixBlobs = blobUtil.CreateRandomBlob(container, noprefixes); Test.Assert(agent.GetAzureStorageBlob("prefix*", containerName), Utility.GenComparisonData("Get-AzureStorageBlob with wildcard", true)); Test.Assert(agent.Output.Count == prefixBlobs.Count, String.Format("Expect to retrieve {0} blobs, actually retrieved {1} blobs", prefixBlobs.Count, agent.Output.Count)); agent.OutputValidation(prefixBlobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get snapshot blobs /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 8. Validate that all the blob snapshots can be enumerated /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetSnapshotBlobs() { string containerName = Utility.GenNameString("container"); string pageBlobName = Utility.GenNameString("page"); string blockBlobName = Utility.GenNameString("block"); Test.Info("Create test container and blobs"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); List<ICloudBlob> blobs = new List<ICloudBlob>(); pageBlob.FetchAttributes(); blockBlob.FetchAttributes(); int minSnapshot = 1; int maxSnapshot = 5; int count = random.Next(minSnapshot, maxSnapshot); int snapshotInterval = 1 * 1000; Test.Info("Create random snapshot for specified blobs"); for (int i = 0; i < count; i++) { CloudBlockBlob snapshot = ((CloudBlockBlob)blockBlob).CreateSnapshot(); snapshot.FetchAttributes(); blobs.Add(snapshot); Thread.Sleep(snapshotInterval); } blobs.Add(blockBlob); count = random.Next(minSnapshot, maxSnapshot); for (int i = 0; i < count; i++) { CloudPageBlob snapshot = ((CloudPageBlob)pageBlob).CreateSnapshot(); snapshot.FetchAttributes(); blobs.Add(snapshot); Thread.Sleep(snapshotInterval); } blobs.Add(pageBlob); Test.Assert(agent.GetAzureStorageBlob(string.Empty, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with snapshot blobs", true)); Test.Assert(agent.Output.Count == blobs.Count, String.Format("Expect to retrieve {0} blobs, actually retrieved {1} blobs", blobs.Count, agent.Output.Count)); agent.OutputValidation(blobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blob with lease /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 9. Validate that the lease data could be listed correctly /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobWithLease() { string containerName = Utility.GenNameString("container"); string pageBlobName = Utility.GenNameString("page"); string blockBlobName = Utility.GenNameString("block"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); ((CloudPageBlob)pageBlob).AcquireLease(null, string.Empty); ((CloudBlockBlob)blockBlob).AcquireLease(null, string.Empty); pageBlob.FetchAttributes(); blockBlob.FetchAttributes(); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with lease", true)); agent.OutputValidation(new List<ICloudBlob>() { pageBlob }); Test.Assert(agent.GetAzureStorageBlob(blockBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with lease", true)); agent.OutputValidation(new List<ICloudBlob>() { blockBlob }); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blob with lease /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 10. Write Metadata to the specific blob Get the Metadata from the specific blob /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobWithMetadata() { string containerName = Utility.GenNameString("container"); string pageBlobName = Utility.GenNameString("page"); string blockBlobName = Utility.GenNameString("block"); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); pageBlob.Metadata.Add(Utility.GenNameString("GetBlobWithMetadata"), Utility.GenNameString("GetBlobWithMetadata")); pageBlob.SetMetadata(); blockBlob.Metadata.Add(Utility.GenNameString("GetBlobWithMetadata"), Utility.GenNameString("GetBlobWithMetadata")); blockBlob.SetMetadata(); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with metadata", true)); Test.Assert(agent.Output.Count == 1, String.Format("Expect to retrieve {0} blobs, but retrieved {1} blobs", 1, agent.Output.Count)); agent.OutputValidation(new List<ICloudBlob>() { pageBlob }); Test.Assert(agent.GetAzureStorageBlob(blockBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with metadata", true)); Test.Assert(agent.Output.Count == 1, String.Format("Expect to retrieve {0} blobs, but retrieved {1} blobs", 1, agent.Output.Count)); agent.OutputValidation(new List<ICloudBlob>() { blockBlob }); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blob in subdirectory /// 8.12 Get-AzureStorageBlob Positive Functional Cases /// 11. Validate that blobs with a sub directory path could also be listed /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetBlobInSubdirectory() { //TODO add test cases for special characters string containerName = Utility.GenNameString("container"); string blobName = Utility.GenNameString("blob"); string subBlobName = Utility.GenNameString(string.Format("{0}/",blobName)); string subsubBlobName = Utility.GenNameString(string.Format("{0}/", subBlobName)); List<string> blobNames = new List<string> { blobName, subBlobName, subsubBlobName }; CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<ICloudBlob> blobs = blobUtil.CreateRandomBlob(container, blobNames); Test.Assert(agent.GetAzureStorageBlob(string.Empty, containerName), Utility.GenComparisonData("Get-AzureStorageBlob in sub directory", true)); Test.Assert(agent.Output.Count == blobs.Count, String.Format("Expect to retrieve {0} blobs, but retrieved {1} blobs", blobs.Count, agent.Output.Count)); agent.OutputValidation(blobs); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// get blob in subdirectory /// 8.12 Get-AzureStorageBlob Negative Functional Cases /// 1. Get a non-existing blob /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlob)] public void GetNonExistingBlob() { string containerName = Utility.GenNameString("container"); string blobName = Utility.GenNameString("blob"); List<ICloudBlob> blobs = new List<ICloudBlob>(); CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { ICloudBlob blob = blobUtil.CreatePageBlob(container, blobName); string notExistingBlobName = "notexistingblob"; Test.Assert(!agent.GetAzureStorageBlob(notExistingBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob with not existing blob", false)); Test.Assert(agent.ErrorMessages.Count == 1, "only throw an exception"); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find blob '{0}' in container '{1}'.", notExistingBlobName, containerName)), agent.ErrorMessages[0]); } finally { blobUtil.RemoveContainer(containerName); } } } }
44.026316
186
0.576624
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.Storage.ScenarioTest/Functional/Blob/GetBlob.cs
21,256
C#
using Newtonsoft.Json; namespace WGnet.Model.WoT.Stronghold { /// <summary> /// Информацию из энциклопедии обо всех строениях Укрепрайона /// См. описание <see cref="http://ru.wargaming.net/developers/api_reference/wot/stronghold/buildings/"/> /// </summary> public class StrongholdBuildings { /// <summary> /// Локализованное полное описание /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// Ссылка на изображение /// </summary> [JsonProperty("image_url")] public string ImageUrl { get; set; } /// <summary> /// Локализованное краткое описание /// </summary> [JsonProperty("short_description")] public string ShortDescription { get; set; } /// <summary> /// Локализованное название /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// Уникальный тип /// </summary> [JsonProperty("type")] public int Type { get; set; } /// <summary> /// Информация о резерве /// См. <see cref="StrongholdBuildingsReserve"/> /// </summary> [JsonProperty("reserve")] public StrongholdBuildingsReserve Reserve { get; set; } } }
28.204082
109
0.560781
[ "BSD-3-Clause" ]
mishamyte/WGnet
WGnet/Model/WoT/Stronghold/StrongholdBuildings.cs
1,576
C#
using System; using System.Configuration; namespace Bitshare.Common { /// <summary> /// web.config操作类 /// Copyright (C) Maticsoft /// </summary> public sealed class ConfigHelper { /// <summary> /// 得到AppSettings中的配置字符串信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetConfigString(string key) { string CacheKey = "AppSettings-" + key; object objModel = DataCache.GetCache(CacheKey); if (objModel == null) { try { objModel = ConfigurationManager.AppSettings[key]; if (objModel != null) { DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(180), TimeSpan.Zero); } } catch { } } return objModel.ToString(); } /// <summary> /// 得到AppSettings中的配置Bool信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool GetConfigBool(string key) { bool result = false; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = bool.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } /// <summary> /// 得到AppSettings中的配置Decimal信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static decimal GetConfigDecimal(string key) { decimal result = 0; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = decimal.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } /// <summary> /// 得到AppSettings中的配置int信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static int GetConfigInt(string key) { int result = 0; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = int.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } } }
21.775701
108
0.537768
[ "Apache-2.0" ]
Nocturnexol/ITMS
Bitshare.Common/ConfigHelper.cs
2,408
C#
/*The MIT License (MIT) Copyright (c) 2014 PMU Staff Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Drawing; using System.Windows.Forms; namespace PMDToolkit.Editors { public class MapLayerListBox : CheckedListBox { private const int WM_LBUTTONDOWN = 0x0201; private const int WM_LBUTTONUP = 0x0202; private const int WM_LBUTTONDBLCLK = 0x0203; protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_LBUTTONDOWN: { Point point = PointToClient(Cursor.Position); for (int i = 0; i < Items.Count; i++) { Rectangle checkboxRect = GetItemRectangle(i); checkboxRect.Width = checkboxRect.Height; if (checkboxRect.Contains(point)) { SetItemChecked(i, !GetItemChecked(i)); break; } else if (GetItemRectangle(i).Contains(point)) { SelectedIndex = i; break; } } return; } case WM_LBUTTONDBLCLK: { Point point = PointToClient(Cursor.Position); for (int i = 0; i < Items.Count; i++) { Rectangle checkboxRect = GetItemRectangle(i); checkboxRect.Width = checkboxRect.Height; if (checkboxRect.Contains(point)) { break; } else if (GetItemRectangle(i).Contains(point)) { SelectedIndex = i; break; } } return; } } base.WndProc(ref m); } } }
36.820225
77
0.50473
[ "MIT" ]
SupaFresh/PMD-Toolkit
PMDToolkit/Editors/MapLayerListBox.cs
3,279
C#
using System; namespace Keyfactor.HydrantId.Exceptions { public class RetryCountExceededException : Exception { public RetryCountExceededException(string message) : base(message) { } } }
20.363636
74
0.678571
[ "Apache-2.0" ]
Keyfactor/hydrantid-cagateway
HydrantIdProxy/src/HydrantIdProxy/Exceptions/RetryCountExceededException.cs
226
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Security.Cryptography.Certificates { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public partial class CertificateStore { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string Name { get { throw new global::System.NotImplementedException("The member string CertificateStore.Name is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Add( global::Windows.Security.Cryptography.Certificates.Certificate certificate) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Cryptography.Certificates.CertificateStore", "void CertificateStore.Add(Certificate certificate)"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Delete( global::Windows.Security.Cryptography.Certificates.Certificate certificate) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Cryptography.Certificates.CertificateStore", "void CertificateStore.Delete(Certificate certificate)"); } #endif // Forced skipping of method Windows.Security.Cryptography.Certificates.CertificateStore.Name.get } }
38.810811
197
0.770195
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Cryptography.Certificates/CertificateStore.cs
1,436
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("E_commerce")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("E_commerce")] [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("950f65be-b41f-4e58-a3ba-a06c222a822f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.444444
84
0.750742
[ "MIT" ]
ericaglimsholt/shop
E-commerce/Properties/AssemblyInfo.cs
1,351
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using OpenReservation.API.Test.MockServices; using OpenReservation.Common; using OpenReservation.Database; using OpenReservation.Events; using OpenReservation.Services; using WeihanLi.Common; using WeihanLi.Common.Event; using WeihanLi.Redis; using WeihanLi.Web.Authentication; using WeihanLi.Web.Authentication.HeaderAuthentication; namespace OpenReservation.API.Test { public class TestStartup { public TestStartup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddResponseCaching(); services.AddControllers(options => { options.CacheProfiles.Add("default", new CacheProfile() { Duration = 300, VaryByQueryKeys = new[] { "*" } }); options.CacheProfiles.Add("private", new CacheProfile() { Duration = 300, Location = ResponseCacheLocation.Client, VaryByQueryKeys = new[] { "*" } }); options.CacheProfiles.Add("noCache", new CacheProfile() { NoStore = true }); }) .AddApplicationPart(typeof(ApiControllerBase).Assembly) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // 设置时区为 UTC options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }) .SetCompatibilityVersion(CompatibilityVersion.Latest); // addDbContext services.AddDbContextPool<ReservationDbContext>(options => options.UseInMemoryDatabase("Reservation")); services.AddGoogleRecaptchaHelper(Configuration.GetSection("GoogleRecaptcha")); services.AddTencentCaptchaHelper(options => { options.AppId = Configuration["Tencent:Captcha:AppId"]; options.AppSecret = Configuration["Tencent:Captcha:AppSecret"]; }); // registerApplicationSettingService services.TryAddSingleton<IApplicationSettingService, ApplicationSettingInMemoryService>(); // register access control service services.AddAccessControlHelper<AdminPermissionRequireStrategy, AdminOnlyControlAccessStrategy>(); services.AddEvents() .AddEventHandler<NoticeViewEvent, NoticeViewEventHandler>() .AddEventHandler<OperationLogEvent, OperationLogEventHandler>() ; services.TryAddSingleton<ICacheClient, MockRedisCacheClient>(); // RegisterAssemblyModules services.RegisterAssemblyModules(); services .AddAuthentication(HeaderAuthenticationDefaults.AuthenticationSchema) .AddHeader() //.AddAuthentication(QueryAuthenticationDefaults.AuthenticationSchema) //.AddQuery() ; services.AddAuthorization(options => { options.AddPolicy("ReservationApi", builder => builder.RequireAuthenticatedUser()); }); // SetDependencyResolver DependencyResolver.SetDependencyResolver(services); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseResponseCaching(); app.UseRouting(); app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); TestDataInitializer.Initialize(app.ApplicationServices); } } }
38.959677
115
0.619333
[ "MIT" ]
bigvvc/ReservationServer
OpenReservation.API.Test/TestStartup.cs
4,843
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.OsConfig.V1.Snippets { // [START osconfig_v1_generated_OsConfigZonalService_CreateOSPolicyAssignment_sync_flattened_resourceNames] using Google.Api.Gax.ResourceNames; using Google.Cloud.OsConfig.V1; using Google.LongRunning; public sealed partial class GeneratedOsConfigZonalServiceClientSnippets { /// <summary>Snippet for CreateOSPolicyAssignment</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateOSPolicyAssignmentResourceNames() { // Create client OsConfigZonalServiceClient osConfigZonalServiceClient = OsConfigZonalServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); OSPolicyAssignment osPolicyAssignment = new OSPolicyAssignment(); string osPolicyAssignmentId = ""; // Make the request Operation<OSPolicyAssignment, OSPolicyAssignmentOperationMetadata> response = osConfigZonalServiceClient.CreateOSPolicyAssignment(parent, osPolicyAssignment, osPolicyAssignmentId); // Poll until the returned long-running operation is complete Operation<OSPolicyAssignment, OSPolicyAssignmentOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result OSPolicyAssignment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<OSPolicyAssignment, OSPolicyAssignmentOperationMetadata> retrievedResponse = osConfigZonalServiceClient.PollOnceCreateOSPolicyAssignment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result OSPolicyAssignment retrievedResult = retrievedResponse.Result; } } } // [END osconfig_v1_generated_OsConfigZonalService_CreateOSPolicyAssignment_sync_flattened_resourceNames] }
49.868852
192
0.719264
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.OsConfig.V1/Google.Cloud.OsConfig.V1.GeneratedSnippets/OsConfigZonalServiceClient.CreateOSPolicyAssignmentResourceNamesSnippet.g.cs
3,042
C#
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace SharpYAJ { public static class YAJWriter { public static string WriteJSON(object element, bool indent) { var indentWriter = indent ? new IndentWriter() : null; return WriteJSON(element, indentWriter); } public static string WriteJSON(object element, string indentWriter, string newLine = null) { return WriteJSON(element, new IndentWriter(indentString: indentWriter, newLineStr: newLine)); } public static string WriteJSON(object element, IndentWriter indentWriter = null) { var stringBuilder = WriteJSONToStringBuilder(element, indentWriter: indentWriter); return stringBuilder.ToString(); } public static StringBuilder WriteJSONToStringBuilder(object element, StringBuilder stringBuilder = null, IndentWriter indentWriter = null) { if(indentWriter == null) indentWriter = new NoIndentWriter(); stringBuilder = stringBuilder ?? new StringBuilder(); WriteElement(element, stringBuilder, indentWriter); return stringBuilder; } public static void WriteElement(object input, StringBuilder sb, IndentWriter indentWriter) { if(input is string) WriteString((string)input, sb); else if(input is char) WriteString(input.ToString(), sb); else if(input is long) WriteLong((long)input, sb); else if(input is int) WriteInt((int)input, sb); else if(input is short) WriteShort((short)input, sb); else if(input is double) WriteDouble((double)input, sb); else if(input is float) WriteFloat((float)input, sb); else if(input is bool) WriteBool((bool)input, sb); else if(input is null) WriteNull(sb); else if(IsObject(input)) WriteObject((IDictionary<string, object>)input, sb, indentWriter); else if(IsArray(input)) WriteArray((IEnumerable)input, sb, indentWriter); else WriteString(input.ToString(), sb); } public static void WriteObject(IDictionary<string, object> input, StringBuilder sb, IndentWriter indentWriter) { sb.Append("{"); var childIndentWriter = indentWriter + 1; bool firstElement = true; foreach(var child in input) { if(!firstElement) sb.Append(","); indentWriter.WriteLineBreak(sb); childIndentWriter.Write(sb); WriteString(child.Key, sb); sb.Append(":"); if(IsObject(child.Value) || IsArray(child.Value)) { childIndentWriter.WriteLineBreak(sb); childIndentWriter.Write(sb); } else { childIndentWriter.WriteSeparator(sb); } WriteElement(child.Value, sb, childIndentWriter); firstElement = false; } indentWriter.WriteLineBreak(sb); indentWriter.Write(sb); sb.Append("}"); } public static void WriteArray(IEnumerable input, StringBuilder sb, IndentWriter indentWriter) { sb.Append("["); var childIndentWriter = indentWriter + 1; bool firstElement = true; foreach(var child in input) { if(!firstElement) sb.Append(","); indentWriter.WriteLineBreak(sb); childIndentWriter.Write(sb); WriteElement(child, sb, childIndentWriter); firstElement = false; } indentWriter.WriteLineBreak(sb); indentWriter.Write(sb); sb.Append("]"); } public static void WriteString(string input, StringBuilder sb) { var escaped = input .Replace("\b", @"\b") .Replace("\f", @"\f") .Replace("\n", @"\n") .Replace("\r", @"\r") .Replace("\t", @"\t") .Replace("\"", "\\\"") .Replace("\\", @"\\"); sb.Append("\""); sb.Append(escaped); sb.Append("\""); } public static void WriteShort(short input, StringBuilder sb) { sb.Append(input); } public static void WriteInt(int input, StringBuilder sb) { sb.Append(input); } public static void WriteLong(long input, StringBuilder sb) { sb.Append(input); } public static void WriteFloat(float input, StringBuilder sb) { sb.Append(input); } public static void WriteDouble(double input, StringBuilder sb) { sb.Append(input); } public static void WriteBool(bool input, StringBuilder sb) { sb.Append(input ? "true" : "false"); } public static void WriteNull(StringBuilder sb) { sb.Append("null"); } public static bool IsObject(object input) { return input is IDictionary<string, object> && !IsPrimitive(input); } public static bool IsArray(object input) { return input is IEnumerable && !IsPrimitive(input); } public static bool IsPrimitive(object input) { switch(input) { case int intVal: case string stringVal: case char charVal: case bool boolVal: case float floatVal: case long longVal: case short shortVal: case double doubleVal: case uint uintVal: case ushort ushortVal: case ulong ulongVal: case byte byteVal: case sbyte sbyteVal: return true; default: return false; } } } }
25.153061
140
0.675862
[ "MIT" ]
JaegerMa/SharpYAJ
SharpYAJ/YAJWriter.cs
4,932
C#
// Copyright (c) 2013 Richard Long & HexBeerium // // Released under the MIT license ( http://opensource.org/licenses/MIT ) // using System; using System.Collections.Generic; using System.Text; using dotnet.lib.CoreAnnex.exception; namespace dotnet.lib.CoreAnnex.json { public class JsonArray { List<Object> _values; public JsonArray() { _values = new List<Object>(); } public JsonArray(int capacity) { _values = new List<Object>(capacity); } public int GetInteger(int index) { Object blob = _values[index]; if (null == blob) { String technicalError = String.Format("null == blob; index = {0}", index); throw new BaseException(this, technicalError); } if (!(blob is int)) { String technicalError = String.Format("!(blob is int); index = {0}; blob.GetType().Name = {1}", index, blob.GetType().Name); throw new BaseException(this, technicalError ); } return (int)blob; } public JsonArray GetJsonArray( int index ) { Object blob = _values[index]; if (null == blob) { return null; } if( !(blob is JsonArray) ) { String technicalError = String.Format("!(blob is JSONArray); index = {0}; blob.GetType().Name = {1}", index, blob.GetType().Name); throw new BaseException(this, technicalError); } return (JsonArray)blob; } public JsonObject GetJsonObject( int index ) { Object blob = _values[index]; if (null == blob) { return null; } if (!(blob is JsonObject)) { String technicalError = String.Format("!(blob is JSONObject); index = {0}; blob.GetType().Name = {1}", index, blob.GetType().Name); throw new BaseException(this, technicalError); } return (JsonObject)blob; } public Object GetObject(int index) { Object blob = _values[index]; if (null == blob) { String technicalError = String.Format("null == blob; index = {0}", index); throw new BaseException(this, technicalError); } return blob; } public Object GetObject(int index, Object defaultValue ) { Object blob = _values[index]; if (null == blob) { return defaultValue; } return blob; } public String GetString(int index) { Object blob = _values[index]; if (null == blob) { return null; } if (!(blob is String)) { String technicalError = String.Format("!(blob is String); index = {0}; blob.GetType().Name = {1}", index, blob.GetType().Name); throw new BaseException(this, technicalError); } return (String)blob; } public String GetString(int index, String defaultValue) { Object blob = _values[index]; if (null == blob) { return defaultValue; } if (!(blob is String)) { String technicalError = String.Format("!(blob is String); index = {0}; blob.GetType().Name = {1}", index, blob.GetType().Name); throw new BaseException(this, technicalError); } return (String)blob; } public void Add(Object obj) { _values.Add(obj); } public int Count() { return _values.Count; } public int Length() { return _values.Count; } } }
23.278689
148
0.460329
[ "MIT" ]
rlong/dotnet.lib.CoreAnnex
json/JsonArray.cs
4,262
C#
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text.Json; namespace Scraper { ///DOLATER <summary>add description for class: Json</summary> public static partial class Json { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Filepath"></param> /// <returns></returns> public static T Load<T>([DisallowNull] String Filepath) { if (!File.Exists(Filepath)) { return default; } T Out = default; try { String Data = File.ReadAllText(Filepath); Out = JsonSerializer.Deserialize<T>(Data, Json.ReadOptions); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return Out; } /// <summary> /// /// </summary> /// <param name="Filepath"></param> /// <returns></returns> [return: NotNull] public static T LoadEnsure<T>([DisallowNull] String Filepath) where T : class, new() { T Out = Load<T>(Filepath) ?? new T(); return Out; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Filepath"></param> public static void Save<T>(T Data, [DisallowNull] String Filepath) { FileStream Writer = null; try { var JW = new JsonWriterOptions() { Indented = true }; Writer = new FileStream(Filepath, FileMode.Create, FileAccess.ReadWrite); var JWriter = new Utf8JsonWriter(Writer, JW); JsonSerializer.Serialize<T>(JWriter, Data, Json.WriteOptions); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Writer?.Close(); } } /// <summary> /// /// </summary> /// <param name="Filepath"></param> /// <returns></returns> public static JsonDocument GetDoc(String Filepath) { if (!File.Exists(Filepath)) return null; JsonDocument Doc = null; Stream Reader = null; var Options = new JsonDocumentOptions() { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }; try { Reader = new FileStream(Filepath, FileMode.Open, FileAccess.Read); Doc = JsonDocument.Parse(Reader, Options); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (Reader != null) { Reader.Close(); } } return Doc; } } }
28.980198
89
0.485138
[ "BSD-3-Clause" ]
Blockception/BC-Minecraft-Bedrock-Vanilla-Data
scraper/Scraper/Static Classes/Json/Json.cs
2,929
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of ImplementTwoInterfaceGen<int> using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(ValueType o) { return Helper.Compare((ImplementTwoInterfaceGen<int>)o, Helper.Create(default(ImplementTwoInterfaceGen<int>))); } private static bool BoxUnboxToQ(ValueType o) { return Helper.Compare((ImplementTwoInterfaceGen<int>?)o, Helper.Create(default(ImplementTwoInterfaceGen<int>))); } private static int Main() { ImplementTwoInterfaceGen<int>? s = Helper.Create(default(ImplementTwoInterfaceGen<int>)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
28.904762
120
0.69687
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/jit64/valuetypes/nullable/box-unbox/value/box-unbox-value041.cs
1,214
C#
#pragma checksum "D:\aula Woman Can Code\ProjetoFlavia\BibliotecaMVC\BibliotecaMVC\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\aula Woman Can Code\ProjetoFlavia\BibliotecaMVC\BibliotecaMVC\Views\_ViewImports.cshtml" using BibliotecaMVC; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\aula Woman Can Code\ProjetoFlavia\BibliotecaMVC\BibliotecaMVC\Views\_ViewImports.cshtml" using BibliotecaMVC.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Views/_ViewStart.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"754068e205fb75f1f1a1e44ec2818872f5e92324", @"/Views/_ViewImports.cshtml")] public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "D:\aula Woman Can Code\ProjetoFlavia\BibliotecaMVC\BibliotecaMVC\Views\_ViewStart.cshtml" Layout = "_Layout"; #line default #line hidden #nullable disable } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
47.661017
191
0.771337
[ "MIT" ]
DevPamela/Biblioteca
obj/Debug/net5.0/Razor/Views/_ViewStart.cshtml.g.cs
2,812
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StoreManager.Domain.Entities.Catalog { public class ExpenseCategory { public int Id { get; set; } public string Name { get; set; } public string Code { get; set; } public List<ExpenseClaimLineItem> ExpensClaimLineItems { get; set; } = new List<ExpenseClaimLineItem>(); } }
22.4
112
0.685268
[ "MIT" ]
rayjung95/ExpenseReport
StoreManager.Domain/Entities/Catalog/ExpenseCategory.cs
450
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 cloudhsmv2-2017-04-28.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.CloudHSMV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudHSMV2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UntagResource operation /// </summary> public class UntagResourceResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UntagResourceResponse response = new UntagResourceResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmAccessDeniedException")) { return CloudHsmAccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmInternalFailureException")) { return CloudHsmInternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmInvalidRequestException")) { return CloudHsmInvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmResourceNotFoundException")) { return CloudHsmResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmServiceException")) { return CloudHsmServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("CloudHsmTagException")) { return CloudHsmTagExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonCloudHSMV2Exception(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static UntagResourceResponseUnmarshaller _instance = new UntagResourceResponseUnmarshaller(); internal static UntagResourceResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UntagResourceResponseUnmarshaller Instance { get { return _instance; } } } }
41.218487
193
0.656677
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CloudHSMV2/Generated/Model/Internal/MarshallTransformations/UntagResourceResponseUnmarshaller.cs
4,905
C#
// The MIT License (MIT) // // gitea.net (https://github.com/mkloubert/gitea.net) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // 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 using Gitea.API.v1.Users; using Newtonsoft.Json; using System; using System.Runtime.Serialization; namespace Gitea.API.v1.Repositories { /// <summary> /// A repository. /// </summary> [DataContract] public class Repository : JsonEntityBase { protected RepositoryPermissions _permissions; /// <summary> /// clone_url /// </summary> [DataMember] [JsonProperty("clone_url")] public string CloneUrl { get; set; } /// <summary> /// created_at /// </summary> [DataMember] [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } /// <summary> /// default_branch /// </summary> [DataMember] [JsonProperty("default_branch")] public string DefaultBranch { get; set; } /// <summary> /// description /// </summary> [DataMember] [JsonProperty("description")] public string Description { get; set; } /// <summary> /// forks_count /// </summary> [DataMember] [JsonProperty("forks_count")] public long Forks { get; set; } /// <summary> /// full_name /// </summary> [DataMember] [JsonProperty("full_name")] public string FullName { get; set; } /// <summary> /// html_url /// </summary> [DataMember] [JsonProperty("html_url")] public string HtmlUrl { get; set; } /// <summary> /// id /// </summary> [DataMember] [JsonProperty("id")] public long ID { get; set; } /// <summary> /// empty /// </summary> [DataMember] [JsonProperty("empty")] public bool IsEmpty { get; set; } /// <summary> /// fork /// </summary> [DataMember] [JsonProperty("fork")] public bool IsFork { get; set; } /// <summary> /// mirror /// </summary> [DataMember] [JsonProperty("mirror")] public bool IsMirror { get; set; } /// <summary> /// private /// </summary> [DataMember] [JsonProperty("private")] public bool IsPrivate { get; set; } /// <summary> /// open_issues_count /// </summary> [DataMember] [JsonProperty("open_issues_count")] public long OpenIssuesCount { get; set; } /// <summary> /// name /// </summary> [DataMember] [JsonProperty("name")] public string Name { get; set; } /// <summary> /// owner /// </summary> [DataMember] [JsonProperty("owner")] public User Owner { get; set; } /// <summary> /// parent /// </summary> // [DataMember] // [JsonProperty("parent")] // public Repository Parent { get; set; } /// <summary> /// permissions /// </summary> /// <exception cref="ArgumentException">Cannot set permissions.</exception> [DataMember] [JsonProperty("permissions")] public RepositoryPermissions Permissions { get { return _permissions; } set { if (value != null) { if (!Equals(value, _permissions)) { if (value.Repository == null) { value.Repository = this; } else { throw new ArgumentException(nameof(Permissions)); } } } _permissions = value; } } /// <summary> /// size /// </summary> [DataMember] [JsonProperty("size")] public long Size { get; set; } /// <summary> /// stars_count /// </summary> [DataMember] [JsonProperty("stars_count")] public long StarsCount { get; set; } /// <summary> /// ssh_url /// </summary> [DataMember] [JsonProperty("ssh_url")] public string SSHUrl { get; set; } /// <summary> /// updated_at /// </summary> [DataMember] [JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; } /// <summary> /// watchers_count /// </summary> [DataMember] [JsonProperty("watchers_count")] public long WatchersCount { get; set; } /// <summary> /// website /// </summary> [DataMember] [JsonProperty("website")] public string Website { get; set; } } }
28.475336
84
0.5
[ "MIT" ]
maikebing/gitea.net
Gitea.API/v1/Repositories/Repository.cs
6,352
C#
using System; namespace NewLife.Security { /// <summary>RC4对称加密算法</summary> /// <remarks> /// RC4于1987年提出,和DES算法一样,是一种对称加密算法,也就是说使用的密钥为单钥(或称为私钥)。 /// 但不同于DES的是,RC4不是对明文进行分组处理,而是字节流的方式依次加密明文中的每一个字节,解密的时候也是依次对密文中的每一个字节进行解密。 /// /// RC4算法的特点是算法简单,运行速度快,而且密钥长度是可变的,可变范围为1-256字节(8-2048比特), /// 在如今技术支持的前提下,当密钥长度为128比特时,用暴力法搜索密钥已经不太可行,所以可以预见RC4的密钥范围任然可以在今后相当长的时间里抵御暴力搜索密钥的攻击。 /// 实际上,如今也没有找到对于128bit密钥长度的RC4加密算法的有效攻击方法。 /// </remarks> class RC4 { /// <summary>加密</summary> /// <param name="data">数据</param> /// <param name="pass">密码</param> /// <returns></returns> public static Byte[] Encrypt(Byte[] data, Byte[] pass) { if (data == null || data.Length == 0) return new Byte[0]; if (pass == null || pass.Length == 0) return data; var output = new Byte[data.Length]; var i = 0; var j = 0; var box = GetKey(pass, 256); // 加密 for (var k = 0; k < data.Length; k++) { i = (i + 1) % box.Length; j = (j + box[i]) % box.Length; var temp = box[i]; box[i] = box[j]; box[j] = temp; var a = data[k]; var b = box[(box[i] + box[j]) % box.Length]; output[k] = (Byte)(a ^ b); } return output; } /// <summary>打乱密码</summary> /// <param name="pass">密码</param> /// <param name="len">密码箱长度</param> /// <returns>打乱后的密码</returns> private static Byte[] GetKey(Byte[] pass, Int32 len) { var box = new Byte[len]; for (var i = 0; i < len; i++) { box[i] = (Byte)i; } var j = 0; for (var i = 0; i < len; i++) { j = (j + box[i] + pass[i % pass.Length]) % len; var temp = box[i]; box[i] = box[j]; box[j] = temp; } return box; } } }
32.61194
89
0.434783
[ "MIT" ]
19900623/X
NewLife.Core/Security/RC4.cs
2,745
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVC.Models { public class ReviewsPerAnnouncement { public int CurrentAnnouncementId { get; set; } public decimal AverageRating { get; set; } public IEnumerable<Review> Reviews { get; set; } } }
23.285714
56
0.687117
[ "MIT" ]
PracticaNetRom/iulia.simion
SummerCamp2017/MVC/Models/ReviewsPerAnnouncement.cs
328
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { using Telerik.Web.UI; public class DnnMenu : RadMenu {} }
29.181818
72
0.725857
[ "MIT" ]
EPTamminga/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs
323
C#
using System; using System.Collections.Generic; using System.Text; namespace TeachMeSkills.DotNet.FitnessTrackerCore.Models { public class Statistic { public double AveragePpg { get; set; } public double AverageSpeed { get; set; } public double AverageCount { get; set; } } }
22.428571
56
0.684713
[ "MIT" ]
AndrewBynkov/TeachMeSkills-DotNet-Lessons
src/Homeworks/FitnessTracker/TeachMeSkills.DotNet.FitnessTrackerCore/Models/Statistic.cs
316
C#
using Newtonsoft.Json; namespace Stl.Time.Internal; public class MomentNewtonsoftJsonConverter : JsonConverter<Moment> { public override void WriteJson(JsonWriter writer, Moment value, JsonSerializer serializer) => writer.WriteValue(value.ToString()); public override Moment ReadJson( JsonReader reader, Type objectType, Moment existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.Value is DateTime d) return d; return Moment.Parse((string?) reader.Value!); } }
28.3
94
0.69788
[ "MIT" ]
ScriptBox21/Stl.Fusion
src/Stl/Time/Internal/MomentNewtonsoftJsonConverter.cs
566
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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.Win32; using Microsoft.Build.Shared; namespace Microsoft.Build.CommandLine { /// <summary> /// This class encapsulates the switches gathered from the application command line. It helps with switch detection, parameter /// accumulation, and error generation. /// </summary> internal sealed class CommandLineSwitches { /// <summary> /// Enumeration of all recognized switches that do not take any parameters. /// </summary> /// <remarks> /// WARNING: the values of this enumeration are also used to index/size arrays, and thus the following rules apply: /// 1) the first valid switch must have a value/index of 0 /// 2) the value of the last member of the enumeration must indicate the number of valid switches /// 3) the values of the first and last members of the enumeration are invalid array indices /// </remarks> internal enum ParameterlessSwitch { Invalid = -1, Help = 0, Version, NoLogo, NoAutoResponse, NoConsoleLogger, FileLogger, FileLogger1, FileLogger2, FileLogger3, FileLogger4, FileLogger5, FileLogger6, FileLogger7, FileLogger8, FileLogger9, #if (!STANDALONEBUILD) OldOM, #endif DistributedFileLogger, #if FEATURE_MSBUILD_DEBUGGER Debugger, #endif DetailedSummary, #if DEBUG WaitForDebugger, #endif NumberOfParameterlessSwitches } /// <summary> /// Enumeration of all recognized switches that take/require parameters. /// </summary> /// <remarks> /// WARNING: the values of this enumeration are also used to index/size arrays, and thus the following rules apply: /// 1) the first valid switch must have a value/index of 0 /// 2) the value of the last member of the enumeration must indicate the number of valid switches /// 3) the values of the first and last members of the enumeration are invalid array indices /// </remarks> internal enum ParameterizedSwitch { Invalid = -1, Project = 0, Target, Property, Logger, DistributedLogger, Verbosity, #if FEATURE_XML_SCHEMA_VALIDATION Validate, #endif ConsoleLoggerParameters, NodeMode, MaxCPUCount, IgnoreProjectExtensions, ToolsVersion, FileLoggerParameters, FileLoggerParameters1, FileLoggerParameters2, FileLoggerParameters3, FileLoggerParameters4, FileLoggerParameters5, FileLoggerParameters6, FileLoggerParameters7, FileLoggerParameters8, FileLoggerParameters9, #if FEATURE_NODE_REUSE NodeReuse, #endif Preprocess, #if !FEATURE_NAMED_PIPES_FULL_DUPLEX ClientToServerPipeHandle, ServerToClientPipeHandle, #endif WarningsAsErrors, WarningsAsMessages, BinaryLogger, NumberOfParameterizedSwitches } /// <summary> /// This struct packages the information required to identify a switch that doesn't take any parameters. It is used when /// parsing the command line. /// </summary> private struct ParameterlessSwitchInfo { /// <summary> /// Initializes struct data. /// </summary> /// <param name="switchNames"></param> /// <param name="parameterlessSwitch"></param> /// <param name="duplicateSwitchErrorMessage"></param> internal ParameterlessSwitchInfo ( string[] switchNames, ParameterlessSwitch parameterlessSwitch, string duplicateSwitchErrorMessage, string lightUpRegistryKey ) { this.switchNames = switchNames; this.duplicateSwitchErrorMessage = duplicateSwitchErrorMessage; this.parameterlessSwitch = parameterlessSwitch; this.lightUpKey = lightUpRegistryKey; this.lightUpKeyRead = false; this.lightUpKeyResult = false; } // names of the switch (without leading switch indicator) internal string[] switchNames; // if null, indicates that switch is allowed to appear multiple times on the command line; otherwise, holds the error // message to display if switch appears more than once internal string duplicateSwitchErrorMessage; // the switch id internal ParameterlessSwitch parameterlessSwitch; // The registry key that lights up this switch. internal string lightUpKey; // Holds the result of reading the lightUpKey. internal bool lightUpKeyRead; // Holds the result of reading the lightUpKey. internal bool lightUpKeyResult; } /// <summary> /// This struct packages the information required to identify a switch that takes parameters. It is used when parsing the /// command line. /// </summary> private struct ParameterizedSwitchInfo { /// <summary> /// Initializes struct data. /// </summary> /// <param name="switchNames"></param> /// <param name="parameterizedSwitch"></param> /// <param name="duplicateSwitchErrorMessage"></param> /// <param name="multipleParametersAllowed"></param> /// <param name="missingParametersErrorMessage"></param> /// <param name="unquoteParameters"></param> internal ParameterizedSwitchInfo ( string[] switchNames, ParameterizedSwitch parameterizedSwitch, string duplicateSwitchErrorMessage, bool multipleParametersAllowed, string missingParametersErrorMessage, bool unquoteParameters, bool emptyParametersAllowed ) { this.switchNames = switchNames; this.duplicateSwitchErrorMessage = duplicateSwitchErrorMessage; this.multipleParametersAllowed = multipleParametersAllowed; this.missingParametersErrorMessage = missingParametersErrorMessage; this.unquoteParameters = unquoteParameters; this.parameterizedSwitch = parameterizedSwitch; this.emptyParametersAllowed = emptyParametersAllowed; } // names of the switch (without leading switch indicator) internal string[] switchNames; // if null, indicates that switch is allowed to appear multiple times on the command line; otherwise, holds the error // message to display if switch appears more than once internal string duplicateSwitchErrorMessage; // indicates if switch can take multiple parameters (equivalent to switch appearing multiple times on command line) // NOTE: for most switches, if a switch is allowed to appear multiple times on the command line, then multiple // parameters can be provided per switch; however, some switches cannot take multiple parameters internal bool multipleParametersAllowed; // if null, indicates that switch is allowed to have no parameters; otherwise, holds the error message to show if // switch is found without parameters on the command line internal string missingParametersErrorMessage; // indicates if quotes should be removed from the switch parameters internal bool unquoteParameters; // the switch id internal ParameterizedSwitch parameterizedSwitch; // indicates if empty parameters are allowed and if so an empty string will be added to the list of parameter values internal bool emptyParametersAllowed; } // map switches that do not take parameters to their identifiers (taken from ParameterlessSwitch enum) // WARNING: keep this map in the same order as the ParameterlessSwitch enumeration private static readonly ParameterlessSwitchInfo[] s_parameterlessSwitchesMap = { //--------------------------------------------------------------------------------------------------------------------------------------------------- // Switch Names Switch Id Dup Error Light up key //--------------------------------------------------------------------------------------------------------------------------------------------------- new ParameterlessSwitchInfo( new string[] { "help", "h", "?" }, ParameterlessSwitch.Help, null, null ), new ParameterlessSwitchInfo( new string[] { "version", "ver" }, ParameterlessSwitch.Version, null, null ), new ParameterlessSwitchInfo( new string[] { "nologo" }, ParameterlessSwitch.NoLogo, null, null ), new ParameterlessSwitchInfo( new string[] { "noautoresponse", "noautorsp" }, ParameterlessSwitch.NoAutoResponse, null, null ), new ParameterlessSwitchInfo( new string[] { "noconsolelogger", "noconlog" }, ParameterlessSwitch.NoConsoleLogger, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger", "fl" }, ParameterlessSwitch.FileLogger, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger1", "fl1" }, ParameterlessSwitch.FileLogger1, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger2", "fl2" }, ParameterlessSwitch.FileLogger2, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger3", "fl3" }, ParameterlessSwitch.FileLogger3, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger4", "fl4" }, ParameterlessSwitch.FileLogger4, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger5", "fl5" }, ParameterlessSwitch.FileLogger5, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger6", "fl6" }, ParameterlessSwitch.FileLogger6, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger7", "fl7" }, ParameterlessSwitch.FileLogger7, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger8", "fl8" }, ParameterlessSwitch.FileLogger8, null, null ), new ParameterlessSwitchInfo( new string[] { "filelogger9", "fl9" }, ParameterlessSwitch.FileLogger9, null, null ), #if (!STANDALONEBUILD) new ParameterlessSwitchInfo( new string[] { "oldom" }, ParameterlessSwitch.OldOM, null, null ), #endif new ParameterlessSwitchInfo( new string[] { "distributedfilelogger", "dfl" }, ParameterlessSwitch.DistributedFileLogger, null, null ), #if FEATURE_MSBUILD_DEBUGGER new ParameterlessSwitchInfo( new string[] { "debug", "d" }, ParameterlessSwitch.Debugger, null, "DebuggerEnabled" ), #endif new ParameterlessSwitchInfo( new string[] { "detailedsummary", "ds" }, ParameterlessSwitch.DetailedSummary, null , null ), #if DEBUG new ParameterlessSwitchInfo( new string[] { "waitfordebugger", "wfd" }, ParameterlessSwitch.WaitForDebugger, null , null ), #endif }; // map switches that take parameters to their identifiers (taken from ParameterizedSwitch enum) // WARNING: keep this map in the same order as the ParameterizedSwitch enumeration private static readonly ParameterizedSwitchInfo[] s_parameterizedSwitchesMap = { //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ // Switch Names Switch Id Duplicate Switch Error Multi Params? Missing Parameters Error Unquote? Empty? //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ new ParameterizedSwitchInfo( new string[] { null }, ParameterizedSwitch.Project, "DuplicateProjectSwitchError", false, null, true, false ), new ParameterizedSwitchInfo( new string[] { "target", "t"}, ParameterizedSwitch.Target, null, true, "MissingTargetError", true, false ), new ParameterizedSwitchInfo( new string[] { "property", "p" }, ParameterizedSwitch.Property, null, true, "MissingPropertyError", true, false ), new ParameterizedSwitchInfo( new string[] { "logger", "l" }, ParameterizedSwitch.Logger, null, false, "MissingLoggerError", false, false ), new ParameterizedSwitchInfo( new string[] { "distributedlogger", "dl" }, ParameterizedSwitch.DistributedLogger, null, false, "MissingLoggerError", false, false ), new ParameterizedSwitchInfo( new string[] { "verbosity", "v" }, ParameterizedSwitch.Verbosity, null, false, "MissingVerbosityError", true, false ), #if FEATURE_XML_SCHEMA_VALIDATION new ParameterizedSwitchInfo( new string[] { "validate", "val" }, ParameterizedSwitch.Validate, null, false, null, true, false ), #endif new ParameterizedSwitchInfo( new string[] { "consoleloggerparameters", "clp" }, ParameterizedSwitch.ConsoleLoggerParameters, null, false, "MissingConsoleLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "nodemode", "nmode" }, ParameterizedSwitch.NodeMode, null, false, null, false, false ), new ParameterizedSwitchInfo( new string[] { "maxcpucount", "m" }, ParameterizedSwitch.MaxCPUCount, null, false, "MissingMaxCPUCountError", true, false ), new ParameterizedSwitchInfo( new string[] { "ignoreprojectextensions", "ignore" }, ParameterizedSwitch.IgnoreProjectExtensions, null, true, "MissingIgnoreProjectExtensionsError", true, false ), new ParameterizedSwitchInfo( new string[] { "toolsversion","tv" }, ParameterizedSwitch.ToolsVersion, null, false, "MissingToolsVersionError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters", "flp" }, ParameterizedSwitch.FileLoggerParameters, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters1", "flp1" }, ParameterizedSwitch.FileLoggerParameters1, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters2", "flp2" }, ParameterizedSwitch.FileLoggerParameters2, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters3", "flp3" }, ParameterizedSwitch.FileLoggerParameters3, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters4", "flp4" }, ParameterizedSwitch.FileLoggerParameters4, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters5", "flp5" }, ParameterizedSwitch.FileLoggerParameters5, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters6", "flp6" }, ParameterizedSwitch.FileLoggerParameters6, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters7", "flp7" }, ParameterizedSwitch.FileLoggerParameters7, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters8", "flp8" }, ParameterizedSwitch.FileLoggerParameters8, null, false, "MissingFileLoggerParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "fileloggerparameters9", "flp9" }, ParameterizedSwitch.FileLoggerParameters9, null, false, "MissingFileLoggerParameterError", true, false ), #if FEATURE_NODE_REUSE new ParameterizedSwitchInfo( new string[] { "nodereuse", "nr" }, ParameterizedSwitch.NodeReuse, null, false, "MissingNodeReuseParameterError", true, false ), #endif new ParameterizedSwitchInfo( new string[] { "preprocess", "pp" }, ParameterizedSwitch.Preprocess, null, false, null, true, false ), #if !FEATURE_NAMED_PIPES_FULL_DUPLEX new ParameterizedSwitchInfo( new string[] { "clientToServerPipeHandle", "c2s" }, ParameterizedSwitch.ClientToServerPipeHandle, null, false, null, true, false ), new ParameterizedSwitchInfo( new string[] { "serverToClientPipeHandle", "s2c" }, ParameterizedSwitch.ServerToClientPipeHandle, null, false, null, true, false ), #endif new ParameterizedSwitchInfo( new string[] { "warnaserror", "err" }, ParameterizedSwitch.WarningsAsErrors, null, true, null, true, true ), new ParameterizedSwitchInfo( new string[] { "warnasmessage", "nowarn" }, ParameterizedSwitch.WarningsAsMessages, null, true, "MissingWarnAsMessageParameterError", true, false ), new ParameterizedSwitchInfo( new string[] { "binarylogger", "bl" }, ParameterizedSwitch.BinaryLogger, null, false, null, true, false ), }; /// <summary> /// Identifies/detects a switch that takes no parameters. /// </summary> /// <param name="switchName"></param> /// <param name="parameterlessSwitch">[out] switch identifier (from ParameterlessSwitch enumeration)</param> /// <param name="duplicateSwitchErrorMessage"></param> /// <returns>true, if switch is a recognized switch that doesn't take parameters</returns> internal static bool IsParameterlessSwitch ( string switchName, out ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage ) { parameterlessSwitch = ParameterlessSwitch.Invalid; duplicateSwitchErrorMessage = null; foreach (ParameterlessSwitchInfo switchInfo in s_parameterlessSwitchesMap) { if (IsParameterlessSwitchEnabled(switchInfo)) { foreach (string parameterlessSwitchName in switchInfo.switchNames) { if (String.Compare(switchName, parameterlessSwitchName, StringComparison.OrdinalIgnoreCase) == 0) { parameterlessSwitch = switchInfo.parameterlessSwitch; duplicateSwitchErrorMessage = switchInfo.duplicateSwitchErrorMessage; break; } } } } return (parameterlessSwitch != ParameterlessSwitch.Invalid); } /// <summary> /// Identifies/detects a switch that takes no parameters. /// </summary> internal static bool IsParameterlessSwitch ( string switchName ) { ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; return CommandLineSwitches.IsParameterlessSwitch(switchName, out parameterlessSwitch, out duplicateSwitchErrorMessage); } /// <summary> /// Identifies/detects a switch that takes parameters. /// </summary> /// <param name="switchName"></param> /// <param name="parameterizedSwitch">[out] switch identifier (from ParameterizedSwitch enumeration)</param> /// <param name="duplicateSwitchErrorMessage"></param> /// <param name="multipleParametersAllowed"></param> /// <param name="missingParametersErrorMessage"></param> /// <param name="unquoteParameters"></param> /// <returns>true, if switch is a recognized switch that takes parameters</returns> internal static bool IsParameterizedSwitch ( string switchName, out ParameterizedSwitch parameterizedSwitch, out string duplicateSwitchErrorMessage, out bool multipleParametersAllowed, out string missingParametersErrorMessage, out bool unquoteParameters, out bool emptyParametersAllowed ) { parameterizedSwitch = ParameterizedSwitch.Invalid; duplicateSwitchErrorMessage = null; multipleParametersAllowed = false; missingParametersErrorMessage = null; unquoteParameters = false; emptyParametersAllowed = false; foreach (ParameterizedSwitchInfo switchInfo in s_parameterizedSwitchesMap) { foreach (string parameterizedSwitchName in switchInfo.switchNames) { if (String.Equals(switchName, parameterizedSwitchName, StringComparison.OrdinalIgnoreCase)) { parameterizedSwitch = switchInfo.parameterizedSwitch; duplicateSwitchErrorMessage = switchInfo.duplicateSwitchErrorMessage; multipleParametersAllowed = switchInfo.multipleParametersAllowed; missingParametersErrorMessage = switchInfo.missingParametersErrorMessage; unquoteParameters = switchInfo.unquoteParameters; emptyParametersAllowed = switchInfo.emptyParametersAllowed; break; } } } return (parameterizedSwitch != ParameterizedSwitch.Invalid); } /// <summary> /// This struct stores the details of a switch that doesn't take parameters that is detected on the command line. /// </summary> private struct DetectedParameterlessSwitch { // the actual text of the switch internal string commandLineArg; } /// <summary> /// This struct stores the details of a switch that takes parameters that is detected on the command line. /// </summary> private struct DetectedParameterizedSwitch { // the actual text of the switch internal string commandLineArg; // the parsed switch parameters internal ArrayList parameters; } // for each recognized switch that doesn't take parameters, this array indicates if the switch has been detected on the // command line private DetectedParameterlessSwitch[] _parameterlessSwitches; // for each recognized switch that takes parameters, this array indicates if the switch has been detected on the command // line, and it provides a store for the switch parameters private DetectedParameterizedSwitch[] _parameterizedSwitches; // NOTE: the above arrays are instance members because this class is not required to be a singleton /// <summary> /// Default constructor. /// </summary> internal CommandLineSwitches() { #if DEBUG Debug.Assert(s_parameterlessSwitchesMap.Length == (int)ParameterlessSwitch.NumberOfParameterlessSwitches, "The map of parameterless switches must have an entry for each switch in the ParameterlessSwitch enumeration."); Debug.Assert(s_parameterizedSwitchesMap.Length == (int)ParameterizedSwitch.NumberOfParameterizedSwitches, "The map of parameterized switches must have an entry for each switch in the ParameterizedSwitch enumeration."); for (int i = 0; i < s_parameterlessSwitchesMap.Length; i++) { Debug.Assert(i == (int)(s_parameterlessSwitchesMap[i].parameterlessSwitch), "The map of parameterless switches must be ordered the same way as the ParameterlessSwitch enumeration."); } for (int i = 0; i < s_parameterizedSwitchesMap.Length; i++) { Debug.Assert(i == (int)(s_parameterizedSwitchesMap[i].parameterizedSwitch), "The map of parameterized switches must be ordered the same way as the ParameterizedSwitch enumeration."); } #endif _parameterlessSwitches = new DetectedParameterlessSwitch[(int)ParameterlessSwitch.NumberOfParameterlessSwitches]; _parameterizedSwitches = new DetectedParameterizedSwitch[(int)ParameterizedSwitch.NumberOfParameterizedSwitches]; } /// <summary> /// Called when a recognized switch that doesn't take parameters is detected on the command line. /// </summary> /// <param name="parameterlessSwitch"></param> internal void SetParameterlessSwitch(ParameterlessSwitch parameterlessSwitch, string commandLineArg) { // save the switch text _parameterlessSwitches[(int)parameterlessSwitch].commandLineArg = commandLineArg; } // list of recognized switch parameter separators -- for switches that take multiple parameters private static readonly char[] s_parameterSeparators = { ',', ';' }; /// <summary> /// Called when a recognized switch that takes parameters is detected on the command line. /// </summary> /// <param name="parameterizedSwitch"></param> /// <param name="switchParameters"></param> /// <param name="multipleParametersAllowed"></param> /// <param name="unquoteParameters"></param> /// <returns>true, if the given parameters were successfully stored</returns> internal bool SetParameterizedSwitch ( ParameterizedSwitch parameterizedSwitch, string commandLineArg, string switchParameters, bool multipleParametersAllowed, bool unquoteParameters, bool emptyParametersAllowed ) { bool parametersStored = false; // if this is the first time this switch has been detected if (_parameterizedSwitches[(int)parameterizedSwitch].commandLineArg == null) { // initialize its parameter storage _parameterizedSwitches[(int)parameterizedSwitch].parameters = new ArrayList(); // save the switch text _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg = commandLineArg; } else { // append the switch text _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg = string.Concat( _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg, " ", commandLineArg ); } // check if the switch has multiple parameters if (multipleParametersAllowed) { if (String.Empty.Equals(switchParameters) && emptyParametersAllowed) { // Store a null parameter if its allowed _parameterizedSwitches[(int) parameterizedSwitch].parameters.Add(null); parametersStored = true; } else { // store all the switch parameters int emptyParameters; _parameterizedSwitches[(int)parameterizedSwitch].parameters.AddRange(QuotingUtilities.SplitUnquoted(switchParameters, int.MaxValue, false /* discard empty parameters */, unquoteParameters, out emptyParameters, s_parameterSeparators)); // check if they were all stored successfully i.e. they were all non-empty (after removing quoting, if requested) parametersStored = (emptyParameters == 0); } } else { if (unquoteParameters) { // NOTE: removing quoting from the parameters can reduce the parameters to an empty string switchParameters = QuotingUtilities.Unquote(switchParameters); } // if the switch actually has parameters, store them if (switchParameters.Length > 0) { _parameterizedSwitches[(int)parameterizedSwitch].parameters.Add(switchParameters); parametersStored = true; } } return parametersStored; } /// <summary> /// Get the equivalent command line, with response files expanded /// and duplicates removed. Prettified, sorted, parameterless first. /// Don't include the project file, the caller can put it last. /// </summary> /// <returns></returns> internal string GetEquivalentCommandLineExceptProjectFile() { var commandLineA = new List<string>(); var commandLineB = new List<string>(); for (int i = 0; i < _parameterlessSwitches.Length; i++) { if (IsParameterlessSwitchSet((ParameterlessSwitch)i)) { commandLineA.Add(GetParameterlessSwitchCommandLineArg((ParameterlessSwitch)i)); } } for (int i = 0; i < _parameterizedSwitches.Length; i++) { if (IsParameterizedSwitchSet((ParameterizedSwitch)i) && ((ParameterizedSwitch)i != ParameterizedSwitch.Project)) { commandLineB.Add(GetParameterizedSwitchCommandLineArg((ParameterizedSwitch)i)); } } commandLineA.Sort(StringComparer.OrdinalIgnoreCase); commandLineB.Sort(StringComparer.OrdinalIgnoreCase); return (String.Join(" ", commandLineA).Trim() + " " + String.Join(" ", commandLineB).Trim()).Trim(); } /// <summary> /// Indicates if the given switch that doesn't take parameters has already been detected on the command line. /// </summary> /// <param name="parameterlessSwitch"></param> /// <returns>true, if switch has been seen before</returns> internal bool IsParameterlessSwitchSet(ParameterlessSwitch parameterlessSwitch) { return (_parameterlessSwitches[(int)parameterlessSwitch].commandLineArg != null); } /// <summary> /// Gets the on/off state on the command line of the given parameterless switch. /// </summary> /// <remarks> /// This indexer is functionally equivalent to IsParameterlessSwitchSet, but semantically very different. /// </remarks> /// <param name="parameterlessSwitch"></param> /// <returns>true if on, false if off</returns> internal bool this[ParameterlessSwitch parameterlessSwitch] { get { return (_parameterlessSwitches[(int)parameterlessSwitch].commandLineArg != null); } } /// <summary> /// Gets the command line argument (if any) in which the given parameterless switch was detected. /// </summary> /// <param name="parameterlessSwitch"></param> /// <returns>The switch text, or null if switch was not detected on the command line.</returns> internal string GetParameterlessSwitchCommandLineArg(ParameterlessSwitch parameterlessSwitch) { return _parameterlessSwitches[(int)parameterlessSwitch].commandLineArg; } /// <summary> /// Indicates if the given switch that takes parameters has already been detected on the command line. /// </summary> /// <remarks>This method is very light-weight.</remarks> /// <param name="parameterizedSwitch"></param> /// <returns>true, if switch has been seen before</returns> internal bool IsParameterizedSwitchSet(ParameterizedSwitch parameterizedSwitch) { return (_parameterizedSwitches[(int)parameterizedSwitch].commandLineArg != null); } // used to indicate a null parameter list for a switch private static readonly string[] s_noParameters = { }; /// <summary> /// Gets the parameters (if any) detected on the command line for the given parameterized switch. /// </summary> /// <remarks> /// WARNING: this indexer is not equivalent to IsParameterizedSwitchSet, and is not light-weight. /// </remarks> /// <param name="parameterizedSwitch"></param> /// <returns> /// An array of all the detected parameters for the given switch, or an empty array (NOT null), if the switch has not yet /// been detected on the command line. /// </returns> internal string[] this[ParameterizedSwitch parameterizedSwitch] { get { // if switch has not yet been detected if (_parameterizedSwitches[(int)parameterizedSwitch].commandLineArg == null) { // return an empty parameter list return s_noParameters; } else { // return an array of all detected parameters return (string[])_parameterizedSwitches[(int)parameterizedSwitch].parameters.ToArray(typeof(string)); } } } /// <summary> /// Returns an array containing an array of logger parameters for every file logger enabled on the command line. /// If a logger is enabled but no parameters were supplied, the array entry is an empty array. /// If a particular logger is not supplied, the array entry is null. /// </summary> internal string[][] GetFileLoggerParameters() { string[][] groupedFileLoggerParameters = new string[10][]; groupedFileLoggerParameters[0] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger, ParameterizedSwitch.FileLoggerParameters); groupedFileLoggerParameters[1] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger1, ParameterizedSwitch.FileLoggerParameters1); groupedFileLoggerParameters[2] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger2, ParameterizedSwitch.FileLoggerParameters2); groupedFileLoggerParameters[3] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger3, ParameterizedSwitch.FileLoggerParameters3); groupedFileLoggerParameters[4] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger4, ParameterizedSwitch.FileLoggerParameters4); groupedFileLoggerParameters[5] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger5, ParameterizedSwitch.FileLoggerParameters5); groupedFileLoggerParameters[6] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger6, ParameterizedSwitch.FileLoggerParameters6); groupedFileLoggerParameters[7] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger7, ParameterizedSwitch.FileLoggerParameters7); groupedFileLoggerParameters[8] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger8, ParameterizedSwitch.FileLoggerParameters8); groupedFileLoggerParameters[9] = GetSpecificFileLoggerParameters(ParameterlessSwitch.FileLogger9, ParameterizedSwitch.FileLoggerParameters9); return groupedFileLoggerParameters; } /// <summary> /// If the specified parameterized switch is set, returns the array of parameters. /// Otherwise, if the specified parameterless switch is set, returns an empty array. /// Otherwise returns null. /// This allows for example "/flp:foo=bar" to imply "/fl". /// </summary> private string[] GetSpecificFileLoggerParameters(ParameterlessSwitch parameterlessSwitch, ParameterizedSwitch parameterizedSwitch) { string[] result = null; if (IsParameterizedSwitchSet(parameterizedSwitch)) { result = this[parameterizedSwitch]; } else if (IsParameterlessSwitchSet(parameterlessSwitch)) { result = new string[] { }; } return result; } /// <summary> /// Gets the command line argument (if any) in which the given parameterized switch was detected. /// </summary> /// <param name="parameterizedSwitch"></param> /// <returns>The switch text, or null if switch was not detected on the command line.</returns> internal string GetParameterizedSwitchCommandLineArg(ParameterizedSwitch parameterizedSwitch) { return _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg; } /// <summary> /// Determines whether any switches have been set in this bag. /// </summary> /// <returns>Returns true if any switches are set, otherwise false.</returns> internal bool HaveAnySwitchesBeenSet() { for (int i = 0; i < (int)ParameterlessSwitch.NumberOfParameterlessSwitches; i++) { if (IsParameterlessSwitchSet((ParameterlessSwitch)i)) { return true; } } for (int j = 0; j < (int)ParameterizedSwitch.NumberOfParameterizedSwitches; j++) { if (IsParameterizedSwitchSet((ParameterizedSwitch)j)) { return true; } } return false; } /// <summary> /// Called to flag an error when an unrecognized switch is detected on the command line. /// </summary> /// <param name="badCommandLineArg"></param> internal void SetUnknownSwitchError(string badCommandLineArgValue) { SetSwitchError("UnknownSwitchError", badCommandLineArgValue); } /// <summary> /// Called to flag an error when a switch that doesn't take parameters is found with parameters on the command line. /// </summary> /// <param name="badCommandLineArg"></param> internal void SetUnexpectedParametersError(string badCommandLineArgValue) { SetSwitchError("UnexpectedParametersError", badCommandLineArgValue); } // information about last flagged error // NOTE: these instance members are not initialized unless an error is found private string _errorMessage; private string _badCommandLineArg; private Exception _innerException; private bool _isParameterError; /// <summary> /// Used to flag/store switch errors. /// </summary> /// <param name="messageResourceName"></param> /// <param name="badCommandLineArg"></param> internal void SetSwitchError(string messageResourceNameValue, string badCommandLineArgValue) { SetError(messageResourceNameValue, badCommandLineArgValue, null, false); } /// <summary> /// Used to flag/store parameter errors. /// </summary> /// <param name="messageResourceName"></param> /// <param name="badCommandLineArg"></param> internal void SetParameterError(string messageResourceNameValue, string badCommandLineArgValue) { SetParameterError(messageResourceNameValue, badCommandLineArgValue, null); } /// <summary> /// Used to flag/store parameter errors. /// </summary> /// <param name="messageResourceName"></param> /// <param name="badCommandLineArg"></param> /// <param name="innerException"></param> internal void SetParameterError(string messageResourceNameValue, string badCommandLineArgValue, Exception innerExceptionValue) { SetError(messageResourceNameValue, badCommandLineArgValue, innerExceptionValue, true); } /// <summary> /// Used to flag/store switch and/or parameter errors. /// </summary> /// <param name="messageResourceName"></param> /// <param name="badCommandLineArg"></param> /// <param name="innerException"></param> /// <param name="isParameterError"></param> private void SetError(string messageResourceNameValue, string badCommandLineArgValue, Exception innerExceptionValue, bool isParameterErrorValue) { if (!HaveErrors()) { _errorMessage = messageResourceNameValue; _badCommandLineArg = badCommandLineArgValue; _innerException = innerExceptionValue; _isParameterError = isParameterErrorValue; } } /// <summary> /// Indicates if any errors were found while parsing the command-line. /// </summary> /// <returns>true, if any errors were found</returns> internal bool HaveErrors() { return (_errorMessage != null); } /// <summary> /// Throws an exception if any errors were found while parsing the command-line. /// </summary> internal void ThrowErrors() { if (HaveErrors()) { if (_isParameterError) { InitializationException.Throw(_errorMessage, _badCommandLineArg, _innerException, false); } else { CommandLineSwitchException.Throw(_errorMessage, _badCommandLineArg); } } } /// <summary> /// Appends the given collection of command-line switches to this one. /// </summary> /// <remarks> /// Command-line switches have left-to-right precedence i.e. switches on the right override switches on the left. As a /// result, this "append" operation is also performed in a left-to-right manner -- the switches being appended to are /// considered to be on the "left", and the switches being appended are on the "right". /// </remarks> /// <param name="switchesToAppend"></param> internal void Append(CommandLineSwitches switchesToAppend) { // if this collection doesn't already have an error registered, but the collection being appended does if (!HaveErrors() && switchesToAppend.HaveErrors()) { // register the error from the given collection // NOTE: we always store the first error found (parsing left-to-right), and since this collection is considered to // be on the "left" of the collection being appended, the error flagged in this collection takes priority over the // error in the collection being appended _errorMessage = switchesToAppend._errorMessage; _badCommandLineArg = switchesToAppend._badCommandLineArg; _innerException = switchesToAppend._innerException; _isParameterError = switchesToAppend._isParameterError; } // NOTE: we might run into some duplicate switch errors below, but if we've already registered the error from the // collection being appended, all the duplicate switch errors will be ignored; this is fine because we really have no // way of telling which error would occur first in the left-to-right order without keeping track of a lot more error // information -- so we play it safe, and register the guaranteed error // append the parameterless switches with left-to-right precedence, flagging duplicate switches as necessary for (int i = 0; i < (int)ParameterlessSwitch.NumberOfParameterlessSwitches; i++) { if (switchesToAppend.IsParameterlessSwitchSet((ParameterlessSwitch)i)) { if (!IsParameterlessSwitchSet((ParameterlessSwitch)i) || (s_parameterlessSwitchesMap[i].duplicateSwitchErrorMessage == null)) { _parameterlessSwitches[i].commandLineArg = switchesToAppend._parameterlessSwitches[i].commandLineArg; } else { SetSwitchError(s_parameterlessSwitchesMap[i].duplicateSwitchErrorMessage, switchesToAppend.GetParameterlessSwitchCommandLineArg((ParameterlessSwitch)i)); } } } // append the parameterized switches with left-to-right precedence, flagging duplicate switches as necessary for (int j = 0; j < (int)ParameterizedSwitch.NumberOfParameterizedSwitches; j++) { if (switchesToAppend.IsParameterizedSwitchSet((ParameterizedSwitch)j)) { if (!IsParameterizedSwitchSet((ParameterizedSwitch)j) || (s_parameterizedSwitchesMap[j].duplicateSwitchErrorMessage == null)) { if (_parameterizedSwitches[j].commandLineArg == null) { _parameterizedSwitches[j].parameters = new ArrayList(); } _parameterizedSwitches[j].commandLineArg = switchesToAppend._parameterizedSwitches[j].commandLineArg; _parameterizedSwitches[j].parameters.AddRange(switchesToAppend._parameterizedSwitches[j].parameters); } else { SetSwitchError(s_parameterizedSwitchesMap[j].duplicateSwitchErrorMessage, switchesToAppend.GetParameterizedSwitchCommandLineArg((ParameterizedSwitch)j)); } } } } #region Flag Lightup Support /// <summary> /// Read a lightup key from either HKLM or HKCU depending on what is passed in root. /// The key may either be a string, in which case it needs to be like "true" or "false" /// or it may be a DWORD in which case it should be 0 or !=0. /// </summary> private static bool? ReadLightupBool(string root, string valueName) { #if FEATURE_WIN32_REGISTRY try { string key = String.Format(CultureInfo.InvariantCulture, @"{0}\software\microsoft\msbuild\{1}", root, MSBuildConstants.CurrentProductVersion); object value = Registry.GetValue(key, valueName, null); if (value != null) { if (value is int) { return ((int)value) != 0; } else if (value is string) { bool result; if (bool.TryParse((string)value, out result)) { return result; } return null; } else { // Recover by assuming the flag is not set. Debug.Assert(false, "Could not read debugger enabled flag. Key was found but it had type {0}" + value.GetType().ToString()); return null; } } return null; } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } // Recover by assuming the flag is not set. Debug.Assert(false, "Could not read debugger enabled flag. {0}" + e.ToString()); return null; } #else return null; #endif } /// <summary> /// Try to read a lightup key first from HKCU and then HKLM. /// </summary> private static bool ReadLightupBool(string valueName) { bool? result = ReadLightupBool("hkey_current_user", valueName) ?? ReadLightupBool("hkey_local_machine", valueName); if (result.HasValue) { return result.Value; } return false; } /// <summary> /// Returns true if the switch is enabled. Handles lightup logic. /// </summary> private static bool IsParameterlessSwitchEnabled(ParameterlessSwitchInfo parameterlessSwitch) { if (parameterlessSwitch.lightUpKey == null) { return true; } if (parameterlessSwitch.lightUpKeyRead) { return parameterlessSwitch.lightUpKeyResult; } // Need to read the registry parameterlessSwitch.lightUpKeyRead = true; parameterlessSwitch.lightUpKeyResult = ReadLightupBool(parameterlessSwitch.lightUpKey); return parameterlessSwitch.lightUpKeyResult; } #endregion } }
53.929078
254
0.577854
[ "MIT" ]
JetBrains/msbuild
src/MSBuild/CommandLineSwitches.cs
53,230
C#
using UnityEngine; using System.Collections; public class DonePlayerInventory : MonoBehaviour { public bool hasKey; // Whether or not the player has the key. }
21.375
65
0.74269
[ "Apache-2.0" ]
bcso/WanderLust
NamePending/Assets/Done/DoneScripts/PlayerScripts/DonePlayerInventory.cs
171
C#
using Microsoft.Excel.InterviewB.Shapes; namespace Microsoft.Excel.InterviewB.RollBack { public class AddRollbackAction : IRollbackAction { readonly IShape shape; public AddRollbackAction(IShape shape) { this.shape = shape ?? throw new System.ArgumentNullException(nameof(shape)); } public void Undo(Canvas canvas) { Logger.Log($"\nUndo AddRollbackAction with shape:\n{shape}"); shape.ShapeChanging += canvas.ShapeModify; canvas.AllShapes.Add(shape); } } }
23.2
88
0.624138
[ "MIT" ]
Bar-Amsalem/Microsoft.Excel
Microsoft.Excel.InterviewB/RollBack/AddRollbackAction.cs
582
C#
 namespace SkiaInk.GeometryPipeline.OuelletConvexHullAvl3 { public enum ConvexHullThreadUsageAvl { AutoSelect = 0, OnlyOne = 1, All = 2, FixedFour = 4, OneOrFour = 8 } } // ******************************************************************
18.285714
71
0.507813
[ "MIT" ]
jordanisaacs/SkiaInk
SkiaInk/GeometryPipeline/OuelletConvexHullAvl3/ConvexHullThreadUsage.cs
258
C#
namespace Boxed.AspNetCore.Test { using Boxed.AspNetCore; using Microsoft.AspNetCore.Hosting; using Xunit; public class WebHostBuilderExtensionsTest { private readonly WebHostBuilder webHostBuilder; public WebHostBuilderExtensionsTest() => this.webHostBuilder = new WebHostBuilder(); [Theory] [InlineData(true)] [InlineData(false)] public void UseIf_TrueCondition_ActionCalled(bool condition) { var actionCalled = false; this.webHostBuilder.UseIf( condition, x => { actionCalled = true; return x; }); Assert.Equal(actionCalled, condition); } [Theory] [InlineData(true)] [InlineData(false)] public void UseIfElse_TrueCondition_ActionCalled(bool condition) { var ifActionCalled = false; var elseActionCalled = false; this.webHostBuilder.UseIfElse( condition, x => { ifActionCalled = true; return x; }, x => { elseActionCalled = true; return x; }); Assert.Equal(ifActionCalled, condition); Assert.NotEqual(elseActionCalled, condition); } } }
25.637931
72
0.498319
[ "MIT" ]
davihar/Framework
Tests/Boxed.AspNetCore.Test/WebHostBuilderExtensionsTest.cs
1,487
C#
using Top.Api.Cluster; namespace Top.Api { public class AutoRetryClusterTopClient : AutoRetryTopClient { public AutoRetryClusterTopClient(string serverUrl, string appKey, string appSecret) : base(serverUrl, appKey, appSecret) { ClusterManager.InitRefreshThread(this); } public AutoRetryClusterTopClient(string serverUrl, string appKey, string appSecret, string format) : base(serverUrl, appKey, appSecret, format) { ClusterManager.InitRefreshThread(this); } internal override string GetServerUrl(string serverUrl, string apiName, string session) { DnsConfig dnsConfig = ClusterManager.GetDnsConfigFromCache(); if (dnsConfig == null) { return serverUrl; } else { return dnsConfig.GetBestVipUrl(serverUrl, apiName, session); } } internal override string GetSdkVersion() { return Constants.SDK_VERSION_CLUSTER; } } }
29.026316
106
0.597461
[ "MIT" ]
buyongfeng521/SmallBelief
TaobaoSDK/AutoRetryClusterTopClient.cs
1,105
C#
// ========================================================================== // Notifo.io // ========================================================================== // Copyright (c) Sebastian Stehle // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Globalization; using NodaTime; using Notifo.Domain.Apps; using Notifo.Domain.Log; using Notifo.Domain.Resources; using Notifo.Domain.UserEvents; using Notifo.Domain.Users; using Notifo.Infrastructure; using Notifo.Infrastructure.Reflection; namespace Notifo.Domain.UserNotifications { public sealed class UserNotificationFactory : IUserNotificationFactory { private const string DefaultConfirmText = "Confirm"; private readonly IUserNotificationUrl url; private readonly IClock clock; private readonly ILogStore logstore; public UserNotificationFactory(ILogStore logstore, IUserNotificationUrl url, IClock clock) { this.clock = clock; this.logstore = logstore; this.url = url; } public UserNotification? Create(App app, User user, UserEventMessage userEvent) { Guard.NotNull(user); Guard.NotNull(userEvent); if (userEvent.Formatting == null || string.IsNullOrWhiteSpace(userEvent.AppId) || string.IsNullOrWhiteSpace(userEvent.EventId) || string.IsNullOrWhiteSpace(userEvent.Topic) || string.IsNullOrWhiteSpace(userEvent.UserId)) { return null; } var language = user.PreferredLanguage; if (!app.Languages.Contains(language)) { logstore.LogAsync(app.Id, string.Format(CultureInfo.InvariantCulture, Texts.UserLanguage_NotValid, language, app.Language)); language = app.Language; } var formatting = userEvent.Formatting.SelectText(language); if (!formatting.HasSubject()) { return null; } var notification = SimpleMapper.Map(userEvent, new UserNotification { Id = Guid.NewGuid() }); notification.Updated = clock.GetCurrentInstant(); notification.UserLanguage = language; notification.Formatting = formatting; ConfigureTracking(notification, userEvent); ConfigureSettings(notification, userEvent, user); return notification; } private void ConfigureTracking(UserNotification notification, UserEventMessage userEvent) { var confirmMode = userEvent.Formatting.ConfirmMode; if (confirmMode == ConfirmMode.Explicit) { notification.ConfirmUrl = url.TrackConfirmed(notification.Id, notification.UserLanguage); if (string.IsNullOrWhiteSpace(notification.Formatting.ConfirmText)) { notification.Formatting.ConfirmText = DefaultConfirmText; } } else { notification.Formatting.ConfirmText = null; } notification.TrackDeliveredUrl = url.TrackDelivered(notification.Id, notification.UserLanguage); notification.TrackSeenUrl = url.TrackSeen(notification.Id, notification.UserLanguage); } private static void ConfigureSettings(UserNotification notification, UserEventMessage userEvent, User user) { notification.Channels = new Dictionary<string, UserNotificationChannel>(); OverrideBy(notification, user.Settings); OverrideBy(notification, userEvent.Settings); } private static void OverrideBy(UserNotification notification, ChannelSettings? source) { foreach (var (channel, setting) in source.OrEmpty()) { notification.Channels.GetOrAddNew(channel).Setting.OverrideBy(setting); } } } }
34.94958
140
0.586679
[ "MIT" ]
idist-hn/notifo
backend/src/Notifo.Domain/UserNotifications/UserNotificationFactory.cs
4,161
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Insights.Inputs { /// <summary> /// State of the private endpoint connection. /// </summary> public sealed class PrivateLinkServiceConnectionStatePropertyArgs : Pulumi.ResourceArgs { /// <summary> /// The private link service connection description. /// </summary> [Input("description", required: true)] public Input<string> Description { get; set; } = null!; /// <summary> /// The private link service connection status. /// </summary> [Input("status", required: true)] public Input<string> Status { get; set; } = null!; public PrivateLinkServiceConnectionStatePropertyArgs() { } } }
29.857143
91
0.645933
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Insights/Inputs/PrivateLinkServiceConnectionStatePropertyArgs.cs
1,045
C#
using System; namespace Microsoft.VisualStudio.ComponentDiagnostics { static class GuidList { public const string PackageString = "358da9fb-1568-3e9a-8ec9-e41a0d763fef"; public const string ToolWindowString = "7d12284c-f8fd-49b0-b6d6-becdcd896e1f"; public const string CommandSetString = "2112b0e0-26ed-4848-b325-f2e5192798b7"; public const string UiFactoryString = "08ad9d3f-5023-4bf1-905e-aaa0ec595941"; public const string RdtDiagnosticsProviderString = "ced6ef6d-091f-4faf-9628-e1c67152f39e"; public const string ScrollbarDiagnosticsProviderString = "e886170b-b0c4-4155-9b00-04745b300d91"; public const string WindowFramesDiagnosticsProviderString = "0E255C2C-6D87-469F-BCA8-8FFE0841C560"; public static readonly Guid CommandSet = new Guid(CommandSetString); public static readonly Guid UiFactory = new Guid(UiFactoryString); } }
53.789474
107
0.679061
[ "MIT" ]
pharring/ComponentDiagnostics
src/ComponentDiagnostics/GuidList.cs
1,024
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using AccountSecurity.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace AccountSecurity.Services { public interface IAuthy { Task<string> registerUserAsync(RegisterViewModel user); Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token); Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token); Task<string> sendSmsAsync(string authyId); Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber); Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber); Task<string> createApprovalRequestAsync(string authyId); Task<object> checkRequestStatusAsync(string onetouch_uuid); } public class Authy : IAuthy { private readonly IConfiguration Configuration; private readonly IHttpClientFactory ClientFactory; private readonly ILogger<Authy> logger; private readonly HttpClient client; public string message { get; private set; } public Authy(IConfiguration config, IHttpClientFactory clientFactory, ILoggerFactory loggerFactory) { Configuration = config; logger = loggerFactory.CreateLogger<Authy>(); ClientFactory = clientFactory; client = ClientFactory.CreateClient(); client.BaseAddress = new Uri("https://api.authy.com"); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("user-agent", "Twilio Account Security C# Sample"); // Get Authy API Key from Configuration client.DefaultRequestHeaders.Add("X-Authy-API-Key", Configuration["AuthyApiKey"]); } public async Task<string> registerUserAsync(RegisterViewModel user) { var userRegData = new Dictionary<string, string>() { { "email", user.Email }, { "country_code", user.CountryCode }, { "cellphone", user.PhoneNumber } }; var userRegRequestData = new Dictionary<string, object>() { }; userRegRequestData.Add("user", userRegData); var encodedContent = new FormUrlEncodedContent(userRegData); var result = await client.PostAsJsonAsync("/protected/json/users/new", userRegRequestData); logger.LogDebug(result.Content.ReadAsStringAsync().Result); result.EnsureSuccessStatusCode(); var response = await result.Content.ReadAsAsync<Dictionary<string, object>>(); return JObject.FromObject(response["user"])["id"].ToString(); } public async Task<TokenVerificationResult> verifyTokenAsync(string authyId, string token) { var result = await client.GetAsync($"/protected/json/verify/{token}/{authyId}"); logger.LogDebug(result.ToString()); logger.LogDebug(result.Content.ReadAsStringAsync().Result); var message = await result.Content.ReadAsStringAsync(); if (result.StatusCode == HttpStatusCode.OK) { return new TokenVerificationResult(message); } return new TokenVerificationResult(message, false); } public async Task<TokenVerificationResult> verifyPhoneTokenAsync(string phoneNumber, string countryCode, string token) { var result = await client.GetAsync( $"/protected/json/phones/verification/check?phone_number={phoneNumber}&country_code={countryCode}&verification_code={token}" ); logger.LogDebug(result.ToString()); logger.LogDebug(result.Content.ReadAsStringAsync().Result); var message = await result.Content.ReadAsStringAsync(); if (result.StatusCode == HttpStatusCode.OK) { return new TokenVerificationResult(message); } return new TokenVerificationResult(message, false); } public async Task<string> sendSmsAsync(string authyId) { var result = await client.GetAsync($"/protected/json/sms/{authyId}?force=true"); logger.LogDebug(result.ToString()); result.EnsureSuccessStatusCode(); return await result.Content.ReadAsStringAsync(); } public async Task<string> phoneVerificationCallRequestAsync(string countryCode, string phoneNumber) { var result = await client.PostAsync( $"/protected/json/phones/verification/start?via=call&country_code={countryCode}&phone_number={phoneNumber}", null ); var content = await result.Content.ReadAsStringAsync(); logger.LogDebug(result.ToString()); logger.LogDebug(content); result.EnsureSuccessStatusCode(); return await result.Content.ReadAsStringAsync(); } public async Task<string> phoneVerificationRequestAsync(string countryCode, string phoneNumber) { var result = await client.PostAsync( $"/protected/json/phones/verification/start?via=sms&country_code={countryCode}&phone_number={phoneNumber}", null ); var content = await result.Content.ReadAsStringAsync(); logger.LogDebug(result.ToString()); logger.LogDebug(content); result.EnsureSuccessStatusCode(); return await result.Content.ReadAsStringAsync(); } public async Task<string> createApprovalRequestAsync(string authyId) { var requestData = new Dictionary<string, string>() { { "message", "OneTouch Approval Request" }, { "details", "My Message Details" }, { "seconds_to_expire", "300" } }; var result = await client.PostAsJsonAsync( $"/onetouch/json/users/{authyId}/approval_requests", requestData ); logger.LogDebug(result.ToString()); var str_content = await result.Content.ReadAsStringAsync(); logger.LogDebug(str_content); result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsAsync<Dictionary<string, object>>(); var approval_request_data = (JObject)content["approval_request"]; return (string)approval_request_data["uuid"]; } public async Task<object> checkRequestStatusAsync(string onetouch_uuid) { var result = await client.GetAsync($"/onetouch/json/approval_requests/{onetouch_uuid}"); logger.LogDebug(result.ToString()); var str_content = await result.Content.ReadAsStringAsync(); logger.LogDebug(str_content); result.EnsureSuccessStatusCode(); return await result.Content.ReadAsAsync<object>(); } } public class TokenVerificationResult { public TokenVerificationResult(string message, bool succeeded = true) { this.Message = message; this.Succeeded = succeeded; } public bool Succeeded { get; set; } public string Message { get; set; } } }
33.901478
134
0.70154
[ "MIT" ]
OpticalExpressOnline/account-security-csharp
src/AccountSecurity/Services/Authy.cs
6,882
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. namespace StarkPlatform.CodeAnalysis.ExtractMethod { internal partial class OperationStatus { public static readonly OperationStatus Succeeded = new OperationStatus(OperationStatusFlag.Succeeded, reason: null); public static readonly OperationStatus FailedWithUnknownReason = new OperationStatus(OperationStatusFlag.None, reason: FeaturesResources.Unknown_error_occurred); public static readonly OperationStatus OverlapsHiddenPosition = new OperationStatus(OperationStatusFlag.None, FeaturesResources.generated_code_is_overlapping_with_hidden_portion_of_the_code); public static readonly OperationStatus NoActiveStatement = new OperationStatus(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_no_active_statement); public static readonly OperationStatus ErrorOrUnknownType = new OperationStatus(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_an_error_or_unknown_type); public static readonly OperationStatus UnsafeAddressTaken = new OperationStatus(OperationStatusFlag.BestEffort, FeaturesResources.The_address_of_a_variable_is_used_inside_the_selected_code); /// <summary> /// create operation status with the given data /// </summary> public static OperationStatus<T> Create<T>(OperationStatus status, T data) { return new OperationStatus<T>(status, data); } } }
66.666667
199
0.79375
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Features/Core/Portable/ExtractMethod/OperationStatus_Statics.cs
1,602
C#
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information. using Microsoft.Build.Framework.XamlTypes; using Microsoft.VisualStudio.Mocks; using Microsoft.VisualStudio.ProjectSystem.Debug; namespace Microsoft.VisualStudio.ProjectSystem.Properties { public class LaunchProfilesProjectPropertiesTests { private const string DefaultTestProjectPath = @"C:\alpha\beta\gamma.csproj"; private static readonly ImmutableArray<Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>> EmptyLaunchProfileExtensionValueProviders = ImmutableArray<Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>>.Empty; private static readonly ImmutableArray<Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>> EmptyGlobalSettingExtensionValueProviders = ImmutableArray<Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>>.Empty; [Fact] public void WhenRetrievingItemProperties_TheContextHasTheExpectedValues() { var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var context = properties.Context; Assert.Equal(expected: DefaultTestProjectPath, actual: context.File); Assert.True(context.IsProjectFile); Assert.Equal(expected: "Profile1", actual: context.ItemName); Assert.Equal(expected: LaunchProfileProjectItemProvider.ItemType, actual: context.ItemType); } [Fact] public void WhenRetrievingItemProperties_TheFilePathIsTheProjectPath() { var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); Assert.Equal(expected: DefaultTestProjectPath, actual: properties.FileFullPath); } [Fact] public void WhenRetrievingItemProperties_ThePropertyKindIsItemGroup() { var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); Assert.Equal(expected: PropertyKind.ItemGroup, actual: properties.PropertyKind); } [Fact] public async Task WhenRetrievingItemPropertyNames_AllStandardProfilePropertyNamesAreReturnedEvenIfNotDefined() { var profile1 = new WritableLaunchProfile { Name = "Profile1" }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var propertyNames = await properties.GetPropertyNamesAsync(); Assert.Contains("CommandName", propertyNames); Assert.Contains("ExecutablePath", propertyNames); Assert.Contains("CommandLineArguments", propertyNames); Assert.Contains("WorkingDirectory", propertyNames); Assert.Contains("LaunchBrowser", propertyNames); Assert.Contains("LaunchUrl", propertyNames); Assert.Contains("EnvironmentVariables", propertyNames); } [Fact] public async Task WhenRetrievingStandardPropertyValues_TheEmptyStringIsReturnedForUndefinedProperties() { var profile1 = new WritableLaunchProfile { Name = "Profile1" }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var standardPropertyNames = new[] { "CommandName", "ExecutablePath", "CommandLineArguments", "WorkingDirectory", "LaunchUrl", "EnvironmentVariables" }; foreach (var standardPropertyName in standardPropertyNames) { var evaluatedValue = await properties.GetEvaluatedPropertyValueAsync(standardPropertyName); Assert.Equal(expected: string.Empty, actual: evaluatedValue); var unevaluatedValue = await properties.GetUnevaluatedPropertyValueAsync(standardPropertyName); Assert.Equal(expected: string.Empty, actual: unevaluatedValue); } } [Fact] public async Task WhenRetrievingTheLaunchBrowserValue_TheDefaultValueIsFalse() { var profile1 = new WritableLaunchProfile { Name = "Profile1" }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var evaluatedValue = await properties.GetEvaluatedPropertyValueAsync("LaunchBrowser"); Assert.Equal(expected: "false", actual: evaluatedValue); var unevaluatedValue = await properties.GetUnevaluatedPropertyValueAsync("LaunchBrowser"); Assert.Equal(expected: "false", actual: unevaluatedValue); } [Fact] public async Task WhenRetrievingStandardPropertyValues_TheExpectedValuesAreReturned() { var profile1 = new WritableLaunchProfile { Name = "Profile1", CommandLineArgs = "alpha beta gamma", CommandName = "epsilon", EnvironmentVariables = { ["One"] = "1", ["Two"] = "2" }, ExecutablePath = @"D:\five\six\seven\eight.exe", LaunchBrowser = true, LaunchUrl = "https://localhost/profile", WorkingDirectory = @"C:\users\other\temp" }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var expectedValues = new Dictionary<string, string> { ["CommandLineArguments"] = "alpha beta gamma", ["CommandName"] = "epsilon", ["EnvironmentVariables"] = "One=1,Two=2", ["ExecutablePath"] = @"D:\five\six\seven\eight.exe", ["LaunchBrowser"] = "true", ["LaunchUrl"] = "https://localhost/profile", ["WorkingDirectory"] = @"C:\users\other\temp", }; foreach (var (propertyName, expectedPropertyValue) in expectedValues) { var actualUnevaluatedValue = await properties.GetUnevaluatedPropertyValueAsync(propertyName); var actualEvaluatedValue = await properties.GetEvaluatedPropertyValueAsync(propertyName); Assert.Equal(expectedPropertyValue, actualUnevaluatedValue); Assert.Equal(expectedPropertyValue, actualEvaluatedValue); } } [Fact] public async Task WhenSettingStandardPropertyValues_StandardCallbacksAreFound() { var profile1 = new WritableLaunchProfile { Name = "Profile1", CommandName = "epsilon", }; bool callbackInvoked; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }, tryUpdateProfileCallback: (profile, action) => { callbackInvoked = true; }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var newValues = new Dictionary<string, string> { ["CommandLineArguments"] = "delta epsilon", ["CommandName"] = "arugula", ["EnvironmentVariables"] = "Three=3,Four=4", ["ExecutablePath"] = @"D:\nine\ten.exe", ["LaunchBrowser"] = "false", ["LaunchUrl"] = "https://localhost/myOtherProfile", ["WorkingDirectory"] = @"D:\aardvark", }; foreach (var (propertyName, newPropertyValue) in newValues) { callbackInvoked = false; await properties.SetPropertyValueAsync(propertyName, newPropertyValue); Assert.True(callbackInvoked); } } [Fact] public async Task WhenRetrievingAnExtensionProperty_TheExtensionValueProviderIsCalled() { string? requestedPropertyName = null; var extensionValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( (propertyName, profile, globals, rule) => { requestedPropertyName = propertyName; return "alpha"; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), ImmutableArray.Create(lazy), EmptyGlobalSettingExtensionValueProviders); var propertyValue = await properties.GetEvaluatedPropertyValueAsync("MyProperty"); Assert.Equal(expected: "MyProperty", actual: requestedPropertyName); Assert.Equal(expected: "alpha", actual: propertyValue); } [Fact] public async Task WhenRetrievingAnExtensionProperty_TheRuleIsPassedToTheExtensionValueProvider() { bool rulePassed = false; var extensionValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( (propertyName, profile, globals, rule) => { rulePassed = rule is not null; return "alpha"; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), ImmutableArray.Create(lazy), EmptyGlobalSettingExtensionValueProviders); var rule = new Rule(); properties.SetRuleContext(rule); var propertyValue = await properties.GetEvaluatedPropertyValueAsync("MyProperty"); Assert.True(rulePassed); Assert.Equal(expected: "alpha", actual: propertyValue); } [Fact] public async Task WhenRetrievingPropertyNames_LaunchProfileExtensionNamesAreIncludedForDefinedProperties() { var alphaValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( (propertyName, profile, globals, rule) => { return "alpha"; }); var alphaMetadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("AlphaProperty"); var alphaLazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => alphaValueProvider, alphaMetadata); var betaValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( (propertyName, profile, globals, rule) => { return ""; }); var betaMetadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("BetaProperty"); var betaLazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => betaValueProvider, betaMetadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), ImmutableArray.Create(alphaLazy, betaLazy), EmptyGlobalSettingExtensionValueProviders); var names = await properties.GetPropertyNamesAsync(); Assert.Contains("AlphaProperty", names); Assert.DoesNotContain("BetaProperty", names); } [Fact] public async Task WhenSettingAnExtensionProperty_TheExtensionValueProviderIsCalled() { string? updatedPropertyName = null; string? updatedPropertyValue = null; var extensionValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( onSetPropertyValue: (propertyName, value, profile, globals, rule) => { updatedPropertyName = propertyName; updatedPropertyValue = value; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), ImmutableArray.Create(lazy), EmptyGlobalSettingExtensionValueProviders); await properties.SetPropertyValueAsync("MyProperty", "alpha"); Assert.Equal(expected: "MyProperty", actual: updatedPropertyName); Assert.Equal(expected: "alpha", actual: updatedPropertyValue); } [Fact] public async Task WhenSettingAnExtensionProperty_TheRuleIsPassedToTheExtensionValueProvider() { bool rulePassed = false; var extensionValueProvider = ILaunchProfileExtensionValueProviderFactory.Create( onSetPropertyValue: (propertyName, value, profile, globals, rule) => { rulePassed = rule is not null; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<ILaunchProfileExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), ImmutableArray.Create(lazy), EmptyGlobalSettingExtensionValueProviders); properties.SetRuleContext(new Rule()); await properties.SetPropertyValueAsync("MyProperty", "alpha"); Assert.True(rulePassed); } [Fact] public async Task WhenRetrievingAGlobalProperty_TheExtensionValueProviderIsCalled() { string? requestedPropertyName = null; var extensionValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( (propertyName, globals, rule) => { requestedPropertyName = propertyName; return "alpha"; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, ImmutableArray.Create(lazy)); var propertyValue = await properties.GetEvaluatedPropertyValueAsync("MyProperty"); Assert.Equal(expected: "MyProperty", actual: requestedPropertyName); Assert.Equal(expected: "alpha", actual: propertyValue); } [Fact] public async Task WhenRetrievingAGlobalProperty_TheRuleIsPassedToTheExtensionValueProvider() { bool rulePassed = false; var extensionValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( (propertyName, globals, rule) => { rulePassed = rule is not null; return "alpha"; }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, ImmutableArray.Create(lazy)); properties.SetRuleContext(new Rule()); var propertyValue = await properties.GetEvaluatedPropertyValueAsync("MyProperty"); Assert.True(rulePassed); Assert.Equal(expected: "alpha", actual: propertyValue); } [Fact] public async Task WhenSettingAGlobalProperty_TheExtensionValueProviderIsCalled() { string? updatedPropertyName = null; string? updatedPropertyValue = null; var extensionValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( onSetPropertyValue: (propertyName, value, globals, rule) => { updatedPropertyName = propertyName; updatedPropertyValue = value; return ImmutableDictionary<string, object?>.Empty.Add(propertyName, value); }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, ImmutableArray.Create(lazy)); await properties.SetPropertyValueAsync("MyProperty", "alpha"); Assert.Equal(expected: "MyProperty", actual: updatedPropertyName); Assert.Equal(expected: "alpha", actual: updatedPropertyValue); } [Fact] public async Task WhenSettingAGlobalProperty_TheRuleIsPassedToTheExtensionValueProvider() { bool rulePassed = false; var extensionValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( onSetPropertyValue: (propertyName, value, globals, rule) => { rulePassed = rule is not null; return ImmutableDictionary<string, object?>.Empty.Add(propertyName, value); }); var metadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("MyProperty"); var lazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => extensionValueProvider, metadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, ImmutableArray.Create(lazy)); properties.SetRuleContext(new Rule()); await properties.SetPropertyValueAsync("MyProperty", "alpha"); Assert.True(rulePassed); } [Fact] public async Task WhenRetrievingPropertyNames_GlobalSettingExtensionNamesAreIncludedForDefinedProperties() { var alphaValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( (propertyName, globals, rule) => { return "alpha"; }); var alphaMetadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("AlphaProperty"); var alphaLazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => alphaValueProvider, alphaMetadata); var betaValueProvider = IGlobalSettingExtensionValueProviderFactory.Create( (propertyName, globals, rule) => { return ""; }); var betaMetadata = ILaunchProfileExtensionValueProviderMetadataFactory.Create("BetaProperty"); var betaLazy = new Lazy<IGlobalSettingExtensionValueProvider, ILaunchProfileExtensionValueProviderMetadata>( () => betaValueProvider, betaMetadata); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", CreateDefaultTestLaunchSettings(), EmptyLaunchProfileExtensionValueProviders, ImmutableArray.Create(alphaLazy, betaLazy)); var names = await properties.GetPropertyNamesAsync(); Assert.Contains("AlphaProperty", names); Assert.DoesNotContain("BetaProperty", names); } [Fact] public async Task WhenRetrievingPropertyNames_PropertiesInOtherSettingsAreIncluded() { var profile1 = new WritableLaunchProfile { Name = "Profile1", OtherSettings = { { "alpha", 1 } } }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var names = await properties.GetPropertyNamesAsync(); Assert.Contains("alpha", names); } [Fact] public async Task WhenRetrievingPropertyNames_PropertiesInGlobalSettingsAreNotIncluded() { var profile1 = new WritableLaunchProfile { Name = "Profile1", OtherSettings = { { "alpha", 1 } } }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }, globalSettings: ImmutableDictionary<string, object>.Empty.Add("beta", "value")); var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); var names = await properties.GetPropertyNamesAsync(); Assert.DoesNotContain("beta", names); } [Fact] public async Task WhenRetrievingValuesFromOtherSettings_ValuesArePropertyConvertedToStrings() { var profile1 = new WritableLaunchProfile { Name = "Profile1", OtherSettings = { { "anInteger", 1 }, { "aBoolean", true }, { "aString", "Hello, world" }, { "anEnumStoredAsAsAString", "valueOne" }, { "anotherString", "Hi, friends!" } } }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile() }); var rule = new Rule { Properties = { new IntProperty { Name = "anInteger" }, new BoolProperty { Name = "aBoolean" }, new StringProperty { Name = "aString" }, new EnumProperty { Name = "anEnumStoredAsAString" } // anotherString intentionally not represented } }; var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); properties.SetRuleContext(rule); var anIntegerValue = await properties.GetEvaluatedPropertyValueAsync("anInteger"); Assert.Equal(expected: "1", actual: anIntegerValue); var aBooleanValue = await properties.GetEvaluatedPropertyValueAsync("aBoolean"); Assert.Equal(expected: "true", actual: aBooleanValue); var aStringValue = await properties.GetEvaluatedPropertyValueAsync("aString"); Assert.Equal(expected: "Hello, world", actual: aStringValue); var anEnumStoredAsAsAStringValue = await properties.GetEvaluatedPropertyValueAsync("anEnumStoredAsAsAString"); Assert.Equal(expected: "valueOne", actual: anEnumStoredAsAsAStringValue); var anotherStringValue = await properties.GetEvaluatedPropertyValueAsync("anotherString"); Assert.Equal(expected: "Hi, friends!", actual: anotherStringValue); } [Fact] public async Task WhenSettingValuesNotHandledByExtenders_ValuesOfTheExpectedTypesAreStoredInOtherSettings() { var writableProfile = new WritableLaunchProfile { Name = "Profile1", }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { writableProfile.ToLaunchProfile() }, tryUpdateProfileCallback: (profile, action) => { // Update writableProfile since we're hanging on to it rather than the profile given us by the mock. action(writableProfile); }); var rule = new Rule { Properties = { new IntProperty { Name = "anInteger" }, new BoolProperty { Name = "aBoolean" }, new StringProperty { Name = "aString" }, new EnumProperty { Name = "anEnumStoredAsAString" } // anotherString intentionally not represented } }; var properties = new LaunchProfileProjectProperties( DefaultTestProjectPath, "Profile1", launchSettingsProvider, EmptyLaunchProfileExtensionValueProviders, EmptyGlobalSettingExtensionValueProviders); properties.SetRuleContext(rule); await properties.SetPropertyValueAsync("anInteger", "2"); await properties.SetPropertyValueAsync("aBoolean", "false"); await properties.SetPropertyValueAsync("aString", "Hello, world!"); await properties.SetPropertyValueAsync("anEnumStoredAsAString", "valueTwo"); await properties.SetPropertyValueAsync("anotherString", "Hello, friends!"); Assert.Equal(expected: 2, actual: writableProfile.OtherSettings["anInteger"]); Assert.Equal(expected: false, actual: writableProfile.OtherSettings["aBoolean"]); Assert.Equal(expected: "Hello, world!", actual: writableProfile.OtherSettings["aString"]); Assert.Equal(expected: "valueTwo", actual: writableProfile.OtherSettings["anEnumStoredAsAString"]); Assert.Equal(expected: "Hello, friends!", actual: writableProfile.OtherSettings["anotherString"]); } /// <summary> /// Creates an <see cref="ILaunchSettingsProvider"/> with two empty profiles named /// "Profile1" and "Profile2". /// </summary> private static ILaunchSettingsProvider3 CreateDefaultTestLaunchSettings() { var profile1 = new WritableLaunchProfile { Name = "Profile1" }; var profile2 = new WritableLaunchProfile { Name = "Profile2" }; var launchSettingsProvider = ILaunchSettingsProviderFactory.Create( launchProfiles: new[] { profile1.ToLaunchProfile(), profile2.ToLaunchProfile() }); return launchSettingsProvider; } } }
45.848138
201
0.602681
[ "MIT" ]
adamint/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/ProjectSystem/Properties/LaunchProfiles/LaunchProfilesProjectPropertiesTests.cs
31,307
C#
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Params.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Params { /// <java-name> /// org/apache/http/client/params/CookiePolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)] public sealed partial class CookiePolicy /* scope: __dot42__ */ { /// <summary> /// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para> /// </summary> /// <java-name> /// BROWSER_COMPATIBILITY /// </java-name> [Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)] public const string BROWSER_COMPATIBILITY = "compatibility"; /// <summary> /// <para>The Netscape cookie draft compliant policy. </para> /// </summary> /// <java-name> /// NETSCAPE /// </java-name> [Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)] public const string NETSCAPE = "netscape"; /// <summary> /// <para>The RFC 2109 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2109 /// </java-name> [Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2109 = "rfc2109"; /// <summary> /// <para>The RFC 2965 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2965 /// </java-name> [Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2965 = "rfc2965"; /// <summary> /// <para>The default 'best match' policy. </para> /// </summary> /// <java-name> /// BEST_MATCH /// </java-name> [Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)] public const string BEST_MATCH = "best-match"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal CookiePolicy() /* MethodBuilder.Create */ { } } /// <summary> /// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/HttpClientParams /// </java-name> [Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)] public partial class HttpClientParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpClientParams() /* MethodBuilder.Create */ { } /// <java-name> /// isRedirecting /// </java-name> [Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setRedirecting /// </java-name> [Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// isAuthenticating /// </java-name> [Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setAuthenticating /// </java-name> [Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getCookiePolicy /// </java-name> [Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/params/AuthPolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)] public sealed partial class AuthPolicy /* scope: __dot42__ */ { /// <summary> /// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para> /// </summary> /// <java-name> /// NTLM /// </java-name> [Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)] public const string NTLM = "NTLM"; /// <summary> /// <para>Digest authentication scheme as defined in RFC2617. </para> /// </summary> /// <java-name> /// DIGEST /// </java-name> [Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)] public const string DIGEST = "Digest"; /// <summary> /// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para> /// </summary> /// <java-name> /// BASIC /// </java-name> [Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)] public const string BASIC = "Basic"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal AuthPolicy() /* MethodBuilder.Create */ { } } /// <summary> /// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/AllClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)] public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { } /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY_CLASS_NAME /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name"; /// <summary> /// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object"; /// <summary> /// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_REDIRECTS /// </java-name> [Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects"; /// <summary> /// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// REJECT_RELATIVE_REDIRECT /// </java-name> [Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)] public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; /// <summary> /// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_REDIRECTS /// </java-name> [Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_REDIRECTS = "http.protocol.max-redirects"; /// <summary> /// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// ALLOW_CIRCULAR_REDIRECTS /// </java-name> [Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; /// <summary> /// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_AUTHENTICATION /// </java-name> [Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; /// <summary> /// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// COOKIE_POLICY /// </java-name> [Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_POLICY = "http.protocol.cookie-policy"; /// <summary> /// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// VIRTUAL_HOST /// </java-name> [Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string VIRTUAL_HOST = "http.virtual-host"; /// <summary> /// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para> /// </summary> /// <java-name> /// DEFAULT_HEADERS /// </java-name> [Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HEADERS = "http.default-headers"; /// <summary> /// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_HOST /// </java-name> [Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HOST = "http.default-host"; } /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)] public partial interface IClientPNames /* scope: __dot42__ */ { } /// <java-name> /// org/apache/http/client/params/ClientParamBean /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)] public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactoryClassName /// </java-name> [Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactory /// </java-name> [Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleRedirects /// </java-name> [Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setRejectRelativeRedirect /// </java-name> [Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)] public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxRedirects /// </java-name> [Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)] public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */ { } /// <java-name> /// setAllowCircularRedirects /// </java-name> [Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleAuthentication /// </java-name> [Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)] public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */ { } /// <java-name> /// setVirtualHost /// </java-name> [Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHeaders /// </java-name> [Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")] public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHost /// </java-name> [Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } }
43.42615
597
0.669306
[ "Apache-2.0" ]
Dot42Xna/master
Generated/v2.3.3/Org.Apache.Http.Client.Params.cs
17,935
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.EventGrid { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// EventSubscriptionsOperations operations. /// </summary> public partial interface IEventSubscriptionsOperations { /// <summary> /// Get an event subscription /// </summary> /// <remarks> /// Get properties of an event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> GetWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update an event subscription /// </summary> /// <remarks> /// Asynchronously creates a new event subscription or updates an /// existing event subscription based on the specified scope. /// </remarks> /// <param name='scope'> /// The identifier of the resource to which the event subscription /// needs to be created or updated. The scope can be a subscription, or /// a resource group, or a top level resource belonging to a resource /// provider namespace, or an EventGrid topic. For example, use /// '/subscriptions/{subscriptionId}/' for a subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription. Event subscription names must be /// between 3 and 64 characters in length and should use alphanumeric /// letters only. /// </param> /// <param name='eventSubscriptionInfo'> /// Event subscription properties containing the destination and filter /// information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> CreateOrUpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscription eventSubscriptionInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an event subscription /// </summary> /// <remarks> /// Delete an existing event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an event subscription /// </summary> /// <remarks> /// Asynchronously updates an existing event subscription. /// </remarks> /// <param name='scope'> /// The scope of existing event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be updated /// </param> /// <param name='eventSubscriptionUpdateParameters'> /// Updated event subscription information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> UpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get full URL of an event subscription /// </summary> /// <remarks> /// Get the full endpoint URL for an event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscriptionFullUrl>> GetFullUrlWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an aggregated list of all global event subscriptions under an /// Azure subscription /// </summary> /// <remarks> /// List all aggregated global event subscriptions under a specific /// Azure subscription /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions for a topic type /// </summary> /// <remarks> /// List all global event subscriptions under an Azure subscription for /// a topic type. /// </remarks> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalBySubscriptionForTopicTypeWithHttpMessagesAsync(string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions under an Azure subscription and /// resource group /// </summary> /// <remarks> /// List all global event subscriptions under a specific Azure /// subscription and resource group /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions under a resource group for a /// topic type /// </summary> /// <remarks> /// List all global event subscriptions under a resource group for a /// specific topic type. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalByResourceGroupForTopicTypeWithHttpMessagesAsync(string resourceGroupName, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription /// </remarks> /// <param name='location'> /// Name of the location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalBySubscriptionWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// and resource group /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and resource group /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='location'> /// Name of the location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// for a topic type /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and topic type. /// </remarks> /// <param name='location'> /// Name of the location /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalBySubscriptionForTopicTypeWithHttpMessagesAsync(string location, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// and resource group for a topic type /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and resource group and topic type /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='location'> /// Name of the location /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalByResourceGroupForTopicTypeWithHttpMessagesAsync(string resourceGroupName, string location, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all event subscriptions for a specific topic /// </summary> /// <remarks> /// List all event subscriptions that have been created for a specific /// topic /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='providerNamespace'> /// Namespace of the provider of the topic /// </param> /// <param name='resourceTypeName'> /// Name of the resource type /// </param> /// <param name='resourceName'> /// Name of the resource /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListByResourceWithHttpMessagesAsync(string resourceGroupName, string providerNamespace, string resourceTypeName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update an event subscription /// </summary> /// <remarks> /// Asynchronously creates a new event subscription or updates an /// existing event subscription based on the specified scope. /// </remarks> /// <param name='scope'> /// The identifier of the resource to which the event subscription /// needs to be created or updated. The scope can be a subscription, or /// a resource group, or a top level resource belonging to a resource /// provider namespace, or an EventGrid topic. For example, use /// '/subscriptions/{subscriptionId}/' for a subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription. Event subscription names must be /// between 3 and 64 characters in length and should use alphanumeric /// letters only. /// </param> /// <param name='eventSubscriptionInfo'> /// Event subscription properties containing the destination and filter /// information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> BeginCreateOrUpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscription eventSubscriptionInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an event subscription /// </summary> /// <remarks> /// Delete an existing event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an event subscription /// </summary> /// <remarks> /// Asynchronously updates an existing event subscription. /// </remarks> /// <param name='scope'> /// The scope of existing event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be updated /// </param> /// <param name='eventSubscriptionUpdateParameters'> /// Updated event subscription information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> BeginUpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
52.023064
324
0.636741
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SDKs/EventGrid/management/Management.EventGrid/Generated/IEventSubscriptionsOperations.cs
31,578
C#