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 |
|---|---|---|---|---|---|---|---|---|
namespace SparkPostFun.Accounts
{
public record RetrieveSubaccountsSummaryResponseResult
{
public int? Total { get; init; }
}
} | 21.142857 | 58 | 0.689189 | [
"Apache-2.0"
] | jmojiwat/SparkPostFun | src/SparkPostFun/Accounts/RetrieveSubaccountsSummaryResponseResult.cs | 150 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Batch;
using Microsoft.Azure.Commands.Batch.Models;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System.Management.Automation;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;
namespace Microsoft.Azure.Commands.Batch
{
[GenericBreakingChange("Get-AzBatchJobStatistics alias will be removed in an upcoming breaking change release", "2.0.0")]
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzurePrefix + "BatchJobStatistic"), OutputType(typeof(PSJobStatistics))]
[Alias("Get-AzBatchJobStatistics")]
public class GetBatchJobStatisticCommand : BatchObjectModelCmdletBase
{
public override void ExecuteCmdlet()
{
PSJobStatistics jobStatistics = BatchClient.GetAllJobsLifetimeStatistics(this.BatchContext, this.AdditionalBehaviors);
WriteObject(jobStatistics);
}
}
}
| 48.457143 | 132 | 0.672759 | [
"MIT"
] | AladdinBI/azure-powershell | src/Batch/Batch/Jobs/GetBatchJobStatisticCommand.cs | 1,664 | C# |
namespace Forum.App.Models.Commands
{
using Forum.App.Contracts;
public class CategoriesMenuCommand : ICommand
{
private IMenuFactory menuFactory;
public CategoriesMenuCommand(IMenuFactory menuFactory)
{
this.menuFactory = menuFactory;
}
public IMenu Execute(params string[] args)
{
string commandName = this.GetType().Name;
string menuName = commandName.Substring(0, commandName.Length - "Command".Length);
IMenu menu = this.menuFactory.CreateMenu(menuName);
return menu;
}
}
} | 26.73913 | 94 | 0.621138 | [
"MIT"
] | MustafaAmish/All-Curses-in-SoftUni | 05. C# OOP Advanced/15. Workshop/Forum.App/Models/Commands/CategoriesMenuCommand.cs | 617 | C# |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkix;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Tests
{
[TestFixture]
public class CertPathTest
: SimpleTest
{
internal static readonly byte[] rootCertBin = Base64.Decode(
"MIIBqzCCARQCAQEwDQYJKoZIhvcNAQEFBQAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZTAeFw0wODA5MDQwNDQ1MDhaFw0wODA5MTEwNDQ1MDhaMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMRLUjhPe4YUdLo6EcjKcWUOG7CydFTH53Pr1lWjOkbmszYDpkhCTT9LOsI+disk18nkBxSl8DAHTqV+VxtuTPt64iyi10YxyDeep+DwZG/f8cVQv97U3hA9cLurZ2CofkMLGr6JpSGCMZ9FcstcTdHB4lbErIJ54YqfF4pNOs4/AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAgyrTEFY7ALpeY59jL6xFOLpuPqoBOWrUWv6O+zy5BCU0qiX71r3BpigtxRj+DYcfLIM9FNERDoHu3TthD3nwYWUBtFX8N0QUJIdJabxqAMhLjSC744koiFpCYse5Ye3ZvEdFwDzgAQsJTp5eFGgTZPkPzcdhkFJ2p9+OWs+cb24=");
internal static readonly byte[] interCertBin = Base64.Decode(
"MIICSzCCAbSgAwIBAgIBATANBgkqhkiG9w0BAQUFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlMB4XDTA4MDkwNDA0NDUwOFoXDTA4MDkxMTA0NDUwOFowKDEmMCQGA1UEAxMdVGVzdCBJbnRlcm1lZGlhdGUgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAISS9OOZ2wxzdWny9aVvk4Joq+dwSJ+oqvHUxX3PflZyuiLiCBUOUE4q59dGKdtNX5fIfwyK3cpV0e73Y/0fwfM3m9rOWFrCKOhfeswNTes0w/2PqPVVDDsF/nj7NApuqXwioeQlgTL251RDF4sVoxXqAU7lRkcqwZt3mwqS4KTJAgMBAAGjgY4wgYswRgYDVR0jBD8wPYAUhv8BOT27EB9JaCccJD4YASPP5XWhIqQgMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGWCAQEwHQYDVR0OBBYEFL/IwAGOkHzaQyPZegy79CwM5oTFMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4GBAE4TRgUz4sUvZyVdZxqV+XyNRnqXAeLOOqFGYv2D96tQrS+zjd0elVlT6lFrtchZdOmmX7R6/H/tjMWMcTBICZyRYrvK8cCAmDOI+EIdq5p6lj2Oq6Pbw/wruojAqNrpaR6IkwNpWtdOSSupv4IJL+YU9q2YFTh4R1j3tOkPoFGr");
internal static readonly byte[] finalCertBin = Base64.Decode(
"MIICRjCCAa+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAoMSYwJAYDVQQDEx1UZXN0IEludGVybWVkaWF0ZSBDZXJ0aWZpY2F0ZTAeFw0wODA5MDQwNDQ1MDhaFw0wODA5MTEwNDQ1MDhaMB8xHTAbBgNVBAMTFFRlc3QgRW5kIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChpUeo0tPYywWKiLlbWKNJBcCpSaLSlaZ+4+yer1AxI5yJIVHP6SAlBghlbD5Qne5ImnN/15cz1xwYAiul6vGKJkVPlFEe2Mr+g/J/WJPQQPsjbZ1G+vxbAwXEDA4KaQrnpjRZFq+CdKHwOjuPLYS/MYQNgdIvDVEQcTbPQ8GaiQIDAQABo4GIMIGFMEYGA1UdIwQ/MD2AFL/IwAGOkHzaQyPZegy79CwM5oTFoSKkIDAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlggEBMB0GA1UdDgQWBBSVkw+VpqBf3zsLc/9GdkK9TzHPwDAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQBLv/0bVDjzTs/y1vN3FUiZNknEbzupIZduTuXJjqv/vBX+LDPjUfu/+iOCXOSKoRn6nlOWhwB1z6taG2usQkFG8InMkRcPREi2uVgFdhJ/1C3dAWhsdlubjdL926bftXvxnx/koDzyrePW5U96RlOQM2qLvbaky2Giz6hrc3Wl+w==");
internal static readonly byte[] rootCrlBin = Base64.Decode(
"MIIBYjCBzAIBATANBgkqhkiG9w0BAQsFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlFw0wODA5MDQwNDQ1MDhaFw0wODA5MDQwNzMxNDhaMCIwIAIBAhcNMDgwOTA0MDQ0NTA4WjAMMAoGA1UdFQQDCgEJoFYwVDBGBgNVHSMEPzA9gBSG/wE5PbsQH0loJxwkPhgBI8/ldaEipCAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZYIBATAKBgNVHRQEAwIBATANBgkqhkiG9w0BAQsFAAOBgQCAbaFCo0BNG4AktVf6jjBLeawP1u0ELYkOCEGvYZE0mBpQ+OvFg7subZ6r3lRIj030nUli28sPFtu5ZQMBNcpE4nS1ziF44RfT3Lp5UgHx9x17Krz781iEyV+7zU8YxYMY9wULD+DCuK294kGKIssVNbmTYXZatBNoXQN5CLIocA==");
internal static readonly byte[] interCrlBin = Base64.Decode(
"MIIBbDCB1gIBATANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQDEx1UZXN0IEludGVybWVkaWF0ZSBDZXJ0aWZpY2F0ZRcNMDgwOTA0MDQ0NTA4WhcNMDgwOTA0MDczMTQ4WjAiMCACAQIXDTA4MDkwNDA0NDUwOFowDDAKBgNVHRUEAwoBCaBWMFQwRgYDVR0jBD8wPYAUv8jAAY6QfNpDI9l6DLv0LAzmhMWhIqQgMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGWCAQEwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQADgYEAEVCr5TKs5yguGgLH+dBzmSPoeSIWJFLsgWwJEit/iUDJH3dgYmaczOcGxIDtbYYHLWIHM+P2YRyQz3MEkCXEgm/cx4y7leAmux5l+xQWgmxFPz+197vaphPeCZo+B7V1CWtm518gcq4mrs9ovfgNqgyFj7KGjcBpWdJE32KMt50=");
/*
* certpath with a circular reference
*/
internal static readonly byte[] certA = Base64.Decode(
"MIIC6jCCAlOgAwIBAgIBBTANBgkqhkiG9w0BAQUFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIzMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ2NTda"
+ "Fw0xNzAzMzAwODQ0MDBaMIGlMScwJQYDVQQDHh4AQQByAG0AaQBuACAASADkAGIA"
+ "ZQByAGwAaQBuAGcxCzAJBgNVBAYTAkNIMQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNV"
+ "BAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNwaGVyZSBBRzEQMA4GA1UECxMHVGVzdGlu"
+ "ZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5AcHJpdmFzcGhlcmUuY29tMIGfMA0GCSqG"
+ "SIb3DQEBAQUAA4GNADCBiQKBgQCfHfyVs5dbxG35H/Thd29qR4NZU88taCu/OWA1"
+ "GdACI02lXWYpmLWiDgnU0ULP+GG8OnVp1IES9fz2zcrXKQ19xZzsen/To3h5sNte"
+ "cJpS00XMM24q/jDwy5NvkBP9YIfFKQ1E/0hFHXcqwlw+b/y/v6YGsZCU2h6QDzc4"
+ "5m0+BwIDAQABo0AwPjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIE8DAeBglg"
+ "hkgBhvhCAQ0EERYPeGNhIGNlcnRpZmljYXRlMA0GCSqGSIb3DQEBBQUAA4GBAJEu"
+ "KiSfIwsY7SfobMLrv2v/BtLhGLi4RnmjiwzBhuv5rn4rRfBpq1ppmqQMJ2pmA67v"
+ "UWCY+mNwuyjHyivpCCyJGsZ9d5H09g2vqxzkDBMz7X9VNMZYFH8j/R3/Cfvqks31"
+ "z0OFslJkeKLa1I0P/dfVHsRKNkLRT3Ws5LKksErQ");
internal static readonly byte[] certB = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBBDANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIyMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ2Mzha"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjMxCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxCXIB"
+ "QRnmVvl2h7Q+0SsRxDLnyM1dJG9jMa+UCCmHy0k/ZHs5VirSbjEJSjkQ9BGeh9SC"
+ "7JwbMpXO7UE+gcVc2RnWUY+MA+fWIeTV4KtkYA8WPu8wVGCXbN8wwh/StOocszxb"
+ "g+iLvGeh8CYSRqg6QN3S/02etH3o8H4e7Z0PZwIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCtWdirSsmt"
+ "+CBBCNn6ZnbU3QqQfiiQIomjenNEHESJgaS/+PvPE5i3xWFXsunTHLW321/Km16I"
+ "7+ZvT8Su1cqHg79NAT8QB0yke1saKSy2C0Pic4HwrNqVBWFNSxMU0hQzpx/ZXDbZ"
+ "DqIXAp5EfyRYBy2ul+jm6Rot6aFgzuopKg==");
internal static readonly byte[] certC = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBAjANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIxMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ0Mzla"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjIxCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0rLr6"
+ "f2/ONeJzTb0q9M/NNX+MnAFMSqiQGVBkT76u5nOH4KLkpHXkzI82JI7GuQMzoT3a"
+ "+RP1hO6FneO92ms2soC6xiOFb4EC69Dfhh87Nww5O35JxVF0bzmbmIAWd6P/7zGh"
+ "nd2S4tKkaZcubps+C0j9Fgi0hipVicAOUVVoDQIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCLPvc1IMA4"
+ "YP+PmnEldyUoRWRnvPWjBGeu0WheBP7fdcnGBf93Nmc5j68ZN+eTZ5VMuZ99YdvH"
+ "CXGNX6oodONLU//LlFKdLl5xjLAS5X9p1RbOEGytnalqeiEpjk4+C/7rIBG1kllO"
+ "dItmI6LlEMV09Hkpg6ZRAUmRkb8KrM4X7A==");
internal static readonly byte[] certD = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBBjANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIzMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ5NTNa"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjExCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCae3TP"
+ "jIVKeASqvNabaiUHAMGUgFxB7L0yUsIj39azLcLtUj4S7XkDf7SMGtYV0JY1XNaQ"
+ "sHJAsnJivDZc50oiYvqDYfgFZx5+AsN5l5X5rjRzs/OX+Jo+k1OgsIyu6+mf9Kfb"
+ "5IdWOVB2EcOg4f9tPjLM8CIj9Pp7RbKLyqUUgwIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCgr9kUdWUT"
+ "Lt9UcztSzR3pnHRsyvS0E/z850OKQKS5/VxLEalpFvhj+3EcZ7Y6mFxaaS2B7vXg"
+ "2YWyqV1PRb6iF7/u9EXkpSTKGrJahwANirCa3V/HTUuPdCE2GITlnWI8h3eVA+xQ"
+ "D4LF0PXHOkXbwmhXRSb10lW1bSGkUxE9jg==");
private void doTestExceptions()
{
byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 };
// MyCertPath mc = new MyCertPath(enc);
MemoryStream os = new MemoryStream();
MemoryStream ins;
byte[] arr;
// TODO Support serialization of cert paths?
// ObjectOutputStream oos = new ObjectOutputStream(os);
// oos.WriteObject(mc);
// oos.Flush();
// oos.Close();
try
{
// CertificateFactory cFac = CertificateFactory.GetInstance("X.509");
arr = os.ToArray();
ins = new MemoryStream(arr, false);
// cFac.generateCertPath(ins);
new PkixCertPath(ins);
}
catch (CertificateException)
{
// ignore okay
}
// CertificateFactory cf = CertificateFactory.GetInstance("X.509");
X509CertificateParser cf = new X509CertificateParser();
IList certCol = new ArrayList();
certCol.Add(cf.ReadCertificate(certA));
certCol.Add(cf.ReadCertificate(certB));
certCol.Add(cf.ReadCertificate(certC));
certCol.Add(cf.ReadCertificate(certD));
// CertPathBuilder pathBuilder = CertPathBuilder.GetInstance("PKIX");
PkixCertPathBuilder pathBuilder = new PkixCertPathBuilder();
X509CertStoreSelector select = new X509CertStoreSelector();
select.Subject = ((X509Certificate)certCol[0]).SubjectDN;
ISet trustanchors = new HashSet();
trustanchors.Add(new TrustAnchor(cf.ReadCertificate(rootCertBin), null));
// CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));
IX509Store x509CertStore = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certCol));
PkixBuilderParameters parameters = new PkixBuilderParameters(trustanchors, select);
parameters.AddStore(x509CertStore);
try
{
PkixCertPathBuilderResult result = pathBuilder.Build(parameters);
PkixCertPath path = result.CertPath;
Fail("found cert path in circular set");
}
catch (PkixCertPathBuilderException)
{
// expected
}
}
public override void PerformTest()
{
X509CertificateParser cf = new X509CertificateParser();
X509Certificate rootCert = cf.ReadCertificate(rootCertBin);
X509Certificate interCert = cf.ReadCertificate(interCertBin);
X509Certificate finalCert = cf.ReadCertificate(finalCertBin);
//Testing CertPath generation from List
IList list = new ArrayList();
list.Add(interCert);
// CertPath certPath1 = cf.generateCertPath(list);
PkixCertPath certPath1 = new PkixCertPath(list);
//Testing CertPath encoding as PkiPath
byte[] encoded = certPath1.GetEncoded("PkiPath");
//Testing CertPath generation from InputStream
MemoryStream inStream = new MemoryStream(encoded, false);
// CertPath certPath2 = cf.generateCertPath(inStream, "PkiPath");
PkixCertPath certPath2 = new PkixCertPath(inStream, "PkiPath");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
encoded = certPath1.GetEncoded("PKCS7");
//Testing CertPath generation from InputStream
inStream = new MemoryStream(encoded, false);
// certPath2 = cf.generateCertPath(inStream, "PKCS7");
certPath2 = new PkixCertPath(inStream, "PKCS7");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
encoded = certPath1.GetEncoded("PEM");
//Testing CertPath generation from InputStream
inStream = new MemoryStream(encoded, false);
// certPath2 = cf.generateCertPath(inStream, "PEM");
certPath2 = new PkixCertPath(inStream, "PEM");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
//
// empty list test
//
list = new ArrayList();
// CertPath certPath = CertificateFactory.GetInstance("X.509","BC").generateCertPath(list);
PkixCertPath certPath = new PkixCertPath(list);
if (certPath.Certificates.Count != 0)
{
Fail("list wrong size.");
}
//
// exception tests
//
doTestExceptions();
}
public override string Name
{
get { return "CertPath"; }
}
public static void Main(
string[] args)
{
RunTest(new CertPathTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
// private class MyCertificate : X509Certificate
// {
// private readonly string type;
// private readonly byte[] encoding;
//
// public MyCertificate(string type, byte[] encoding)
//// : base(type)
// {
// this.type = type;
//
// // don't copy to allow null parameter in test
// this.encoding = encoding;
// }
//
// public override byte[] GetEncoded()
// {
// // do copy to force NPE in test
// return (byte[])encoding.Clone();
// }
//
// public override void Verify(AsymmetricKeyParameter publicKey)
// {
// }
//
// public override string ToString()
// {
// return "[My test Certificate, type: " + type + "]";
// }
//
// public override AsymmetricKeyParameter GetPublicKey()
// {
// throw new NotImplementedException();
//
//// return new PublicKey()
//// {
//// public string getAlgorithm()
//// {
//// return "TEST";
//// }
////
//// public byte[] getEncoded()
//// {
//// return new byte[] { (byte)1, (byte)2, (byte)3 };
//// }
////
//// public string getFormat()
//// {
//// return "TEST_FORMAT";
//// }
//// };
// }
// }
// private class MyCertPath : PkixCertPath
// {
// private readonly ArrayList certificates;
//
// private readonly ArrayList encodingNames;
//
// private readonly byte[] encoding;
//
// public MyCertPath(byte[] encoding)
// : base("MyEncoding")
// {
// this.encoding = encoding;
// certificates = new ArrayList();
// certificates.Add(new MyCertificate("MyEncoding", encoding));
// encodingNames = new ArrayList();
// encodingNames.Add("MyEncoding");
// }
//
// public override IList Certificates
// {
// get { return CollectionUtilities.ReadOnly(certificates); }
// }
//
// public override byte[] GetEncoded()
// {
// return (byte[])encoding.Clone();
// }
//
// public override byte[] GetEncoded(
// string encoding)
// {
// if (Type.Equals(encoding))
// {
// return (byte[])this.encoding.Clone();
// }
// throw new CertificateEncodingException("Encoding not supported: "
// + encoding);
// }
//
// public override IEnumerable Encodings
// {
// get { return new EnumerableProxy(encodingNames); }
// }
// }
}
}
| 43.652778 | 796 | 0.764493 | [
"BSD-3-Clause"
] | GaloisInc/hacrypto | src/C#/BouncyCastle/BouncyCastle-1.7/crypto/test/src/test/CertPathTest.cs | 15,715 | C# |
using System.Collections.Generic;
using System.Linq;
namespace EnterpriseWebLibrary.EnterpriseWebFramework {
public interface PageComponent {}
public static class PageComponentExtensionCreators {
/// <summary>
/// Concatenates page components.
/// </summary>
public static IEnumerable<ComponentType> Concat<ComponentType>( this ComponentType first, IEnumerable<ComponentType> second )
where ComponentType: PageComponent =>
second.Prepend( first );
/// <summary>
/// Returns a sequence of two page components.
/// </summary>
public static IEnumerable<ComponentType> Append<ComponentType>( this ComponentType first, ComponentType second ) where ComponentType: PageComponent =>
Enumerable.Empty<ComponentType>().Append( first ).Append( second );
}
} | 38 | 153 | 0.743108 | [
"MIT"
] | enduracode/enterprise-web-library | Core/EnterpriseWebFramework/Page Infrastructure/Page Structure/Components/PageComponent.cs | 800 | C# |
using Accord.Bot.Infrastructure;
using Microsoft.Extensions.Options;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Objects;
namespace Accord.Bot.Helpers;
public class DiscordAvatarHelper
{
private readonly DiscordConfiguration _discordConfiguration;
public DiscordAvatarHelper(IOptions<DiscordConfiguration> discordConfiguration)
{
_discordConfiguration = discordConfiguration.Value;
}
public EmbedThumbnail GetAvatar(IUser user)
{
var url = GetAvatarUrl(user);
return new EmbedThumbnail(url);
}
public string GetAvatarUrl(IUser user)
{
if (user.Avatar is null)
{
var resultModulus = user.Discriminator % 5;
return $"{_discordConfiguration.CdnBaseUrl}/embed/avatars/{resultModulus}.png";
}
var extension = "png";
if (user.Avatar.HasGif)
{
extension = "gif";
}
return $"{_discordConfiguration.CdnBaseUrl}/avatars/{user.ID.Value}/{user.Avatar.Value}.{extension}";
}
} | 26.6 | 109 | 0.673872 | [
"MIT"
] | patrickklaeren/Accord | src/Accord.Bot/Helpers/DiscordAvatarHelper.cs | 1,066 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the secretsmanager-2017-10-17.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SecretsManager.Model
{
/// <summary>
/// This is the response object from the RestoreSecret operation.
/// </summary>
public partial class RestoreSecretResponse : AmazonWebServiceResponse
{
private string _arn;
private string _name;
/// <summary>
/// Gets and sets the property ARN.
/// <para>
/// The ARN of the secret that was restored.
/// </para>
/// </summary>
[AWSProperty(Min=20, Max=2048)]
public string ARN
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if ARN property is set
internal bool IsSetARN()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The friendly name of the secret that was restored.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
} | 27.782051 | 112 | 0.603138 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SecretsManager/Generated/Model/RestoreSecretResponse.cs | 2,167 | C# |
using System;
using System.ComponentModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Helpers;
namespace LivestreamStarter.Presentation.Common
{
public class AsyncRelayCommand : ICommand
{
private readonly BackgroundWorker canExecuteworker;
private readonly WeakAction execute;
private readonly WeakFunc<bool> canExecute;
private bool canExecuteResult;
public AsyncRelayCommand(Action execute, Func<bool> canExecute = null)
{
this.canExecuteResult = false;
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = new WeakAction(execute);
if (canExecute == null)
{
return;
}
this.canExecute = new WeakFunc<bool>(canExecute);
this.canExecuteworker = new BackgroundWorker();
this.canExecuteworker.DoWork += (sender, args) => this.RunCanExecute(args);
this.canExecuteworker.RunWorkerCompleted += (sender, args) => this.RaiseCanExecuteChanged(args);
}
public event EventHandler CanExecuteChanged
{
add
{
if (this.canExecute == null)
{
return;
}
CommandManager.RequerySuggested += value;
}
remove
{
if (this.canExecute == null)
{
return;
}
CommandManager.RequerySuggested -= value;
}
}
public bool CanExecute(object parameter)
{
if (!this.canExecuteworker.IsBusy)
{
this.canExecuteworker.RunWorkerAsync();
}
return this.canExecuteResult;
}
public void Execute(object parameter)
{
if (!this.CanExecute(parameter) || this.execute == null || !this.execute.IsStatic && !this.execute.IsAlive)
{
return;
}
this.execute.Execute();
}
private void RaiseCanExecuteChanged(RunWorkerCompletedEventArgs args)
{
if ((bool)args.Result == this.canExecuteResult)
{
return;
}
this.canExecuteResult = (bool)args.Result;
CommandManager.InvalidateRequerySuggested();
}
private void RunCanExecute(DoWorkEventArgs args)
{
if (this.canExecute == null)
{
args.Result = true;
return;
}
if (this.canExecute.IsStatic || this.canExecute.IsAlive)
{
args.Result = this.canExecute.Execute();
return;
}
args.Result = false;
}
}
} | 25.964286 | 119 | 0.514443 | [
"MIT"
] | prayzzz/LivestreamStarter | LivestreamStarter.Presentation/Common/AsyncRelayCommand.cs | 2,910 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Generic.Tests
{
public abstract partial class ComparersGenericTests<T>
{
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Missing https://github.com/dotnet/coreclr/pull/4340")]
[Fact]
public void EqualityComparer_EqualityComparerDefault()
{
var firstResult = EqualityComparer<T>.Default;
Assert.NotNull(firstResult);
Assert.Same(firstResult, EqualityComparer<T>.Default);
}
[Fact]
public void EqualityComparer_EqualsShouldBeOverriddenAndWorkForDifferentInstances()
{
var comparer = EqualityComparer<T>.Default;
// Whether the comparer has overridden Object.Equals or not, all of these
// comparisons should be false
Assert.False(comparer.Equals(null));
Assert.False(comparer.Equals(3));
Assert.False(comparer.Equals("foo"));
Assert.False(comparer.Equals(EqualityComparer<Task<T>>.Default));
}
[Fact]
public void EqualityComparer_EqualsShouldBeOverriddenAndWorkForDifferentInstances_cloned()
{
var comparer = EqualityComparer<T>.Default;
var cloned = ObjectCloner.MemberwiseClone(comparer); // calls MemberwiseClone() on the comparer via reflection, which returns a different instance
// Whatever the type of the comparer, it should have overridden Equals(object) so
// it can return true as long as the other object is the same type (not nec. the same instance)
Assert.True(cloned.Equals(comparer));
Assert.True(comparer.Equals(cloned));
// Equals() should not return true for null
// Prevent a faulty implementation like Equals(obj) => obj is FooEqualityComparer<T>, which will be true for null
Assert.False(cloned.Equals(null));
}
[Fact]
public void EqualityComparer_GetHashCodeShouldBeOverriddenAndBeTheSameAsLongAsTheTypeIsTheSame()
{
var comparer = EqualityComparer<T>.Default;
// Multiple invocations should return the same result,
// whether GetHashCode() was overridden or not
Assert.Equal(comparer.GetHashCode(), comparer.GetHashCode());
}
[Fact]
public void EqualityComparer_GetHashCodeShouldBeOverriddenAndBeTheSameAsLongAsTheTypeIsTheSame_cloned()
{
var comparer = EqualityComparer<T>.Default;
var cloned = ObjectCloner.MemberwiseClone(comparer);
Assert.Equal(cloned.GetHashCode(), cloned.GetHashCode());
// Since comparer and cloned should have the same type, they should have the same hash
Assert.Equal(comparer.GetHashCode(), cloned.GetHashCode());
}
[Fact]
public void EqualityComparer_IEqualityComparerEqualsWithObjectsNotOfMatchingType()
{
// EqualityComparer<T> implements IEqualityComparer for back-compat reasons.
// The explicit implementation of IEqualityComparer.Equals(object, object) should
// throw if the inputs are not reference-equal, both non-null and either of them
// is not of type T.
IEqualityComparer comparer = EqualityComparer<T>.Default;
Task<T> notOfTypeT = Task.FromResult(default(T));
Assert.True(comparer.Equals(default(T), default(T))); // This should not throw since both inputs will either be null or Ts.
Assert.True(comparer.Equals(notOfTypeT, notOfTypeT)); // This should not throw since the inputs are reference-equal.
// Null inputs should never raise an exception.
Assert.Equal(default(T) == null, comparer.Equals(default(T), null));
Assert.Equal(default(T) == null, comparer.Equals(null, default(T)));
Assert.True(comparer.Equals(null, null));
if (default(T) != null) // if default(T) is null this assert will fail as IEqualityComparer.Equals returns early if either input is null
{
AssertExtensions.Throws<ArgumentException>(null, () => comparer.Equals(notOfTypeT, default(T))); // lhs is the problem
AssertExtensions.Throws<ArgumentException>(null, () => comparer.Equals(default(T), notOfTypeT)); // rhs is the problem
}
if (!(notOfTypeT is T)) // catch cases where Task<T> actually is a T, like object or non-generic Task
{
AssertExtensions.Throws<ArgumentException>(null, () => comparer.Equals(notOfTypeT, Task.FromResult(default(T))));
}
}
[Fact]
public void EqualityComparer_IEqualityComparerGetHashCodeWithObjectNotOfMatchingType()
{
// IEqualityComparer.GetHashCode explicit implementation should
// first return 0 if null, then check for T, then throw an ArgumentException.
IEqualityComparer comparer = EqualityComparer<T>.Default;
Task<T> notOfTypeT = Task.FromResult(default(T));
Assert.Equal(0, comparer.GetHashCode(null));
Assert.Equal(comparer.GetHashCode(default(T)), comparer.GetHashCode(default(T)));
if (!(notOfTypeT is T))
{
AssertExtensions.Throws<ArgumentException>(null, () => comparer.GetHashCode(notOfTypeT));
}
}
}
}
| 47.25 | 158 | 0.653968 | [
"MIT"
] | 2E0PGS/corefx | src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Tests.cs | 5,670 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media.Imaging;
using IOPath = System.IO.Path;
using System.IO;
namespace ClipSynth
{
class CheckBoxContent : StackPanel
{
public CheckBox CheckBox;
public Label Label;
public String Path;
public Image Thumbnail;
public TextBox StartTextBox;
public TextBox EndTextBox;
public Label UniqueIdLabel;
public string Content
{
get
{
return (String)Label.Content;
}
set
{
Label.Content = value;
}
}
public UInt32 UniqueId
{
get
{
return (UInt32)UniqueIdLabel.Content;
}
set
{
UniqueIdLabel.Content = value;
}
}
public int Start
{
get
{
int result;
if (int.TryParse(StartTextBox.Text, out result))
{
return result;
}
return 1;
}
set
{
StartTextBox.Text = value.ToString();
}
}
public int End
{
get
{
int result;
if (int.TryParse(EndTextBox.Text, out result))
{
return result;
}
return 1;
}
set
{
EndTextBox.Text = value.ToString();
}
}
public CheckBoxContent(String path, String content, RoutedEventHandler checkBoxHandler)
{
Path = path;
Orientation = Orientation.Horizontal;
CheckBox = new CheckBox();
CheckBox.Margin = new Thickness(0, 2, 0, 2);
CheckBox.Content = null;
CheckBox.IsChecked = false;
CheckBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
CheckBox.Checked += checkBoxHandler;
CheckBox.Unchecked += checkBoxHandler;
CheckBox.Indeterminate += checkBoxHandler;
Label = new Label();
Label.Padding = new Thickness(2, 0, 0, 0);
Label.Margin = new Thickness(0, 0, 0, 2);
Label.VerticalAlignment = System.Windows.VerticalAlignment.Center;
Content = content;
Children.Add(CheckBox);
Children.Add(Label);
}
public CheckBoxContent(String path, String content, RoutedEventHandler checkBoxHandler, string thumbnail, int start, int end, UInt32 uniqueId)
: this(path, content, checkBoxHandler)
{
UniqueIdLabel = new Label();
UniqueIdLabel.Padding = new Thickness(0, 0, 0, 0);
UniqueIdLabel.Margin = new Thickness(4, 0, 0, 4);
UniqueIdLabel.VerticalAlignment = System.Windows.VerticalAlignment.Center;
UniqueId = uniqueId;
Thumbnail = new Image();
Thumbnail.Margin = new Thickness(2, 0, 0, 2);
Thumbnail.Width = 128;
Thumbnail.VerticalAlignment = System.Windows.VerticalAlignment.Center;
if (!String.IsNullOrEmpty(thumbnail) && File.Exists(thumbnail))
{
Thumbnail.Source = new BitmapImage(new Uri(thumbnail));
}
StartTextBox = new TextBox();
StartTextBox.Padding = new Thickness(0, 0, 0, 0);
StartTextBox.Margin = new Thickness(2, 0, 0, 2);
StartTextBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
Start = start;
EndTextBox = new TextBox();
EndTextBox.Padding = new Thickness(0, 0, 0, 0);
EndTextBox.Margin = new Thickness(2, 0, 0, 2);
EndTextBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
End = end;
Children.Insert(1, EndTextBox);
Children.Insert(1, StartTextBox);
Children.Insert(1, Thumbnail);
Children.Insert(1, UniqueIdLabel);
}
}
}
| 29.458904 | 150 | 0.524529 | [
"MIT"
] | greymind/ClipSynth | ClipSynth/CheckBoxContent.cs | 4,303 | C# |
using Memberships.Models;
using Memberships.Models.Core;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Memberships.Areas.Admin.Controllers
{
public class ItemController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Admin/Item
public async Task<ActionResult> Index()
{
return View(await db.Items.ToListAsync());
}
// GET: Admin/Item/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Item item = await db.Items.FindAsync(id);
if (item == null)
{
return HttpNotFound();
}
return View(item);
}
// GET: Admin/Item/Create
public ActionResult Create()
{
var model = new Item
{
ItemTypes = db.ItemTypes.ToList(),
Parts = db.Parts.ToList(),
Sections = db.Sections.ToList()
};
return View(model);
}
// POST: Admin/Item/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Title,Description,Url,ImageUrl,HTML,WaitDays,ProductId,ItemTypeId,SectionId,PartId,IsFree")] Item item)
{
if (ModelState.IsValid)
{
db.Items.Add(item);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(item);
}
// GET: Admin/Item/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Item item = await db.Items.FindAsync(id);
if (item == null)
{
return HttpNotFound();
}
item.ItemTypes = await db.ItemTypes.ToListAsync();
item.Parts = await db.Parts.ToListAsync();
item.Sections = await db.Sections.ToListAsync();
return View(item);
}
// POST: Admin/Item/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,Title,Description,Url,ImageUrl,HTML,WaitDays,ProductId,ItemTypeId,SectionId,PartId,IsFree")] Item item)
{
if (ModelState.IsValid)
{
db.Entry(item).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(item);
}
// GET: Admin/Item/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Item item = await db.Items.FindAsync(id);
if (item == null)
{
return HttpNotFound();
}
return View(item);
}
// POST: Admin/Item/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Item item = await db.Items.FindAsync(id);
db.Items.Remove(item);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 30.361702 | 170 | 0.538659 | [
"MIT"
] | jessepatricio/Memberships | Memberships/Areas/Admin/Controllers/ItemController.cs | 4,283 | C# |
namespace RayCarrot.BizHawk.R1Tool
{
// Anything which is not 1-4 will toggle PLACE_RAY. The game sets the mode to 0 when exiting a level. When PLACE_RAY is toggled in-game it inverts the value (so 1 would become -1 and then back to 1, preserving the previous mode)
public enum R1_RayMode : short
{
PLACE_RAY = -1,
None = 0,
RAYMAN = 1,
RAY_ON_MS = 2,
MORT_DE_RAY_0 = 3,
MORT_DE_RAY_1 = 4,
}
} | 35.230769 | 232 | 0.637555 | [
"MIT"
] | RayCarrot/RayCarrot.BizHawk.R1Tool | src/DataTypes/R1/R1_RayMode.cs | 460 | 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.
/*=============================================================================
**
**
**
** Purpose: Exception class for invalid array indices.
**
**
=============================================================================*/
using System.Runtime.Serialization;
namespace System
{
[Serializable]
public sealed class IndexOutOfRangeException : SystemException
{
public IndexOutOfRangeException()
: base(SR.Arg_IndexOutOfRangeException)
{
HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
public IndexOutOfRangeException(String message)
: base(message)
{
HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
public IndexOutOfRangeException(String message, Exception innerException)
: base(message, innerException)
{
HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
internal IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| 29.619048 | 117 | 0.584405 | [
"MIT"
] | guhuro/coreclr | src/mscorlib/src/System/IndexOutOfRangeException.cs | 1,244 | 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.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace SharedTypes
{
[NativeMarshalling(typeof(StringContainerNative))]
public struct StringContainer
{
public string str1;
public string str2;
}
[BlittableType]
public struct StringContainerNative
{
public IntPtr str1;
public IntPtr str2;
public StringContainerNative(StringContainer managed)
{
str1 = Marshal.StringToCoTaskMemUTF8(managed.str1);
str2 = Marshal.StringToCoTaskMemUTF8(managed.str2);
}
public StringContainer ToManaged()
{
return new StringContainer
{
str1 = Marshal.PtrToStringUTF8(str1),
str2 = Marshal.PtrToStringUTF8(str2)
};
}
public void FreeNative()
{
Marshal.FreeCoTaskMem(str1);
Marshal.FreeCoTaskMem(str2);
}
}
public struct DoubleToLongMarshaler
{
public long l;
public DoubleToLongMarshaler(double d)
{
l = MemoryMarshal.Cast<double, long>(MemoryMarshal.CreateSpan(ref d, 1))[0];
}
public double ToManaged() => MemoryMarshal.Cast<long, double>(MemoryMarshal.CreateSpan(ref l, 1))[0];
public long Value
{
get => l;
set => l = value;
}
}
[NativeMarshalling(typeof(BoolStructNative))]
public struct BoolStruct
{
public bool b1;
public bool b2;
public bool b3;
}
[BlittableType]
public struct BoolStructNative
{
public byte b1;
public byte b2;
public byte b3;
public BoolStructNative(BoolStruct bs)
{
b1 = (byte)(bs.b1 ? 1 : 0);
b2 = (byte)(bs.b2 ? 1 : 0);
b3 = (byte)(bs.b3 ? 1 : 0);
}
public BoolStruct ToManaged()
{
return new BoolStruct
{
b1 = b1 != 0,
b2 = b2 != 0,
b3 = b3 != 0
};
}
}
[NativeMarshalling(typeof(IntWrapperMarshaler))]
public class IntWrapper
{
public int i;
public ref int GetPinnableReference() => ref i;
}
public unsafe struct IntWrapperMarshaler
{
public IntWrapperMarshaler(IntWrapper managed)
{
Value = (int*)Marshal.AllocCoTaskMem(sizeof(int));
*Value = managed.i;
}
public int* Value { get; set; }
public IntWrapper ToManaged() => new IntWrapper { i = *Value };
public void FreeNative()
{
Marshal.FreeCoTaskMem((IntPtr)Value);
}
}
public unsafe ref struct Utf16StringMarshaler
{
private ushort* allocated;
private Span<ushort> span;
private bool isNullString;
public Utf16StringMarshaler(string str)
: this(str, default(Span<byte>))
{
}
public Utf16StringMarshaler(string str, Span<byte> buffer)
{
isNullString = false;
if (str is null)
{
allocated = null;
span = default;
isNullString = true;
}
else if ((str.Length + 1) < buffer.Length)
{
span = MemoryMarshal.Cast<byte, ushort>(buffer);
str.AsSpan().CopyTo(MemoryMarshal.Cast<byte, char>(buffer));
// Supplied memory is in an undefined state so ensure
// there is a trailing null in the buffer.
span[str.Length] = '\0';
allocated = null;
}
else
{
allocated = (ushort*)Marshal.StringToCoTaskMemUni(str);
span = new Span<ushort>(allocated, str.Length + 1);
}
}
public ref ushort GetPinnableReference()
{
return ref span.GetPinnableReference();
}
public ushort* Value
{
get
{
return (ushort*)Unsafe.AsPointer(ref GetPinnableReference());
}
set
{
allocated = value;
span = new Span<ushort>(value, value == null ? 0 : FindStringLength(value));
isNullString = value == null;
static int FindStringLength(ushort* ptr)
{
// Implemented similarly to string.wcslen as we can't access that outside of CoreLib
var searchSpace = new Span<ushort>(ptr, int.MaxValue);
return searchSpace.IndexOf((ushort)0);
}
}
}
public string ToManaged()
{
return isNullString ? null : MemoryMarshal.Cast<ushort, char>(span).ToString();
}
public void FreeNative()
{
Marshal.FreeCoTaskMem((IntPtr)allocated);
}
public const int StackBufferSize = 0x100;
}
[NativeMarshalling(typeof(IntStructWrapperNative))]
public struct IntStructWrapper
{
public int Value;
}
public struct IntStructWrapperNative
{
public int value;
public IntStructWrapperNative(IntStructWrapper managed)
{
value = managed.Value;
}
public IntStructWrapper ToManaged() => new IntStructWrapper { Value = value };
}
[GenericContiguousCollectionMarshaller]
public unsafe ref struct ListMarshaller<T>
{
private List<T> managedList;
private readonly int sizeOfNativeElement;
private IntPtr allocatedMemory;
public ListMarshaller(int sizeOfNativeElement)
: this()
{
this.sizeOfNativeElement = sizeOfNativeElement;
}
public ListMarshaller(List<T> managed, int sizeOfNativeElement)
:this(managed, Span<byte>.Empty, sizeOfNativeElement)
{
}
public ListMarshaller(List<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
{
allocatedMemory = default;
this.sizeOfNativeElement = sizeOfNativeElement;
if (managed is null)
{
managedList = null;
NativeValueStorage = default;
return;
}
managedList = managed;
// Always allocate at least one byte when the list is zero-length.
int spaceToAllocate = Math.Max(managed.Count * sizeOfNativeElement, 1);
if (spaceToAllocate <= stackSpace.Length)
{
NativeValueStorage = stackSpace[0..spaceToAllocate];
}
else
{
allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
NativeValueStorage = new Span<byte>((void*)allocatedMemory, spaceToAllocate);
}
}
/// <summary>
/// Stack-alloc threshold set to 256 bytes to enable small arrays to be passed on the stack.
/// Number kept small to ensure that P/Invokes with a lot of array parameters doesn't
/// blow the stack since this is a new optimization in the code-generated interop.
/// </summary>
public const int StackBufferSize = 0x200;
public Span<T> ManagedValues => CollectionsMarshal.AsSpan(managedList);
public Span<byte> NativeValueStorage { get; private set; }
public ref byte GetPinnableReference() => ref NativeValueStorage.GetPinnableReference();
public void SetUnmarshalledCollectionLength(int length)
{
managedList = new List<T>(length);
for (int i = 0; i < length; i++)
{
managedList.Add(default);
}
}
public byte* Value
{
get
{
return (byte*)Unsafe.AsPointer(ref GetPinnableReference());
}
set
{
if (value == null)
{
managedList = null;
NativeValueStorage = default;
}
else
{
allocatedMemory = (IntPtr)value;
NativeValueStorage = new Span<byte>(value, (managedList?.Count ?? 0) * sizeOfNativeElement);
}
}
}
public List<T> ToManaged() => managedList;
public void FreeNative()
{
Marshal.FreeCoTaskMem(allocatedMemory);
}
}
}
| 28.546926 | 112 | 0.540982 | [
"MIT"
] | AntonLapounov/runtime | src/libraries/System.Runtime.InteropServices/tests/TestAssets/SharedTypes/NonBlittable.cs | 8,821 | C# |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// Includes operations for importing and exporting Azure SQL Databases
/// into and out of Azure blob storage.
/// </summary>
internal partial class DacOperations : IServiceOperations<SqlManagementClient>, IDacOperations
{
/// <summary>
/// Initializes a new instance of the DacOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DacOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Exports an Azure SQL Database into a DACPAC file in Azure Blob
/// Storage.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server in which the
/// database to export resides.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters needed to initiate the export request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response that the service returns once an import or
/// export operation has been initiated.
/// </returns>
public async Task<DacImportExportResponse> ExportAsync(string serverName, DacExportParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters != null)
{
if (parameters.BlobCredentials != null)
{
if (parameters.BlobCredentials.StorageAccessKey == null)
{
throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey");
}
if (parameters.BlobCredentials.Uri == null)
{
throw new ArgumentNullException("parameters.BlobCredentials.Uri");
}
}
if (parameters.ConnectionInfo != null)
{
if (parameters.ConnectionInfo.DatabaseName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName");
}
if (parameters.ConnectionInfo.Password == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.Password");
}
if (parameters.ConnectionInfo.ServerName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.ServerName");
}
if (parameters.ConnectionInfo.UserName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.UserName");
}
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ExportAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/DacOperations/Export";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
if (parameters != null)
{
XElement exportInputElement = new XElement(XName.Get("ExportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
requestDoc.Add(exportInputElement);
if (parameters.BlobCredentials != null)
{
XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
exportInputElement.Add(blobCredentialsElement);
XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), "");
typeAttribute.Value = "BlobStorageAccessKeyCredentials";
blobCredentialsElement.Add(typeAttribute);
XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
uriElement.Value = parameters.BlobCredentials.Uri.AbsoluteUri;
blobCredentialsElement.Add(uriElement);
XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey;
blobCredentialsElement.Add(storageAccessKeyElement);
}
if (parameters.ConnectionInfo != null)
{
XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
exportInputElement.Add(connectionInfoElement);
XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName;
connectionInfoElement.Add(databaseNameElement);
XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
passwordElement.Value = parameters.ConnectionInfo.Password;
connectionInfoElement.Add(passwordElement);
XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
serverNameElement.Value = parameters.ConnectionInfo.ServerName;
connectionInfoElement.Add(serverNameElement);
XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
userNameElement.Value = parameters.ConnectionInfo.UserName;
connectionInfoElement.Add(userNameElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DacImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DacImportExportResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/"));
if (guidElement != null)
{
result.Guid = guidElement.Value;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of the import or export operation in the specified
/// server with the corresponding request ID. The request ID is
/// provided in the responses of the import or export operation.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the server in which the import or export
/// operation is taking place.
/// </param>
/// <param name='fullyQualifiedServerName'>
/// Required. The fully qualified domain name of the Azure SQL Database
/// Server where the operation is taking place. Example:
/// a9s7f7s9d3.database.windows.net
/// </param>
/// <param name='username'>
/// Required. The administrator username for the Azure SQL Database
/// Server.
/// </param>
/// <param name='password'>
/// Required. The administrator password for the Azure SQL Database
/// Server.
/// </param>
/// <param name='requestId'>
/// Required. The request ID of the operation being queried. The
/// request ID is obtained from the responses of the import and export
/// operations.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents a list of import or export status values returned from
/// GetStatus.
/// </returns>
public async Task<DacGetStatusResponse> GetStatusAsync(string serverName, string fullyQualifiedServerName, string username, string password, string requestId, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (fullyQualifiedServerName == null)
{
throw new ArgumentNullException("fullyQualifiedServerName");
}
if (username == null)
{
throw new ArgumentNullException("username");
}
if (password == null)
{
throw new ArgumentNullException("password");
}
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("fullyQualifiedServerName", fullyQualifiedServerName);
tracingParameters.Add("username", username);
tracingParameters.Add("password", password);
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/DacOperations/Status";
List<string> queryParameters = new List<string>();
queryParameters.Add("servername=" + Uri.EscapeDataString(fullyQualifiedServerName));
queryParameters.Add("username=" + Uri.EscapeDataString(username));
queryParameters.Add("password=" + Uri.EscapeDataString(password));
queryParameters.Add("reqId=" + Uri.EscapeDataString(requestId));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DacGetStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DacGetStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfStatusInfoElement = responseDoc.Element(XName.Get("ArrayOfStatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (arrayOfStatusInfoElement != null)
{
if (arrayOfStatusInfoElement != null)
{
foreach (XElement statusInfoElement in arrayOfStatusInfoElement.Elements(XName.Get("StatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")))
{
StatusInfo statusInfoInstance = new StatusInfo();
result.StatusInfoList.Add(statusInfoInstance);
XElement blobUriElement = statusInfoElement.Element(XName.Get("BlobUri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (blobUriElement != null)
{
Uri blobUriInstance = TypeConversion.TryParseUri(blobUriElement.Value);
statusInfoInstance.BlobUri = blobUriInstance;
}
XElement databaseNameElement = statusInfoElement.Element(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (databaseNameElement != null)
{
string databaseNameInstance = databaseNameElement.Value;
statusInfoInstance.DatabaseName = databaseNameInstance;
}
XElement errorMessageElement = statusInfoElement.Element(XName.Get("ErrorMessage", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (errorMessageElement != null)
{
bool isNil = false;
XAttribute nilAttribute = errorMessageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
string errorMessageInstance = errorMessageElement.Value;
statusInfoInstance.ErrorMessage = errorMessageInstance;
}
}
XElement lastModifiedTimeElement = statusInfoElement.Element(XName.Get("LastModifiedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (lastModifiedTimeElement != null)
{
DateTime lastModifiedTimeInstance = DateTime.Parse(lastModifiedTimeElement.Value, CultureInfo.InvariantCulture);
statusInfoInstance.LastModifiedTime = lastModifiedTimeInstance;
}
XElement queuedTimeElement = statusInfoElement.Element(XName.Get("QueuedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (queuedTimeElement != null)
{
DateTime queuedTimeInstance = DateTime.Parse(queuedTimeElement.Value, CultureInfo.InvariantCulture);
statusInfoInstance.QueuedTime = queuedTimeInstance;
}
XElement requestIdElement = statusInfoElement.Element(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (requestIdElement != null)
{
string requestIdInstance = requestIdElement.Value;
statusInfoInstance.RequestId = requestIdInstance;
}
XElement requestTypeElement = statusInfoElement.Element(XName.Get("RequestType", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (requestTypeElement != null)
{
string requestTypeInstance = requestTypeElement.Value;
statusInfoInstance.RequestType = requestTypeInstance;
}
XElement serverNameElement = statusInfoElement.Element(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (serverNameElement != null)
{
string serverNameInstance = serverNameElement.Value;
statusInfoInstance.ServerName = serverNameInstance;
}
XElement statusElement = statusInfoElement.Element(XName.Get("Status", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (statusElement != null)
{
string statusInstance = statusElement.Value;
statusInfoInstance.Status = statusInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of the import or export operation in the specified
/// server with the corresponding request ID. The request ID is
/// provided in the responses of the import or export operation.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the server in which the import or export
/// operation is taking place.
/// </param>
/// <param name='parameters'>
/// Required. The parameters needed to get the status of an import or
/// export operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents a list of import or export status values returned from
/// GetStatus.
/// </returns>
public async Task<DacGetStatusResponse> GetStatusPostAsync(string serverName, DacGetStatusParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Password == null)
{
throw new ArgumentNullException("parameters.Password");
}
if (parameters.RequestId == null)
{
throw new ArgumentNullException("parameters.RequestId");
}
if (parameters.ServerName == null)
{
throw new ArgumentNullException("parameters.ServerName");
}
if (parameters.UserName == null)
{
throw new ArgumentNullException("parameters.UserName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "GetStatusPostAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/DacOperations/Status";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement statusInputElement = new XElement(XName.Get("StatusInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
requestDoc.Add(statusInputElement);
XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
passwordElement.Value = parameters.Password;
statusInputElement.Add(passwordElement);
XElement requestIdElement = new XElement(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
requestIdElement.Value = parameters.RequestId;
statusInputElement.Add(requestIdElement);
XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
serverNameElement.Value = parameters.ServerName;
statusInputElement.Add(serverNameElement);
XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
userNameElement.Value = parameters.UserName;
statusInputElement.Add(userNameElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DacGetStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DacGetStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfStatusInfoElement = responseDoc.Element(XName.Get("ArrayOfStatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (arrayOfStatusInfoElement != null)
{
if (arrayOfStatusInfoElement != null)
{
foreach (XElement statusInfoElement in arrayOfStatusInfoElement.Elements(XName.Get("StatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")))
{
StatusInfo statusInfoInstance = new StatusInfo();
result.StatusInfoList.Add(statusInfoInstance);
XElement blobUriElement = statusInfoElement.Element(XName.Get("BlobUri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (blobUriElement != null)
{
Uri blobUriInstance = TypeConversion.TryParseUri(blobUriElement.Value);
statusInfoInstance.BlobUri = blobUriInstance;
}
XElement databaseNameElement = statusInfoElement.Element(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (databaseNameElement != null)
{
string databaseNameInstance = databaseNameElement.Value;
statusInfoInstance.DatabaseName = databaseNameInstance;
}
XElement errorMessageElement = statusInfoElement.Element(XName.Get("ErrorMessage", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (errorMessageElement != null)
{
bool isNil = false;
XAttribute nilAttribute = errorMessageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
string errorMessageInstance = errorMessageElement.Value;
statusInfoInstance.ErrorMessage = errorMessageInstance;
}
}
XElement lastModifiedTimeElement = statusInfoElement.Element(XName.Get("LastModifiedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (lastModifiedTimeElement != null)
{
DateTime lastModifiedTimeInstance = DateTime.Parse(lastModifiedTimeElement.Value, CultureInfo.InvariantCulture);
statusInfoInstance.LastModifiedTime = lastModifiedTimeInstance;
}
XElement queuedTimeElement = statusInfoElement.Element(XName.Get("QueuedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (queuedTimeElement != null)
{
DateTime queuedTimeInstance = DateTime.Parse(queuedTimeElement.Value, CultureInfo.InvariantCulture);
statusInfoInstance.QueuedTime = queuedTimeInstance;
}
XElement requestIdElement2 = statusInfoElement.Element(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (requestIdElement2 != null)
{
string requestIdInstance = requestIdElement2.Value;
statusInfoInstance.RequestId = requestIdInstance;
}
XElement requestTypeElement = statusInfoElement.Element(XName.Get("RequestType", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (requestTypeElement != null)
{
string requestTypeInstance = requestTypeElement.Value;
statusInfoInstance.RequestType = requestTypeInstance;
}
XElement serverNameElement2 = statusInfoElement.Element(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (serverNameElement2 != null)
{
string serverNameInstance = serverNameElement2.Value;
statusInfoInstance.ServerName = serverNameInstance;
}
XElement statusElement = statusInfoElement.Element(XName.Get("Status", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
if (statusElement != null)
{
string statusInstance = statusElement.Value;
statusInfoInstance.Status = statusInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Initiates an Import of a DACPAC file from Azure Blob Storage into a
/// Azure SQL Database.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server into which the
/// database is being imported.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters needed to initiated the Import request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response that the service returns once an import or
/// export operation has been initiated.
/// </returns>
public async Task<DacImportExportResponse> ImportAsync(string serverName, DacImportParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters != null)
{
if (parameters.BlobCredentials != null)
{
if (parameters.BlobCredentials.StorageAccessKey == null)
{
throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey");
}
if (parameters.BlobCredentials.Uri == null)
{
throw new ArgumentNullException("parameters.BlobCredentials.Uri");
}
}
if (parameters.ConnectionInfo != null)
{
if (parameters.ConnectionInfo.DatabaseName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName");
}
if (parameters.ConnectionInfo.Password == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.Password");
}
if (parameters.ConnectionInfo.ServerName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.ServerName");
}
if (parameters.ConnectionInfo.UserName == null)
{
throw new ArgumentNullException("parameters.ConnectionInfo.UserName");
}
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ImportAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/DacOperations/Import";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
if (parameters != null)
{
XElement importInputElement = new XElement(XName.Get("ImportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
requestDoc.Add(importInputElement);
if (parameters.AzureEdition != null)
{
XElement azureEditionElement = new XElement(XName.Get("AzureEdition", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
azureEditionElement.Value = parameters.AzureEdition;
importInputElement.Add(azureEditionElement);
}
if (parameters.BlobCredentials != null)
{
XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
importInputElement.Add(blobCredentialsElement);
XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), "");
typeAttribute.Value = "BlobStorageAccessKeyCredentials";
blobCredentialsElement.Add(typeAttribute);
XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
uriElement.Value = parameters.BlobCredentials.Uri.AbsoluteUri;
blobCredentialsElement.Add(uriElement);
XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey;
blobCredentialsElement.Add(storageAccessKeyElement);
}
if (parameters.ConnectionInfo != null)
{
XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
importInputElement.Add(connectionInfoElement);
XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName;
connectionInfoElement.Add(databaseNameElement);
XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
passwordElement.Value = parameters.ConnectionInfo.Password;
connectionInfoElement.Add(passwordElement);
XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
serverNameElement.Value = parameters.ConnectionInfo.ServerName;
connectionInfoElement.Add(serverNameElement);
XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
userNameElement.Value = parameters.ConnectionInfo.UserName;
connectionInfoElement.Add(userNameElement);
}
XElement databaseSizeInGBElement = new XElement(XName.Get("DatabaseSizeInGB", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
databaseSizeInGBElement.Value = parameters.DatabaseSizeInGB.ToString();
importInputElement.Add(databaseSizeInGBElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DacImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DacImportExportResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/"));
if (guidElement != null)
{
result.Guid = guidElement.Value;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| 52.274385 | 221 | 0.504682 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/Sql/SqlManagement/Generated/DacOperations.cs | 57,345 | C# |
//
// This CSharp output file generated by Gardens Point LEX
// Version: 1.1.3.301
// Machine: DESKTOP-MQGTEI6
// DateTime: 21.09.2021 0:15:46
// UserName: Jingle
// GPLEX input file <SimpleLex.lex>
// GPLEX frame file <embedded resource>
//
// Option settings: unicode, parser, minimize
// Option settings: classes, compressMap, compressNext, persistBuffer, embedbuffers
// Fallback code page: Target machine default
//
//
// Experimental embedded frame
// Version 1.1.3 of 18-April-2010
//
//
#define BACKUP
#define PERSIST
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
using SimpleParser;
using QUT.Gppg;
using System.Linq;
namespace SimpleScanner
{
/// <summary>
/// Summary Canonical example of GPLEX automaton
/// </summary>
#if STANDALONE
//
// These are the dummy declarations for stand-alone GPLEX applications
// normally these declarations would come from the parser.
// If you declare /noparser, or %option noparser then you get this.
//
public enum Tokens
{
EOF = 0, maxParseToken = int.MaxValue
// must have at least these two, values are almost arbitrary
}
public abstract class ScanBase
{
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yylex")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yylex")]
public abstract int yylex();
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yywrap")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yywrap")]
protected virtual bool yywrap() { return true; }
#if BABEL
protected abstract int CurrentSc { get; set; }
// EolState is the 32-bit of state data persisted at
// the end of each line for Visual Studio colorization.
// The default is to return CurrentSc. You must override
// this if you want more complicated behavior.
public virtual int EolState {
get { return CurrentSc; }
set { CurrentSc = value; }
}
}
public interface IColorScan
{
void SetSource(string source, int offset);
int GetNext(ref int state, out int start, out int end);
#endif // BABEL
}
#endif // STANDALONE
// If the compiler can't find the scanner base class maybe you
// need to run GPPG with the /gplex option, or GPLEX with /noparser
#if BABEL
public sealed partial class Scanner : ScanBase, IColorScan
{
private ScanBuff buffer;
int currentScOrd; // start condition ordinal
protected override int CurrentSc
{
// The current start state is a property
// to try to avoid the user error of setting
// scState but forgetting to update the FSA
// start state "currentStart"
//
get { return currentScOrd; } // i.e. return YY_START;
set { currentScOrd = value; // i.e. BEGIN(value);
currentStart = startState[value]; }
}
#else // BABEL
public sealed partial class Scanner : ScanBase
{
private ScanBuff buffer;
int currentScOrd; // start condition ordinal
#endif // BABEL
/// <summary>
/// The input buffer for this scanner.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ScanBuff Buffer { get { return buffer; } }
private static int GetMaxParseToken() {
System.Reflection.FieldInfo f = typeof(Tokens).GetField("maxParseToken");
return (f == null ? int.MaxValue : (int)f.GetValue(null));
}
static int parserMax = GetMaxParseToken();
enum Result {accept, noMatch, contextFound};
const int maxAccept = 14;
const int initial = 15;
const int eofNum = 0;
const int goStart = -1;
const int INITIAL = 0;
#region user code
#endregion user code
int state;
int currentStart = startState[0];
int code; // last code read
int cCol; // column number of code
int lNum; // current line number
//
// The following instance variables are used, among other
// things, for constructing the yylloc location objects.
//
int tokPos; // buffer position at start of token
int tokCol; // zero-based column number at start of token
int tokLin; // line number at start of token
int tokEPos; // buffer position at end of token
int tokECol; // column number at end of token
int tokELin; // line number at end of token
string tokTxt; // lazily constructed text of token
#if STACK
private Stack<int> scStack = new Stack<int>();
#endif // STACK
#region ScannerTables
struct Table {
public int min; public int rng; public int dflt;
public sbyte[] nxt;
public Table(int m, int x, int d, sbyte[] n) {
min = m; rng = x; dflt = d; nxt = n;
}
};
static int[] startState = new int[] {15, 0};
#region CompressedCharacterMap
//
// There are 15 equivalence classes
// There are 2 character sequence regions
// There are 1 tables, 123 entries
// There are 1 runs, 0 singletons
// Decision tree depth is 1
//
static sbyte[] mapC0 = new sbyte[123] {
/* '\0' */ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 0, 14, 14,
/* '\x10' */ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
/* '\x20' */ 0, 14, 14, 14, 14, 14, 14, 14, 7, 8, 12, 10, 9, 11, 2, 13,
/* '0' */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 6, 14, 5, 14, 14,
/* '@' */ 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* 'P' */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 3,
/* '`' */ 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* 'p' */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
static sbyte MapC(int code)
{ // '\0' <= code <= '\U0010FFFF'
if (code < 123) // '\0' <= code <= 'z'
return mapC0[code - 0];
else // '{' <= code <= '\U0010FFFF'
return (sbyte)14;
}
#endregion
static Table[] NxS = new Table[17] {
/* NxS[ 0] */ new Table(0, 0, 0, null),
/* NxS[ 1] */ new Table(1, 2, -1, new sbyte[] {1, 16}),
/* NxS[ 2] */ new Table(0, 0, -1, null),
/* NxS[ 3] */ new Table(1, 3, -1, new sbyte[] {3, -1, 3}),
/* NxS[ 4] */ new Table(5, 1, -1, new sbyte[] {13}),
/* NxS[ 5] */ new Table(0, 0, -1, null),
/* NxS[ 6] */ new Table(0, 0, -1, null),
/* NxS[ 7] */ new Table(0, 0, -1, null),
/* NxS[ 8] */ new Table(0, 0, -1, null),
/* NxS[ 9] */ new Table(0, 0, -1, null),
/* NxS[ 10] */ new Table(0, 0, -1, null),
/* NxS[ 11] */ new Table(0, 0, -1, null),
/* NxS[ 12] */ new Table(0, 0, -1, null),
/* NxS[ 13] */ new Table(0, 0, -1, null),
/* NxS[ 14] */ new Table(1, 1, -1, new sbyte[] {14}),
/* NxS[ 15] */ new Table(1, 14, -1, new sbyte[] {1, 2, 3, 4, 2, 5,
6, 7, 8, 9, 10, 11, 12, 2}),
/* NxS[ 16] */ new Table(1, 1, -1, new sbyte[] {14}),
};
int NextState() {
if (code == ScanBuff.EndOfFile)
return eofNum;
else
unchecked {
int rslt;
int idx = MapC(code) - NxS[state].min;
if (idx < 0) idx += 15;
if ((uint)idx >= (uint)NxS[state].rng) rslt = NxS[state].dflt;
else rslt = NxS[state].nxt[idx];
return rslt;
}
}
#endregion
#if BACKUP
// ==============================================================
// == Nested struct used for backup in automata that do backup ==
// ==============================================================
struct Context // class used for automaton backup.
{
public int bPos;
public int rPos; // scanner.readPos saved value
public int cCol;
public int lNum; // Need this in case of backup over EOL.
public int state;
public int cChr;
}
private Context ctx = new Context();
#endif // BACKUP
// ==============================================================
// ==== Nested struct to support input switching in scanners ====
// ==============================================================
struct BufferContext {
internal ScanBuff buffSv;
internal int chrSv;
internal int cColSv;
internal int lNumSv;
}
// ==============================================================
// ===== Private methods to save and restore buffer contexts ====
// ==============================================================
/// <summary>
/// This method creates a buffer context record from
/// the current buffer object, together with some
/// scanner state values.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
BufferContext MkBuffCtx()
{
BufferContext rslt;
rslt.buffSv = this.buffer;
rslt.chrSv = this.code;
rslt.cColSv = this.cCol;
rslt.lNumSv = this.lNum;
return rslt;
}
/// <summary>
/// This method restores the buffer value and allied
/// scanner state from the given context record value.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
void RestoreBuffCtx(BufferContext value)
{
this.buffer = value.buffSv;
this.code = value.chrSv;
this.cCol = value.cColSv;
this.lNum = value.lNumSv;
}
// =================== End Nested classes =======================
#if !NOFILES
public Scanner(Stream file) {
SetSource(file, 0); // unicode option
}
public Scanner(Stream file, string codepage) {
SetSource(file, CodePageHandling.GetCodePage(codepage));
}
#endif // !NOFILES
public Scanner() { }
private int readPos;
void GetCode()
{
if (code == '\n') // This needs to be fixed for other conventions
// i.e. [\r\n\205\u2028\u2029]
{
cCol = -1;
lNum++;
}
readPos = buffer.Pos;
// Now read new codepoint.
code = buffer.Read();
if (code > ScanBuff.EndOfFile)
{
#if (!BYTEMODE)
if (code >= 0xD800 && code <= 0xDBFF)
{
int next = buffer.Read();
if (next < 0xDC00 || next > 0xDFFF)
code = ScanBuff.UnicodeReplacementChar;
else
code = (0x10000 + (code & 0x3FF << 10) + (next & 0x3FF));
}
#endif
cCol++;
}
}
void MarkToken()
{
#if (!PERSIST)
buffer.Mark();
#endif
tokPos = readPos;
tokLin = lNum;
tokCol = cCol;
}
void MarkEnd()
{
tokTxt = null;
tokEPos = readPos;
tokELin = lNum;
tokECol = cCol;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
int Peek()
{
int rslt, codeSv = code, cColSv = cCol, lNumSv = lNum, bPosSv = buffer.Pos;
GetCode(); rslt = code;
lNum = lNumSv; cCol = cColSv; code = codeSv; buffer.Pos = bPosSv;
return rslt;
}
// ==============================================================
// ===== Initialization of string-based input buffers ====
// ==============================================================
/// <summary>
/// Create and initialize a StringBuff buffer object for this scanner
/// </summary>
/// <param name="source">the input string</param>
/// <param name="offset">starting offset in the string</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public void SetSource(string source, int offset)
{
this.buffer = ScanBuff.GetBuffer(source);
this.buffer.Pos = offset;
this.lNum = 0;
this.code = '\n'; // to initialize yyline, yycol and lineStart
GetCode();
}
#if !NOFILES
// ================ LineBuffer Initialization ===================
/// <summary>
/// Create and initialize a LineBuff buffer object for this scanner
/// </summary>
/// <param name="source">the list of input strings</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public void SetSource(IList<string> source)
{
this.buffer = ScanBuff.GetBuffer(source);
this.code = '\n'; // to initialize yyline, yycol and lineStart
this.lNum = 0;
GetCode();
}
// =============== StreamBuffer Initialization ==================
/// <summary>
/// Create and initialize a StreamBuff buffer object for this scanner.
/// StreamBuff is buffer for 8-bit byte files.
/// </summary>
/// <param name="source">the input byte stream</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public void SetSource(Stream source)
{
this.buffer = ScanBuff.GetBuffer(source);
this.lNum = 0;
this.code = '\n'; // to initialize yyline, yycol and lineStart
GetCode();
}
#if !BYTEMODE
// ================ TextBuffer Initialization ===================
/// <summary>
/// Create and initialize a TextBuff buffer object for this scanner.
/// TextBuff is a buffer for encoded unicode files.
/// </summary>
/// <param name="source">the input text file</param>
/// <param name="fallbackCodePage">Code page to use if file has
/// no BOM. For 0, use machine default; for -1, 8-bit binary</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public void SetSource(Stream source, int fallbackCodePage)
{
this.buffer = ScanBuff.GetBuffer(source, fallbackCodePage);
this.lNum = 0;
this.code = '\n'; // to initialize yyline, yycol and lineStart
GetCode();
}
#endif // !BYTEMODE
#endif // !NOFILES
// ==============================================================
#if BABEL
//
// Get the next token for Visual Studio
//
// "state" is the inout mode variable that maintains scanner
// state between calls, using the EolState property. In principle,
// if the calls of EolState are costly set could be called once
// only per line, at the start; and get called only at the end
// of the line. This needs more infrastructure ...
//
public int GetNext(ref int state, out int start, out int end)
{
Tokens next;
int s, e;
s = state; // state at start
EolState = state;
next = (Tokens)Scan();
state = EolState;
e = state; // state at end;
start = tokPos;
end = tokEPos - 1; // end is the index of last char.
return (int)next;
}
#endif // BABEL
// ======== AbstractScanner<> Implementation =========
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yylex")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yylex")]
public override int yylex()
{
// parserMax is set by reflecting on the Tokens
// enumeration. If maxParseToken is defined
// that is used, otherwise int.MaxValue is used.
int next;
do { next = Scan(); } while (next >= parserMax);
return next;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
int yypos { get { return tokPos; } }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
int yyline { get { return tokLin; } }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
int yycol { get { return tokCol; } }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yytext")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yytext")]
public string yytext
{
get
{
if (tokTxt == null)
tokTxt = buffer.GetString(tokPos, tokEPos);
return tokTxt;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
void yyless(int n)
{
buffer.Pos = tokPos;
// Must read at least one char, so set before start.
cCol = tokCol - 1;
GetCode();
// Now ensure that line counting is correct.
lNum = tokLin;
// And count the rest of the text.
for (int i = 0; i < n; i++) GetCode();
MarkEnd();
}
//
// It would be nice to count backward in the text
// but it does not seem possible to re-establish
// the correct column counts except by going forward.
//
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
void _yytrunc(int n) { yyless(yyleng - n); }
//
// This is painful, but we no longer count
// codepoints. For the overwhelming majority
// of cases the single line code is fast, for
// the others, well, at least it is all in the
// buffer so no files are touched. Note that we
// can't use (tokEPos - tokPos) because of the
// possibility of surrogate pairs in the token.
//
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yyleng")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yyleng")]
public int yyleng
{
get {
#if BYTEMODE
return tokEPos - tokPos;
#else
if (tokELin == tokLin)
return tokECol - tokCol;
else {
int ch;
int count = 0;
int save = buffer.Pos;
buffer.Pos = tokPos;
do {
ch = buffer.Read();
if (!char.IsHighSurrogate((char)ch)) count++;
} while (buffer.Pos < tokEPos && ch != ScanBuff.EndOfFile);
buffer.Pos = save;
return count;
}
#endif // BYTEMODE
}
}
// ============ methods available in actions ==============
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal int YY_START {
get { return currentScOrd; }
set { currentScOrd = value;
currentStart = startState[value];
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void BEGIN(int next) {
currentScOrd = next;
currentStart = startState[next];
}
// ============== The main tokenizer code =================
int Scan()
{
try {
for (; ; )
{
int next; // next state to enter
#if BACKUP
Result rslt = Result.noMatch;
#endif // BACKUP
#if LEFTANCHORS
for (;;)
{
// Discard characters that do not start any pattern.
// Must check the left anchor condition after *every* GetCode!
state = ((cCol == 0) ? anchorState[currentScOrd] : currentStart);
if ((next = NextState()) != goStart)
break; // LOOP EXIT HERE...
GetCode();
}
#else // !LEFTANCHORS
state = currentStart;
while ((next = NextState()) == goStart)
// At this point, the current character has no
// transition from the current state. We discard
// the "no-match" char. In traditional LEX such
// characters are echoed to the console.
GetCode();
#endif // LEFTANCHORS
// At last, a valid transition ...
MarkToken();
state = next;
GetCode();
while ((next = NextState()) > eofNum) // Exit for goStart AND for eofNum
#if BACKUP
if (state <= maxAccept && next > maxAccept) // need to prepare backup data
{
// ctx is an object. The fields may be
// mutated by the call to Recurse2.
// On return the data in ctx is the
// *latest* accept state that was found.
rslt = Recurse2(ref ctx, next);
if (rslt == Result.noMatch)
RestoreStateAndPos(ref ctx);
break;
}
else
#endif // BACKUP
{
state = next;
GetCode();
}
if (state <= maxAccept)
{
MarkEnd();
#region ActionSwitch
#pragma warning disable 162
switch (state)
{
case eofNum:
if (yywrap())
return (int)Tokens.EOF;
break;
case 1:
yylval.iVal = int.Parse(yytext);
return (int)Tokens.INUM;
break;
case 2:
case 4:
LexError();
break;
case 3:
int res = ScannerHelper.GetIDToken(yytext);
if (res == (int)Tokens.ID)
yylval.sVal = yytext;
return res;
break;
case 5:
return (int)Tokens.SEMICOLON;
break;
case 6:
return (int)Tokens.LBRACKET;
break;
case 7:
return (int)Tokens.RBRACKET;
break;
case 8:
return (int)Tokens.COMMA;
break;
case 9:
return (int)Tokens.PLUS;
break;
case 10:
return (int)Tokens.MINUS;
break;
case 11:
return (int)Tokens.MULT;
break;
case 12:
return (int)Tokens.DIVISION;
break;
case 13:
return (int)Tokens.ASSIGN;
break;
case 14:
yylval.dVal = double.Parse(yytext);
return (int)Tokens.RNUM;
break;
default:
break;
}
#pragma warning restore 162
#endregion
}
}
} // end try
finally {
// User-specified epilog to scan()
yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol);
// End, user-specified epilog
} // end finally
}
#if BACKUP
Result Recurse2(ref Context ctx, int next)
{
// Assert: at entry "state" is an accept state AND
// NextState(state, code) != goStart AND
// NextState(state, code) is not an accept state.
//
SaveStateAndPos(ref ctx);
state = next;
GetCode();
while ((next = NextState()) > eofNum)
{
if (state <= maxAccept && next > maxAccept) // need to update backup data
SaveStateAndPos(ref ctx);
state = next;
if (state == eofNum) return Result.accept;
GetCode();
}
return (state <= maxAccept ? Result.accept : Result.noMatch);
}
void SaveStateAndPos(ref Context ctx)
{
ctx.bPos = buffer.Pos;
ctx.rPos = readPos;
ctx.cCol = cCol;
ctx.lNum = lNum;
ctx.state = state;
ctx.cChr = code;
}
void RestoreStateAndPos(ref Context ctx)
{
buffer.Pos = ctx.bPos;
readPos = ctx.rPos;
cCol = ctx.cCol;
lNum = ctx.lNum;
state = ctx.state;
code = ctx.cChr;
}
#endif // BACKUP
// ============= End of the tokenizer code ================
#if STACK
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void yy_clear_stack() { scStack.Clear(); }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal int yy_top_state() { return scStack.Peek(); }
internal void yy_push_state(int state)
{
scStack.Push(currentScOrd);
BEGIN(state);
}
internal void yy_pop_state()
{
// Protect against input errors that pop too far ...
if (scStack.Count > 0) {
int newSc = scStack.Pop();
BEGIN(newSc);
} // Otherwise leave stack unchanged.
}
#endif // STACK
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void ECHO() { Console.Out.Write(yytext); }
#region UserCodeSection
public override void yyerror(string format, params object[] args) // обработка синтаксических ошибок
{
var ww = args.Skip(1).Cast<string>().ToArray();
string errorMsg = string.Format("({0},{1}): Встречено {2}, а ожидалось {3}", yyline, yycol, args[0], string.Join(" или ", ww));
throw new SyntaxException(errorMsg);
}
public void LexError()
{
string errorMsg = string.Format("({0},{1}): Неизвестный символ {2}", yyline, yycol, yytext);
throw new LexException(errorMsg);
}
class ScannerHelper
{
private static Dictionary<string,int> keywords;
static ScannerHelper()
{
keywords = new Dictionary<string,int>();
keywords.Add("begin",(int)Tokens.BEGIN);
keywords.Add("end",(int)Tokens.END);
keywords.Add("cycle",(int)Tokens.CYCLE);
keywords.Add("while",(int)Tokens.WHILE);
keywords.Add("do",(int)Tokens.DO);
keywords.Add("until",(int)Tokens.UNTIL);
keywords.Add("repeat",(int)Tokens.REPEAT);
keywords.Add("for",(int)Tokens.FOR);
keywords.Add("to",(int)Tokens.TO);
keywords.Add("write",(int)Tokens.WRITE);
keywords.Add("if",(int)Tokens.IF);
keywords.Add("then",(int)Tokens.THEN);
keywords.Add("else",(int)Tokens.ELSE);
keywords.Add("var",(int)Tokens.VAR);
}
public static int GetIDToken(string s)
{
if (keywords.ContainsKey(s.ToLower()))
return keywords[s];
else
return (int)Tokens.ID;
}
}
#endregion
} // end class $Scanner
// ==============================================================
// <auto-generated>
// This code automatically produced from an embedded resource.
// Do not edit this file, or it will become incompatible with
// the specification from which it was generated.
// </auto-generated>
// ==============================================================
// Code copied from GPLEX embedded resource
[Serializable]
public class BufferException : Exception
{
public BufferException() { }
public BufferException(string message) : base(message) { }
public BufferException(string message, Exception innerException)
: base(message, innerException) { }
protected BufferException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
public abstract class ScanBuff
{
private string fileNm;
public const int EndOfFile = -1;
public const int UnicodeReplacementChar = 0xFFFD;
public bool IsFile { get { return (fileNm != null); } }
public string FileName { get { return fileNm; } set { fileNm = value; } }
public abstract int Pos { get; set; }
public abstract int Read();
public virtual void Mark() { }
public abstract string GetString(int begin, int limit);
public static ScanBuff GetBuffer(string source)
{
return new StringBuffer(source);
}
public static ScanBuff GetBuffer(IList<string> source)
{
return new LineBuffer(source);
}
public static ScanBuff GetBuffer(Stream source)
{
return new BuildBuffer(source);
}
#if (!BYTEMODE)
public static ScanBuff GetBuffer(Stream source, int fallbackCodePage)
{
return new BuildBuffer(source, fallbackCodePage);
}
#endif
}
#region Buffer classes
// ==============================================================
// ===== Definitions for various ScanBuff derived classes ====
// ==============================================================
// =============== String input ================
// ==============================================================
/// <summary>
/// This class reads characters from a single string as
/// required, for example, by Visual Studio language services
/// </summary>
sealed class StringBuffer : ScanBuff
{
string str; // input buffer
int bPos; // current position in buffer
int sLen;
public StringBuffer(string source)
{
this.str = source;
this.sLen = source.Length;
this.FileName = null;
}
public override int Read()
{
if (bPos < sLen) return str[bPos++];
else if (bPos == sLen) { bPos++; return '\n'; } // one strike, see new line
else { bPos++; return EndOfFile; } // two strikes and you're out!
}
public override string GetString(int begin, int limit)
{
// "limit" can be greater than sLen with the BABEL
// option set. Read returns a "virtual" EOL if
// an attempt is made to read past the end of the
// string buffer. Without the guard any attempt
// to fetch yytext for a token that includes the
// EOL will throw an index exception.
if (limit > sLen) limit = sLen;
if (limit <= begin) return "";
else return str.Substring(begin, limit - begin);
}
public override int Pos
{
get { return bPos; }
set { bPos = value; }
}
public override string ToString() { return "StringBuffer"; }
}
// ==============================================================
// The LineBuff class contributed by Nigel Horspool,
// nigelh@cs.uvic.cs
// ==============================================================
sealed class LineBuffer : ScanBuff
{
IList<string> line; // list of source lines from a file
int numLines; // number of strings in line list
string curLine; // current line in that list
int cLine; // index of current line in the list
int curLen; // length of current line
int curLineStart; // position of line start in whole file
int curLineEnd; // position of line end in whole file
int maxPos; // max position ever visited in whole file
int cPos; // ordinal number of code in source
// Constructed from a list of strings, one per source line.
// The lines have had trailing '\n' characters removed.
public LineBuffer(IList<string> lineList)
{
line = lineList;
numLines = line.Count;
cPos = curLineStart = 0;
curLine = (numLines > 0 ? line[0] : "");
maxPos = curLineEnd = curLen = curLine.Length;
cLine = 1;
FileName = null;
}
public override int Read()
{
if (cPos < curLineEnd)
return curLine[cPos++ - curLineStart];
if (cPos++ == curLineEnd)
return '\n';
if (cLine >= numLines)
return EndOfFile;
curLine = line[cLine];
curLen = curLine.Length;
curLineStart = curLineEnd + 1;
curLineEnd = curLineStart + curLen;
if (curLineEnd > maxPos)
maxPos = curLineEnd;
cLine++;
return curLen > 0 ? curLine[0] : '\n';
}
// To speed up searches for the line containing a position
private int cachedPosition;
private int cachedIxdex;
private int cachedLineStart;
// Given a position pos within the entire source, the results are
// ix -- the index of the containing line
// lstart -- the position of the first character on that line
private void findIndex(int pos, out int ix, out int lstart)
{
if (pos >= cachedPosition)
{
ix = cachedIxdex; lstart = cachedLineStart;
}
else
{
ix = lstart = 0;
}
for (; ; )
{
int len = line[ix].Length + 1;
if (pos < lstart + len) break;
lstart += len;
ix++;
}
cachedPosition = pos;
cachedIxdex = ix;
cachedLineStart = lstart;
}
public override string GetString(int begin, int limit)
{
if (begin >= maxPos || limit <= begin) return "";
int endIx, begIx, endLineStart, begLineStart;
findIndex(begin, out begIx, out begLineStart);
int begCol = begin - begLineStart;
findIndex(limit, out endIx, out endLineStart);
int endCol = limit - endLineStart;
string s = line[begIx];
if (begIx == endIx)
{
// the usual case, substring all on one line
return (endCol <= s.Length) ?
s.Substring(begCol, endCol - begCol)
: s.Substring(begCol) + "\n";
}
// the string spans multiple lines, yuk!
StringBuilder sb = new StringBuilder();
if (begCol < s.Length)
sb.Append(s.Substring(begCol));
for (; ; )
{
sb.Append("\n");
s = line[++begIx];
if (begIx >= endIx) break;
sb.Append(s);
}
if (endCol <= s.Length)
{
sb.Append(s.Substring(0, endCol));
}
else
{
sb.Append(s);
sb.Append("\n");
}
return sb.ToString();
}
public override int Pos
{
get { return cPos; }
set
{
cPos = value;
findIndex(cPos, out cLine, out curLineStart);
curLine = line[cLine];
curLineEnd = curLineStart + curLine.Length;
}
}
public override string ToString() { return "LineBuffer"; }
}
// ==============================================================
// ===== class BuildBuff : for unicode text files ========
// ==============================================================
class BuildBuffer : ScanBuff
{
// Double buffer for char stream.
class BufferElement
{
StringBuilder bldr = new StringBuilder();
StringBuilder next = new StringBuilder();
int minIx;
int maxIx;
int brkIx;
bool appendToNext;
internal BufferElement() { }
internal int MaxIndex { get { return maxIx; } }
// internal int MinIndex { get { return minIx; } }
internal char this[int index]
{
get
{
if (index < minIx || index >= maxIx)
throw new BufferException("Index was outside data buffer");
else if (index < brkIx)
return bldr[index - minIx];
else
return next[index - brkIx];
}
}
internal void Append(char[] block, int count)
{
maxIx += count;
if (appendToNext)
this.next.Append(block, 0, count);
else
{
this.bldr.Append(block, 0, count);
brkIx = maxIx;
appendToNext = true;
}
}
internal string GetString(int start, int limit)
{
if (limit <= start)
return "";
if (start >= minIx && limit <= maxIx)
if (limit < brkIx) // String entirely in bldr builder
return bldr.ToString(start - minIx, limit - start);
else if (start >= brkIx) // String entirely in next builder
return next.ToString(start - brkIx, limit - start);
else // Must do a string-concatenation
return
bldr.ToString(start - minIx, brkIx - start) +
next.ToString(0, limit - brkIx);
else
throw new BufferException("String was outside data buffer");
}
internal void Mark(int limit)
{
if (limit > brkIx + 16) // Rotate blocks
{
StringBuilder temp = bldr;
bldr = next;
next = temp;
next.Length = 0;
minIx = brkIx;
brkIx = maxIx;
}
}
}
BufferElement data = new BufferElement();
int bPos; // Postion index in the StringBuilder
BlockReader NextBlk; // Delegate that serves char-arrays;
private string EncodingName
{
get
{
StreamReader rdr = NextBlk.Target as StreamReader;
return (rdr == null ? "raw-bytes" : rdr.CurrentEncoding.BodyName);
}
}
public BuildBuffer(Stream stream)
{
FileStream fStrm = (stream as FileStream);
if (fStrm != null) FileName = fStrm.Name;
NextBlk = BlockReaderFactory.Raw(stream);
}
#if (!BYTEMODE)
public BuildBuffer(Stream stream, int fallbackCodePage)
{
FileStream fStrm = (stream as FileStream);
if (fStrm != null) FileName = fStrm.Name;
NextBlk = BlockReaderFactory.Get(stream, fallbackCodePage);
}
#endif
/// <summary>
/// Marks a conservative lower bound for the buffer,
/// allowing space to be reclaimed. If an application
/// needs to call GetString at arbitrary past locations
/// in the input stream, Mark() is not called.
/// </summary>
public override void Mark() { data.Mark(bPos - 2); }
public override int Pos
{
get { return bPos; }
set { bPos = value; }
}
/// <summary>
/// Read returns the ordinal number of the next char, or
/// EOF (-1) for an end of stream. Note that the next
/// code point may require *two* calls of Read().
/// </summary>
/// <returns></returns>
public override int Read()
{
//
// Characters at positions
// [data.offset, data.offset + data.bldr.Length)
// are available in data.bldr.
//
if (bPos < data.MaxIndex)
{
// ch0 cannot be EOF
return (int)data[bPos++];
}
else // Read from underlying stream
{
// Experimental code, blocks of page size
char[] chrs = new char[4096];
int count = NextBlk(chrs, 0, 4096);
if (count == 0)
return EndOfFile;
else
{
data.Append(chrs, count);
return (int)data[bPos++];
}
}
}
public override string GetString(int begin, int limit)
{
return data.GetString(begin, limit);
}
public override string ToString()
{
return "StringBuilder buffer, encoding: " + this.EncodingName;
}
}
// =============== End ScanBuff-derived classes ==================
public delegate int BlockReader(char[] block, int index, int number);
// A delegate factory, serving up a delegate that
// reads a block of characters from the underlying
// encoded stream, via a StreamReader object.
//
public static class BlockReaderFactory
{
public static BlockReader Raw(Stream stream)
{
return delegate(char[] block, int index, int number)
{
byte[] b = new byte[number];
int count = stream.Read(b, 0, number);
int i = 0;
int j = index;
for (; i < count; i++, j++)
block[j] = (char)b[i];
return count;
};
}
#if (!BYTEMODE)
public static BlockReader Get(Stream stream, int fallbackCodePage)
{
Encoding encoding;
int preamble = Preamble(stream);
if (preamble != 0) // There is a valid BOM here!
encoding = Encoding.GetEncoding(preamble);
else if (fallbackCodePage == -1) // Fallback is "raw" bytes
return Raw(stream);
else if (fallbackCodePage != -2) // Anything but "guess"
encoding = Encoding.GetEncoding(fallbackCodePage);
else // This is the "guess" option
{
int guess = new Guesser(stream).GuessCodePage();
stream.Seek(0, SeekOrigin.Begin);
if (guess == -1) // ==> this is a 7-bit file
encoding = Encoding.ASCII;
else if (guess == 65001)
encoding = Encoding.UTF8;
else // ==> use the machine default
encoding = Encoding.Default;
}
StreamReader reader = new StreamReader(stream, encoding);
return reader.Read;
}
static int Preamble(Stream stream)
{
int b0 = stream.ReadByte();
int b1 = stream.ReadByte();
if (b0 == 0xfe && b1 == 0xff)
return 1201; // UTF16BE
if (b0 == 0xff && b1 == 0xfe)
return 1200; // UTF16LE
int b2 = stream.ReadByte();
if (b0 == 0xef && b1 == 0xbb && b2 == 0xbf)
return 65001; // UTF8
//
// There is no unicode preamble, so we
// return denoter for the machine default.
//
stream.Seek(0, SeekOrigin.Begin);
return 0;
}
#endif // !BYTEMODE
}
#endregion Buffer classes
// ==============================================================
// ============ class CodePageHandling =============
// ==============================================================
public static class CodePageHandling
{
public static int GetCodePage(string option)
{
string command = option.ToUpperInvariant();
if (command.StartsWith("CodePage:", StringComparison.OrdinalIgnoreCase))
command = command.Substring(9);
try
{
if (command.Equals("RAW"))
return -1;
else if (command.Equals("GUESS"))
return -2;
else if (command.Equals("DEFAULT"))
return 0;
else if (char.IsDigit(command[0]))
return int.Parse(command, CultureInfo.InvariantCulture);
else
{
Encoding enc = Encoding.GetEncoding(command);
return enc.CodePage;
}
}
catch (FormatException)
{
Console.Error.WriteLine(
"Invalid format \"{0}\", using machine default", option);
}
catch (ArgumentException)
{
Console.Error.WriteLine(
"Unknown code page \"{0}\", using machine default", option);
}
return 0;
}
}
#region guesser
#if (!BYTEMODE)
// ==============================================================
// ============ Encoding Guesser =============
// ==============================================================
/// <summary>
/// This class provides a simple finite state automaton that
/// scans the file looking for (1) valid UTF-8 byte patterns,
/// (2) bytes >= 0x80 which are not part of a UTF-8 sequence.
/// The method then guesses whether it is UTF-8 or maybe some
/// local machine default encoding. This works well for the
/// various Latin encodings.
/// </summary>
internal class Guesser
{
ScanBuff buffer;
public int GuessCodePage() { return Scan(); }
const int maxAccept = 10;
const int initial = 0;
const int eofNum = 0;
const int goStart = -1;
const int INITIAL = 0;
const int EndToken = 0;
#region user code
/*
* Reads the bytes of a file to determine if it is
* UTF-8 or a single-byte code page file.
*/
public long utfX;
public long uppr;
#endregion user code
int state;
int currentStart = startState[0];
int code;
#region ScannerTables
static int[] startState = new int[] { 11, 0 };
#region CharacterMap
static sbyte[] map = new sbyte[256] {
/* '\0' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '\x10' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '\x20' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '0' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '@' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 'P' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '`' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 'p' */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* '\x80' */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* '\x90' */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* '\xA0' */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* '\xB0' */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* '\xC0' */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* '\xD0' */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* '\xE0' */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* '\xF0' */ 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5 };
#endregion
static sbyte[][] nextState = new sbyte[][] {
new sbyte[] {0, 0, 0, 0, 0, 0},
new sbyte[] {-1, -1, 10, -1, -1, -1},
new sbyte[] {-1, -1, -1, -1, -1, -1},
new sbyte[] {-1, -1, 8, -1, -1, -1},
new sbyte[] {-1, -1, 5, -1, -1, -1},
new sbyte[] {-1, -1, 6, -1, -1, -1},
new sbyte[] {-1, -1, 7, -1, -1, -1},
null,
new sbyte[] {-1, -1, 9, -1, -1, -1},
null,
null,
new sbyte[] {-1, 1, 2, 3, 4, 2}
};
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
// Reason for suppression: cannot have self-reference in array initializer.
static Guesser()
{
nextState[7] = nextState[2];
nextState[9] = nextState[2];
nextState[10] = nextState[2];
}
int NextState()
{
if (code == ScanBuff.EndOfFile)
return eofNum;
else
return nextState[state][map[code]];
}
#endregion
public Guesser(System.IO.Stream file) { SetSource(file); }
public void SetSource(System.IO.Stream source)
{
this.buffer = new BuildBuffer(source);
code = buffer.Read();
}
int Scan()
{
for (; ; )
{
int next;
state = currentStart;
while ((next = NextState()) == goStart)
code = buffer.Read();
state = next;
code = buffer.Read();
while ((next = NextState()) > eofNum)
{
state = next;
code = buffer.Read();
}
if (state <= maxAccept)
{
#region ActionSwitch
#pragma warning disable 162
switch (state)
{
case eofNum:
switch (currentStart)
{
case 11:
if (utfX == 0 && uppr == 0) return -1; /* raw ascii */
else if (uppr * 10 > utfX) return 0; /* default code page */
else return 65001; /* UTF-8 encoding */
break;
}
return EndToken;
case 1: // Recognized '{Upper128}', Shortest string "\xC0"
case 2: // Recognized '{Upper128}', Shortest string "\x80"
case 3: // Recognized '{Upper128}', Shortest string "\xE0"
case 4: // Recognized '{Upper128}', Shortest string "\xF0"
uppr++;
break;
case 5: // Recognized '{Utf8pfx4}{Utf8cont}', Shortest string "\xF0\x80"
uppr += 2;
break;
case 6: // Recognized '{Utf8pfx4}{Utf8cont}{2}', Shortest string "\xF0\x80\x80"
uppr += 3;
break;
case 7: // Recognized '{Utf8pfx4}{Utf8cont}{3}', Shortest string "\xF0\x80\x80\x80"
utfX += 3;
break;
case 8: // Recognized '{Utf8pfx3}{Utf8cont}', Shortest string "\xE0\x80"
uppr += 2;
break;
case 9: // Recognized '{Utf8pfx3}{Utf8cont}{2}', Shortest string "\xE0\x80\x80"
utfX += 2;
break;
case 10: // Recognized '{Utf8pfx2}{Utf8cont}', Shortest string "\xC0\x80"
utfX++;
break;
default:
break;
}
#pragma warning restore 162
#endregion
}
}
}
} // end class Guesser
#endif // !BYTEMODE
#endregion
// End of code copied from embedded resource
} // end namespace
| 34.871158 | 129 | 0.484958 | [
"MIT"
] | dkicenko/Indiv_Compilers_20 | Module6/SimpleLex.cs | 53,386 | C# |
/* This file was created automatically, do not edit! */
using System.Runtime.Serialization;
namespace Iviz.Msgs.Actionlib
{
[Preserve, DataContract (Name = "actionlib/TwoIntsResult")]
public sealed class TwoIntsResult : IDeserializable<TwoIntsResult>, IResult<TwoIntsActionResult>
{
[DataMember (Name = "sum")] public long Sum { get; set; }
/// <summary> Constructor for empty message. </summary>
public TwoIntsResult()
{
}
/// <summary> Explicit constructor. </summary>
public TwoIntsResult(long Sum)
{
this.Sum = Sum;
}
/// <summary> Constructor with buffer. </summary>
public TwoIntsResult(ref Buffer b)
{
Sum = b.Deserialize<long>();
}
public ISerializable RosDeserialize(ref Buffer b)
{
return new TwoIntsResult(ref b);
}
TwoIntsResult IDeserializable<TwoIntsResult>.RosDeserialize(ref Buffer b)
{
return new TwoIntsResult(ref b);
}
public void RosSerialize(ref Buffer b)
{
b.Serialize(Sum);
}
public void Dispose()
{
}
public void RosValidate()
{
}
/// <summary> Constant size of this message. </summary>
[Preserve] public const int RosFixedMessageLength = 8;
public int RosMessageLength => RosFixedMessageLength;
public string RosType => RosMessageType;
/// <summary> Full ROS name of this message. </summary>
[Preserve] public const string RosMessageType = "actionlib/TwoIntsResult";
/// <summary> MD5 hash of a compact representation of the message. </summary>
[Preserve] public const string RosMd5Sum = "b88405221c77b1878a3cbbfff53428d7";
/// <summary> Base64 of the GZip'd compression of the concatenated dependencies file. </summary>
[Preserve] public const string RosDependenciesBase64 =
"H4sIAAAAAAAAE8vMKzEzUSguzeUCAHohbPwKAAAA";
public override string ToString() => Extensions.ToString(this);
}
}
| 31.027778 | 104 | 0.58684 | [
"MIT"
] | KIT-ISAS/iviz | iviz_msgs/actionlib/msg/TwoIntsResult.cs | 2,234 | C# |
namespace StringifierTests
{
public enum MainMediaType
{
Movies = 1,
TvSeries = 2
}
}
| 12.777778 | 29 | 0.556522 | [
"MIT"
] | fellipeborges/lara | src/Lara.Tests/Stringifier/Model/MainMediaTypeEnum.cs | 117 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeafSplit : MonoBehaviour
{
public bool canSplit;
public bool isGrabbable;
public float leafTime;
public float currentTime;
bool grounded;
[SerializeField]
Object destructableLeaf;
private SpriteRenderer leafRend;
bool hasFaded;
void Awake()
{
hasFaded = false;
}
void Start()
{
leafRend = GetComponent<SpriteRenderer>();
leafTime = transform.localScale.x * 2;
currentTime = leafTime;
isGrabbable = true;
}
void Update()
{
if (grounded)
{
currentTime -= Time.deltaTime;
if (currentTime <= 0)
{
//Destroy(this.gameObject);
if (!hasFaded)
// skipping grabbing a leaf while fading
isGrabbable = false;
StartCoroutine(FadeTo(0, transform.localScale.x));
}
}
else
{
currentTime = leafTime;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
grounded = true;
}
if (canSplit)
{
ExplodeThisGameObject();
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
grounded = false;
}
/* Substitution of Original Prefab for one that is the same object broken into pieces */
void ExplodeThisGameObject()
{
GameObject destructable = (GameObject)Instantiate(destructableLeaf);
destructable.transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.z);
// destruible en posicion de objeto original
destructable.transform.position = transform.position;
destructable.transform.rotation = transform.rotation;
foreach (Transform child in destructable.transform)
{
child.parent = null;
}
Destroy(gameObject);
}
// Fade of Main Leaf
IEnumerator FadeTo(float aValue, float aTime)
{
hasFaded = true;
float alpha = leafRend.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
{
Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, t));
leafRend.color = newColor;
if (leafRend.color.a <= 0.05f)
{
Destroy(gameObject);
}
yield return null;
}
}
}
| 22.675 | 128 | 0.554943 | [
"MIT"
] | MigQP/Rite_Autumn | Assets/Scripts/LeafSplit.cs | 2,721 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace KZ.AdventureWorks.Products.Api.Models
{
public partial class VIndividualCustomer
{
public int BusinessEntityId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string PhoneNumber { get; set; }
public string PhoneNumberType { get; set; }
public string EmailAddress { get; set; }
public int EmailPromotion { get; set; }
public string AddressType { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string StateProvinceName { get; set; }
public string PostalCode { get; set; }
public string CountryRegionName { get; set; }
public string Demographics { get; set; }
}
}
| 34.633333 | 53 | 0.628489 | [
"MIT"
] | az00s/KZ.AdventureWorks.Products.Api | KZ.AdventureWorks.Products.Api/Models/VIndividualCustomer.cs | 1,041 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AElf.Modularity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Volo.Abp.Modularity;
namespace AElf
{
public class CoreAElfModule : AElfModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddConventionalRegistrar(new AElfDefaultConventionalRegistrar());
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddTransient(typeof(IServiceContainer<>),
typeof(ServiceContainerFactory<>));
}
}
public static class ServiceProviderExtensions
{
public static IEnumerable<T> GetServices<T>(this IServiceProvider provider, IEnumerable<Type> types)
{
return types.Select(type => (T) provider.GetService(type));
}
/*public static IEnumerable<T> GetServices<T>(this IServiceProvider provider, params Type[] types)
{
return provider.GetServices<T>((IEnumerable<Type>) types);
}*/
}
public interface IServiceContainer<T> : IEnumerable<T>
{
}
public class ServiceContainerFactoryOptions<T>
{
/// <summary>
/// if Types is null, it will return all services of T
/// </summary>
public List<Type> Types { get; set; }
}
public class ServiceContainerFactory<T> : IServiceContainer<T>
{
public static ServiceContainerFactory<T> Empty { get; } = new ServiceContainerFactory<T>();
private readonly IEnumerable<T> _services;
private ServiceContainerFactory()
{
_services = Enumerable.Empty<T>();
}
public ServiceContainerFactory(IOptionsSnapshot<ServiceContainerFactoryOptions<T>> options,
IServiceProvider serviceProvider)
{
if (options.Value.Types == null)
{
_services = serviceProvider.GetServices<T>();
return;
}
_services = serviceProvider.GetServices<T>(options.Value.Types);
}
public IEnumerator<T> GetEnumerator()
{
return _services.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | 28.858824 | 108 | 0.63351 | [
"MIT"
] | 380086154/AElf | src/AElf.Core/CoreAElfModule.cs | 2,453 | C# |
using Laurus.Mileage.Services;
using Laurus.Mileage.UWP.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Xamarin.Forms;
[assembly: Dependency(typeof(FileHelper))]
namespace Laurus.Mileage.UWP.Services
{
public class FileHelper : IFileHelper
{
public string GetLocalFilePath(string filename)
{
return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
}
public Stream ReadTemplate()
{
throw new NotImplementedException();
}
public void Save(string filename, Stream stream)
{
throw new NotImplementedException();
}
}
}
| 22.69697 | 81 | 0.70494 | [
"MIT"
] | thebeekeeper/Laurus.Mileage | Laurus.Mileage/Laurus.Mileage.UWP/Services/FileHelper.cs | 751 | C# |
//#define SAVE
using System.Net.Http;
using System.Text;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Io;
using AngleSharp.Io.Network;
using AngleSharp.Scripting;
using Jint.Native;
using Jint.Native.Function;
using Jint.Native.Object;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json;
using Xunit;
namespace Tests.RazorPages
{
public class AddNewItemPageTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly HttpClient client;
private readonly WebApplicationFactory<Startup> factory;
private readonly IConfiguration config;
public AddNewItemPageTests(WebApplicationFactory<Startup> factory)
{
this.factory = factory;
this.client = this.factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = true,
});
this.config = Configuration.Default
.WithCss()
.WithJs()
.WithCookies()
.WithEventLoop()
.WithRequester(new HttpClientRequester(this.client))
.WithDefaultLoader(new LoaderOptions
{
IsResourceLoadingEnabled = true,
IsNavigationDisabled = false
});
}
[Fact]
public async void ListEditorFor_ScriptsShouldLoadCorrectly()
{
// Arrange
var context = BrowsingContext.New(config);
// Act
var document = await context.OpenAsync("http://localhost:5000/EditSimple");
await document.WaitForReadyAsync();
// Assert
JsScriptingService js = (JsScriptingService)context.GetJsScripting();
ObjectInstance jquery = (ObjectInstance)js.EvaluateScript(document, "jQuery");
Assert.NotNull(jquery);
ObjectInstance dmvl = (ObjectInstance)js.EvaluateScript(document, "dvml");
Assert.NotNull(dmvl);
JsValue add = dmvl.Get("add");
Assert.NotNull(add);
JsValue remove = dmvl.Get("remove");
Assert.NotNull(remove);
}
[Fact]
public async void ListEditorFor_Get_onClickShouldFindRightElement()
{
// Arrange
var context = BrowsingContext.New(config);
var document = await context.OpenAsync("http://localhost:5000/EditSimple");
await document.WaitForReadyAsync();
JsScriptingService js = (JsScriptingService)context.GetJsScripting();
// Act
await document.WaitUntilAvailable();
string actual = document.ToHtml();
IHtmlAnchorElement link = (IHtmlAnchorElement)document.QuerySelector("a[name='dynamic-list-addnewitem']");
string onclick = link.GetAttribute("onclick");
Assert.Equal("dvml.add('I', 'AddSimpleItem/?" +
"ContainerId=I" +
"&ListTemplate=EditorTemplates%2fDynamicList" +
"&ItemContainerTemplate=DynamicItemContainer" +
"&ItemTemplate=SimpleItem" +
"&Prefix=Input.Items" +
"&Mode=0');", onclick);
ObjectInstance result = (ObjectInstance)js.EvaluateScript(document, onclick);
ObjectInstance containerObj = result.Get("container").AsObject();
IHtmlDivElement container = (IHtmlDivElement)containerObj.GetType().GetProperty("Value").GetValue(containerObj);
ObjectInstance optionsObj = result.Get("options").AsObject();
string url = optionsObj.Get("url").ToString();
string type = optionsObj.Get("type").ToString();
bool cache = optionsObj.Get("cache").AsBoolean();
// Assert
Assert.Equal("I", container.Id);
Assert.Equal("AddSimpleItem/?" +
"ContainerId=I" +
"&ListTemplate=EditorTemplates%2fDynamicList" +
"&ItemContainerTemplate=DynamicItemContainer" +
"&ItemTemplate=SimpleItem" +
"&Prefix=Input.Items" +
"&Mode=0", url);
Assert.Equal("GET", type);
Assert.False(cache);
}
[Fact]
public async void ListEditorFor_Get_onClickShouldAddElementToRightPlace()
{
// Arrange
var context = BrowsingContext.New(config);
string pageAddress = "http://localhost:5000/EditSimple/";
var document = await context.OpenAsync(pageAddress);
await document.WaitForReadyAsync();
JsScriptingService js = (JsScriptingService)context.GetJsScripting();
// Act
await document.WaitUntilAvailable();
string before = document.ToStandardizedHtml();
IHtmlAnchorElement link = (IHtmlAnchorElement)document.QuerySelector("a[name='dynamic-list-addnewitem']");
ObjectInstance result = (ObjectInstance)js.EvaluateScript(document, link.GetAttribute("onclick"));
ObjectInstance containerObj = result.Get("container").AsObject();
IHtmlDivElement container = (IHtmlDivElement)containerObj.GetType().GetProperty("Value").GetValue(containerObj);
ObjectInstance optionsObj = result.Get("options").AsObject();
string url = optionsObj.Get("url").ToString();
ScriptFunctionInstance success = optionsObj.Get("success").As<ScriptFunctionInstance>();
// Call the controller action manually
var response = await client.GetAsync(pageAddress + url);
string newItemHtml = await response.Content.ReadAsStringAsync();
success.Call(null, new[] { new JsValue(newItemHtml) });
string after = document.ToStandardizedHtml();
// Assert
string beforePath = Helpers.GetResourcePath(@"AddNewItem\razor-simple-before.html");
string afterPath = Helpers.GetResourcePath(@"AddNewItem\razor-simple-after.html");
#if SAVE
after.ToFile(afterPath);
before.ToFile(beforePath);
#endif
string expectedBefore = beforePath.ToHtml();
string expectedAfter = afterPath.ToHtml();
Assert.Equal(expectedBefore, before);
Assert.Equal(expectedAfter, after);
}
[Fact]
public async void ListEditorFor_Post_onClickShouldAddElementToRightPlace()
{
// Arrange
var context = BrowsingContext.New(config);
string pageAddress = "http://localhost:5000/EditSimpleByPost/";
var document = await context.OpenAsync(pageAddress);
await document.WaitForReadyAsync();
JsScriptingService js = (JsScriptingService)context.GetJsScripting();
// Act
await document.WaitUntilAvailable();
string before = document.ToStandardizedHtml();
IHtmlAnchorElement link = (IHtmlAnchorElement)document.QuerySelector("a[name='dynamic-list-addnewitem']");
ObjectInstance result = (ObjectInstance)js.EvaluateScript(document, link.GetAttribute("onclick"));
ObjectInstance containerObj = result.Get("container").AsObject();
IHtmlDivElement container = (IHtmlDivElement)containerObj.GetType().GetProperty("Value").GetValue(containerObj);
ObjectInstance optionsObj = result.Get("options").AsObject();
string url = optionsObj.Get("url").ToString();
string data = optionsObj.Get("data").ToString();
string contentType = optionsObj.Get("contentType").ToString();
string type = optionsObj.Get("type").ToString();
bool cache = optionsObj.Get("cache").AsBoolean();
ScriptFunctionInstance success = optionsObj.Get("success").As<ScriptFunctionInstance>();
Assert.Equal("AddSimpleItemByPost", url);
Assert.Equal("{\"ContainerId\":\"I\"," +
"\"ItemTemplate\":\"SimpleItem\"," +
"\"ItemContainerTemplate\":\"DynamicItemContainer\"," +
"\"ListTemplate\":\"EditorTemplates/DynamicList\"," +
"\"Prefix\":\"Input.Items\"," +
"\"Mode\":0,\"" +
"AdditionalViewData\":\"eyJEYXRhIjoibXlEYXRhIn0=\"}",
data);
Assert.Equal("application/json; charset=utf-8", contentType);
Assert.Equal("POST", type);
Assert.False(cache);
// Call the controller action manually
var response = await client.PostAsync(pageAddress + url,
new StringContent(data, Encoding.UTF8, "application/json"));
string json = await response.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeAnonymousType(json, new
{
success = false,
html = ""
});
Assert.True(content.success);
Assert.NotEmpty(content.html);
ObjectInstance p = new ObjectInstance(result.Engine);
p.FastAddProperty("success", new JsValue(true), true, false, false);
p.FastAddProperty("html", new JsValue(content.html), true, false, false);
success.Call(null, new[] { new JsValue(p) });
string after = document.ToStandardizedHtml();
// Assert
string beforePath = Helpers.GetResourcePath(@"AddNewItem\razor-simple-post-before.html");
string afterPath = Helpers.GetResourcePath(@"AddNewItem\razor-simple-post-after.html");
#if SAVE
after.ToFile(afterPath);
before.ToFile(beforePath);
#endif
string expectedBefore = beforePath.ToHtml();
string expectedAfter = afterPath.ToHtml();
Assert.Equal(expectedBefore, before);
Assert.Equal(expectedAfter, after);
}
[Fact]
public async void ListEditorFor_Post_WithAntiForgeryTokens_onClickShouldAddElementToRightPlace()
{
// Arrange
var context = BrowsingContext.New(config);
string pageAddress = "http://localhost:5000/EditSimpleByPostWithAntiForgeryTokens";
IDocument document = await context.OpenAsync(pageAddress);
await document.WaitForReadyAsync();
JsScriptingService js = (JsScriptingService)context.GetJsScripting();
// Act
await document.WaitUntilAvailable();
IHtmlInputElement antiForgeryField = (IHtmlInputElement)document.QuerySelector("input[name=\"__RequestVerificationToken\"]");
Assert.NotNull(antiForgeryField);
Assert.NotEmpty(antiForgeryField.Value);
IHtmlAnchorElement link = (IHtmlAnchorElement)document.QuerySelector("a[name='dynamic-list-addnewitem']");
ObjectInstance result = (ObjectInstance)js.EvaluateScript(document, link.GetAttribute("onclick"));
ObjectInstance containerObj = result.Get("container").AsObject();
IHtmlDivElement container = (IHtmlDivElement)containerObj.GetType().GetProperty("Value").GetValue(containerObj);
ObjectInstance optionsObj = result.Get("options").AsObject();
string url = optionsObj.Get("url").ToString();
string data = optionsObj.Get("data").ToString();
string contentType = optionsObj.Get("contentType").ToString();
string type = optionsObj.Get("type").ToString();
bool cache = optionsObj.Get("cache").AsBoolean();
ScriptFunctionInstance success = optionsObj.Get("success").As<ScriptFunctionInstance>();
Assert.Equal("?handler=AddSimpleItemByPost", url);
Assert.Equal("{\"ContainerId\":\"I\"," +
"\"ItemTemplate\":\"SimpleItem\"," +
"\"ItemContainerTemplate\":\"DynamicItemContainer\"," +
"\"ListTemplate\":\"EditorTemplates/DynamicList\"," +
"\"Prefix\":\"Input.Items\"," +
"\"Mode\":0,\"" +
"AdditionalViewData\":\"eyJEYXRhIjoibXlEYXRhIn0=\"}",
data);
Assert.Equal("application/json; charset=utf-8", contentType);
Assert.Equal("POST", type);
Assert.False(cache);
ObjectInstance headers = optionsObj.Get("headers").AsObject();
string verificationToken = headers.Get("RequestVerificationToken").AsString();
Assert.Equal(antiForgeryField.Value, verificationToken);
// Call the controller action manually
var contentToSend = new StringContent(data, Encoding.UTF8, "application/json");
contentToSend.Headers.Add("RequestVerificationToken", verificationToken);
var response = await client.PostAsync(pageAddress + url, contentToSend);
string json = await response.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeAnonymousType(json, new
{
success = false,
html = ""
});
Assert.True(content.success);
Assert.NotEmpty(content.html);
ObjectInstance p = new ObjectInstance(result.Engine);
p.FastAddProperty("success", new JsValue(true), true, false, false);
p.FastAddProperty("html", new JsValue(content.html), true, false, false);
success.Call(null, new[] { new JsValue(p) });
}
}
}
| 43.941368 | 137 | 0.612454 | [
"MIT"
] | cesarsouza/dvml | tests/Unit Tests/Pages/AddNewItemPageTests.cs | 13,490 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
namespace DiscoveryTestProject3
{
[TestClass]
public class LongDiscoveryTestClass
{
// This is for discovery cancellation test.
// 20 tests below to be discovered until we reach the X_ Y_ Z_LongDiscoveryTestMethod which haver attribute that
// takes a very long time to create, which prolongs the discovery time and keeps us discovering while we
// are cancelling the discovery from the test.
#region 20 empty tests
[TestMethod]
public void TestMethod1()
{
}
[TestMethod]
public void TestMethod2()
{
}
[TestMethod]
public void TestMethod3()
{
}
[TestMethod]
public void TestMethod4()
{
}
[TestMethod]
public void TestMethod5()
{
}
[TestMethod]
public void TestMethod6()
{
}
[TestMethod]
public void TestMethod7()
{
}
[TestMethod]
public void TestMethod8()
{
}
[TestMethod]
public void TestMethod9()
{
}
[TestMethod]
public void TestMethod10()
{
}
[TestMethod]
public void TestMethod11()
{
}
[TestMethod]
public void TestMethod12()
{
}
[TestMethod]
public void TestMethod13()
{
}
[TestMethod]
public void TestMethod14()
{
}
[TestMethod]
public void TestMethod15()
{
}
[TestMethod]
public void TestMethod16()
{
}
[TestMethod]
public void TestMethod17()
{
}
[TestMethod]
public void TestMethod18()
{
}
[TestMethod]
public void TestMethod19()
{
}
[TestMethod]
public void TestMethod20()
{
}
#endregion
// X_ to make it discover last.
[TestMethodWithDelay]
public void X_LongDiscoveryTestMethod()
{
}
// Y_ to make it discover last.
[TestMethodWithDelay]
public void Y_LongDiscoveryTestMethod()
{
}
// Z_ to make it discover last.
[TestMethodWithDelay]
public void Z_LongDiscoveryTestMethod()
{
}
}
internal class TestMethodWithDelayAttribute : TestMethodAttribute
{
public TestMethodWithDelayAttribute()
{
// This will be multiplied by 3 because the framework will internally create this
// attribute 3 times. And by another 3 because we have 3 slow tests.
Thread.Sleep(100);
}
}
}
| 19.901961 | 120 | 0.533005 | [
"MIT"
] | Evangelink/vstest | test/TestAssets/DiscoveryTestProject/LongDiscoveryTestClass.cs | 3,047 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AuthenticationWebApi
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class UserCredentialsEntities : DbContext
{
public UserCredentialsEntities()
: base("name=UserCredentialsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<UserDetail> UserDetails { get; set; }
}
}
| 31.419355 | 85 | 0.553388 | [
"MIT"
] | kranthi467/KranthiPOCs | .NET/AuthenticationWebApi/AuthenticationWebApi/UserCredentials.Context.cs | 976 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dnc
{
/// <summary>
/// Used for parallel computation and starting some threads to process items.
/// <see cref="Task"/>
/// <see cref="Parallel"/>
/// </summary>
public class TaskManager
{
/// <summary>
/// Pallel computation using tasks <see cref="Task"/>.
/// </summary>
/// <typeparam name="T">WorkItem</typeparam>
/// <param name="workItems">list</param>
/// <param name="batch">count per batch</param>
/// <param name="act">Action for list</param>
public static void QueueWorkItemUsingTasks<T>(IEnumerable<T> workItems,
int batch,
Action<IEnumerable<T>> act)
where T : class, new()
{
if (workItems == null || workItems.Count() == 0)
throw new ArgumentNullException("Work items not allowed null or empty.");
var total = workItems.Count();
var pageCount = (total + batch - 1) / batch;
var tasks = new List<Task>();
for (int i = 0; i < pageCount; i++)
{
var pageIndex = i + 1;
var items = workItems.Skip((pageIndex - 1) * batch).Take(batch);
tasks.Add(Task.Run(() =>
{
act.Invoke(items);
}));
}
Task.WaitAll(tasks.ToArray());
}
/// <summary>
/// Pallel computation using parallel <see cref="Parallel"/>.
/// </summary>
/// <typeparam name="T">WorkItem</typeparam>
/// <param name="workItems">list</param>
/// <param name="batch">count per batch</param>
/// <param name="act">Action for list</param>
public static void QueueWorkItemsUsingParallel<T>(IEnumerable<T> workItems,
int batch,
Action<IEnumerable<T>> act)
where T : class, new()
{
if (workItems == null || workItems.Count() == 0)
throw new ArgumentNullException("Work items not allowed null or empty.");
var total = workItems.Count();
var pageCount = (total + batch - 1) / batch;
var actions = new List<Action>();
for (int i = 0; i < pageCount; i++)
{
var pageIndex = i + 1;
var items = workItems.Skip((pageIndex - 1) * batch).Take(batch);
actions.Add(() =>
{
act.Invoke(items);
});
}
Parallel.Invoke(actions.ToArray());
}
}
}
| 32.46988 | 89 | 0.504267 | [
"MIT"
] | gainorloss/Dnc.Core | src/Dnc.Core/Helpers/TaskManager.cs | 2,697 | 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.Diagnostics;
using System.IO;
using System.Globalization;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Collections;
namespace Microsoft.Build.Execution
{
/// <summary>
/// Contains the result items for a single target as well as the overall result code.
/// </summary>
public class TargetResult : ITargetResult, ITranslatable
{
/// <summary>
/// The result for this target.
/// </summary>
private WorkUnitResult _result;
/// <summary>
/// Flag indicating whether to consider this target failure as having caused a build failure.
/// </summary>
private bool _targetFailureDoesntCauseBuildFailure;
/// <summary>
/// Flag indicating whether at least one target which has run after us (transitively via AfterTargets) failed.
/// </summary>
private bool _afterTargetsHaveFailed;
/// <summary>
/// The store of items in this result.
/// </summary>
private TaskItem[] _items;
/// <summary>
/// The context under which these results have been cached.
/// </summary>
private CacheInfo _cacheInfo;
/// <summary>
/// The (possibly null) <see cref="BuildEventContext"/> from the original target build
/// </summary>
private BuildEventContext _originalBuildEventContext;
/// <summary>
/// Initializes the results with specified items and result.
/// </summary>
/// <param name="items">The items produced by the target.</param>
/// <param name="result">The overall result for the target.</param>
/// <param name="originalBuildEventContext">The original build event context from when the target was first built, if available.
/// Non-null when creating a <see cref="TargetResult"/> after building the target initially (or skipping due to false condition).
/// Null when the <see cref="TargetResult"/> is being created in other scenarios:
/// * Target that never ran because a dependency had an error
/// * in <see cref="ITargetBuilderCallback.LegacyCallTarget"/> when Cancellation was requested
/// * in ProjectCache.CacheResult.ConstructBuildResult
/// </param>
internal TargetResult(TaskItem[] items, WorkUnitResult result, BuildEventContext originalBuildEventContext = null)
{
ErrorUtilities.VerifyThrowArgumentNull(items, nameof(items));
ErrorUtilities.VerifyThrowArgumentNull(result, nameof(result));
_items = items;
_result = result;
_originalBuildEventContext = originalBuildEventContext;
}
/// <summary>
/// Private constructor for deserialization
/// </summary>
private TargetResult(ITranslator translator)
{
((ITranslatable)this).Translate(translator);
}
/// <summary>
/// Returns the exception which aborted this target, if any.
/// </summary>
/// <value>The exception which aborted this target, if any.</value>
public Exception Exception
{
[DebuggerStepThrough]
get => _result.Exception;
}
/// <summary>
/// Returns the items produced by the target.
/// These are ITaskItem's, so they have no item-type.
/// </summary>
/// <value>The items produced by the target.</value>
public ITaskItem[] Items
{
[DebuggerStepThrough]
get
{
lock (_result)
{
RetrieveItemsFromCache();
return _items;
}
}
}
/// <summary>
/// Returns the result code for the target.
/// </summary>
/// <value>The result code for the target.</value>
public TargetResultCode ResultCode
{
[DebuggerStepThrough]
get
{
switch (_result.ResultCode)
{
case WorkUnitResultCode.Canceled:
case WorkUnitResultCode.Failed:
return TargetResultCode.Failure;
case WorkUnitResultCode.Skipped:
return TargetResultCode.Skipped;
case WorkUnitResultCode.Success:
return TargetResultCode.Success;
default:
return TargetResultCode.Skipped;
}
}
}
/// <summary>
/// Returns the internal result for the target.
/// </summary>
internal WorkUnitResult WorkUnitResult
{
[DebuggerStepThrough]
get => _result;
}
/// <summary>
/// The (possibly null) <see cref="BuildEventContext"/> from the original target build
/// </summary>
internal BuildEventContext OriginalBuildEventContext => _originalBuildEventContext;
/// <summary>
/// Sets or gets a flag indicating whether or not a failure results should cause the build to fail.
/// </summary>
internal bool TargetFailureDoesntCauseBuildFailure
{
[DebuggerStepThrough]
get => _targetFailureDoesntCauseBuildFailure;
[DebuggerStepThrough]
set => _targetFailureDoesntCauseBuildFailure = value;
}
/// <summary>
/// Sets or gets a flag indicating whether at least one target which has run after us (transitively via AfterTargets) failed.
/// </summary>
internal bool AfterTargetsHaveFailed
{
[DebuggerStepThrough]
get => _afterTargetsHaveFailed;
[DebuggerStepThrough]
set => _afterTargetsHaveFailed = value;
}
#region INodePacketTranslatable Members
/// <summary>
/// Reads or writes the packet to the serializer.
/// </summary>
void ITranslatable.Translate(ITranslator translator)
{
if (translator.Mode == TranslationDirection.WriteToStream)
{
lock (_result)
{
// Should we have cached these items but now want to send them to another node, we need to
// ensure they are loaded before doing so.
RetrieveItemsFromCache();
InternalTranslate(translator);
}
}
else
{
InternalTranslate(translator);
}
}
/// <summary>
/// Factory for serialization.
/// </summary>
internal static TargetResult FactoryForDeserialization(ITranslator translator)
{
return new TargetResult(translator);
}
#endregion
/// <summary>
/// Gets the name of the cache file for this configuration.
/// </summary>
internal static string GetCacheFile(int configId, string targetToCache)
{
string filename = Path.Combine(FileUtilities.GetCacheDirectory(), String.Format(CultureInfo.InvariantCulture, Path.Combine("Results{0}", "{1}.cache"), configId, targetToCache));
return filename;
}
/// <summary>
/// Gets the name of the cache file for this configuration.
/// </summary>
internal static string GetCacheDirectory(int configId, string targetToCache)
{
string filename = GetCacheFile(configId, targetToCache);
string directoryName = Path.GetDirectoryName(filename);
return directoryName;
}
/// <summary>
/// Cache the items.
/// </summary>
internal void CacheItems(int configId, string targetName)
{
lock (_result)
{
if (_items == null)
{
// Already cached.
return;
}
if (_items.Length == 0)
{
// Nothing to cache.
return;
}
ITranslator translator = GetResultsCacheTranslator(configId, targetName, TranslationDirection.WriteToStream);
// If the translator is null, it means these results were cached once before. Since target results are immutable once they
// have been created, there is no point in writing them again.
if (translator != null)
{
try
{
TranslateItems(translator);
_items = null;
_cacheInfo = new CacheInfo(configId, targetName);
}
finally
{
translator.Writer.BaseStream.Dispose();
}
}
}
}
/// <summary>
/// Performs the actual translation
/// </summary>
private void InternalTranslate(ITranslator translator)
{
translator.Translate(ref _result, WorkUnitResult.FactoryForDeserialization);
translator.Translate(ref _targetFailureDoesntCauseBuildFailure);
translator.Translate(ref _afterTargetsHaveFailed);
translator.TranslateOptionalBuildEventContext(ref _originalBuildEventContext);
TranslateItems(translator);
}
/// <summary>
/// Retrieve the items from the cache.
/// </summary>
private void RetrieveItemsFromCache()
{
lock (_result)
{
if (_items == null)
{
ITranslator translator = GetResultsCacheTranslator(_cacheInfo.ConfigId, _cacheInfo.TargetName, TranslationDirection.ReadFromStream);
try
{
TranslateItems(translator);
_cacheInfo = new CacheInfo();
}
finally
{
translator.Reader.BaseStream.Dispose();
}
}
}
}
private void TranslateItems(ITranslator translator)
{
var itemsCount = _items?.Length ?? 0;
translator.Translate(ref itemsCount);
if (translator.Mode == TranslationDirection.WriteToStream)
{
// We will just calculate a very rough starting buffer size for the memory stream based on the number of items and a
// rough guess for an average number of bytes needed to store them. This doesn't have to be accurate, just
// big enough to avoid unnecessary buffer reallocations in most cases.
var defaultBufferCapacity = _items.Length * 128;
using var itemsStream = new MemoryStream(defaultBufferCapacity);
var itemTranslator = BinaryTranslator.GetWriteTranslator(itemsStream);
// When creating the interner, we use the number of items as the initial size of the collections since the
// number of strings will be of the order of the number of items in the collection. This assumes basically
// one unique string per item (frequently a path related to the item) with most of the rest of the metadata
// being the same (and thus interning.) This is a hueristic meant to get us in the ballpark to avoid
// too many reallocations when growing the collections.
var interner = new LookasideStringInterner(StringComparer.Ordinal, _items.Length);
foreach (TaskItem t in _items)
{
t.TranslateWithInterning(itemTranslator, interner);
}
interner.Translate(translator);
var buffer = itemsStream.GetBuffer();
var bufferSize = (int)itemsStream.Length;
translator.Translate(ref buffer, ref bufferSize);
}
else
{
var interner = new LookasideStringInterner(translator);
byte[] buffer = null;
translator.Translate(ref buffer);
ErrorUtilities.VerifyThrow(buffer != null, "Unexpected null items buffer during translation.");
using MemoryStream itemsStream = new MemoryStream(buffer, 0, buffer.Length, writable: false, publiclyVisible: true);
var itemTranslator = BinaryTranslator.GetReadTranslator(itemsStream, null);
_items = new TaskItem[itemsCount];
for (int i = 0; i < _items.Length; i++)
{
_items[i] = TaskItem.FactoryForDeserialization(itemTranslator, interner);
}
}
}
/// <summary>
/// Gets the translator for this configuration.
/// </summary>
private static ITranslator GetResultsCacheTranslator(int configId, string targetToCache, TranslationDirection direction)
{
string cacheFile = GetCacheFile(configId, targetToCache);
if (direction == TranslationDirection.WriteToStream)
{
Directory.CreateDirectory(Path.GetDirectoryName(cacheFile));
if (FileSystems.Default.FileExists(cacheFile))
{
// If the file already exists, then we have cached this once before. No need to cache it again since it cannot have changed.
return null;
}
return BinaryTranslator.GetWriteTranslator(File.Create(cacheFile));
}
else
{
return BinaryTranslator.GetReadTranslator(File.OpenRead(cacheFile), null);
}
}
/// <summary>
/// Information about where the cache for the items in this result are stored.
/// </summary>
private struct CacheInfo
{
/// <summary>
/// Constructor.
/// </summary>
public CacheInfo(int configId, string targetName)
{
ConfigId = configId;
TargetName = targetName;
}
/// <summary>
/// Retrieves the configuration id.
/// </summary>
public int ConfigId { get; }
/// <summary>
/// Retrieves the target name.
/// </summary>
public string TargetName { get; }
}
}
}
| 37.7325 | 189 | 0.561055 | [
"MIT"
] | 478254406/msbuild | src/Build/BackEnd/Shared/TargetResult.cs | 15,095 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseNullPropagation
{
internal abstract class AbstractUseNullPropagationCodeFixProvider<
TSyntaxKind,
TExpressionSyntax,
TConditionalExpressionSyntax,
TBinaryExpressionSyntax,
TInvocationExpression,
TMemberAccessExpression,
TConditionalAccessExpression,
TElementAccessExpression> : SyntaxEditorBasedCodeFixProvider
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
where TBinaryExpressionSyntax : TExpressionSyntax
where TInvocationExpression : TExpressionSyntax
where TMemberAccessExpression : TExpressionSyntax
where TConditionalAccessExpression : TExpressionSyntax
where TElementAccessExpression : TExpressionSyntax
{
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseNullPropagationDiagnosticId);
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return SpecializedTasks.EmptyTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionalPart = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan, getInnermostNodeForTie: true);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan, getInnermostNodeForTie: true);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
var whenPartIsNullable = diagnostic.Properties.ContainsKey(UseNullPropagationConstants.WhenPartIsNullable);
editor.ReplaceNode(conditionalExpression,
(c, g) => {
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
var currentWhenPartToCheck = whenPart == whenTrue ? currentWhenTrue : currentWhenFalse;
var match = AbstractUseNullPropagationDiagnosticAnalyzer<
TSyntaxKind, TExpressionSyntax, TConditionalExpressionSyntax,
TBinaryExpressionSyntax, TInvocationExpression, TMemberAccessExpression,
TConditionalAccessExpression, TElementAccessExpression>.GetWhenPartMatch(syntaxFacts, semanticFacts, semanticModel, conditionalPart, currentWhenPartToCheck);
if (match == null)
{
return c;
}
var newNode = CreateConditionalAccessExpression(
syntaxFacts, g, whenPartIsNullable, currentWhenPartToCheck, match, c);
newNode = newNode.WithTriviaFrom(c);
return newNode;
});
}
}
private SyntaxNode CreateConditionalAccessExpression(
ISyntaxFactsService syntaxFacts, SyntaxGenerator generator, bool whenPartIsNullable,
SyntaxNode whenPart, SyntaxNode match, SyntaxNode currentConditional)
{
if (whenPartIsNullable)
{
if (match.Parent is TMemberAccessExpression memberAccess)
{
var nameNode = syntaxFacts.GetNameOfMemberAccessExpression(memberAccess);
syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity);
var comparer = syntaxFacts.StringComparer;
if (arity == 0 && comparer.Equals(name, nameof(Nullable<int>.Value)))
{
// They're calling ".Value" off of a nullable. Because we're moving to ?.
// we want to remove the .Value as well. i.e. we should generate:
//
// goo?.Bar() not goo?.Value.Bar();
return CreateConditionalAccessExpression(
syntaxFacts, generator, whenPart, match,
memberAccess.Parent, currentConditional);
}
}
}
return CreateConditionalAccessExpression(
syntaxFacts, generator, whenPart, match,
match.Parent, currentConditional);
}
private SyntaxNode CreateConditionalAccessExpression(
ISyntaxFactsService syntaxFacts, SyntaxGenerator generator,
SyntaxNode whenPart, SyntaxNode match, SyntaxNode matchParent, SyntaxNode currentConditional)
{
if (matchParent is TMemberAccessExpression memberAccess)
{
return whenPart.ReplaceNode(memberAccess,
generator.ConditionalAccessExpression(
match,
generator.MemberBindingExpression(
syntaxFacts.GetNameOfMemberAccessExpression(memberAccess))));
}
if (matchParent is TElementAccessExpression elementAccess)
{
return whenPart.ReplaceNode(elementAccess,
generator.ConditionalAccessExpression(
match,
generator.ElementBindingExpression(
syntaxFacts.GetArgumentListOfElementAccessExpression(elementAccess))));
}
return currentConditional;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Use_null_propagation, createChangedDocument)
{
}
}
}
}
| 47.69375 | 185 | 0.639497 | [
"Apache-2.0"
] | DaiMichael/roslyn | src/Features/Core/Portable/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs | 7,633 | C# |
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace DanTup.DartVS
{
// https://github.com/Sectoid/debian-dlr-languages/blob/5f1b292f62f2b5a2d92c5a564ff58816419af1da/Tools/IronStudio/IronPythonTools/IronPythonTools/Navigation/CodeWindowManager.cs
class DartCodeWindowManager : IVsCodeWindowManager
{
IVsDropdownBarManager barManager;
IWpfTextView wpfTextView;
ITextDocument textDocument;
DartAnalysisServiceFactory analysisServiceFactory;
NavigationDropdown dropdown;
public DartCodeWindowManager(ITextDocumentFactoryService textDocumentFactory, IVsEditorAdaptersFactoryService editorAdapterFactory, IVsCodeWindow codeWindow, DartAnalysisServiceFactory analysisServiceFactory)
{
this.barManager = ((IVsDropdownBarManager)codeWindow);
this.analysisServiceFactory = analysisServiceFactory;
// Figure out the filename (seriously; this is the best way?!).
IVsTextView textView;
codeWindow.GetPrimaryView(out textView);
wpfTextView = editorAdapterFactory.GetWpfTextView(textView);
textDocumentFactory.TryGetTextDocument(wpfTextView.TextBuffer, out this.textDocument);
}
public int AddAdornments()
{
dropdown = new NavigationDropdown(analysisServiceFactory, textDocument.FilePath, wpfTextView);
barManager.AddDropdownBar(2, dropdown);
return VSConstants.S_OK;
}
public int OnNewView(IVsTextView pView)
{
return VSConstants.S_OK;
}
public int RemoveAdornments()
{
dropdown.Unregister();
barManager.RemoveDropdownBar();
return VSConstants.S_OK;
}
}
}
| 33.62 | 210 | 0.812612 | [
"MIT"
] | DartVS/DartVS | DanTup.DartVS.Vsix/Navigation/DartCodeWindowManager.cs | 1,683 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ServiceBus;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Capture storage details for capture description
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class Destination
{
/// <summary>
/// Initializes a new instance of the Destination class.
/// </summary>
public Destination()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Destination class.
/// </summary>
/// <param name="name">Name for capture destination</param>
/// <param name="storageAccountResourceId">Resource id of the storage
/// account to be used to create the blobs</param>
/// <param name="blobContainer">Blob container Name</param>
/// <param name="archiveNameFormat">Blob naming convention for archive,
/// e.g.
/// {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}.
/// Here all the parameters (Namespace,EventHub .. etc) are mandatory
/// irrespective of order</param>
public Destination(string name = default(string), string storageAccountResourceId = default(string), string blobContainer = default(string), string archiveNameFormat = default(string))
{
Name = name;
StorageAccountResourceId = storageAccountResourceId;
BlobContainer = blobContainer;
ArchiveNameFormat = archiveNameFormat;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets name for capture destination
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets resource id of the storage account to be used to
/// create the blobs
/// </summary>
[JsonProperty(PropertyName = "properties.storageAccountResourceId")]
public string StorageAccountResourceId { get; set; }
/// <summary>
/// Gets or sets blob container Name
/// </summary>
[JsonProperty(PropertyName = "properties.blobContainer")]
public string BlobContainer { get; set; }
/// <summary>
/// Gets or sets blob naming convention for archive, e.g.
/// {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}.
/// Here all the parameters (Namespace,EventHub .. etc) are mandatory
/// irrespective of order
/// </summary>
[JsonProperty(PropertyName = "properties.archiveNameFormat")]
public string ArchiveNameFormat { get; set; }
}
}
| 38.078652 | 192 | 0.628799 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/ServiceBus/Management.ServiceBus/Generated/Models/Destination.cs | 3,389 | C# |
namespace Octokit.GraphQL
{
/// <summary>
/// Represents a product header value. This is used to generate the User Agent string sent with each request. The
/// name used should represent the product that's using Octokit.net.
/// </summary>
/// <remarks>
/// This class is a wrapper around <seealso href="https://msdn.microsoft.com/en-us/library/system.net.http.headers.productheadervalue(v=vs.118).aspx"/>
/// so that consumers of Octokit.net would not have to add a reference to the System.Net.Http.Headers namespace.
/// </remarks>
public class ProductHeaderValue
{
readonly System.Net.Http.Headers.ProductHeaderValue _productHeaderValue;
/// <summary>
/// Initializes a new instance of the <see cref="ProductHeaderValue"/> class.
/// </summary>
/// <param name="name">The name of the product that's using Octokit</param>
public ProductHeaderValue(string name)
: this(new System.Net.Http.Headers.ProductHeaderValue(name))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductHeaderValue"/> class.
/// </summary>
/// <param name="name">The name of the product that's using Octokit</param>
/// <param name="version">The version of the product that's using Octokit</param>
public ProductHeaderValue(string name, string version)
: this(new System.Net.Http.Headers.ProductHeaderValue(name, version))
{
}
ProductHeaderValue(System.Net.Http.Headers.ProductHeaderValue productHeader)
{
_productHeaderValue = productHeader;
}
/// <summary>
/// The name of the product that's using Octokit
/// </summary>
public string Name
{
get { return _productHeaderValue.Name; }
}
/// <summary>
/// The version of the product.
/// </summary>
public string Version
{
get { return _productHeaderValue.Version; }
}
public override bool Equals(object obj)
{
return _productHeaderValue.Equals(obj);
}
public override int GetHashCode()
{
return _productHeaderValue.GetHashCode();
}
public override string ToString()
{
return _productHeaderValue.ToString();
}
/// <summary>
/// Parses a string in the format "foo" or "foo/1.0" and returns the corresponding
/// <see cref="ProductHeaderValue" /> instance.
/// </summary>
/// <param name="input">The input.</param>
public static ProductHeaderValue Parse(string input)
{
return new ProductHeaderValue(System.Net.Http.Headers.ProductHeaderValue.Parse(input));
}
/// <summary>
/// Parses a string in the format "foo" or "foo/1.0" and returns the corresponding
/// <see cref="ProductHeaderValue" /> instance via an out parameter.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="parsedValue">The parsed value.</param>
public static bool TryParse(string input,
out ProductHeaderValue parsedValue)
{
System.Net.Http.Headers.ProductHeaderValue value;
var result = System.Net.Http.Headers.ProductHeaderValue.TryParse(input, out value);
parsedValue = result ? Parse(input) : null;
return result;
}
}
}
| 36.885417 | 156 | 0.603219 | [
"MIT"
] | 0xced/octokit.graphql.net | Octokit.GraphQL.Core/ProductHeaderValue.cs | 3,543 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenHtmlToPdf.Tests.Helpers;
namespace OpenHtmlToPdf.Tests
{
[TestClass]
public class HtmlToPdfConversion
{
private const string HtmlDocumentFormat = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Title</title></head><body>{0}</body></html>";
private const int _210mmInPostScriptPoints = 595;
private const int _297mmInPostScriptPoints = 842;
[TestMethod]
public void Pdf_document_content()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Text_encoding()
{
const string expectedDocumentContent = "Äöåõ";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).EncodedWith("utf-8").Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Document_title()
{
const string expectedTitle = "Expected title";
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).WithTitle(expectedTitle).Content();
Assert.AreEqual(expectedTitle, PdfDocumentReader.Title(result));
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Page_size()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).OfSize(PaperSize.A4).Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
Assert.AreEqual(_210mmInPostScriptPoints, PdfDocumentReader.WidthOfFirstPage(result));
Assert.AreEqual(_297mmInPostScriptPoints, PdfDocumentReader.HeightOfFirstPage(result));
}
[TestMethod]
public void Portrait()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).Portrait().Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
Assert.AreEqual(_210mmInPostScriptPoints, PdfDocumentReader.WidthOfFirstPage(result));
Assert.AreEqual(_297mmInPostScriptPoints, PdfDocumentReader.HeightOfFirstPage(result));
}
[TestMethod]
public void Landscape()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).Landscape().Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
Assert.AreEqual(_297mmInPostScriptPoints, PdfDocumentReader.WidthOfFirstPage(result));
Assert.AreEqual(_210mmInPostScriptPoints, PdfDocumentReader.HeightOfFirstPage(result));
}
[TestMethod]
public void Margins()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).WithMargins(1.25.Centimeters()).Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void With_outline()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).WithOutline().Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Without_outline()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var result = Pdf.From(html).WithoutOutline().Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Is_directory_agnostic()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
Directory.SetCurrentDirectory(@"c:\");
var result = Pdf.From(html).Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(result));
}
[TestMethod]
public void Convert_multiple_documents_concurrently()
{
const string expectedDocumentContent = "Expected document content";
const int documentCount = 10;
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var tasks = new List<Task<byte[]>>();
for (var i = 0; i < documentCount; i++)
tasks.Add(Task.Run(() => Pdf.From(html).Content()));
Task.WaitAll(tasks.OfType<Task>().ToArray());
foreach (var task in tasks)
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(task.Result));
}
[TestMethod]
public void Convert_multiple_documents_sequently()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var first = Pdf.From(html).Content();
var second = Pdf.From(html).Content();
var third = Pdf.From(html).Content();
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(first));
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(second));
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(third));
}
[TestMethod]
public void No_temporary_files_are_left_behind()
{
const string expectedDocumentContent = "Expected document content";
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
Pdf.From(html).Content();
Assert.AreEqual(0, Directory.GetFiles(Path.Combine(Path.GetTempPath(), "OpenHtmlToPdf"), "*.pdf").Count());
}
[TestMethod]
public void Convert_massive_number_of_documents()
{
const string expectedDocumentContent = "Expected document content";
const int documentCount = 100;
var html = string.Format(HtmlDocumentFormat, expectedDocumentContent);
var tasks = new List<Task<byte[]>>();
for (var i = 0; i < documentCount; i++)
tasks.Add(Task.Run(() => Pdf.From(html).Content()));
Task.WaitAll(tasks.OfType<Task>().ToArray());
foreach (var task in tasks)
TextAssert.AreEqual(expectedDocumentContent, PdfDocumentReader.ToText(task.Result));
}
}
} | 38.850746 | 152 | 0.653477 | [
"MIT"
] | InfiniSwiss/InfiniSwiss.OpenHtmlToPdf | InfiniSwiss.OpenHtmlToPdf.Tests/HtmlToPdfConversion.cs | 7,815 | C# |
#nullable enable
using System;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
namespace Content.Shared.Throwing
{
[RequiresExplicitImplementation]
public interface IThrowCollide
{
void HitBy(ThrowCollideEventArgs eventArgs) {}
void DoHit(ThrowCollideEventArgs eventArgs) {}
}
public class ThrowCollideEventArgs : EventArgs
{
/// <summary>
/// The entity that threw <see cref="Thrown"/> and hit <see cref="Target"/>.
/// </summary>
public IEntity? User { get; }
/// <summary>
/// The entity thrown by <see cref="User"/> that hit <see cref="Target"/>
/// </summary>
public IEntity Thrown { get; }
/// <summary>
/// The entity hit with <see cref="Thrown"/> by <see cref="User"/>
/// </summary>
public IEntity Target { get; }
public ThrowCollideEventArgs(IEntity? user, IEntity thrown, IEntity target)
{
User = user;
Thrown = thrown;
Target = target;
}
}
public class ThrowCollideEvent : HandledEntityEventArgs
{
/// <summary>
/// The entity that threw <see cref="Thrown"/>.
/// </summary>
public IEntity? User { get; }
/// <summary>
/// The entity thrown by <see cref="User"/> that hit <see cref="Target"/>
/// </summary>
public IEntity Thrown { get; }
/// <summary>
/// The entity hit with <see cref="Thrown"/> by <see cref="User"/>
/// </summary>
public IEntity Target { get; }
public ThrowCollideEvent(IEntity? user, IEntity thrown, IEntity target)
{
User = user;
Thrown = thrown;
Target = target;
}
}
}
| 28.030769 | 88 | 0.547201 | [
"MIT"
] | Bright0/space-station-14 | Content.Shared/Throwing/IThrowCollide.cs | 1,822 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Datadog.Outputs
{
[OutputType]
public sealed class DashboardWidgetToplistDefinitionRequestQueryProcessQuery
{
public readonly string? Aggregator;
public readonly string DataSource;
public readonly bool? IsNormalizedCpu;
public readonly int? Limit;
public readonly string Metric;
public readonly string Name;
public readonly string? Sort;
public readonly ImmutableArray<string> TagFilters;
public readonly string? TextFilter;
[OutputConstructor]
private DashboardWidgetToplistDefinitionRequestQueryProcessQuery(
string? aggregator,
string dataSource,
bool? isNormalizedCpu,
int? limit,
string metric,
string name,
string? sort,
ImmutableArray<string> tagFilters,
string? textFilter)
{
Aggregator = aggregator;
DataSource = dataSource;
IsNormalizedCpu = isNormalizedCpu;
Limit = limit;
Metric = metric;
Name = name;
Sort = sort;
TagFilters = tagFilters;
TextFilter = textFilter;
}
}
}
| 26.913793 | 88 | 0.625881 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-datadog | sdk/dotnet/Outputs/DashboardWidgetToplistDefinitionRequestQueryProcessQuery.cs | 1,561 | C# |
namespace SmartConnect.Web.Infrastructure.ModelBinders
{
using System;
using System.Web.Mvc;
using Contracts;
using Data.Models.Contracts;
using Data.Repositories.Contracts;
public class EntityModelBinder<TEntity> : IModelBinder<TEntity, Guid>
where TEntity : class, IEntity<Guid>
{
private readonly IRepository<TEntity, Guid> repository;
public EntityModelBinder(IRepository<TEntity, Guid> repository)
{
this.repository = repository;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue("id");
var id = Guid.Parse(value.AttemptedValue);
var entity = this.repository.GetById(id);
return entity;
}
}
}
| 29.655172 | 104 | 0.660465 | [
"MIT"
] | vassildinev/Smart-Connect | Source/Web/SmartConnect.Web.Infrastructure/ModelBinders/EntityModelBinder{TEntity}.cs | 862 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
namespace DotNetWebApi.Tests
{
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:5000");
//POST
Product product = new Product();
product.title = "Comprar azucar";
Console.WriteLine("Serializado:" + JsonConvert.SerializeObject(product).ToString());
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(product));
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var responsePost = client.PostAsync("/api/v1/todos", httpContent).GetAwaiter().GetResult();
if(responsePost.IsSuccessStatusCode)
{
Console.WriteLine("Post exitoso");
}
else
{
Console.WriteLine("Error al realizar el post");
}
Console.WriteLine("Response Post:" + responsePost);
//GET
var response = client.GetAsync("/api/v1/todos").GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Conexion exitosa");
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine("Content:" + content);
var jsonArray = JsonConvert.DeserializeObject<JArray>(content);
Console.WriteLine("Array:" + jsonArray);
Console.WriteLine("Elemento 0:" + jsonArray[0]);
Console.WriteLine("Title 0:" + jsonArray[0]["title"]);
}
else
{
Console.WriteLine("Error en la respuesta");
}
Console.WriteLine("Response:" + response);
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
public class Product
{
public int id { get; set; }
public string title { get; set; }
public bool isComplete { get; set; }
}
}
| 29.857143 | 116 | 0.541975 | [
"MIT"
] | alegh1390/curso-rest-apis-lab5 | src/services/DotNetWebApi.Tests/DotNetWebApi.Tests/Program.cs | 2,301 | C# |
using System;
namespace Chesham.Forza.ForzaHorizon4.Data.Attribute
{
[AttributeUsage(AttributeTargets.Property)]
class PlaceholderAttribute : System.Attribute
{
public int Size { get; }
public PlaceholderAttribute(int sizeInBytes)
{
this.Size = sizeInBytes;
}
}
}
| 21.375 | 53 | 0.616959 | [
"MIT"
] | Chesham/Chesham.Forza | Chesham.Forza.ForzaHorizon4.Data/Attribute/PlaceholderAttribute.cs | 344 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A09Level11111ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="A09Level11111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A08Level1111"/> collection.
/// </remarks>
[Serializable]
public partial class A09Level11111ReChild : BusinessBase<A09Level11111ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int cNarentID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A09Level11111ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A09Level11111ReChild"/> object.</returns>
internal static A09Level11111ReChild NewA09Level11111ReChild()
{
return DataPortal.CreateChild<A09Level11111ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="A09Level11111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A09Level11111ReChild"/> object.</returns>
internal static A09Level11111ReChild GetA09Level11111ReChild(SafeDataReader dr)
{
A09Level11111ReChild obj = new A09Level11111ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A09Level11111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private A09Level11111ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A09Level11111ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A09Level11111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name"));
cNarentID2 = dr.GetInt32("CNarentID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A09Level11111ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddA09Level11111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A09Level11111ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateA09Level11111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="A09Level11111ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteA09Level11111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| 39.240664 | 180 | 0.586021 | [
"MIT"
] | CslaGenFork/CslaGenFork | tags/DeepLoad sample v.1.0.0/ParentLoad.Business/ERLevel/A09Level11111ReChild.Designer.cs | 9,457 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public partial class FairyGUIUtilsHtmlInputWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(FairyGUI.Utils.HtmlInput);
Utils.BeginObjectRegister(type, L, translator, 0, 11, 5, 0);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Create", _m_Create);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "SetPosition", _m_SetPosition);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Add", _m_Add);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Remove", _m_Remove);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Release", _m_Release);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Dispose", _m_Dispose);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "gettextInput", _g_get_textInput);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getdisplayObject", _g_get_displayObject);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getelement", _g_get_element);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getwidth", _g_get_width);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getheight", _g_get_height);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "textInput", _g_get_textInput);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "displayObject", _g_get_displayObject);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "element", _g_get_element);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "width", _g_get_width);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "height", _g_get_height);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 13, 3, 3);
Utils.RegisterFunc(L, Utils.CLS_IDX, "getdefaultBorderSize", _g_get_defaultBorderSize);
Utils.RegisterFunc(L, Utils.CLS_IDX, "getdefaultBorderColor", _g_get_defaultBorderColor);
Utils.RegisterFunc(L, Utils.CLS_IDX, "getdefaultBackgroundColor", _g_get_defaultBackgroundColor);
Utils.RegisterFunc(L, Utils.CLS_IDX, "setdefaultBorderSize", _s_set_defaultBorderSize);
Utils.RegisterFunc(L, Utils.CLS_IDX, "setdefaultBorderColor", _s_set_defaultBorderColor);
Utils.RegisterFunc(L, Utils.CLS_IDX, "setdefaultBackgroundColor", _s_set_defaultBackgroundColor);
Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "defaultBorderSize", _g_get_defaultBorderSize);
Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "defaultBorderColor", _g_get_defaultBorderColor);
Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "defaultBackgroundColor", _g_get_defaultBackgroundColor);
Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "defaultBorderSize", _s_set_defaultBorderSize);
Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "defaultBorderColor", _s_set_defaultBorderColor);
Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "defaultBackgroundColor", _s_set_defaultBackgroundColor);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
FairyGUI.Utils.HtmlInput gen_ret = new FairyGUI.Utils.HtmlInput();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to FairyGUI.Utils.HtmlInput constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Create(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
FairyGUI.RichTextField _owner = (FairyGUI.RichTextField)translator.GetObject(L, 2, typeof(FairyGUI.RichTextField));
FairyGUI.Utils.HtmlElement _element = (FairyGUI.Utils.HtmlElement)translator.GetObject(L, 3, typeof(FairyGUI.Utils.HtmlElement));
gen_to_be_invoked.Create(
_owner,
_element );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_SetPosition(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
float _x = (float)LuaAPI.lua_tonumber(L, 2);
float _y = (float)LuaAPI.lua_tonumber(L, 3);
gen_to_be_invoked.SetPosition(
_x,
_y );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Add(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
gen_to_be_invoked.Add( );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Remove(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
gen_to_be_invoked.Remove( );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Release(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
gen_to_be_invoked.Release( );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Dispose(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
{
gen_to_be_invoked.Dispose( );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_textInput(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.textInput);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_displayObject(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.displayObject);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_element(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.element);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_width(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushnumber(L, gen_to_be_invoked.width);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_height(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.Utils.HtmlInput gen_to_be_invoked = (FairyGUI.Utils.HtmlInput)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushnumber(L, gen_to_be_invoked.height);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_defaultBorderSize(RealStatePtr L)
{
try {
LuaAPI.xlua_pushinteger(L, FairyGUI.Utils.HtmlInput.defaultBorderSize);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_defaultBorderColor(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
translator.PushUnityEngineColor(L, FairyGUI.Utils.HtmlInput.defaultBorderColor);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_defaultBackgroundColor(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
translator.PushUnityEngineColor(L, FairyGUI.Utils.HtmlInput.defaultBackgroundColor);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_defaultBorderSize(RealStatePtr L)
{
try {
FairyGUI.Utils.HtmlInput.defaultBorderSize = LuaAPI.xlua_tointeger(L, 1);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_defaultBorderColor(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
UnityEngine.Color gen_value;translator.Get(L, 1, out gen_value);
FairyGUI.Utils.HtmlInput.defaultBorderColor = gen_value;
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_defaultBackgroundColor(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
UnityEngine.Color gen_value;translator.Get(L, 1, out gen_value);
FairyGUI.Utils.HtmlInput.defaultBackgroundColor = gen_value;
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
}
}
| 33.842105 | 149 | 0.552164 | [
"MIT"
] | dayfox5317/ET_Lua | Unity/Assets/Cold/XLua/Gen/FairyGUIUtilsHtmlInputWrap.cs | 15,434 | C# |
namespace Silky.Core.Runtime.Session
{
public static class SessionExtensions
{
public static bool IsLogin(this ISession session)
{
if (session == null)
{
return false;
}
return session.UserId != null;
}
}
} | 20.533333 | 57 | 0.503247 | [
"MIT"
] | Dishone/silky | framework/src/Silky.Core/Runtime/Session/SessionExtensions.cs | 310 | C# |
namespace TrafficManager.Patch._VehicleAI._CarAI {
using System.Reflection;
using API.Traffic.Enums;
using ColossalFramework;
using CSUtil.Commons;
using HarmonyLib;
using JetBrains.Annotations;
using Manager.Impl;
using State;
using State.ConfigData;
using TrafficManager.Util.Extensions;
using UnityEngine;
using Util;
[UsedImplicitly]
[HarmonyPatch]
public class CalculateSegmentPositionPatch2 {
private delegate void CalculatePositionDelegate(ushort vehicleID,
ref Vehicle vehicleData,
PathUnit.Position nextPosition,
PathUnit.Position position,
uint laneID,
byte offset,
PathUnit.Position prevPos,
uint prevLaneID,
byte prevOffset,
int index,
out Vector3 pos,
out Vector3 dir,
out float maxSpeed);
[UsedImplicitly]
public static MethodBase TargetMethod() => TranspilerUtil.DeclaredMethod<CalculatePositionDelegate>( typeof(CarAI), "CalculateSegmentPosition");
[UsedImplicitly]
public static bool Prefix(CarAI __instance,
ushort vehicleID,
ref Vehicle vehicleData,
PathUnit.Position nextPosition,
PathUnit.Position position,
uint laneID,
byte offset,
PathUnit.Position prevPos,
uint prevLaneID,
byte prevOffset,
int index,
out Vector3 pos,
out Vector3 dir,
out float maxSpeed) {
ushort nextSourceNodeId;
ushort nextTargetNodeId;
ref NetSegment currentPositionSegment = ref position.m_segment.ToSegment();
if (offset < position.m_offset) {
nextSourceNodeId = currentPositionSegment.m_startNode;
nextTargetNodeId = currentPositionSegment.m_endNode;
} else {
nextSourceNodeId = currentPositionSegment.m_endNode;
nextTargetNodeId = currentPositionSegment.m_startNode;
}
ref NetSegment previousPositionSegment = ref prevPos.m_segment.ToSegment();
ushort curTargetNodeId;
curTargetNodeId = prevOffset == 0
? previousPositionSegment.m_startNode
: previousPositionSegment.m_endNode;
#if DEBUG
bool logCalculation = DebugSwitch.CalculateSegmentPosition.Get()
&& (DebugSettings.NodeId <= 0
|| curTargetNodeId == DebugSettings.NodeId)
&& (GlobalConfig.Instance.Debug.ApiExtVehicleType == ExtVehicleType.None
|| GlobalConfig.Instance.Debug.ApiExtVehicleType == ExtVehicleType.RoadVehicle)
&& (DebugSettings.VehicleId == 0
|| DebugSettings.VehicleId == vehicleID);
if (logCalculation) {
Log._Debug($"CustomCarAI.CustomCalculateSegmentPosition({vehicleID}) called.\n" +
$"\tcurPosition.m_segment={prevPos.m_segment}, " +
$"curPosition.m_offset={prevPos.m_offset}\n" +
$"\tposition.m_segment={position.m_segment}, " +
$"position.m_offset={position.m_offset}\n" +
$"\tnextNextPosition.m_segment={nextPosition.m_segment}, " +
$"nextNextPosition.m_offset={nextPosition.m_offset}\n" +
$"\tcurLaneId={prevLaneID}, prevOffset={prevOffset}\n" +
$"\tnextLaneId={laneID}, nextOffset={offset}\n" +
$"\tnextSourceNodeId={nextSourceNodeId}, nextTargetNodeId={nextTargetNodeId}\n" +
$"\tcurTargetNodeId={curTargetNodeId}, curTargetNodeId={curTargetNodeId}\n" +
$"\tindex={index}");
}
#endif
Vehicle.Frame lastFrameData = vehicleData.GetLastFrameData();
Vector3 lastFrameVehiclePos = lastFrameData.m_position;
float sqrVelocity = lastFrameData.m_velocity.sqrMagnitude;
laneID.ToLane().CalculatePositionAndDirection(
Constants.ByteToFloat(offset),
out pos,
out dir);
float braking = __instance.m_info.m_braking;
if ((vehicleData.m_flags & Vehicle.Flags.Emergency2) != 0) {
braking *= 2f;
}
// car position on the Bezier curve of the lane
Vector3 refVehiclePosOnBezier = prevLaneID.ToLane().CalculatePosition(Constants.ByteToFloat(prevOffset));
// ushort currentSegmentId = prevLaneID.ToLane().m_segment;
// this seems to be like the required braking force in order to stop the vehicle within its half length.
float crazyValue = (0.5f * sqrVelocity / braking) +
(__instance.m_info.m_generatedInfo.m_size.z * 0.5f);
float d = Vector3.Distance(lastFrameVehiclePos, refVehiclePosOnBezier);
bool withinBrakingDistance = d >= crazyValue - 1f;
if (nextSourceNodeId == curTargetNodeId
&& withinBrakingDistance) {
// NON-STOCK CODE START (stock code replaced)
if (!VehicleBehaviorManager.Instance.MayChangeSegment(
vehicleID,
ref vehicleData,
sqrVelocity,
ref prevPos,
ref previousPositionSegment,
curTargetNodeId,
prevLaneID,
ref position,
nextSourceNodeId,
ref nextSourceNodeId.ToNode(),
laneID,
ref nextPosition,
nextTargetNodeId,
out maxSpeed)) {
// NON-STOCK CODE
return false;
}
ExtVehicleManager.Instance.UpdateVehiclePosition(
vehicleID,
ref vehicleData /*, lastFrameData.m_velocity.magnitude*/);
// NON-STOCK CODE END
}
NetInfo currentPositionSegmentInfo = currentPositionSegment.Info;
// NON-STOCK CODE START (stock code replaced)
VehicleAICommons.CustomCalculateTargetSpeed(
__instance,
vehicleID,
ref vehicleData,
position,
laneID,
currentPositionSegmentInfo,
out maxSpeed);
maxSpeed = Constants.ManagerFactory.VehicleBehaviorManager.CalcMaxSpeed(
vehicleID,
ref Constants.ManagerFactory.ExtVehicleManager.ExtVehicles[vehicleID],
__instance.m_info,
position,
ref currentPositionSegment,
pos,
maxSpeed,
false);
// NON-STOCK CODE END
return false;
}
}
} | 46.47093 | 152 | 0.499187 | [
"MIT"
] | Elesbaan70/TMPE | TLM/TLM/Patch/_VehicleAI/_CarAI/CalculateSegmentPositionPatch2.cs | 7,993 | C# |
using System;
using CPUx86 = XSharp.Assembler.x86;
using CPU = XSharp.Assembler.x86;
using XSharp.Assembler.x86;
using XSharp.Assembler;
using XSharp.Assembler.x86.SSE;
using XSharp.Assembler.x86.x87;
using XSharp;
using static XSharp.XSRegisters;
using static XSharp.Assembler.x86.SSE.ComparePseudoOpcodes;
namespace Cosmos.IL2CPU.X86.IL
{
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Cgt)]
public class Cgt : ILOp
{
public Cgt(XSharp.Assembler.Assembler aAsmblr)
: base(aAsmblr)
{
}
public override void Execute(Il2cpuMethodInfo aMethod, ILOpCode aOpCode)
{
var xStackItem = aOpCode.StackPopTypes[0];
var xStackItemSize = SizeOfType(xStackItem);
var xStackItemIsFloat = TypeIsFloat(xStackItem);
if (xStackItemSize > 8)
{
//EmitNotImplementedException( Assembler, GetServiceProvider(), "Cgt: StackSizes>8 not supported", CurInstructionLabel, mMethodInfo, mCurrentOffset, NextInstructionLabel );
throw new NotImplementedException("Cosmos.IL2CPU.x86->IL->Cgt.cs->Error: StackSizes > 8 not supported");
//return;
}
string BaseLabel = GetLabel(aMethod, aOpCode) + ".";
string LabelTrue = BaseLabel + "True";
string LabelFalse = BaseLabel + "False";
var xNextLabel = GetLabel(aMethod, aOpCode.NextPosition);
if (xStackItemSize > 4)
{
// Using SSE registers (that do NOT branch!) This is needed only for long now
#if false
XS.Set(XSRegisters.ESI, 1);
// esi = 1
XS.Xor(XSRegisters.EDI, XSRegisters.EDI);
// edi = 0
#endif
if (xStackItemIsFloat)
{
// Please note that SSE supports double operations only from version 2
XS.SSE2.MoveSD(XMM0, ESP, sourceIsIndirect: true);
// Increment ESP to get the value of the next double
XS.Add(ESP, 8);
XS.SSE2.MoveSD(XMM1, ESP, sourceIsIndirect: true);
XS.SSE2.CompareSD(XMM1, XMM0, comparision: NotLessThanOrEqualTo);
XS.MoveD(EBX, XMM1);
XS.And(EBX, 1);
// We need to move the stack pointer of 4 Byte to "eat" the second double that is yet in the stack or we get a corrupted stack!
XS.Add(ESP, 4);
XS.Set(ESP, EBX, destinationIsIndirect: true);
}
else
{
XS.Set(ESI, 1);
// esi = 1
XS.Xor(EDI, EDI);
// edi = 0
XS.Pop(EAX);
XS.Pop(EDX);
//value2: EDX:EAX
XS.Pop(EBX);
XS.Pop(ECX);
//value1: ECX:EBX
XS.Compare(ECX, EDX);
XS.Jump(ConditionalTestEnum.GreaterThan, LabelTrue);
XS.Jump(ConditionalTestEnum.LessThan, LabelFalse);
XS.Compare(EBX, EAX);
XS.Label(LabelTrue);
new ConditionalMove { Condition = ConditionalTestEnum.Above, DestinationReg = RegistersEnum.EDI, SourceReg = RegistersEnum.ESI };
XS.Label(LabelFalse);
XS.Push(EDI);
}
/*
XS.Jump(ConditionalTestEnum.GreaterThan, LabelTrue);
XS.Label(LabelFalse);
XS.Push(0);
XS.Jump(xNextLabel);
XS.Label(LabelTrue );
XS.Push(1);*/
}
else
{
if (xStackItemIsFloat)
{
XS.SSE.MoveSS(XMM0, ESP, sourceIsIndirect: true);
XS.Add(XSRegisters.ESP, 4);
XS.SSE.MoveSS(XMM1, ESP, sourceIsIndirect: true);
XS.SSE.CompareSS(XMM1, XMM0, comparision: NotLessThanOrEqualTo);
XS.MoveD(EBX, XMM1);
XS.And(XSRegisters.EBX, 1);
XS.Set(ESP, EBX, destinationIsIndirect: true);
}
else
{
XS.Pop(EAX);
XS.Compare(EAX, ESP, sourceIsIndirect: true);
XS.Jump(ConditionalTestEnum.LessThan, LabelTrue);
XS.Jump(LabelFalse);
XS.Label(LabelTrue);
XS.Add(XSRegisters.ESP, 4);
XS.Push(1);
XS.Jump(xNextLabel);
XS.Label(LabelFalse);
XS.Add(XSRegisters.ESP, 4);
XS.Push(0);
}
}
}
}
}
| 29.577236 | 176 | 0.666575 | [
"BSD-3-Clause"
] | xccoreco/IL2CPU | source/Cosmos.IL2CPU/IL/Cgt.cs | 3,638 | C# |
using AssetManagementBase;
using Microsoft.Xna.Framework;
using Myra.Graphics2D.UI;
using NUnit.Framework;
namespace Myra.Tests
{
[TestFixture]
public class MMLTests
{
[Test]
public void LoadMMLWithExternalAssets()
{
var assembly = typeof(MMLTests).Assembly;
ResourceAssetResolver assetResolver = new ResourceAssetResolver(assembly, "Resources.");
AssetManager assetManager = new AssetManager(assetResolver);
var mml = assetManager.Load<string>("GridWithExternalResources.xmmp");
var project = Project.LoadFromXml(mml, assetManager);
var imageButton1 = (ImageButton)project.Root.FindWidgetById("spawnUnit1");
Assert.IsNotNull(imageButton1);
Assert.IsNotNull(imageButton1.Image);
Assert.AreEqual(imageButton1.Image.Size, new Point(64, 64));
var label = (Label)project.Root.FindWidgetById("label");
Assert.IsNotNull(label);
Assert.IsNotNull(label.Font);
}
}
}
| 27.636364 | 91 | 0.757675 | [
"MIT"
] | AtomicBlom/Myra | src/Myra.Tests/MMLTests.cs | 914 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEIDR.JobExecutor
{
/// <summary>
/// Removes delay for any JobExecution records that have been flagged to 'RunNow'.
/// Also increases the priority and triggers sorting the JobExecutor WorkQueue
/// </summary>
class ResetDelayExecutor : Executor
{
public ResetDelayExecutor( JobExecutorService caller, DataBase.DatabaseManager manager)
:base(manager, caller, ExecutorType.Maintenance)
{
workList = new List<JobExecutionDetail>();
}
List<JobExecutionDetail> workList;
public override int Workload => workList.Count;
protected override void CheckWorkLoad()
{
using (var h = _Manager.GetBasicHelper(true))
{
h.QualifiedProcedure = "[SEIDR].[usp_JobExecutionDetail_RePrioritize]";
h["BatchSize"] = CallerService.BatchSize;
h.BeginTran();
workList = _Manager.SelectList<JobExecutionDetail>(h);
h.CommitTran();
}
}
protected override void Work()
{
while(workList.HasMinimumCount(1))
{
var detail = workList[0];
JobExecutor.Queue(detail, false);
LogInfo("Reprioritized JobID: " + detail.JobExecutionID);
//Replace older version of the execution detail.
workList.RemoveAt(0);
}
}
}
}
| 33.666667 | 95 | 0.581064 | [
"MIT"
] | maron6/SEIDR | SEIDR.JobExecutor/ResetDelayExecutor.cs | 1,618 | C# |
using BenchmarkDotNet.Attributes;
namespace NetFabric.Hyperlinq.Benchmarks
{
public abstract class CountBenchmarksBase : BenchmarksBase
{
[Params(100)]
public int Count { get; set; }
public override void GlobalSetup() { }
}
}
| 20.384615 | 62 | 0.667925 | [
"MIT"
] | Ashrafnet/NetFabric.Hyperlinq | NetFabric.Hyperlinq.Benchmarks/CountBenchmarksBase.cs | 267 | C# |
using System.ComponentModel;
using AmbethIFilterDescriptor = De.Osthus.Ambeth.Filter.Model.IFilterDescriptor;
namespace De.Osthus.Minerva.FilterProvider
{
// Providers must ALWAYS implement INotifyPropertyChanged
public interface IFilterDescriptorProvider : INotifyPropertyChanged
{
AmbethIFilterDescriptor AmbethFilterDescriptor { get; }
}
}
| 30.75 | 80 | 0.794038 | [
"Apache-2.0"
] | Dennis-Koch/ambeth | ambeth/Minerva.Core/minerva/filterprovider/IFilterDescriptorProvider.cs | 371 | C# |
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:文章分类
*│ 作 者:
*│ 版 本:1.0 模板代码自动生成
*│ 创建时间:2021-03-06 12:15:45
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: Henxun.Cms.Models
*│ 类 名:ArticleCategory
*└──────────────────────────────────────────────────────────────┘
*/
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Henxun.Cms.Models
{
/// <summary>
///
/// 2021-03-06 12:15:45
/// 文章分类
/// </summary>
public partial class ArticleCategory
{
}
}
| 46.5 | 70 | 0.145161 | [
"MIT"
] | Henxun/Henxun.CMS | Henxun.Cms.Models/Partial/ArticleCategory.cs | 3,048 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 网站监控
* 云解析OpenAPI网站监控接口
*
* OpenAPI spec version: v2
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Core.Annotation;
using Newtonsoft.Json;
namespace JDCloudSDK.Domainservice.Apis
{
/// <summary>
/// 查询子域名的可用监控对象
/// </summary>
public class DescribeMonitorTargetRequest : JdcloudRequest
{
///<summary>
/// 子域名
///Required:true
///</summary>
[Required]
public string SubDomainName{ get; set; }
///<summary>
/// 实例所属的地域ID
///Required:true
///</summary>
[Required]
[JsonProperty("regionId")]
public string RegionIdValue{ get; set; }
///<summary>
/// 域名ID,请使用describeDomains接口获取。
///Required:true
///</summary>
[Required]
public string DomainId{ get; set; }
}
} | 25.951613 | 76 | 0.645121 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Domainservice/Apis/DescribeMonitorTargetRequest.cs | 1,701 | C# |
using NSubstitute;
using Xunit;
using Xunit.Abstractions;
using Xunit.Runner.MSBuild;
public class StandardOutputVisitorTests
{
public class OnMessage_ErrorMessage
{
[Fact]
public void LogsMessage()
{
var errorMessage = Substitute.For<IErrorMessage>();
errorMessage.ExceptionTypes.Returns(new[] { "ExceptionType" });
errorMessage.Messages.Returns(new[] { "This is my message \t\r\n" });
errorMessage.StackTraces.Returns(new[] { "Line 1\r\nLine 2\r\nLine 3" });
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(errorMessage);
Assert.Collection(logger.Messages,
msg => Assert.Equal("ERROR: ExceptionType : This is my message \\t\\r\\n", msg),
msg => Assert.Equal("ERROR: Line 1\r\nLine 2\r\nLine 3", msg));
}
}
public class OnMessage_TestAssemblyFinished
{
[Fact]
public void LogsMessageWithStatitics()
{
var assembly = Mocks.TestAssembly(@"C:\Assembly\File.dll");
var assemblyStarting = Substitute.For<ITestAssemblyStarting>();
assemblyStarting.TestAssembly.Returns(assembly);
var assemblyFinished = Substitute.For<ITestAssemblyFinished>();
assemblyFinished.TestsRun.Returns(2112);
assemblyFinished.TestsFailed.Returns(42);
assemblyFinished.TestsSkipped.Returns(6);
assemblyFinished.ExecutionTime.Returns(123.4567M);
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(assemblyStarting);
visitor.OnMessage(assemblyFinished);
Assert.Single(logger.Messages, "MESSAGE[High]: Started: File.dll");
Assert.Single(logger.Messages, "MESSAGE[High]: Finished: File.dll");
}
}
public class OnMessage_TestFailed
{
[Fact]
public void LogsTestNameWithExceptionAndStackTrace()
{
var testFailed = Substitute.For<ITestFailed>();
testFailed.TestDisplayName.Returns("This is my display name \t\r\n");
testFailed.Messages.Returns(new[] { "This is my message \t\r\n" });
testFailed.StackTraces.Returns(new[] { "Line 1\r\nLine 2\r\nLine 3" });
testFailed.ExceptionTypes.Returns(new[] { "ExceptionType" });
testFailed.ExceptionParentIndices.Returns(new[] { -1 });
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(testFailed);
Assert.Collection(logger.Messages,
msg => Assert.Equal("ERROR: This is my display name \\t\\r\\n: ExceptionType : This is my message \\t\\r\\n", msg),
msg => Assert.Equal("ERROR: Line 1\r\nLine 2\r\nLine 3", msg));
}
[Fact]
public void NullStackTraceDoesNotLogStackTrace()
{
var testFailed = Substitute.For<ITestFailed>();
testFailed.TestDisplayName.Returns("1");
testFailed.Messages.Returns(new[] { "2" });
testFailed.StackTraces.Returns(new[] { (string)null });
testFailed.ExceptionTypes.Returns(new[] { "ExceptionType" });
testFailed.ExceptionParentIndices.Returns(new[] { -1 });
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(testFailed);
Assert.Collection(logger.Messages,
msg => Assert.Equal("ERROR: 1: ExceptionType : 2", msg));
}
}
public class OnMessage_TestPassed
{
ITestPassed testPassed;
public OnMessage_TestPassed()
{
testPassed = Substitute.For<ITestPassed>();
testPassed.TestDisplayName.Returns("This is my display name \t\r\n");
}
[Fact]
public void LogsTestName()
{
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(testPassed);
Assert.Single(logger.Messages, "MESSAGE[Normal]: This is my display name \\t\\r\\n");
}
[Fact]
public void AddsPassToLogWhenInVerboseMode()
{
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, true, null);
visitor.OnMessage(testPassed);
Assert.Single(logger.Messages, "MESSAGE[Normal]: PASS: This is my display name \\t\\r\\n");
}
}
public class OnMessage_TestSkipped
{
[Fact]
public void LogsTestNameAsWarning()
{
var testSkipped = Substitute.For<ITestSkipped>();
testSkipped.TestDisplayName.Returns("This is my display name \t\r\n");
testSkipped.Reason.Returns("This is my skip reason \t\r\n");
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(testSkipped);
Assert.Single(logger.Messages, "WARNING: This is my display name \\t\\r\\n: This is my skip reason \\t\\r\\n");
}
}
public class OnMessage_TestStarting
{
ITestStarting testStarting;
public OnMessage_TestStarting()
{
testStarting = Substitute.For<ITestStarting>();
testStarting.TestDisplayName.Returns("This is my display name \t\r\n");
}
[Fact]
public void NoOutputWhenNotInVerboseMode()
{
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, false, null);
visitor.OnMessage(testStarting);
Assert.Empty(logger.Messages);
}
[Fact]
public void OutputStartMessageWhenInVerboseMode()
{
var logger = SpyLogger.Create();
var visitor = new StandardOutputVisitor(logger, null, true, null);
visitor.OnMessage(testStarting);
Assert.Single(logger.Messages, "MESSAGE[Normal]: START: This is my display name \\t\\r\\n");
}
}
} | 35.73743 | 131 | 0.599187 | [
"Apache-2.0"
] | chrisaut/xunit | test/test.xunit.runner.msbuild/Visitors/StandardOutputVisitorTests.cs | 6,399 | 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.Vod.V20180717.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeWatermarkTemplatesRequest : AbstractModel
{
/// <summary>
/// Unique ID filter of watermarking templates. Array length limit: 100.
/// </summary>
[JsonProperty("Definitions")]
public long?[] Definitions{ get; set; }
/// <summary>
/// Watermark type filter. Valid values:
/// <li>image: image watermark;</li>
/// <li>text: text watermark.</li>
/// </summary>
[JsonProperty("Type")]
public string Type{ get; set; }
/// <summary>
/// Pagination offset. Default value: 0.
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// Number of returned entries
/// <li>Default value: 10;</li>
/// <li>Maximum value: 100.</li>
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// [Subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID in VOD. If you need to access a resource in a subapplication, enter the subapplication ID in this field; otherwise, leave it empty.
/// </summary>
[JsonProperty("SubAppId")]
public ulong? SubAppId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "Definitions.", this.Definitions);
this.SetParamSimple(map, prefix + "Type", this.Type);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamSimple(map, prefix + "SubAppId", this.SubAppId);
}
}
}
| 35.394737 | 241 | 0.6171 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Vod/V20180717/Models/DescribeWatermarkTemplatesRequest.cs | 2,690 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using ScriptTimer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.ScriptTimer;
using System.Reflection;
using log4net;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
/// <summary>
/// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
/// </summary>
public class AsyncCommandManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
private static int numInstances;
/// <summary>
/// Lock for reading/writing static components of AsyncCommandManager.
/// </summary>
/// <remarks>
/// This lock exists so that multiple threads from different engines and/or different copies of the same engine
/// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
/// </remarks>
private static object staticLock = new object();
private static List<IScriptEngine> m_ScriptEngines =
new List<IScriptEngine>();
public IScriptEngine m_ScriptEngine;
private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
new Dictionary<IScriptEngine, Dataserver>();
private static Dictionary<IScriptEngine, ScriptTimer> m_ScriptTimer =
new Dictionary<IScriptEngine, ScriptTimer>();
private static Dictionary<IScriptEngine, Listener> m_Listener =
new Dictionary<IScriptEngine, Listener>();
private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
new Dictionary<IScriptEngine, HttpRequest>();
private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
new Dictionary<IScriptEngine, SensorRepeat>();
private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
new Dictionary<IScriptEngine, XmlRequest>();
public Dataserver DataserverPlugin
{
get
{
lock (staticLock)
return m_Dataserver[m_ScriptEngine];
}
}
public ScriptTimer TimerPlugin
{
get
{
lock (staticLock)
return m_ScriptTimer[m_ScriptEngine];
}
}
public HttpRequest HttpRequestPlugin
{
get
{
lock (staticLock)
return m_HttpRequest[m_ScriptEngine];
}
}
public Listener ListenerPlugin
{
get
{
lock (staticLock)
return m_Listener[m_ScriptEngine];
}
}
public SensorRepeat SensorRepeatPlugin
{
get
{
lock (staticLock)
return m_SensorRepeat[m_ScriptEngine];
}
}
public XmlRequest XmlRequestPlugin
{
get
{
lock (staticLock)
return m_XmlRequest[m_ScriptEngine];
}
}
public IScriptEngine[] ScriptEngines
{
get
{
lock (staticLock)
return m_ScriptEngines.ToArray();
}
}
public AsyncCommandManager(IScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
// If there is more than one scene in the simulator or multiple script engines are used on the same region
// then more than one thread could arrive at this block of code simultaneously. However, it cannot be
// executed concurrently both because concurrent list operations are not thread-safe and because of other
// race conditions such as the later check of cmdHandlerThread == null.
lock (staticLock)
{
if (m_ScriptEngines.Count == 0)
ReadConfig();
if (!m_ScriptEngines.Contains(m_ScriptEngine))
m_ScriptEngines.Add(m_ScriptEngine);
// Create instances of all plugins
if (!m_Dataserver.ContainsKey(m_ScriptEngine))
m_Dataserver[m_ScriptEngine] = new Dataserver(this);
if (!m_ScriptTimer.ContainsKey(m_ScriptEngine))
m_ScriptTimer[m_ScriptEngine] = new ScriptTimer(this);
if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
if (!m_Listener.ContainsKey(m_ScriptEngine))
m_Listener[m_ScriptEngine] = new Listener(this);
if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
numInstances++;
if (cmdHandlerThread == null)
{
cmdHandlerThread = WorkManager.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread");
}
}
}
private void ReadConfig()
{
// cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
// TODO: Make this sane again
cmdHandlerThreadCycleSleepms = 100;
}
/*
~AsyncCommandManager()
{
// Shut down thread
try
{
lock (staticLock)
{
numInstances--;
if(numInstances > 0)
return;
if (cmdHandlerThread != null)
{
if (cmdHandlerThread.IsAlive == true)
{
cmdHandlerThread.Abort();
//cmdHandlerThread.Join();
cmdHandlerThread = null;
}
}
}
}
catch
{
}
}
*/
/// <summary>
/// Main loop for the manager thread
/// </summary>
private static void CmdHandlerThreadLoop()
{
bool running = true;
while (running)
{
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
Watchdog.UpdateThread();
DoOneCmdHandlerPass();
Watchdog.UpdateThread();
}
catch ( System.Threading.ThreadAbortException)
{
Thread.ResetAbort();
running = false;
}
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
}
}
}
private static void DoOneCmdHandlerPass()
{
lock (staticLock)
{
// Check XMLRPCRequests
try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {}
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check HttpRequests
try { m_HttpRequest[s].CheckHttpRequests(); } catch { }
// Check Listeners
try { m_Listener[s].CheckListeners(); } catch {}
// Check ScriptTimers
try { m_ScriptTimer[s].CheckTimerEvents(); } catch {}
// Check Sensors
try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {}
// Check dataserver
try { m_Dataserver[s].ExpireRequests(); } catch {}
}
}
}
/// <summary>
/// Remove a specific script (and all its pending commands)
/// </summary>
/// <param name="localID"></param>
/// <param name="itemID"></param>
public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID)
{
// Remove a specific script
// m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
lock (staticLock)
{
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
// Remove from: ScriptTimers
m_ScriptTimer[engine].UnSetTimerEvents(localID, itemID);
if(engine.World != null)
{
// Remove from: HttpRequest
IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
if (iHttpReq != null)
iHttpReq.StopHttpRequest(localID, itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
}
public static void StateChange(IScriptEngine engine, uint localID, UUID itemID)
{
// Remove a specific script
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
/// <summary>
/// Get the sensor repeat plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_SensorRepeat.ContainsKey(engine))
return m_SensorRepeat[engine];
else
return null;
}
}
/// <summary>
/// Get the dataserver plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Dataserver GetDataserverPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Dataserver.ContainsKey(engine))
return m_Dataserver[engine];
else
return null;
}
}
/// <summary>
/// Get the ScriptTimer plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static ScriptTimer GetTimerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_ScriptTimer.ContainsKey(engine))
return m_ScriptTimer[engine];
else
return null;
}
}
/// <summary>
/// Get the listener plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Listener GetListenerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Listener.ContainsKey(engine))
return m_Listener[engine];
else
return null;
}
}
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List<Object> data = new List<Object>();
lock (staticLock)
{
Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
if (listeners.Length > 0)
{
data.Add("listener");
data.Add(listeners.Length);
data.AddRange(listeners);
}
Object[] ScriptTimers=m_ScriptTimer[engine].GetSerializationData(itemID);
if (ScriptTimers.Length > 0)
{
data.Add("timer");
data.Add(ScriptTimers.Length);
data.AddRange(ScriptTimers);
}
Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
if (sensors.Length > 0)
{
data.Add("sensor");
data.Add(sensors.Length);
data.AddRange(sensors);
}
}
return data.ToArray();
}
public static void CreateFromData(IScriptEngine engine, uint localID,
UUID itemID, UUID hostID, Object[] data)
{
int idx = 0;
int len;
while (idx < data.Length)
{
string type = data[idx].ToString();
len = (int)data[idx+1];
idx+=2;
if (len > 0)
{
Object[] item = new Object[len];
Array.Copy(data, idx, item, 0, len);
idx+=len;
lock (staticLock)
{
switch (type)
{
case "listener":
m_Listener[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "timer":
m_ScriptTimer[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "sensor":
m_SensorRepeat[engine].CreateFromData(localID,
itemID, hostID, item);
break;
}
}
}
}
}
}
}
| 36.016807 | 119 | 0.524673 | [
"BSD-3-Clause"
] | asmexcaliburwoods/opensim | OpenSim/Region/ScriptEngine/Shared/Api/Implementation/AsyncCommandManager.cs | 17,144 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Vocalia.Ingest.Media
{
public class MediaStorage : IMediaStorage
{
private IConfiguration Config { get; }
public MediaStorage(IConfiguration config)
{
Config = config;
}
/// <summary>
/// Uploads a media stream to the database.
/// </summary>
/// <param name="userUid">UID of the user.</param>
/// <param name="sessionUid">UID of the session.</param>
/// <param name="entryUid">UID of the entry.</param>
/// <param name="stream">Stream to upload.</param>
/// <returns></returns>
public async Task<string> UploadStreamAsync(string userUid, Guid sessionUid, Guid entryUid, Stream stream)
{
var url = string.Concat(Config["BlobStorage:CompiledURL"], sessionUid, "/",
userUid, "/", entryUid, ".wav");
var creds = new StorageCredentials(Config["BlobStorage:Account"], Config["BlobStorage:Key"]);
var newBlob = new CloudBlockBlob(new Uri(url), creds);
stream.Position = 0;
await newBlob.UploadFromStreamAsync(stream);
return url;
}
}
}
| 32.571429 | 114 | 0.616959 | [
"MIT"
] | AdamMYoung/Vocalia-API | src/apis/Ingest/Vocalia.Ingest/Media/MediaStorage.cs | 1,370 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Store
{
/// <summary> Used by MockRAMDirectory to create an input stream that
/// keeps track of when it's been closed.
/// </summary>
public class MockRAMInputStream:RAMInputStream, ILuceneCloneable
{
private MockRAMDirectory dir;
private System.String name;
private bool isClone;
private bool isDisposed;
/// <summary>Construct an empty output buffer. </summary>
/// <throws> IOException </throws>
public MockRAMInputStream(MockRAMDirectory dir, System.String name, RAMFile f):base(f)
{
this.name = name;
this.dir = dir;
}
protected override void Dispose(bool disposing)
{
if (isDisposed) return;
// Pending resolution on LUCENE-686 we may want to
// remove the conditional check so we also track that
// all clones get closed:
if (disposing && !isClone)
{
lock (dir)
{
// Could be null when MockRAMDirectory.crash() was called
if (dir.openFiles[name] != null)
{
System.Int32 v = dir.openFiles[name];
if (v == 1)
{
dir.openFiles.Remove(name);
}
else
{
v = v - 1;
dir.openFiles[name] = v;
}
}
}
}
isDisposed = true;
base.Dispose(disposing);
}
public override System.Object Clone(IState state)
{
MockRAMInputStream clone = (MockRAMInputStream) base.Clone(null);
clone.isClone = true;
// Pending resolution on LUCENE-686 we may want to
// uncomment this code so that we also track that all
// clones get closed:
/*
synchronized(dir.openFiles) {
if (dir.openFiles.containsKey(name)) {
Integer v = (Integer) dir.openFiles.get(name);
v = new Integer(v.intValue()+1);
dir.openFiles.put(name, v);
} else {
throw new RuntimeException("BUG: cloned file was not open?");
}
}
*/
return clone;
}
}
} | 31.845361 | 88 | 0.593396 | [
"Apache-2.0"
] | grisha-kotler/lucenenet | test/Lucene.Net.Test/Store/MockRAMInputStream.cs | 3,089 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using FreelandLabs.Controller;
namespace FreelandLabs
{
public partial class MainForm : Form
{
int x, y;
bool s = false;
Loader loader;
public MainForm()
{
this.InitializeComponent();
this.panelTitle.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MoveForm);
this.panelTitle.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MoveForm);
this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MoveForm);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MoveForm);
this.panelTitle.Text = "Freeland Labs v." + Application.ProductVersion;
}
private void MoveForm(object sender, MouseEventArgs e) {
//перетаскивание формы
if (s == false) { x = e.X; y = e.Y; s = true; }
if (e.Button.ToString() == "Left")
{ this.Location = new Point(this.Left + e.X - x, this.Top + e.Y - y); }
else { s = false; }
}
void Btn_minimizeClick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
void Btn_exitClick(object sender, EventArgs e)
{
Application.Exit();
}
void updateCourseStats() {
//неужели у списка нет метода слияния?
List<string> course_local = loader.LocalCourseList();
List<string> course_crypto = loader.LocalCryptoList();
List<string> volumes_list = loader.LoadExchangeVolumes();
listBox_fiatCourse.Items.Clear();
listBox_cryptoCourse.Items.Clear();
listBox_volumes.Items.Clear();
for(int i=0; i<course_local.Count; i++) {
listBox_fiatCourse.Items.Add(course_local[i]);
}
for(int i=0; i<course_crypto.Count; i++) {
listBox_cryptoCourse.Items.Add(course_crypto[i]);
}
for(int i=0; i<volumes_list.Count; i++) {
listBox_volumes.Items.Add(volumes_list[i]);
}
}
void MainFormShown(object sender, EventArgs e)
{
loader = new Loader();
number_visitor.Text = loader.getVisitorCount().ToString();
number_resident.Text = loader.getResidentCount().ToString();
number_citizen.Text = loader.getCitizenCount().ToString();
updateCourseStats();
}
void Btn_refreshCourseClick(object sender, EventArgs e)
{
updateCourseStats();
}
}
}
| 29.3125 | 97 | 0.678465 | [
"MIT"
] | Sagleft/freeland-labs | View/MainForm.cs | 2,396 | C# |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class Blocks : ModuleRules
{
public Blocks(ReadOnlyTargetRules Target) : base(Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
}
}
| 24.25 | 102 | 0.738832 | [
"MIT"
] | harunpehlivan/AirSim | Unreal/Environments/Blocks/Source/Blocks/Blocks.Build.cs | 291 | C# |
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
singleton Material(fr1tz_mis_alux3d_test_terrainFX)
{
mapTo = "fr1tz_mis_alux3d_test_terrain";
footstepSoundId = "3";
terrainMaterials = "1";
ShowDust = "0";
showFootprints = "true";
materialTag0 = "Terrain";
effectColor[0] = "0.603922 0.505882 0.4 1";
effectColor[1] = "0.701961 0.631373 0.552941 0";
diffuseMap[0] = "content/rotc/p.5.3/textures/nat/Snow.jpg";
normalMap[0] = "content/rotc/p.5.3/textures/nat/normal1.png";
castShadows = "0";
detailMap[0] = "content/rotc/p.5.3/textures/nat/detail1.jpg";
detailScale[0] = "1 1";
};
new TerrainMaterial()
{
internalName = "fr1tz_mis_alux3d_test_terrain";
diffuseMap = "content/fr1tz/alux1/textures/default";
diffuseSize = "16";
detailSize = "16";
detailDistance = "200";
detailStrength = "1";
parallaxScale = "0";
};
| 30.59375 | 65 | 0.662921 | [
"MIT"
] | fr1tz/alux3d | My Projects/Alux3D/game/content/fr1tz/mis_alux3d_debug/materials.cs | 948 | C# |
namespace BitCoinWatcher.BitBayApi.Enums
{
public enum Currency
{
Pln,
BitcoinCash,
BitcoinGold,
Bitcoin,
Ethereum,
Lisk,
LiteCoin,
Game,
Dash,
}
}
| 14.5625 | 41 | 0.493562 | [
"Apache-2.0"
] | yanekk/bitcoin-watcher | BitCoinWatcher.BitBayApi/Enums/Currency.cs | 235 | C# |
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Ballistico.Views
{
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
}
}
} | 17.666667 | 48 | 0.641509 | [
"MIT"
] | jcapellman/Ballistico | Ballistico/Ballistico/Views/AboutPage.xaml.cs | 267 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace PointOfInterestSkill
{
public class CancelRouteState
{
}
}
| 17.9 | 61 | 0.72067 | [
"MIT"
] | jamieo-ms/AI | solutions/Virtual-Assistant/src/csharp/skills/pointofinterestskill/Dialogs/CancelRouteDialog/CancelRouteState.cs | 181 | C# |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Text;
using System.IO;
using System.Data;
using MonoTests.System.Data.Utils;
namespace MonoTests_System.Data
{
[TestFixture] public class ReadOnlyExceptionTest
{
[Test] public void Generate()
{
Exception tmpEx = new Exception() ;
DataTable tbl = DataProvider.CreateParentDataTable();
tbl.Columns[0].ReadOnly = true;
//chaeck for int column
// ReadOnlyException - EndEdit
//tbl.Rows[0].BeginEdit(); // this throw an exception but according to MSDN it shouldn't !!!
//tbl.Rows[0][0] = 99 ;
try
{
tbl.Rows[0][0] = 99 ;
//tbl.Rows[0].EndEdit();
Assert.Fail("ROE1: Rows Indexer failed to raise ReadOnlyException.");
}
catch (ReadOnlyException) {}
catch (AssertionException) { throw; }
catch (Exception exc)
{
Assert.Fail("ROE2: Rows Indexer wrong exception type. Got: " + exc);
}
// ReadOnlyException - ItemArray
try
{
tbl.Rows[0].ItemArray = new object[] {99,"value","value"};
Assert.Fail("ROE3: Rows[0].ItemArray failed to raise ReadOnlyException.");
}
catch (ReadOnlyException) {}
catch (AssertionException) { throw; }
catch (Exception exc)
{
Assert.Fail("ROE4: Rows[0].ItemArray wrong exception type. Got: " + exc);
}
//chaeck for string column
tbl.Columns[0].ReadOnly = false;
tbl.Columns[1].ReadOnly = true;
// ReadOnlyException - EndEdit
//tbl.Rows[0].BeginEdit(); // this throw an exception but according to MSDN it shouldn't !!!
//tbl.Rows[0][0] = 99 ;
try
{
tbl.Rows[0][1] = "NewValue" ;
//tbl.Rows[0].EndEdit();
Assert.Fail("ROE5: Rows Indexer failed to raise ReadOnlyException.");
}
catch (ReadOnlyException) {}
catch (AssertionException) { throw; }
catch (Exception exc)
{
Assert.Fail("ROE6: Rows Indexer wrong exception type. Got: " + exc);
}
// ReadOnlyException - ItemArray
try
{
tbl.Rows[0].ItemArray = new object[] {99,"value","value"};
Assert.Fail("ROE7: Rows[0].ItemArray failed to raise ReadOnlyException.");
}
catch (ReadOnlyException) {}
catch (AssertionException) { throw; }
catch (Exception exc)
{
Assert.Fail("ROE8: Rows[0].ItemArray wrong exception type. Got: " + exc);
}
}
}
}
| 31.705357 | 97 | 0.682061 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Data/Test/System.Data/ReadOnlyExceptionTest.cs | 3,551 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
namespace Microsoft.MixedReality.SpectatorView
{
internal class TextBroadcaster : ComponentBroadcaster<TextService, TextBroadcaster.ChangeType>
{
private Text textComp;
private string previousText;
private TextProperties previousFontAndPlacement;
private MaterialsBroadcaster MaterialsBroadcaster = new MaterialsBroadcaster();
[Flags]
public enum ChangeType : byte
{
None = 0x0,
Text = 0x1,
FontAndPlacement = 0x2,
Materials = 0x4,
MaterialProperty = 0x8
}
public AssetId FontAssetId
{
get { return textComp.font == null ? AssetId.Empty : TextService.Instance.GetFontId(textComp.font); }
}
protected override void Awake()
{
base.Awake();
textComp = GetComponent<Text>();
}
protected override bool HasChanges(ChangeType changeFlags)
{
return changeFlags != ChangeType.None;
}
protected override ChangeType CalculateDeltaChanges()
{
ChangeType change = ChangeType.None;
string newText = textComp.text;
TextProperties newFontAndPlacement = new TextProperties(textComp);
if (previousText != newText)
{
previousText = newText;
change |= ChangeType.Text;
}
if (previousFontAndPlacement != newFontAndPlacement)
{
previousFontAndPlacement = newFontAndPlacement;
change |= ChangeType.FontAndPlacement;
}
bool areMaterialsDifferent;
MaterialsBroadcaster.UpdateMaterials(null, TransformBroadcaster.PerformanceParameters, new Material[] { textComp.materialForRendering }, out areMaterialsDifferent);
if (areMaterialsDifferent)
{
change |= ChangeType.Materials;
}
if (!HasFlag(change, ChangeType.Materials))
{
change |= ChangeType.MaterialProperty;
}
return change;
}
protected override void SendCompleteChanges(IEnumerable<INetworkConnection> connections)
{
SendDeltaChanges(connections, ChangeType.FontAndPlacement | ChangeType.Text | ChangeType.Materials);
}
protected override void SendDeltaChanges(IEnumerable<INetworkConnection> connections, ChangeType changeFlags)
{
if (changeFlags != ChangeType.MaterialProperty)
{
using (MemoryStream memoryStream = new MemoryStream())
using (BinaryWriter message = new BinaryWriter(memoryStream))
{
ComponentBroadcasterService.WriteHeader(message, this);
message.Write((byte)(changeFlags & ~ChangeType.MaterialProperty));
if (HasFlag(changeFlags, ChangeType.Text))
{
message.Write(textComp.text);
}
if (HasFlag(changeFlags, ChangeType.FontAndPlacement))
{
message.Write((byte)textComp.alignment);
message.Write(textComp.color);
message.Write(textComp.fontSize);
message.Write((byte)textComp.fontStyle);
message.Write(textComp.lineSpacing);
message.Write((byte)textComp.horizontalOverflow);
message.Write((byte)textComp.verticalOverflow);
message.Write(FontAssetId);
}
if (HasFlag(changeFlags, ChangeType.Materials))
{
MaterialsBroadcaster.SendMaterials(message, null, ShouldSynchronizeMaterialProperty);
}
message.Flush();
StateSynchronizationSceneManager.Instance.Send(connections, memoryStream.GetBuffer(), 0, memoryStream.Position);
}
}
if (HasFlag(changeFlags, ChangeType.MaterialProperty))
{
MaterialsBroadcaster.SendMaterialPropertyChanges(connections, null, TransformBroadcaster.PerformanceParameters, message =>
{
TextService.Instance.WriteHeader(message, this);
message.Write((byte)ChangeType.MaterialProperty);
}, ShouldSynchronizeMaterialProperty);
}
}
private bool ShouldSynchronizeMaterialProperty(MaterialPropertyAsset materialProperty)
{
return true;
}
public static bool HasFlag(ChangeType changeType, ChangeType flag)
{
return (changeType & flag) == flag;
}
private struct TextProperties
{
public TextProperties(Text text)
{
alignment = text.alignment;
color = text.color;
fontSize = text.fontSize;
fontStyle = text.fontStyle;
lineSpacing = text.lineSpacing;
horizontalOverflow = text.horizontalOverflow;
verticalOverflow = text.verticalOverflow;
}
public TextAnchor alignment;
public Color color;
public int fontSize;
public FontStyle fontStyle;
public float lineSpacing;
public HorizontalWrapMode horizontalOverflow;
public VerticalWrapMode verticalOverflow;
public static bool operator ==(TextProperties first, TextProperties second)
{
return first.Equals(second);
}
public static bool operator !=(TextProperties first, TextProperties second)
{
return !first.Equals(second);
}
public override bool Equals(object obj)
{
if (!(obj is TextProperties))
{
return false;
}
TextProperties other = (TextProperties)obj;
return
other.alignment == alignment &&
other.color == color &&
other.fontSize == fontSize &&
other.fontStyle == fontStyle &&
other.lineSpacing == lineSpacing &&
other.horizontalOverflow == horizontalOverflow &&
other.verticalOverflow == verticalOverflow;
}
public override int GetHashCode()
{
return (int)(fontSize + lineSpacing + fontSize);
}
}
}
} | 37.476684 | 177 | 0.544864 | [
"MIT"
] | Pycorax/MixedReality-SpectatorView | src/SpectatorView.Unity/Assets/SpectatorView/Scripts/StateSynchronization/NetworkedComponents/Text/TextBroadcaster.cs | 7,235 | C# |
using Microsoft.Maui.Graphics;
namespace Microsoft.Maui
{
public interface IScrollView : IContentView
{
/// <summary>
/// Gets a value indicating the visibility rules for the horizontal scroll bar.
/// </summary>
ScrollBarVisibility HorizontalScrollBarVisibility { get; }
/// <summary>
/// Gets a value indicating the visibility rules for the vertical scroll bar.
/// </summary>
ScrollBarVisibility VerticalScrollBarVisibility { get; }
/// <summary>
/// Gets a value indicating the scroll orientation of the ScrollView.
/// </summary>
ScrollOrientation Orientation { get; }
/// <summary>
/// Gets the size of the scrollable content in the ScrollView.
/// </summary>
Size ContentSize { get; }
/// <summary>
/// Gets the current scroll position of the ScrollView along the horizontal axis.
/// </summary>
double HorizontalOffset { get; set; }
/// <summary>
/// Gets the current scroll position of the ScrollView along the vertical axis.
/// </summary>
double VerticalOffset { get; set; }
/// <summary>
/// Allows the platform ScrollView to inform that cross-platform code that a scroll operation has completed.
/// </summary>
void ScrollFinished();
/// <summary>
/// Scrolls to a specific offset.
/// </summary>
/// <param name="horizontalOffset">Represents the horizontal offset.</param>
/// <param name="verticalOffset">Represents the vertical offset.</param>
/// <param name="instant"></param>
void RequestScrollTo(double horizontalOffset, double verticalOffset, bool instant);
}
} | 31.28 | 110 | 0.698849 | [
"MIT"
] | 10088/maui | src/Core/src/Core/IScrollView.cs | 1,566 | C# |
using System;
using System.Reflection;
namespace MethodBoundaryAspect.Fody.Attributes
{
public class MethodExecutionArgs
{
public FlowBehavior FlowBehavior { get; set; }
public object Instance { get; set; }
public MethodBase Method { get; set; }
public object[] Arguments { get; set; }
public object ReturnValue { get; set; }
public Exception Exception { get; set; }
public object MethodExecutionTag { get; set; }
}
} | 30.4375 | 54 | 0.650924 | [
"MIT"
] | NilFusion/MethodBoundaryAspect.Fody | src/MethodBoundaryAspect/Attributes/MethodExecutionArgs.cs | 489 | 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.
#nullable disable
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms.Layout;
namespace System.Windows.Forms
{
[Editor("System.Windows.Forms.Design.ToolStripCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[ListBindable(false)]
public class ToolStripItemCollection : ArrangedElementCollection, IList
{
private readonly ToolStrip _owner;
private readonly bool _itemsCollection;
private readonly bool _isReadOnly;
// We use an index here rather than control so that we don't have lifetime issues by holding on to extra
// references. Note this is not thread safe - but WinForms has to be run in a STA anyways.
private int _lastAccessedIndex = -1;
internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection)
: this(owner, itemsCollection, isReadOnly: false)
{
}
internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection, bool isReadOnly)
{
_owner = owner;
_itemsCollection = itemsCollection;
_isReadOnly = isReadOnly;
}
public ToolStripItemCollection(ToolStrip owner, ToolStripItem[] value)
{
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
AddRange(value);
}
/// <summary>
/// </summary>
public new virtual ToolStripItem this[int index]
{
get
{
return (ToolStripItem)(InnerList[index]);
}
}
/// <summary>
/// Retrieves the child control with the specified key.
/// </summary>
public virtual ToolStripItem this[string key]
{
get
{
// We do not support null and empty string as valid keys.
if ((key is null) || (key.Length == 0))
{
return null;
}
// Search for the key in our collection
int index = IndexOfKey(key);
if (IsValidIndex(index))
{
return (ToolStripItem)InnerList[index];
}
else
{
return null;
}
}
}
public ToolStripItem Add(string text)
{
return Add(text, null, null);
}
public ToolStripItem Add(Image image)
{
return Add(null, image, null);
}
public ToolStripItem Add(string text, Image image)
{
return Add(text, image, null);
}
public ToolStripItem Add(string text, Image image, EventHandler onClick)
{
ToolStripItem item = _owner.CreateDefaultItem(text, image, onClick);
Add(item);
return item;
}
public int Add(ToolStripItem value)
{
CheckCanAddOrInsertItem(value);
SetOwner(value);
int retVal = InnerList.Add(value);
if (_itemsCollection && _owner != null)
{
_owner.OnItemAddedInternal(value);
_owner.OnItemAdded(new ToolStripItemEventArgs(value));
}
return retVal;
}
public void AddRange(ToolStripItem[] toolStripItems)
{
if (toolStripItems is null)
{
throw new ArgumentNullException(nameof(toolStripItems));
}
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
// ToolStripDropDown will look for PropertyNames.Items to determine if it needs
// to resize itself.
using (new LayoutTransaction(_owner, _owner, PropertyNames.Items))
{
for (int i = 0; i < toolStripItems.Length; i++)
{
Add(toolStripItems[i]);
}
}
}
public void AddRange(ToolStripItemCollection toolStripItems)
{
if (toolStripItems is null)
{
throw new ArgumentNullException(nameof(toolStripItems));
}
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
// ToolStripDropDown will look for PropertyNames.Items to determine if it needs
// to resize itself.
using (new LayoutTransaction(_owner, _owner, PropertyNames.Items))
{
int currentCount = toolStripItems.Count;
for (int i = 0; i < currentCount; i++)
{
Add(toolStripItems[i]);
}
}
}
public bool Contains(ToolStripItem value)
{
return InnerList.Contains(value);
}
public virtual void Clear()
{
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
if (Count == 0)
{
return;
}
ToolStripOverflow overflow = null;
if (_owner != null && !_owner.IsDisposingItems)
{
_owner.SuspendLayout();
overflow = _owner.GetOverflow();
if (overflow != null)
{
overflow.SuspendLayout();
}
}
try
{
while (Count != 0)
{
RemoveAt(Count - 1);
}
}
finally
{
if (overflow != null)
{
overflow.ResumeLayout(false);
}
if (_owner != null && !_owner.IsDisposingItems)
{
_owner.ResumeLayout();
}
}
}
/// <summary>
/// Returns true if the collection contains an item with the specified key, false otherwise.
/// </summary>
public virtual bool ContainsKey(string key)
{
return IsValidIndex(IndexOfKey(key));
}
private void CheckCanAddOrInsertItem(ToolStripItem value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
if (_owner is ToolStripDropDown dropDown)
{
// If we're on a dropdown, we can only add non-control host items
// as we dont want anything on a dropdown to get keyboard messages in the Internet.
if (dropDown.OwnerItem == value)
{
throw new NotSupportedException(SR.ToolStripItemCircularReference);
}
}
}
/// <summary>
/// Searches for Items by their Name property, builds up an array
/// of all the controls that match.
/// </summary>
public ToolStripItem[] Find(string key, bool searchAllChildren)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull);
}
List<ToolStripItem> foundItems = new();
FindInternal(key, searchAllChildren, this, foundItems);
return foundItems.ToArray();
}
/// <summary>
/// Searches for Items by their Name property, builds up a list
/// of all the items that match.
/// </summary>
private void FindInternal(string key, bool searchAllChildren, ToolStripItemCollection itemsToLookIn, List<ToolStripItem> foundItems)
{
try
{
for (int i = 0; i < itemsToLookIn.Count; i++)
{
if (itemsToLookIn[i] is null)
{
continue;
}
if (WindowsFormsUtils.SafeCompareStrings(itemsToLookIn[i].Name, key, ignoreCase: true))
{
foundItems.Add(itemsToLookIn[i]);
}
}
// Optional recursive search for controls in child collections.
if (searchAllChildren)
{
for (int j = 0; j < itemsToLookIn.Count; j++)
{
if (itemsToLookIn[j] is not ToolStripDropDownItem item)
{
continue;
}
if (item.HasDropDownItems)
{
// If it has a valid child collection, append those results to our collection.
FindInternal(key, searchAllChildren, item.DropDownItems, foundItems);
}
}
}
}
catch (Exception e) when (!ClientUtils.IsCriticalException(e))
{
}
}
public override bool IsReadOnly { get { return _isReadOnly; } }
void IList.Clear() { Clear(); }
bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } }
bool IList.Contains(object value) { return InnerList.Contains(value); }
void IList.RemoveAt(int index) { RemoveAt(index); }
void IList.Remove(object value) { Remove(value as ToolStripItem); }
int IList.Add(object value) { return Add(value as ToolStripItem); }
int IList.IndexOf(object value) { return IndexOf(value as ToolStripItem); }
void IList.Insert(int index, object value) { Insert(index, value as ToolStripItem); }
object IList.this[int index]
{
get { return InnerList[index]; }
set { throw new NotSupportedException(SR.ToolStripCollectionMustInsertAndRemove); /* InnerList[index] = value; */ }
}
public void Insert(int index, ToolStripItem value)
{
CheckCanAddOrInsertItem(value);
SetOwner(value);
InnerList.Insert(index, value);
if (_itemsCollection && _owner != null)
{
if (_owner.IsHandleCreated)
{
LayoutTransaction.DoLayout(_owner, value, PropertyNames.Parent);
}
else
{
// next time we fetch the preferred size, recalc it.
CommonProperties.xClearPreferredSizeCache(_owner);
}
_owner.OnItemAddedInternal(value);
_owner.OnItemAdded(new ToolStripItemEventArgs(value));
}
}
public int IndexOf(ToolStripItem value)
{
return InnerList.IndexOf(value);
}
/// <summary>
/// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1.
/// </summary>
public virtual int IndexOfKey(string key)
{
// Step 0 - Arg validation
if ((key is null) || (key.Length == 0))
{
return -1; // we dont support empty or null keys.
}
// step 1 - check the last cached item
if (IsValidIndex(_lastAccessedIndex))
{
if (WindowsFormsUtils.SafeCompareStrings(this[_lastAccessedIndex].Name, key, /* ignoreCase = */ true))
{
return _lastAccessedIndex;
}
}
// step 2 - search for the item
for (int i = 0; i < Count; i++)
{
if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true))
{
_lastAccessedIndex = i;
return i;
}
}
// step 3 - we didn't find it. Invalidate the last accessed index and return -1.
_lastAccessedIndex = -1;
return -1;
}
/// <summary>
/// Determines if the index is valid for the collection.
/// </summary>
private bool IsValidIndex(int index)
{
return ((index >= 0) && (index < Count));
}
/// <summary>
/// Do proper cleanup of ownership, etc.
/// </summary>
private void OnAfterRemove(ToolStripItem item)
{
if (_itemsCollection)
{
ToolStrip parent = null;
if (item != null)
{
parent = item.ParentInternal;
item.SetOwner(null);
}
if (_owner != null)
{
_owner.OnItemRemovedInternal(item);
if (!_owner.IsDisposingItems)
{
ToolStripItemEventArgs e = new ToolStripItemEventArgs(item);
_owner.OnItemRemoved(e);
// dont fire the ItemRemoved event for Overflow
// it would fire constantly.... instead clear any state if the item
// is really being removed from the master collection.
if (parent != null && parent != _owner)
{
parent.OnItemVisibleChanged(e, /*performLayout*/false);
}
}
}
}
}
public void Remove(ToolStripItem value)
{
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
InnerList.Remove(value);
OnAfterRemove(value);
}
public void RemoveAt(int index)
{
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
ToolStripItem item = null;
if (index < Count && index >= 0)
{
item = (ToolStripItem)(InnerList[index]);
}
InnerList.RemoveAt(index);
OnAfterRemove(item);
}
/// <summary>
/// Removes the child item with the specified key.
/// </summary>
public virtual void RemoveByKey(string key)
{
if (IsReadOnly)
{
throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly);
}
int index = IndexOfKey(key);
if (IsValidIndex(index))
{
RemoveAt(index);
}
}
public void CopyTo(ToolStripItem[] array, int index)
{
InnerList.CopyTo(array, index);
}
//
internal void MoveItem(ToolStripItem value)
{
if (value.ParentInternal != null)
{
int indexOfItem = value.ParentInternal.Items.IndexOf(value);
if (indexOfItem >= 0)
{
value.ParentInternal.Items.RemoveAt(indexOfItem);
}
}
Add(value);
}
internal void MoveItem(int index, ToolStripItem value)
{
// if moving to the end - call add instead.
if (index == Count)
{
MoveItem(value);
return;
}
if (value.ParentInternal != null)
{
int indexOfItem = value.ParentInternal.Items.IndexOf(value);
if (indexOfItem >= 0)
{
value.ParentInternal.Items.RemoveAt(indexOfItem);
if ((value.ParentInternal == _owner) && (index > indexOfItem))
{
index--;
}
}
}
Insert(index, value);
}
private void SetOwner(ToolStripItem item)
{
if (_itemsCollection)
{
if (item != null)
{
if (item.Owner != null)
{
item.Owner.Items.Remove(item);
}
item.SetOwner(_owner);
if (item.Renderer != null)
{
item.Renderer.InitializeItem(item);
}
}
}
}
}
}
| 32.824092 | 140 | 0.49001 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs | 17,169 | C# |
using System;
using System.Net.Http;
namespace MyToDoApp.Services
{
public interface IHttpFactory
{
HttpClient GetClient();
}
public class HttpFactory : IHttpFactory
{
public virtual HttpClient GetClient()
{
var client = new HttpClient();
if (!string.IsNullOrEmpty(AppConstants.WebServiceUrl))
{
client.BaseAddress = new Uri($"{AppConstants.WebServiceUrl}");
}
return client;
}
}
} | 21.541667 | 78 | 0.5706 | [
"MIT"
] | stvansolano/my-todo-app | MyToDoApp/Utils/IHttpFactory.cs | 519 | C# |
namespace EA.Iws.RequestHandlers.Movement
{
using System;
using System.Threading.Tasks;
using Domain.Movement;
using Prsd.Core.Mediator;
using Requests.Movement;
internal class GetMovementIdByNumberHandler : IRequestHandler<GetMovementIdByNumber, Guid>
{
private readonly IMovementRepository movementRepository;
public GetMovementIdByNumberHandler(IMovementRepository movementRepository)
{
this.movementRepository = movementRepository;
}
public async Task<Guid> HandleAsync(GetMovementIdByNumber message)
{
var movement = await movementRepository.GetByNumberOrDefault(message.Number, message.NotificationId);
if (movement == null)
{
throw new InvalidOperationException("No movement for notification " + message.NotificationId + " exists with number " + message.Number);
}
return movement.Id;
}
}
}
| 31.612903 | 152 | 0.67551 | [
"Unlicense"
] | DEFRA/prsd-iws | src/EA.Iws.RequestHandlers/Movement/GetMovementIdByNumberHandler.cs | 982 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MohyoButton.Models
{
public class KeyInfo
{
/// <summary>
/// Consumer Key
/// </summary>
public string ConsumerKey;
/// <summary>
/// Consumer Secret
/// </summary>
public string ConsumerSecret;
/// <summary>
/// Access Token
/// </summary>
public string AccessToken;
/// <summary>
/// Access Token Secret
/// </summary>
public string AccessTokenSecret;
/// <summary>
/// User defined message
/// </summary>
public string CountMessage;
/// <summary>
/// Post count message
/// </summary>
public bool PostCountMessage;
/// <summary>
/// User defined post word list
/// </summary>
public string UserWordListName;
}
}
| 23.357143 | 40 | 0.536188 | [
"MIT"
] | 0V/MohyoButton | MohyoButton/Models/KeyInfo.cs | 983 | C# |
namespace Microsoft.Pc
{
public enum LivenessOption { None, Standard, Sampling };
} | 21.75 | 60 | 0.735632 | [
"MIT"
] | Drona-Org/Q | Src/Pc/Compiler/LivenessOption.cs | 87 | C# |
using Pyramid.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Entity.Infrastructure;
using Pyramid.Code;
using DevExpress.Web;
using DevExpress.Web.Bootstrap;
namespace Pyramid.Pages
{
public partial class ChildrenDashboard : System.Web.UI.Page
{
private ProgramAndRoleFromSession currentProgramRole;
protected void Page_Load(object sender, EventArgs e)
{
//Get the current program role
currentProgramRole = Utilities.GetProgramRoleFromSession(Session);
//Don't allow aggregate viewers to see the action column
if (currentProgramRole.RoleFK.Value == (int)Utilities.ProgramRoleFKs.AGGREGATE_DATA_VIEWER)
{
//Get the action column index (the farthest right column)
int actionColumnIndex = (bsGRChildren.Columns.Count - 1);
//Hide the action column
bsGRChildren.Columns[actionColumnIndex].Visible = false;
}
if (!IsPostBack)
{
//Set the view only value
if(currentProgramRole.AllowedToEdit.Value)
{
hfViewOnly.Value = "False";
}
else
{
hfViewOnly.Value = "True";
}
//Populate the chart
BindRaceChart();
//Check for messages in the query string
string messageType = Request.QueryString["messageType"];
//Show the message if it exists
if(!String.IsNullOrWhiteSpace(messageType))
{
switch (messageType)
{
case "ChildAdded":
msgSys.ShowMessageToUser("success", "Success", "Child successfully added!", 10000);
break;
case "ChildEdited":
msgSys.ShowMessageToUser("success", "Success", "Child successfully edited!", 10000);
break;
case "ChildCanceled":
msgSys.ShowMessageToUser("info", "Canceled", "The action was canceled, no changes were saved.", 10000);
break;
case "NoChild":
msgSys.ShowMessageToUser("warning", "Warning", "The specified child could not be found, please try again.", 15000);
break;
case "NotAuthorized":
msgSys.ShowMessageToUser("danger", "Not Authorized", "You are not authorized to view that information!", 10000);
break;
default:
break;
}
}
}
}
/// <summary>
/// This method fills the Children by Race chart with data
/// </summary>
private void BindRaceChart()
{
using(PyramidContext context = new PyramidContext())
{
//Get the chart data
var raceData = context.spGetChildrenCountByRace(string.Join(",", currentProgramRole.ProgramFKs), DateTime.Now).ToList();
//Bind the chart to the data
chartChildRace.DataSource = raceData;
chartChildRace.DataBind();
}
}
/// <summary>
/// This method fires when the data source for the child DevExpress GridView is selecting
/// and it handles the select
/// </summary>
/// <param name="sender">The efChildDataSource control</param>
/// <param name="e">The LinqServerModeDataSourceSelectEventArgs event</param>
protected void efChildDataSource_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
{
//Set the key expression
e.KeyExpression = "ChildProgramPK";
//Set the source to a LINQ query
PyramidContext context = new PyramidContext();
e.QueryableSource = from c in context.Child.Include(c => c.ChildProgram).AsNoTracking()
join cp in context.ChildProgram.Include(cp => cp.CodeDischargeReason).Include(cp => cp.Program) on c.ChildPK equals cp.ChildFK
where currentProgramRole.ProgramFKs.Contains(cp.ProgramFK)
select new {
c.ChildPK,
Name = c.FirstName + " " + c.LastName,
c.BirthDate,
cp.ChildProgramPK,
cp.ProgramSpecificID,
cp.HasIEP,
cp.IsDLL,
cp.EnrollmentDate,
cp.DischargeDate,
DischargeReason = cp.CodeDischargeReason.Description,
cp.DischargeReasonSpecify,
cp.ProgramFK,
cp.Program.ProgramName
};
}
/// <summary>
/// This method executes when the user clicks the delete button for a child
/// and it deletes the child information from the database
/// </summary>
/// <param name="sender">The lbDeleteChild LinkButton</param>
/// <param name="e">The Click event</param>
protected void lbDeleteChild_Click(object sender, EventArgs e)
{
if (currentProgramRole.AllowedToEdit.Value)
{
//Get the PK from the hidden field
int? removeChildProgramPK = (String.IsNullOrWhiteSpace(hfDeleteChildProgramPK.Value) ? (int?)null : Convert.ToInt32(hfDeleteChildProgramPK.Value));
//Remove the role if the PK is not null
if (removeChildProgramPK != null)
{
try
{
using (PyramidContext context = new PyramidContext())
{
//Get the child program row to remove
ChildProgram childProgramToRemove = context.ChildProgram
.Find(removeChildProgramPK);
//Get the child to remove
Models.Child childToRemove = context.Child
.Where(c => c.ChildPK == childProgramToRemove.ChildFK).FirstOrDefault();
//Get the notes to remove and remove them
List<ChildNote> notesToRemove = context.ChildNote.Where(cn => cn.ChildFK == childProgramToRemove.ChildFK).ToList();
context.ChildNote.RemoveRange(notesToRemove);
//Get the status rows to remove and remove them
List<ChildStatus> statusToRemove = context.ChildStatus.Where(cs => cs.ChildFK == childProgramToRemove.ChildFK).ToList();
context.ChildStatus.RemoveRange(statusToRemove);
//Get the classroom assignments to remove and remove them
List<ChildClassroom> classroomAssignmentsToRemove = context.ChildClassroom.Where(cc => cc.ChildFK == childProgramToRemove.ChildFK).ToList();
context.ChildClassroom.RemoveRange(classroomAssignmentsToRemove);
//Remove the child program row
context.ChildProgram.Remove(childProgramToRemove);
//Remove the child
context.Child.Remove(childToRemove);
//Save all the changes to the database
context.SaveChanges();
//Show a success message
msgSys.ShowMessageToUser("success", "Success", "Successfully deleted child!", 10000);
}
}
catch (DbUpdateException dbUpdateEx)
{
//Check if it is a foreign key error
if (dbUpdateEx.InnerException?.InnerException is SqlException)
{
//If it is a foreign key error, display a custom message
SqlException sqlEx = (SqlException)dbUpdateEx.InnerException.InnerException;
if (sqlEx.Number == 547)
{
msgSys.ShowMessageToUser("danger", "Error", "Could not delete the child, there are related records in the system!<br/><br/>If you do not know what related records exist, please contact tech support via ticket.", 120000);
}
else
{
msgSys.ShowMessageToUser("danger", "Error", "An error occurred while deleting the child!", 120000);
}
}
else
{
msgSys.ShowMessageToUser("danger", "Error", "An error occurred while deleting the child!", 120000);
}
//Log the error
Elmah.ErrorSignal.FromCurrentContext().Raise(dbUpdateEx);
}
//Rebind the child controls
bsGRChildren.DataBind();
BindRaceChart();
}
else
{
msgSys.ShowMessageToUser("danger", "Error", "Could not find the child to delete!", 120000);
}
}
else
{
msgSys.ShowMessageToUser("danger", "Error", "You are not authorized to make changes!", 120000);
}
}
}
} | 47.61435 | 253 | 0.487662 | [
"MIT"
] | CHSR/PyramidModelWebApp | Pyramid/Pyramid/Pages/ChildrenDashboard.aspx.cs | 10,620 | C# |
namespace TraktNet.Objects.Basic.Tests.Json.Reader
{
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Trakt.NET.Tests.Utility.Traits;
using TraktNet.Objects.Basic;
using TraktNet.Objects.Json;
using Xunit;
[Category("Objects.Basic.JsonReader")]
public partial class CastAndCrewArrayJsonReader_Tests
{
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Empty_Array()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_EMPTY_ARRAY);
traktCastAndCrews.Should().NotBeNull().And.BeEmpty();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Complete()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_COMPLETE);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
ITraktCastMember[] castMemberItems = items[0].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[0].Crew.Should().BeNull();
castMemberItems = items[1].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Incomplete_1()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_INCOMPLETE_1);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
ITraktCastMember[] castMemberItems = items[0].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[0].Crew.Should().BeNull();
castMemberItems = items[1].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().BeNull();
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Incomplete_2()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_INCOMPLETE_2);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
ITraktCastMember[] castMemberItems = items[0].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().BeNull();
items[0].Crew.Should().BeNull();
castMemberItems = items[1].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Not_Valid_1()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_NOT_VALID_1);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
items[0].Cast.Should().BeNull();
items[0].Crew.Should().BeNull();
ITraktCastMember[] castMemberItems = items[1].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Not_Valid_2()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_NOT_VALID_2);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
ITraktCastMember[] castMemberItems = items[0].Cast.ToArray();
castMemberItems[0].Should().NotBeNull();
castMemberItems[0].Characters.Should().NotBeNull().And.HaveCount(1).And.Contain("Joe Brody");
castMemberItems[0].Person.Should().NotBeNull();
castMemberItems[0].Person.Name.Should().Be("Bryan Cranston");
castMemberItems[0].Person.Ids.Should().NotBeNull();
castMemberItems[0].Person.Ids.Trakt.Should().Be(297737U);
castMemberItems[0].Person.Ids.Slug.Should().Be("bryan-cranston");
castMemberItems[0].Person.Ids.Imdb.Should().Be("nm0186505");
castMemberItems[0].Person.Ids.Tmdb.Should().Be(17419U);
castMemberItems[0].Person.Ids.TvRage.Should().Be(1797U);
items[1].Cast.Should().BeNull();
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Not_Valid_3()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(JSON_NOT_VALID_3);
traktCastAndCrews.Should().NotBeNull();
ITraktCastAndCrew[] items = traktCastAndCrews.ToArray();
items[0].Cast.Should().BeNull();
items[0].Crew.Should().BeNull();
items[1].Cast.Should().BeNull();
items[1].Crew.Should().BeNull();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Null()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
Func<Task<IEnumerable<ITraktCastAndCrew>>> traktCastAndCrews = () => jsonReader.ReadArrayAsync(default(string));
await traktCastAndCrews.Should().ThrowAsync<ArgumentNullException>();
}
[Fact]
public async Task Test_CastAndCrewArrayJsonReader_ReadArray_From_Json_String_Empty()
{
var jsonReader = new ArrayJsonReader<ITraktCastAndCrew>();
IEnumerable<ITraktCastAndCrew> traktCastAndCrews = await jsonReader.ReadArrayAsync(string.Empty);
traktCastAndCrews.Should().BeNull();
}
}
}
| 48.293839 | 124 | 0.648283 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Tests/Trakt.NET.Objects.Basic.Tests/Json/Reader/CastAndCrewArrayJsonReader/CastAndCrewArrayJsonReader_Json_String_Tests.cs | 10,192 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using laget.Db.Mongo.Exceptions;
using MongoDB.Driver;
namespace laget.Db.Mongo
{
public class ReadOnlyRepository<TEntity> : Repository<TEntity>, IRepository<TEntity> where TEntity : Entity
{
public ReadOnlyRepository(IMongoDefaultProvider provider)
: base(provider)
{
}
public override void Insert(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override Task InsertAsync(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override void Insert(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override Task InsertAsync(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override void Update(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update, UpdateOptions options)
{
throw new ReadOnlyException();
}
public override Task UpdateAsync(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update, UpdateOptions options)
{
throw new ReadOnlyException();
}
public override void UpdateMany(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update, UpdateOptions options)
{
throw new ReadOnlyException();
}
public override Task UpdateManyAsync(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update, UpdateOptions options)
{
throw new ReadOnlyException();
}
public override void Upsert(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override Task UpsertAsync(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override void Upsert(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override Task UpsertAsync(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override void Upsert(FilterDefinition<TEntity> filter, TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override Task UpsertAsync(FilterDefinition<TEntity> filter, TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override void Delete(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override Task DeleteAsync(IEnumerable<TEntity> entities)
{
throw new ReadOnlyException();
}
public override void Delete(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override Task DeleteAsync(TEntity entity)
{
throw new ReadOnlyException(entity.GetType());
}
public override void Delete(FilterDefinition<TEntity> filter)
{
throw new ReadOnlyException();
}
public override Task DeleteAsync(FilterDefinition<TEntity> filter)
{
throw new ReadOnlyException();
}
}
}
| 29.215517 | 135 | 0.620832 | [
"Apache-2.0"
] | laget-se/laget.Db.Mongo | laget.Db.Mongo/ReadOnlyRepository.cs | 3,391 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace MobileTCC.Droid
{
[Activity(Theme = "@style/Theme.Splash",
MainLauncher = true,
NoHistory = true,
Icon = "@drawable/Scc")]
public class SplashScreen : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
System.Threading.Thread.Sleep(500);
StartActivity(typeof(MainActivity));
}
}
} | 21.451613 | 67 | 0.664662 | [
"MIT"
] | Mogueno/Atena-Desk-and-Mobile | MobileTCC/MobileTCC/MobileTCC.Android/SplashScreen.cs | 667 | C# |
using System;
using System.Collections.Generic;
namespace Newznab
{
public abstract class NewznabWebRequest : Dictionary<String, String>
{
protected NewznabWebRequest(String command)
{
this.Add("t", command);
}
}
}
| 16.285714 | 69 | 0.736842 | [
"MIT"
] | ChristopherHaws/newznab | src/Newznab/NewznabWebRequest.cs | 228 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Formats.Red.Records.Enums;
namespace GameEstate.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CAINpcPhilippaCombat : CAINpcCombat
{
public CAINpcPhilippaCombat(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAINpcPhilippaCombat(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 31.652174 | 132 | 0.748626 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CAINpcPhilippaCombat.cs | 728 | C# |
using System;
using ImageFramework.DirectX;
using ImageFramework.Utility;
using ImageViewer.Controller.TextureViews.Shader;
using ImageViewer.Controller.TextureViews.Shared;
using ImageViewer.Models;
using SharpDX;
using SharpDX.Direct3D11;
using Device = ImageFramework.DirectX.Device;
namespace ImageViewer.Controller.TextureViews.Texture2D
{
public class CubeTextureView : PolarTextureView
{
private readonly CubeViewShader shader;
public CubeTextureView(ModelsEx models)
: base(models)
{
shader = new CubeViewShader(models);
}
public override void Dispose()
{
shader?.Dispose();
base.Dispose();
}
public override void Draw(int id, ITexture texture)
{
if (texture == null) return;
base.Draw(id, texture);
var dev = Device.Get();
dev.OutputMerger.BlendState = models.ViewData.AlphaBlendState;
ShaderResourceView overlay = null;
if (models.Overlay.Overlay != null)
{
overlay = ((TextureArray2D) models.Overlay.Overlay).GetCubeView(models.Display.ActiveMipmap);
}
shader.Run(GetTransform(), CalcFarplane(), ((TextureArray2D)texture).GetCubeView(models.Display.ActiveMipmap), overlay);
dev.OutputMerger.BlendState = models.ViewData.DefaultBlendState;
}
public override Size3? GetTexelPosition(Vector2 mouse)
{
// left handed coordinate system
var transform = GetTransform();
var preViewDir = new Vector4(mouse.X, -mouse.Y, CalcFarplane(), 0.0f);
Vector4.Transform(ref preViewDir, ref transform, out var viewDir);
viewDir.Normalize();
// according to dx spec: https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#PointSampling
// Choose the largest magnitude component of the input vector. Call this magnitude of this value AxisMajor. In the case of a tie, the following precedence should occur: Z, Y, X.
int axisMajor = 0;
int axisFlip = 0;
float axisMajorValue = 0.0f;
for (int i = 0; i < 3; ++i)
{
if (Math.Abs(viewDir[i]) >= axisMajorValue)
{
axisMajor = i;
axisFlip = viewDir[i] < 0.0f ? 1 : 0;
axisMajorValue = Math.Abs(viewDir[i]);
}
}
int faceId = axisMajor * 2 + axisFlip;
// Select and mirror the minor axes as defined by the TextureCube coordinate space. Call this new 2d coordinate Position.
// Project the coordinate onto the cube by dividing the components Position by AxisMajor.
int axisMinor1 = axisMajor == 0 ? 2 : 0; // first coord is x or z
int axisMinor2 = 3 - axisMajor - axisMinor1;
float u = viewDir[axisMinor1] / axisMajorValue;
float v = -viewDir[axisMinor2] / axisMajorValue;
switch (faceId)
{
case 0:
case 5:
u *= -1.0f;
break;
case 2:
v *= -1.0f;
break;
}
models.Display.ActiveLayer = faceId;
var pt = Utility.CanonicalToTexelCoordinates(u, v,
models.Images.GetWidth(models.Display.ActiveMipmap),
models.Images.GetHeight(models.Display.ActiveMipmap));
return new Size3(pt.X, pt.Y, 0);
}
protected override Matrix GetOrientation()
{
return Matrix.Scaling(1.0f);
}
}
}
| 35.392523 | 190 | 0.571429 | [
"MIT"
] | gaybro8777/ImageViewer | ImageViewer/Controller/TextureViews/Texture2D/CubeTextureView.cs | 3,789 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using ZWaveLib.CommandClasses;
namespace ZWaveLib.WebAPI.Controllers
{
[ApiController]
public class CommandController : ControllerBase
{
private readonly ZWaveController controller;
public CommandController(ZWaveController controller)
{
this.controller = controller;
}
[HttpPost("/nodes/{id}/send/{command}")]
public ActionResult<CallbackStatus> SendCommand(byte id, CommandClass command, string parameter = null)
{
if (controller.Status != ControllerStatus.Ready)
return StatusCode((int)HttpStatusCode.InternalServerError, "Controller is not ready yet.");
var node = controller.GetNode(id);
if (node == null)
return NotFound();
ZWaveMessage message;
switch (command)
{
case CommandClass.Basic:
message = Basic.Set(node, int.Parse(parameter));
break;
default:
return StatusCode((int)HttpStatusCode.InternalServerError, "Command not implemented");
}
message.Wait();
return Ok(message.CallbackStatus);
}
}
}
| 29.468085 | 111 | 0.606498 | [
"MIT"
] | trembon/ZWaveLib.WebAPI | ZWaveLib.WebAPI/Controllers/CommandController.cs | 1,387 | C# |
using LotteryCoreConsole.ScrapeAndQuartz.WebsiteScraping.Interfaces;
using Quartz;
using System;
using System.Threading.Tasks;
namespace LotteryCoreConsole.ScrapeAndQuartz.QuartzScheduling.USPowerball
{
/// <summary>
/// Job creation for US Powerball to be executed by Quartz when triggered.
/// </summary>
public class USPowerballJob : IJob
{
/// <summary>
/// Task that gets executed for US Powerball when triggered by Quartz.net
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Execute(IJobExecutionContext context)
{
ILotteryScrape lotteryScrape = ScrapeAndQuartzFactory.CreateLotto649Scrape();
// TODO: Better logging.
Console.WriteLine($"{DateTime.Now} : Starting US Powerball Scrape");
await lotteryScrape.ScrapeLotteryAsync();
}
}
}
| 34.148148 | 89 | 0.661605 | [
"MIT"
] | Toyotomius/LotteryCoreConsole | ScrapeAndQuartz/QuartzScheduling/USPowerball/USPowerballJob.cs | 924 | C# |
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Security;
using System.Security.Permissions;
namespace DeviceIOControl.Native
{
/// <summary>Native methods</summary>
internal static class Methods
{
/// <summary>
/// Creates or opens a file or I/O device.
/// The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe.
/// The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified.
/// </summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx</remarks>
/// <param name="lpFileName">The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name.</param>
/// <param name="dwDesiredAccess">The requested access to the file or device, which can be summarized as read, write, both or neither zero).</param>
/// <param name="dwShareMode">
/// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the following table).
/// Access requests to attributes or extended attributes are not affected by this flag.
/// </param>
/// <param name="lpSecurityAttributes">A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes.</param>
/// <param name="dwCreationDisposition">An action to take on a file or device that exists or does not exist.</param>
/// <param name="dwFlagsAndAttributes">The file or device attributes and flags, FILE_ATTRIBUTE_NORMAL being the most common default value for files.</param>
/// <param name="hTemplateFile">A valid handle to a template file with the GENERIC_READ access right. The template file supplies file attributes and extended attributes for the file that is being created.</param>
/// <returns>If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.</returns>
[DllImport("kernel32.dll", EntryPoint = "CreateFileA", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Ansi)]
private static extern IntPtr CreateFile(
[In] String lpFileName,
WinApi.FILE_ACCESS_FLAGS dwDesiredAccess,
WinApi.FILE_SHARE dwShareMode,
IntPtr lpSecurityAttributes,
WinApi.CreateDisposition dwCreationDisposition,
UInt32 dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary>Opens specified device</summary>
/// <param name="lpFileName">Device path</param>
/// <returns>Handle to the opened device</returns>
public static IntPtr OpenDevice(String lpFileName)
{
return Methods.OpenDevice(lpFileName,
WinApi.FILE_ACCESS_FLAGS.GENERIC_READ | WinApi.FILE_ACCESS_FLAGS.GENERIC_WRITE,
WinApi.FILE_SHARE.READ | WinApi.FILE_SHARE.WRITE);
}
/// <summary>Opens specified device</summary>
/// <param name="lpFileName">Device path</param>
/// <param name="dwDesiredAccess">Desired access flage</param>
/// <param name="dwShareMode">Share mode</param>
/// <exception cref="ArgumentNullException">lpFileName is null or empty</exception>
/// <exception cref="Win32Exception">Device does not opened</exception>
/// <returns>Handle to the opened device</returns>
public static IntPtr OpenDevice(String lpFileName, WinApi.FILE_ACCESS_FLAGS dwDesiredAccess, WinApi.FILE_SHARE dwShareMode)
{
if (String.IsNullOrEmpty(lpFileName))
throw new ArgumentNullException("lpFileName");
IntPtr result = Methods.CreateFile(lpFileName,
dwDesiredAccess,
dwShareMode,
IntPtr.Zero,
WinApi.CreateDisposition.OPEN_EXISTING,
0,
IntPtr.Zero);
if (result == Constant.INVALID_HANDLE_VALUE)
throw new Win32Exception();
return result;
}
/// <summary>
/// The LookupAccountName function accepts the name of a system and an account as input.
/// It retrieves a security identifier (SID) for the account and the name of the domain on which the account was found.
/// The LsaLookupNames function can also retrieve computer accounts.
/// </summary>
/// <param name="lpSystemName">
/// A pointer to a null-terminated character string that specifies the name of the system.
/// This string can be the name of a remote computer.
/// If this string is NULL, the account name translation begins on the local system.
/// If the name cannot be resolved on the local system, this function will try to resolve the name using domain controllers trusted by the local system.
/// Generally, specify a value for <c>lpSystemName</c> only when the account is in an untrusted domain and the name of a computer in that domain is known.
/// </param>
/// <param name="lpAccountName">
/// A pointer to a null-terminated string that specifies the account name.
/// Use a fully qualified string in the <c>domain_name\user_name</c> format to ensure that <c>LookupAccountName</c> finds the account in the desired domain.
/// </param>
/// <param name="Sid">
/// A pointer to a buffer that receives the SID structure that corresponds to the account name pointed to by the <c>lpAccountName</c> parameter.
/// If this parameter is NULL, <c>cbSid</c> must be zero.
/// </param>
/// <param name="cbSid">
/// A pointer to a variable.
/// On input, this value specifies the size, in bytes, of the <c>Sid</c> buffer.
/// If the function fails because the buffer is too small or if <c>cbSid</c> is zero, this variable receives the required buffer size.
/// </param>
/// <param name="ReferencedDomainName">
/// A pointer to a buffer that receives the name of the domain where the account name is found.
/// For computers that are not joined to a domain, this buffer receives the computer name.
/// If this parameter is NULL, the function returns the required buffer size.
/// </param>
/// <param name="cchReferencedDomainName">
/// A pointer to a variable.
/// On input, this value specifies the size, in TCHARs, of the <c>ReferencedDomainName</c> buffer.
/// If the function fails because the buffer is too small, this variable receives the required buffer size, including the terminating null character.
/// If the <c>ReferencedDomainName</c> parameter is NULL, this parameter must be zero.
/// </param>
/// <param name="peUse">
/// A pointer to a <see cref="WinApi.SID_NAME_USE"/> enumerated type that indicates the type of the account when the function returns.
/// </param>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. For extended error information, call <see cref="Marshal.GetLastWin32Error"/>.
/// </returns>
[DllImport("advapi32.dll", EntryPoint = "LookupAccountName", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern Boolean LookupAccountName(
String lpSystemName,
String lpAccountName,
[MarshalAs(UnmanagedType.LPArray)] Byte[] Sid,
ref UInt32 cbSid,
StringBuilder ReferencedDomainName,
ref UInt32 cchReferencedDomainName,
out WinApi.SID_NAME_USE peUse);
/// <summary>
/// The LookupAccountName function accepts the name of a system and an account as input.
/// It retrieves a security identifier (SID) for the account and the name of the domain on which the account was found.
/// The LsaLookupNames function can also retrieve computer accounts.
/// </summary>
/// <param name="accountName">
/// A pointer to a null-terminated string that specifies the account name.
/// Use a fully qualified string in the domain_name\user_name format to ensure that LookupAccountName finds the account in the desired domain.
/// </param>
/// <param name="capacity">
/// A pointer to a variable. On input, this value specifies the size, in bytes, of the Sid buffer.
/// If the function fails because the buffer is too small or if cbSid is zero, this variable receives the required buffer size.
/// </param>
/// <returns>SID structure that corresponds to the account name pointed to by the accountName parameter.</returns>
public static Byte[] LookupAccountName(String accountName, Int32 capacity = 16)
{
Byte[] result = new Byte[capacity];
UInt32 cbSid = (UInt32)capacity;
StringBuilder referencedDomainName = new StringBuilder(capacity);
UInt32 cchReferencedDomainName = (UInt32)referencedDomainName.Capacity;
WinApi.SID_NAME_USE sidUse;
Boolean isSuccess = Methods.LookupAccountName(null,
accountName,
result,
ref cbSid,
referencedDomainName,
ref cchReferencedDomainName,
out sidUse);
if (isSuccess)
return result;
else
{
Int32 error = Marshal.GetLastWin32Error();
switch ((Constant.ERROR)error)
{
case Constant.ERROR.INSUFFICIENT_BUFFER:
case Constant.ERROR.INVALID_FLAGS://On Windows Server 2003 this error is/can be returned, but processing can still continue
return LookupAccountName(accountName, (Int32)cbSid);
default:
throw new Win32Exception((Int32)error);
}
}
}
[DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean CloseHandle(IntPtr hObject);
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", EntryPoint = "GetDevicePowerState", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean GetDevicePowerState(IntPtr hDevice, out Boolean pfOn);
[DllImport("kernel32.dll", EntryPoint = "RequestDeviceWakeup", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean RequestDeviceWakeup(IntPtr hDevice);
[DllImport("kernel32.dll", EntryPoint = "CancelDeviceWakeupRequest", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean CancelDeviceWakeupRequest(IntPtr hDevice);
/// <summary>Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.</summary>
/// <remarks>To determine whether a drive is a USB-type drive, call SetupDiGetDeviceRegistryProperty and specify the SPDRP_REMOVAL_POLICY property.</remarks>
/// <param name="lpRootPathName">
/// The root directory for the drive.
/// A trailing backslash is required. If this parameter is NULL, the function uses the root of the current directory.
/// </param>
/// <returns>The return value specifies the type of drive.</returns>
[SuppressUnmanagedCodeSecurity]
[SecuritySafeCritical]
[DllImport("kernel32.dll", EntryPoint = "GetDriveTypeA", SetLastError = true, ThrowOnUnmappableChar = true)]
public static extern WinApi.DRIVE GetDriveTypeA(
[In] String lpRootPathName);
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx</remarks>
/// <param name="hDevice">A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.</param>
/// <param name="dwIoControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="lpInBuffer">
/// A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.
/// </param>
/// <param name="nInBufferSize">The size of the input buffer, in bytes.</param>
/// <param name="lpOutBuffer">
/// A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.
/// </param>
/// <param name="nOutBufferSize">The size of the output buffer, in bytes.</param>
/// <param name="lpBytesReturned">A pointer to a variable that receives the size of the data stored in the output buffer, in bytes.</param>
/// <param name="lpOverlapped">
/// A pointer to an OVERLAPPED structure.
/// If hDevice was opened without specifying FILE_FLAG_OVERLAPPED, lpOverlapped is ignored.
/// </param>
/// <returns>If the operation completes successfully, the return value is nonzero.</returns>
[DllImport("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern Boolean DeviceIoControl(
IntPtr hDevice,
UInt32 dwIoControlCode,
IntPtr lpInBuffer,
UInt32 nInBufferSize,
IntPtr lpOutBuffer,
UInt32 nOutBufferSize,
ref UInt32 lpBytesReturned,
[In] ref NativeOverlapped lpOverlapped);
public static T DeviceIoControl<T>(
IntPtr hDevice,
UInt32 dwIoControlCode,
Object inParams,
out UInt32 lpBytesReturned) where T : struct
{
T result;
if (Methods.DeviceIoControl<T>(hDevice, dwIoControlCode, inParams, out lpBytesReturned, out result))
return result;
else
throw new Win32Exception();
}
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx</remarks>
/// <param name="hDevice">A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream.</param>
/// <param name="dwIoControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="inParams">
/// A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.
/// </param>
/// <param name="lpBytesReturned">A pointer to a variable that receives the size of the data stored in the output buffer, in bytes.</param>
/// <param name="outBuffer">
/// A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.
/// </param>
/// <returns>If the operation completes successfully, the return value is nonzero.</returns>
//[EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public static Boolean DeviceIoControl<T>(
IntPtr hDevice,
UInt32 dwIoControlCode,
Object inParams,
out UInt32 lpBytesReturned,
out T outBuffer) where T : struct
{
Int32 nInBufferSize = 0;
IntPtr lpInBuffer = IntPtr.Zero;
IntPtr lpOutBuffer = IntPtr.Zero;
try
{
if (inParams != null)
{
nInBufferSize = Marshal.SizeOf(inParams);
lpInBuffer = Marshal.AllocHGlobal(nInBufferSize);
Marshal.StructureToPtr(inParams, lpInBuffer, true);
}
outBuffer = new T();
Int32 nOutBufferSize = Marshal.SizeOf(typeof(T));
lpOutBuffer = Marshal.AllocHGlobal(nOutBufferSize);
Marshal.StructureToPtr(outBuffer, lpOutBuffer, true);
lpBytesReturned = 0;
NativeOverlapped lpOverlapped = new NativeOverlapped();
Boolean result = Methods.DeviceIoControl(
hDevice,
dwIoControlCode,
lpInBuffer,
(UInt32)nInBufferSize,
lpOutBuffer,
(UInt32)nOutBufferSize,
ref lpBytesReturned,
ref lpOverlapped);
//if(result) В некоторых случаях даже при отрицательном значении необходимо читать исходящий буфер
outBuffer = (T)Marshal.PtrToStructure(lpOutBuffer, typeof(T));
return result;
}
finally
{
if (lpInBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpInBuffer);
if (lpOutBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpOutBuffer);
}
}
}
}
| 51.956113 | 280 | 0.738144 | [
"MIT"
] | FanIT/SysMonAvalonia | DeviceIOControl/Native/Methods.cs | 16,651 | C# |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Infrastructure.Commands;
using Infrastructure.Repositories;
using Newtonsoft.Json;
namespace Infrastructure.Services.Camera
{
public class CameraService : ICameraService
{
private readonly IClientRepository _clientRepository;
private readonly ICameraCommandDispatcher _commandDispatcher;
private readonly Process _cameraProcess;
public bool Running { get; protected set; }
public CameraService(IClientRepository clientRepository, ICameraCommandDispatcher commandDispatcher)
{
_clientRepository = clientRepository;
_commandDispatcher = commandDispatcher;
_cameraProcess = new Process
{
StartInfo = new ProcessStartInfo("CameraService.exe")
{
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = false,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
},
EnableRaisingEvents = true
};
}
public void Start()
{
if (Running) return;
_cameraProcess.Exited += (sender, args) => _cameraProcess.Dispose();
try
{
Running = _cameraProcess.Start();
if (Running)
{
ReadAsync();
}
}
catch
{
Debug.WriteLine("Could not start the camera");
}
}
private async void ReadAsync()
{
var stdout = _cameraProcess.StandardOutput;
while (Running)
{
try
{
var buffer = new char[1024];
var bytesRead = await stdout.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
_cameraProcess.Close();
Running = false;
continue;
}
var command = JsonConvert.DeserializeObject<ICameraCommand>(Convert.ToString(buffer));
await _commandDispatcher.DispatchAsync(command);
}
catch
{
Debug.WriteLine("Could not read the data from camera");
}
}
}
public void Stop()
{
if (!Running) return;
_cameraProcess.Close();
Running = false;
}
public async Task RequestAsync(ICameraCommand command)
{
try
{
var json = JsonConvert.SerializeObject(command);
await _cameraProcess.StandardInput.WriteAsync(json);
}
catch
{
Debug.WriteLine($"Failed to send over a {command.GetType()} command");
}
}
}
}
| 29.92381 | 108 | 0.500318 | [
"MIT"
] | Zuravvski/BSc-Thesis | Server/Infrastructure/Services/Camera/CameraService.cs | 3,144 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Cdn.V1.Model
{
/// <summary>
///
/// </summary>
public class TopUrlSummary
{
/// <summary>
/// URL名称。
/// </summary>
[JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)]
public string Url { get; set; }
/// <summary>
/// 对应查询类型的值。(流量单位:Byte)
/// </summary>
[JsonProperty("value", NullValueHandling = NullValueHandling.Ignore)]
public long? Value { get; set; }
/// <summary>
/// 查询起始时间戳。
/// </summary>
[JsonProperty("start_time", NullValueHandling = NullValueHandling.Ignore)]
public long? StartTime { get; set; }
/// <summary>
/// 查询结束时间戳
/// </summary>
[JsonProperty("end_time", NullValueHandling = NullValueHandling.Ignore)]
public long? EndTime { get; set; }
/// <summary>
/// 参数类型支持:flux(流量),req_num(请求总数)。
/// </summary>
[JsonProperty("stat_type", NullValueHandling = NullValueHandling.Ignore)]
public string StatType { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TopUrlSummary {\n");
sb.Append(" url: ").Append(Url).Append("\n");
sb.Append(" value: ").Append(Value).Append("\n");
sb.Append(" startTime: ").Append(StartTime).Append("\n");
sb.Append(" endTime: ").Append(EndTime).Append("\n");
sb.Append(" statType: ").Append(StatType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as TopUrlSummary);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(TopUrlSummary input)
{
if (input == null)
return false;
return
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
) &&
(
this.Value == input.Value ||
(this.Value != null &&
this.Value.Equals(input.Value))
) &&
(
this.StartTime == input.StartTime ||
(this.StartTime != null &&
this.StartTime.Equals(input.StartTime))
) &&
(
this.EndTime == input.EndTime ||
(this.EndTime != null &&
this.EndTime.Equals(input.EndTime))
) &&
(
this.StatType == input.StatType ||
(this.StatType != null &&
this.StatType.Equals(input.StatType))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Url != null)
hashCode = hashCode * 59 + this.Url.GetHashCode();
if (this.Value != null)
hashCode = hashCode * 59 + this.Value.GetHashCode();
if (this.StartTime != null)
hashCode = hashCode * 59 + this.StartTime.GetHashCode();
if (this.EndTime != null)
hashCode = hashCode * 59 + this.EndTime.GetHashCode();
if (this.StatType != null)
hashCode = hashCode * 59 + this.StatType.GetHashCode();
return hashCode;
}
}
}
}
| 31.939394 | 82 | 0.475569 | [
"Apache-2.0"
] | huaweicloud/huaweicloud-sdk-net | Services/Cdn/V1/Model/TopUrlSummary.cs | 4,314 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.live.Model.V20161101;
namespace Aliyun.Acs.live.Transform.V20161101
{
public class DescribeLiveDomainMappingResponseUnmarshaller
{
public static DescribeLiveDomainMappingResponse Unmarshall(UnmarshallerContext context)
{
DescribeLiveDomainMappingResponse describeLiveDomainMappingResponse = new DescribeLiveDomainMappingResponse();
describeLiveDomainMappingResponse.HttpResponse = context.HttpResponse;
describeLiveDomainMappingResponse.RequestId = context.StringValue("DescribeLiveDomainMapping.RequestId");
List<DescribeLiveDomainMappingResponse.DescribeLiveDomainMapping_LiveDomainModel> describeLiveDomainMappingResponse_liveDomainModels = new List<DescribeLiveDomainMappingResponse.DescribeLiveDomainMapping_LiveDomainModel>();
for (int i = 0; i < context.Length("DescribeLiveDomainMapping.LiveDomainModels.Length"); i++) {
DescribeLiveDomainMappingResponse.DescribeLiveDomainMapping_LiveDomainModel liveDomainModel = new DescribeLiveDomainMappingResponse.DescribeLiveDomainMapping_LiveDomainModel();
liveDomainModel.DomainName = context.StringValue("DescribeLiveDomainMapping.LiveDomainModels["+ i +"].DomainName");
liveDomainModel.Type = context.StringValue("DescribeLiveDomainMapping.LiveDomainModels["+ i +"].Type");
describeLiveDomainMappingResponse_liveDomainModels.Add(liveDomainModel);
}
describeLiveDomainMappingResponse.LiveDomainModels = describeLiveDomainMappingResponse_liveDomainModels;
return describeLiveDomainMappingResponse;
}
}
}
| 49.32 | 227 | 0.799676 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-live/Live/Transform/V20161101/DescribeLiveDomainMappingResponseUnmarshaller.cs | 2,466 | C# |
using ARMeilleure.CodeGen.RegisterAllocators;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using static ARMeilleure.IntermediateRepresentation.OperandHelper;
using static ARMeilleure.IntermediateRepresentation.OperationHelper;
namespace ARMeilleure.CodeGen.X86
{
static class PreAllocator
{
public static void RunPass(CompilerContext cctx, StackAllocator stackAlloc, out int maxCallArgs)
{
maxCallArgs = -1;
CallConvName callConv = CallingConvention.GetCurrentCallConv();
Operand[] preservedArgs = new Operand[CallingConvention.GetArgumentsOnRegsCount()];
for (BasicBlock block = cctx.Cfg.Blocks.First; block != null; block = block.ListNext)
{
for (Node node = block.Operations.First; node != null; node = node.ListNext)
{
if (!(node is Operation operation))
{
continue;
}
HandleConstantRegCopy(block.Operations, node, operation);
node = HandleDestructiveRegCopy(block.Operations, node, operation);
node = HandleConstrainedRegCopy(block.Operations, node, operation);
switch (operation.Instruction)
{
case Instruction.Call:
// Get the maximum number of arguments used on a call.
// On windows, when a struct is returned from the call,
// we also need to pass the pointer where the struct
// should be written on the first argument.
int argsCount = operation.SourcesCount - 1;
if (operation.Destination != null && operation.Destination.Type == OperandType.V128)
{
argsCount++;
}
if (maxCallArgs < argsCount)
{
maxCallArgs = argsCount;
}
// Copy values to registers expected by the function
// being called, as mandated by the ABI.
if (callConv == CallConvName.Windows)
{
node = HandleCallWindowsAbi(block.Operations, stackAlloc, node, operation);
}
else /* if (callConv == CallConvName.SystemV) */
{
node = HandleCallSystemVAbi(block.Operations, node, operation);
}
break;
case Instruction.ConvertToFPUI:
node = HandleConvertToFPUI(block.Operations, node, operation);
break;
case Instruction.LoadArgument:
if (callConv == CallConvName.Windows)
{
node = HandleLoadArgumentWindowsAbi(cctx, block.Operations, node, preservedArgs, operation);
}
else /* if (callConv == CallConvName.SystemV) */
{
node = HandleLoadArgumentSystemVAbi(cctx, block.Operations, node, preservedArgs, operation);
}
break;
case Instruction.Negate:
if (!operation.GetSource(0).Type.IsInteger())
{
node = HandleNegate(block.Operations, node, operation);
}
break;
case Instruction.Return:
if (callConv == CallConvName.Windows)
{
HandleReturnWindowsAbi(cctx, block.Operations, node, preservedArgs, operation);
}
else /* if (callConv == CallConvName.SystemV) */
{
HandleReturnSystemVAbi(block.Operations, node, operation);
}
break;
case Instruction.Tailcall:
if (callConv == CallConvName.Windows)
{
HandleTailcallWindowsAbi(block.Operations, stackAlloc, node, operation);
}
else
{
HandleTailcallSystemVAbi(block.Operations, stackAlloc, node, operation);
}
break;
case Instruction.VectorInsert8:
if (!HardwareCapabilities.SupportsSse41)
{
node = HandleVectorInsert8(block.Operations, node, operation);
}
break;
case Instruction.Extended:
IntrinsicOperation intrinOp = (IntrinsicOperation)operation;
if (intrinOp.Intrinsic == Intrinsic.X86Mxcsrmb || intrinOp.Intrinsic == Intrinsic.X86Mxcsrub)
{
int stackOffset = stackAlloc.Allocate(OperandType.I32);
operation.SetSources(new Operand[] { Const(stackOffset), operation.GetSource(0) });
}
break;
}
}
}
}
private static void HandleConstantRegCopy(IntrusiveList<Node> nodes, Node node, Operation operation)
{
if (operation.SourcesCount == 0 || IsIntrinsic(operation.Instruction))
{
return;
}
Instruction inst = operation.Instruction;
Operand src1 = operation.GetSource(0);
Operand src2;
if (src1.Kind == OperandKind.Constant)
{
if (!src1.Type.IsInteger())
{
// Handle non-integer types (FP32, FP64 and V128).
// For instructions without an immediate operand, we do the following:
// - Insert a copy with the constant value (as integer) to a GPR.
// - Insert a copy from the GPR to a XMM register.
// - Replace the constant use with the XMM register.
src1 = AddXmmCopy(nodes, node, src1);
operation.SetSource(0, src1);
}
else if (!HasConstSrc1(inst))
{
// Handle integer types.
// Most ALU instructions accepts a 32-bits immediate on the second operand.
// We need to ensure the following:
// - If the constant is on operand 1, we need to move it.
// -- But first, we try to swap operand 1 and 2 if the instruction is commutative.
// -- Doing so may allow us to encode the constant as operand 2 and avoid a copy.
// - If the constant is on operand 2, we check if the instruction supports it,
// if not, we also add a copy. 64-bits constants are usually not supported.
if (IsCommutative(operation))
{
src2 = operation.GetSource(1);
Operand temp = src1;
src1 = src2;
src2 = temp;
operation.SetSource(0, src1);
operation.SetSource(1, src2);
}
if (src1.Kind == OperandKind.Constant)
{
src1 = AddCopy(nodes, node, src1);
operation.SetSource(0, src1);
}
}
}
if (operation.SourcesCount < 2)
{
return;
}
src2 = operation.GetSource(1);
if (src2.Kind == OperandKind.Constant)
{
if (!src2.Type.IsInteger())
{
src2 = AddXmmCopy(nodes, node, src2);
operation.SetSource(1, src2);
}
else if (!HasConstSrc2(inst) || CodeGenCommon.IsLongConst(src2))
{
src2 = AddCopy(nodes, node, src2);
operation.SetSource(1, src2);
}
}
}
private static Node HandleConstrainedRegCopy(IntrusiveList<Node> nodes, Node node, Operation operation)
{
Operand dest = operation.Destination;
switch (operation.Instruction)
{
case Instruction.CompareAndSwap:
case Instruction.CompareAndSwap16:
case Instruction.CompareAndSwap8:
{
OperandType type = operation.GetSource(1).Type;
if (type == OperandType.V128)
{
// Handle the many restrictions of the compare and exchange (16 bytes) instruction:
// - The expected value should be in RDX:RAX.
// - The new value to be written should be in RCX:RBX.
// - The value at the memory location is loaded to RDX:RAX.
void SplitOperand(Operand source, Operand lr, Operand hr)
{
nodes.AddBefore(node, Operation(Instruction.VectorExtract, lr, source, Const(0)));
nodes.AddBefore(node, Operation(Instruction.VectorExtract, hr, source, Const(1)));
}
Operand rax = Gpr(X86Register.Rax, OperandType.I64);
Operand rbx = Gpr(X86Register.Rbx, OperandType.I64);
Operand rcx = Gpr(X86Register.Rcx, OperandType.I64);
Operand rdx = Gpr(X86Register.Rdx, OperandType.I64);
SplitOperand(operation.GetSource(1), rax, rdx);
SplitOperand(operation.GetSource(2), rbx, rcx);
node = nodes.AddAfter(node, Operation(Instruction.VectorCreateScalar, dest, rax));
node = nodes.AddAfter(node, Operation(Instruction.VectorInsert, dest, dest, rdx, Const(1)));
operation.SetDestinations(new Operand[] { rdx, rax });
operation.SetSources(new Operand[] { operation.GetSource(0), rdx, rax, rcx, rbx });
}
else
{
// Handle the many restrictions of the compare and exchange (32/64) instruction:
// - The expected value should be in (E/R)AX.
// - The value at the memory location is loaded to (E/R)AX.
Operand expected = operation.GetSource(1);
Operand newValue = operation.GetSource(2);
Operand rax = Gpr(X86Register.Rax, expected.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, rax, expected));
// We need to store the new value into a temp, since it may
// be a constant, and this instruction does not support immediate operands.
Operand temp = Local(newValue.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, temp, newValue));
operation.SetSources(new Operand[] { operation.GetSource(0), rax, temp });
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax));
operation.Destination = rax;
}
break;
}
case Instruction.Divide:
case Instruction.DivideUI:
{
// Handle the many restrictions of the division instructions:
// - The dividend is always in RDX:RAX.
// - The result is always in RAX.
// - Additionally it also writes the remainder in RDX.
if (dest.Type.IsInteger())
{
Operand src1 = operation.GetSource(0);
Operand rax = Gpr(X86Register.Rax, src1.Type);
Operand rdx = Gpr(X86Register.Rdx, src1.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1));
nodes.AddBefore(node, Operation(Instruction.Clobber, rdx));
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax));
operation.SetDestinations(new Operand[] { rdx, rax });
operation.SetSources(new Operand[] { rdx, rax, operation.GetSource(1) });
operation.Destination = rax;
}
break;
}
case Instruction.Extended:
{
IntrinsicOperation intrinOp = (IntrinsicOperation)operation;
// BLENDVPD, BLENDVPS, PBLENDVB last operand is always implied to be XMM0 when VEX is not supported.
if ((intrinOp.Intrinsic == Intrinsic.X86Blendvpd ||
intrinOp.Intrinsic == Intrinsic.X86Blendvps ||
intrinOp.Intrinsic == Intrinsic.X86Pblendvb) &&
!HardwareCapabilities.SupportsVexEncoding)
{
Operand xmm0 = Xmm(X86Register.Xmm0, OperandType.V128);
nodes.AddBefore(node, Operation(Instruction.Copy, xmm0, operation.GetSource(2)));
operation.SetSource(2, xmm0);
}
break;
}
case Instruction.Multiply64HighSI:
case Instruction.Multiply64HighUI:
{
// Handle the many restrictions of the i64 * i64 = i128 multiply instructions:
// - The multiplicand is always in RAX.
// - The lower 64-bits of the result is always in RAX.
// - The higher 64-bits of the result is always in RDX.
Operand src1 = operation.GetSource(0);
Operand rax = Gpr(X86Register.Rax, src1.Type);
Operand rdx = Gpr(X86Register.Rdx, src1.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1));
operation.SetSource(0, rax);
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, rdx));
operation.SetDestinations(new Operand[] { rdx, rax });
break;
}
case Instruction.RotateRight:
case Instruction.ShiftLeft:
case Instruction.ShiftRightSI:
case Instruction.ShiftRightUI:
{
// The shift register is always implied to be CL (low 8-bits of RCX or ECX).
if (operation.GetSource(1).Kind == OperandKind.LocalVariable)
{
Operand rcx = Gpr(X86Register.Rcx, OperandType.I32);
nodes.AddBefore(node, Operation(Instruction.Copy, rcx, operation.GetSource(1)));
operation.SetSource(1, rcx);
}
break;
}
}
return node;
}
private static Node HandleDestructiveRegCopy(IntrusiveList<Node> nodes, Node node, Operation operation)
{
if (operation.Destination == null || operation.SourcesCount == 0)
{
return node;
}
Instruction inst = operation.Instruction;
Operand dest = operation.Destination;
Operand src1 = operation.GetSource(0);
// The multiply instruction (that maps to IMUL) is somewhat special, it has
// a three operand form where the second source is a immediate value.
bool threeOperandForm = inst == Instruction.Multiply && operation.GetSource(1).Kind == OperandKind.Constant;
if (IsSameOperandDestSrc1(operation) && src1.Kind == OperandKind.LocalVariable && !threeOperandForm)
{
bool useNewLocal = false;
for (int srcIndex = 1; srcIndex < operation.SourcesCount; srcIndex++)
{
if (operation.GetSource(srcIndex) == dest)
{
useNewLocal = true;
break;
}
}
if (useNewLocal)
{
// Dest is being used as some source already, we need to use a new
// local to store the temporary value, otherwise the value on dest
// local would be overwritten.
Operand temp = Local(dest.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, temp, src1));
operation.SetSource(0, temp);
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, temp));
operation.Destination = temp;
}
else
{
nodes.AddBefore(node, Operation(Instruction.Copy, dest, src1));
operation.SetSource(0, dest);
}
}
else if (inst == Instruction.ConditionalSelect)
{
Operand src2 = operation.GetSource(1);
Operand src3 = operation.GetSource(2);
if (src1 == dest || src2 == dest)
{
Operand temp = Local(dest.Type);
nodes.AddBefore(node, Operation(Instruction.Copy, temp, src3));
operation.SetSource(2, temp);
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, temp));
operation.Destination = temp;
}
else
{
nodes.AddBefore(node, Operation(Instruction.Copy, dest, src3));
operation.SetSource(2, dest);
}
}
return node;
}
private static Node HandleConvertToFPUI(IntrusiveList<Node> nodes, Node node, Operation operation)
{
// Unsigned integer to FP conversions are not supported on X86.
// We need to turn them into signed integer to FP conversions, and
// adjust the final result.
Operand dest = operation.Destination;
Operand source = operation.GetSource(0);
Debug.Assert(source.Type.IsInteger(), $"Invalid source type \"{source.Type}\".");
Node currentNode = node;
if (source.Type == OperandType.I32)
{
// For 32-bits integers, we can just zero-extend to 64-bits,
// and then use the 64-bits signed conversion instructions.
Operand zex = Local(OperandType.I64);
node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend32, zex, source));
node = nodes.AddAfter(node, Operation(Instruction.ConvertToFP, dest, zex));
}
else /* if (source.Type == OperandType.I64) */
{
// For 64-bits integers, we need to do the following:
// - Ensure that the integer has the most significant bit clear.
// -- This can be done by shifting the value right by 1, that is, dividing by 2.
// -- The least significant bit is lost in this case though.
// - We can then convert the shifted value with a signed integer instruction.
// - The result still needs to be corrected after that.
// -- First, we need to multiply the result by 2, as we divided it by 2 before.
// --- This can be done efficiently by adding the result to itself.
// -- Then, we need to add the least significant bit that was shifted out.
// --- We can convert the least significant bit to float, and add it to the result.
Operand lsb = Local(OperandType.I64);
Operand half = Local(OperandType.I64);
Operand lsbF = Local(dest.Type);
node = nodes.AddAfter(node, Operation(Instruction.Copy, lsb, source));
node = nodes.AddAfter(node, Operation(Instruction.Copy, half, source));
node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, lsb, lsb, Const(1L)));
node = nodes.AddAfter(node, Operation(Instruction.ShiftRightUI, half, half, Const(1)));
node = nodes.AddAfter(node, Operation(Instruction.ConvertToFP, lsbF, lsb));
node = nodes.AddAfter(node, Operation(Instruction.ConvertToFP, dest, half));
node = nodes.AddAfter(node, Operation(Instruction.Add, dest, dest, dest));
node = nodes.AddAfter(node, Operation(Instruction.Add, dest, dest, lsbF));
}
Delete(nodes, currentNode, operation);
return node;
}
private static Node HandleNegate(IntrusiveList<Node> nodes, Node node, Operation operation)
{
// There's no SSE FP negate instruction, so we need to transform that into
// a XOR of the value to be negated with a mask with the highest bit set.
// This also produces -0 for a negation of the value 0.
Operand dest = operation.Destination;
Operand source = operation.GetSource(0);
Debug.Assert(dest.Type == OperandType.FP32 ||
dest.Type == OperandType.FP64, $"Invalid destination type \"{dest.Type}\".");
Node currentNode = node;
Operand res = Local(dest.Type);
node = nodes.AddAfter(node, Operation(Instruction.VectorOne, res));
if (dest.Type == OperandType.FP32)
{
node = nodes.AddAfter(node, new IntrinsicOperation(Intrinsic.X86Pslld, res, res, Const(31)));
}
else /* if (dest.Type == OperandType.FP64) */
{
node = nodes.AddAfter(node, new IntrinsicOperation(Intrinsic.X86Psllq, res, res, Const(63)));
}
node = nodes.AddAfter(node, new IntrinsicOperation(Intrinsic.X86Xorps, res, res, source));
node = nodes.AddAfter(node, Operation(Instruction.Copy, dest, res));
Delete(nodes, currentNode, operation);
return node;
}
private static Node HandleVectorInsert8(IntrusiveList<Node> nodes, Node node, Operation operation)
{
// Handle vector insertion, when SSE 4.1 is not supported.
Operand dest = operation.Destination;
Operand src1 = operation.GetSource(0); // Vector
Operand src2 = operation.GetSource(1); // Value
Operand src3 = operation.GetSource(2); // Index
Debug.Assert(src3.Kind == OperandKind.Constant);
byte index = src3.AsByte();
Debug.Assert(index < 16);
Node currentNode = node;
Operand temp1 = Local(OperandType.I32);
Operand temp2 = Local(OperandType.I32);
node = nodes.AddAfter(node, Operation(Instruction.Copy, temp2, src2));
Operation vextOp = Operation(Instruction.VectorExtract16, temp1, src1, Const(index >> 1));
node = nodes.AddAfter(node, vextOp);
if ((index & 1) != 0)
{
node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend8, temp1, temp1));
node = nodes.AddAfter(node, Operation(Instruction.ShiftLeft, temp2, temp2, Const(8)));
node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2));
}
else
{
node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend8, temp2, temp2));
node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, temp1, temp1, Const(0xff00)));
node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2));
}
Operation vinsOp = Operation(Instruction.VectorInsert16, dest, src1, temp1, Const(index >> 1));
node = nodes.AddAfter(node, vinsOp);
Delete(nodes, currentNode, operation);
return node;
}
private static Node HandleCallWindowsAbi(IntrusiveList<Node> nodes, StackAllocator stackAlloc, Node node, Operation operation)
{
Operand dest = operation.Destination;
// Handle struct arguments.
int retArgs = 0;
int stackAllocOffset = 0;
int AllocateOnStack(int size)
{
// We assume that the stack allocator is initially empty (TotalSize = 0).
// Taking that into account, we can reuse the space allocated for other
// calls by keeping track of our own allocated size (stackAllocOffset).
// If the space allocated is not big enough, then we just expand it.
int offset = stackAllocOffset;
if (stackAllocOffset + size > stackAlloc.TotalSize)
{
stackAlloc.Allocate((stackAllocOffset + size) - stackAlloc.TotalSize);
}
stackAllocOffset += size;
return offset;
}
Operand arg0Reg = null;
if (dest != null && dest.Type == OperandType.V128)
{
int stackOffset = AllocateOnStack(dest.Type.GetSizeInBytes());
arg0Reg = Gpr(CallingConvention.GetIntArgumentRegister(0), OperandType.I64);
Operation allocOp = Operation(Instruction.StackAlloc, arg0Reg, Const(stackOffset));
nodes.AddBefore(node, allocOp);
retArgs = 1;
}
int argsCount = operation.SourcesCount - 1;
int maxArgs = CallingConvention.GetArgumentsOnRegsCount() - retArgs;
if (argsCount > maxArgs)
{
argsCount = maxArgs;
}
Operand[] sources = new Operand[1 + retArgs + argsCount];
sources[0] = operation.GetSource(0);
if (arg0Reg != null)
{
sources[1] = arg0Reg;
}
for (int index = 1; index < operation.SourcesCount; index++)
{
Operand source = operation.GetSource(index);
if (source.Type == OperandType.V128)
{
Operand stackAddr = Local(OperandType.I64);
int stackOffset = AllocateOnStack(source.Type.GetSizeInBytes());
nodes.AddBefore(node, Operation(Instruction.StackAlloc, stackAddr, Const(stackOffset)));
Operation storeOp = Operation(Instruction.Store, null, stackAddr, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, storeOp), storeOp);
operation.SetSource(index, stackAddr);
}
}
// Handle arguments passed on registers.
for (int index = 0; index < argsCount; index++)
{
Operand source = operation.GetSource(index + 1);
Operand argReg;
int argIndex = index + retArgs;
if (source.Type.IsInteger())
{
argReg = Gpr(CallingConvention.GetIntArgumentRegister(argIndex), source.Type);
}
else
{
argReg = Xmm(CallingConvention.GetVecArgumentRegister(argIndex), source.Type);
}
Operation copyOp = Operation(Instruction.Copy, argReg, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, copyOp), copyOp);
sources[1 + retArgs + index] = argReg;
}
// The remaining arguments (those that are not passed on registers)
// should be passed on the stack, we write them to the stack with "SpillArg".
for (int index = argsCount; index < operation.SourcesCount - 1; index++)
{
Operand source = operation.GetSource(index + 1);
Operand offset = Const((index + retArgs) * 8);
Operation spillOp = Operation(Instruction.SpillArg, null, offset, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, spillOp), spillOp);
}
if (dest != null)
{
if (dest.Type == OperandType.V128)
{
Operand retValueAddr = Local(OperandType.I64);
nodes.AddBefore(node, Operation(Instruction.Copy, retValueAddr, arg0Reg));
Operation loadOp = Operation(Instruction.Load, dest, retValueAddr);
node = nodes.AddAfter(node, loadOp);
operation.Destination = null;
}
else
{
Operand retReg = dest.Type.IsInteger()
? Gpr(CallingConvention.GetIntReturnRegister(), dest.Type)
: Xmm(CallingConvention.GetVecReturnRegister(), dest.Type);
Operation copyOp = Operation(Instruction.Copy, dest, retReg);
node = nodes.AddAfter(node, copyOp);
operation.Destination = retReg;
}
}
operation.SetSources(sources);
return node;
}
private static Node HandleCallSystemVAbi(IntrusiveList<Node> nodes, Node node, Operation operation)
{
Operand dest = operation.Destination;
List<Operand> sources = new List<Operand>
{
operation.GetSource(0)
};
int argsCount = operation.SourcesCount - 1;
int intMax = CallingConvention.GetIntArgumentsOnRegsCount();
int vecMax = CallingConvention.GetVecArgumentsOnRegsCount();
int intCount = 0;
int vecCount = 0;
int stackOffset = 0;
for (int index = 0; index < argsCount; index++)
{
Operand source = operation.GetSource(index + 1);
bool passOnReg;
if (source.Type.IsInteger())
{
passOnReg = intCount < intMax;
}
else if (source.Type == OperandType.V128)
{
passOnReg = intCount + 1 < intMax;
}
else
{
passOnReg = vecCount < vecMax;
}
if (source.Type == OperandType.V128 && passOnReg)
{
// V128 is a struct, we pass each half on a GPR if possible.
Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64);
Operand argReg2 = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64);
nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0)));
nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg2, source, Const(1)));
continue;
}
if (passOnReg)
{
Operand argReg = source.Type.IsInteger()
? Gpr(CallingConvention.GetIntArgumentRegister(intCount++), source.Type)
: Xmm(CallingConvention.GetVecArgumentRegister(vecCount++), source.Type);
Operation copyOp = Operation(Instruction.Copy, argReg, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, copyOp), copyOp);
sources.Add(argReg);
}
else
{
Operand offset = Const(stackOffset);
Operation spillOp = Operation(Instruction.SpillArg, null, offset, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, spillOp), spillOp);
stackOffset += source.Type.GetSizeInBytes();
}
}
if (dest != null)
{
if (dest.Type == OperandType.V128)
{
Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64);
Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64);
node = nodes.AddAfter(node, Operation(Instruction.VectorCreateScalar, dest, retLReg));
node = nodes.AddAfter(node, Operation(Instruction.VectorInsert, dest, dest, retHReg, Const(1)));
operation.Destination = null;
}
else
{
Operand retReg = dest.Type.IsInteger()
? Gpr(CallingConvention.GetIntReturnRegister(), dest.Type)
: Xmm(CallingConvention.GetVecReturnRegister(), dest.Type);
Operation copyOp = Operation(Instruction.Copy, dest, retReg);
node = nodes.AddAfter(node, copyOp);
operation.Destination = retReg;
}
}
operation.SetSources(sources.ToArray());
return node;
}
private static void HandleTailcallSystemVAbi(IntrusiveList<Node> nodes, StackAllocator stackAlloc, Node node, Operation operation)
{
List<Operand> sources = new List<Operand>
{
operation.GetSource(0)
};
int argsCount = operation.SourcesCount - 1;
int intMax = CallingConvention.GetIntArgumentsOnRegsCount();
int vecMax = CallingConvention.GetVecArgumentsOnRegsCount();
int intCount = 0;
int vecCount = 0;
// Handle arguments passed on registers.
for (int index = 0; index < argsCount; index++)
{
Operand source = operation.GetSource(1 + index);
bool passOnReg;
if (source.Type.IsInteger())
{
passOnReg = intCount + 1 < intMax;
}
else
{
passOnReg = vecCount < vecMax;
}
if (source.Type == OperandType.V128 && passOnReg)
{
// V128 is a struct, we pass each half on a GPR if possible.
Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64);
Operand argReg2 = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64);
nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0)));
nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg2, source, Const(1)));
continue;
}
if (passOnReg)
{
Operand argReg = source.Type.IsInteger()
? Gpr(CallingConvention.GetIntArgumentRegister(intCount++), source.Type)
: Xmm(CallingConvention.GetVecArgumentRegister(vecCount++), source.Type);
Operation copyOp = Operation(Instruction.Copy, argReg, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, copyOp), copyOp);
sources.Add(argReg);
}
else
{
throw new NotImplementedException("Spilling is not currently supported for tail calls. (too many arguments)");
}
}
// The target address must be on the return registers, since we
// don't return anything and it is guaranteed to not be a
// callee saved register (which would be trashed on the epilogue).
Operand retReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64);
Operation addrCopyOp = Operation(Instruction.Copy, retReg, operation.GetSource(0));
nodes.AddBefore(node, addrCopyOp);
sources[0] = retReg;
operation.SetSources(sources.ToArray());
}
private static void HandleTailcallWindowsAbi(IntrusiveList<Node> nodes, StackAllocator stackAlloc, Node node, Operation operation)
{
int argsCount = operation.SourcesCount - 1;
int maxArgs = CallingConvention.GetArgumentsOnRegsCount();
if (argsCount > maxArgs)
{
throw new NotImplementedException("Spilling is not currently supported for tail calls. (too many arguments)");
}
Operand[] sources = new Operand[1 + argsCount];
// Handle arguments passed on registers.
for (int index = 0; index < argsCount; index++)
{
Operand source = operation.GetSource(1 + index);
Operand argReg = source.Type.IsInteger()
? Gpr(CallingConvention.GetIntArgumentRegister(index), source.Type)
: Xmm(CallingConvention.GetVecArgumentRegister(index), source.Type);
Operation copyOp = Operation(Instruction.Copy, argReg, source);
HandleConstantRegCopy(nodes, nodes.AddBefore(node, copyOp), copyOp);
sources[1 + index] = argReg;
}
// The target address must be on the return registers, since we
// don't return anything and it is guaranteed to not be a
// callee saved register (which would be trashed on the epilogue).
Operand retReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64);
Operation addrCopyOp = Operation(Instruction.Copy, retReg, operation.GetSource(0));
nodes.AddBefore(node, addrCopyOp);
sources[0] = retReg;
operation.SetSources(sources);
}
private static Node HandleLoadArgumentWindowsAbi(
CompilerContext cctx,
IntrusiveList<Node> nodes,
Node node,
Operand[] preservedArgs,
Operation operation)
{
Operand source = operation.GetSource(0);
Debug.Assert(source.Kind == OperandKind.Constant, "Non-constant LoadArgument source kind.");
int retArgs = cctx.FuncReturnType == OperandType.V128 ? 1 : 0;
int index = source.AsInt32() + retArgs;
if (index < CallingConvention.GetArgumentsOnRegsCount())
{
Operand dest = operation.Destination;
if (preservedArgs[index] == null)
{
Operand argReg, pArg;
if (dest.Type.IsInteger())
{
argReg = Gpr(CallingConvention.GetIntArgumentRegister(index), dest.Type);
pArg = Local(dest.Type);
}
else if (dest.Type == OperandType.V128)
{
argReg = Gpr(CallingConvention.GetIntArgumentRegister(index), OperandType.I64);
pArg = Local(OperandType.I64);
}
else
{
argReg = Xmm(CallingConvention.GetVecArgumentRegister(index), dest.Type);
pArg = Local(dest.Type);
}
Operation copyOp = Operation(Instruction.Copy, pArg, argReg);
cctx.Cfg.Entry.Operations.AddFirst(copyOp);
preservedArgs[index] = pArg;
}
Operation argCopyOp = Operation(dest.Type == OperandType.V128
? Instruction.Load
: Instruction.Copy, dest, preservedArgs[index]);
Node newNode = nodes.AddBefore(node, argCopyOp);
Delete(nodes, node, operation);
return newNode;
}
else
{
// TODO: Pass on stack.
return node;
}
}
private static Node HandleLoadArgumentSystemVAbi(
CompilerContext cctx,
IntrusiveList<Node> nodes,
Node node,
Operand[] preservedArgs,
Operation operation)
{
Operand source = operation.GetSource(0);
Debug.Assert(source.Kind == OperandKind.Constant, "Non-constant LoadArgument source kind.");
int index = source.AsInt32();
int intCount = 0;
int vecCount = 0;
for (int cIndex = 0; cIndex < index; cIndex++)
{
OperandType argType = cctx.FuncArgTypes[cIndex];
if (argType.IsInteger())
{
intCount++;
}
else if (argType == OperandType.V128)
{
intCount += 2;
}
else
{
vecCount++;
}
}
bool passOnReg;
if (source.Type.IsInteger())
{
passOnReg = intCount < CallingConvention.GetIntArgumentsOnRegsCount();
}
else if (source.Type == OperandType.V128)
{
passOnReg = intCount + 1 < CallingConvention.GetIntArgumentsOnRegsCount();
}
else
{
passOnReg = vecCount < CallingConvention.GetVecArgumentsOnRegsCount();
}
if (passOnReg)
{
Operand dest = operation.Destination;
if (preservedArgs[index] == null)
{
if (dest.Type == OperandType.V128)
{
// V128 is a struct, we pass each half on a GPR if possible.
Operand pArg = Local(OperandType.V128);
Operand argLReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount), OperandType.I64);
Operand argHReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount + 1), OperandType.I64);
Operation copyL = Operation(Instruction.VectorCreateScalar, pArg, argLReg);
Operation copyH = Operation(Instruction.VectorInsert, pArg, pArg, argHReg, Const(1));
cctx.Cfg.Entry.Operations.AddFirst(copyH);
cctx.Cfg.Entry.Operations.AddFirst(copyL);
preservedArgs[index] = pArg;
}
else
{
Operand pArg = Local(dest.Type);
Operand argReg = dest.Type.IsInteger()
? Gpr(CallingConvention.GetIntArgumentRegister(intCount), dest.Type)
: Xmm(CallingConvention.GetVecArgumentRegister(vecCount), dest.Type);
Operation copyOp = Operation(Instruction.Copy, pArg, argReg);
cctx.Cfg.Entry.Operations.AddFirst(copyOp);
preservedArgs[index] = pArg;
}
}
Operation argCopyOp = Operation(Instruction.Copy, dest, preservedArgs[index]);
Node newNode = nodes.AddBefore(node, argCopyOp);
Delete(nodes, node, operation);
return newNode;
}
else
{
// TODO: Pass on stack.
return node;
}
}
private static void HandleReturnWindowsAbi(
CompilerContext cctx,
IntrusiveList<Node> nodes,
Node node,
Operand[] preservedArgs,
Operation operation)
{
if (operation.SourcesCount == 0)
{
return;
}
Operand source = operation.GetSource(0);
Operand retReg;
if (source.Type.IsInteger())
{
retReg = Gpr(CallingConvention.GetIntReturnRegister(), source.Type);
}
else if (source.Type == OperandType.V128)
{
if (preservedArgs[0] == null)
{
Operand preservedArg = Local(OperandType.I64);
Operand arg0 = Gpr(CallingConvention.GetIntArgumentRegister(0), OperandType.I64);
Operation copyOp = Operation(Instruction.Copy, preservedArg, arg0);
cctx.Cfg.Entry.Operations.AddFirst(copyOp);
preservedArgs[0] = preservedArg;
}
retReg = preservedArgs[0];
}
else
{
retReg = Xmm(CallingConvention.GetVecReturnRegister(), source.Type);
}
if (source.Type == OperandType.V128)
{
Operation retStoreOp = Operation(Instruction.Store, null, retReg, source);
nodes.AddBefore(node, retStoreOp);
}
else
{
Operation retCopyOp = Operation(Instruction.Copy, retReg, source);
nodes.AddBefore(node, retCopyOp);
}
operation.SetSources(Array.Empty<Operand>());
}
private static void HandleReturnSystemVAbi(IntrusiveList<Node> nodes, Node node, Operation operation)
{
if (operation.SourcesCount == 0)
{
return;
}
Operand source = operation.GetSource(0);
if (source.Type == OperandType.V128)
{
Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64);
Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64);
nodes.AddBefore(node, Operation(Instruction.VectorExtract, retLReg, source, Const(0)));
nodes.AddBefore(node, Operation(Instruction.VectorExtract, retHReg, source, Const(1)));
}
else
{
Operand retReg = source.Type.IsInteger()
? Gpr(CallingConvention.GetIntReturnRegister(), source.Type)
: Xmm(CallingConvention.GetVecReturnRegister(), source.Type);
Operation retCopyOp = Operation(Instruction.Copy, retReg, source);
nodes.AddBefore(node, retCopyOp);
}
}
private static Operand AddXmmCopy(IntrusiveList<Node> nodes, Node node, Operand source)
{
Operand temp = Local(source.Type);
Operand intConst = AddCopy(nodes, node, GetIntConst(source));
Operation copyOp = Operation(Instruction.VectorCreateScalar, temp, intConst);
nodes.AddBefore(node, copyOp);
return temp;
}
private static Operand AddCopy(IntrusiveList<Node> nodes, Node node, Operand source)
{
Operand temp = Local(source.Type);
Operation copyOp = Operation(Instruction.Copy, temp, source);
nodes.AddBefore(node, copyOp);
return temp;
}
private static Operand GetIntConst(Operand value)
{
if (value.Type == OperandType.FP32)
{
return Const(value.AsInt32());
}
else if (value.Type == OperandType.FP64)
{
return Const(value.AsInt64());
}
return value;
}
private static void Delete(IntrusiveList<Node> nodes, Node node, Operation operation)
{
operation.Destination = null;
for (int index = 0; index < operation.SourcesCount; index++)
{
operation.SetSource(index, null);
}
nodes.Remove(node);
}
private static Operand Gpr(X86Register register, OperandType type)
{
return Register((int)register, RegisterType.Integer, type);
}
private static Operand Xmm(X86Register register, OperandType type)
{
return Register((int)register, RegisterType.Vector, type);
}
private static bool IsSameOperandDestSrc1(Operation operation)
{
switch (operation.Instruction)
{
case Instruction.Add:
case Instruction.Multiply:
case Instruction.Subtract:
return !HardwareCapabilities.SupportsVexEncoding || operation.Destination.Type.IsInteger();
case Instruction.BitwiseAnd:
case Instruction.BitwiseExclusiveOr:
case Instruction.BitwiseNot:
case Instruction.BitwiseOr:
case Instruction.ByteSwap:
case Instruction.Negate:
case Instruction.RotateRight:
case Instruction.ShiftLeft:
case Instruction.ShiftRightSI:
case Instruction.ShiftRightUI:
return true;
case Instruction.Divide:
return !HardwareCapabilities.SupportsVexEncoding && !operation.Destination.Type.IsInteger();
case Instruction.VectorInsert:
case Instruction.VectorInsert16:
case Instruction.VectorInsert8:
return !HardwareCapabilities.SupportsVexEncoding;
case Instruction.Extended:
return IsIntrinsicSameOperandDestSrc1(operation);
}
return IsVexSameOperandDestSrc1(operation);
}
private static bool IsIntrinsicSameOperandDestSrc1(Operation operation)
{
IntrinsicOperation intrinOp = (IntrinsicOperation)operation;
IntrinsicInfo info = IntrinsicTable.GetInfo(intrinOp.Intrinsic);
return info.Type == IntrinsicType.Crc32 || info.Type == IntrinsicType.Fma || IsVexSameOperandDestSrc1(operation);
}
private static bool IsVexSameOperandDestSrc1(Operation operation)
{
if (IsIntrinsic(operation.Instruction))
{
bool isUnary = operation.SourcesCount < 2;
bool hasVecDest = operation.Destination != null && operation.Destination.Type == OperandType.V128;
return !HardwareCapabilities.SupportsVexEncoding && !isUnary && hasVecDest;
}
return false;
}
private static bool HasConstSrc1(Instruction inst)
{
switch (inst)
{
case Instruction.Copy:
case Instruction.LoadArgument:
case Instruction.Spill:
case Instruction.SpillArg:
return true;
}
return false;
}
private static bool HasConstSrc2(Instruction inst)
{
switch (inst)
{
case Instruction.Add:
case Instruction.BitwiseAnd:
case Instruction.BitwiseExclusiveOr:
case Instruction.BitwiseOr:
case Instruction.BranchIf:
case Instruction.Compare:
case Instruction.Multiply:
case Instruction.RotateRight:
case Instruction.ShiftLeft:
case Instruction.ShiftRightSI:
case Instruction.ShiftRightUI:
case Instruction.Store:
case Instruction.Store16:
case Instruction.Store8:
case Instruction.Subtract:
case Instruction.VectorExtract:
case Instruction.VectorExtract16:
case Instruction.VectorExtract8:
return true;
}
return false;
}
private static bool IsCommutative(Operation operation)
{
switch (operation.Instruction)
{
case Instruction.Add:
case Instruction.BitwiseAnd:
case Instruction.BitwiseExclusiveOr:
case Instruction.BitwiseOr:
case Instruction.Multiply:
return true;
case Instruction.BranchIf:
case Instruction.Compare:
{
Operand comp = operation.GetSource(2);
Debug.Assert(comp.Kind == OperandKind.Constant);
var compType = (Comparison)comp.AsInt32();
return compType == Comparison.Equal || compType == Comparison.NotEqual;
}
}
return false;
}
private static bool IsIntrinsic(Instruction inst)
{
return inst == Instruction.Extended;
}
}
} | 38.467799 | 138 | 0.515537 | [
"MIT"
] | derparb/h | ARMeilleure/CodeGen/X86/PreAllocator.cs | 54,355 | C# |
using System;
using System.ComponentModel;
using System.Configuration.Provider;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
namespace Umbraco.Core.Security
{
/// <summary>
/// Default back office user manager
/// </summary>
public class BackOfficeUserManager : BackOfficeUserManager<BackOfficeIdentityUser>
{
public const string OwinMarkerKey = "Umbraco.Web.Security.Identity.BackOfficeUserManagerMarker";
public BackOfficeUserManager(IUserStore<BackOfficeIdentityUser, int> store)
: base(store)
{
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the constructor specifying all dependencies instead")]
public BackOfficeUserManager(
IUserStore<BackOfficeIdentityUser, int> store,
IdentityFactoryOptions<BackOfficeUserManager> options,
MembershipProviderBase membershipProvider)
: this(store, options, membershipProvider, UmbracoConfig.For.UmbracoSettings().Content)
{
}
public BackOfficeUserManager(
IUserStore<BackOfficeIdentityUser, int> store,
IdentityFactoryOptions<BackOfficeUserManager> options,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig)
: base(store)
{
if (options == null) throw new ArgumentNullException("options");
InitUserManager(this, membershipProvider, contentSectionConfig, options);
}
#region Static Create methods
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the overload specifying all dependencies instead")]
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
IUserService userService,
IExternalLoginService externalLoginService,
MembershipProviderBase membershipProvider)
{
return Create(options, userService,
ApplicationContext.Current.Services.EntityService,
externalLoginService, membershipProvider,
UmbracoConfig.For.UmbracoSettings().Content);
}
/// <summary>
/// Creates a BackOfficeUserManager instance with all default options and the default BackOfficeUserManager
/// </summary>
/// <param name="options"></param>
/// <param name="userService"></param>
/// <param name="entityService"></param>
/// <param name="externalLoginService"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <returns></returns>
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
IUserService userService,
IEntityService entityService,
IExternalLoginService externalLoginService,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig)
{
if (options == null) throw new ArgumentNullException("options");
if (userService == null) throw new ArgumentNullException("userService");
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
var manager = new BackOfficeUserManager(
new BackOfficeUserStore(userService, entityService, externalLoginService, membershipProvider));
manager.InitUserManager(manager, membershipProvider, contentSectionConfig, options);
return manager;
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the overload specifying all dependencies instead")]
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
BackOfficeUserStore customUserStore,
MembershipProviderBase membershipProvider)
{
var manager = new BackOfficeUserManager(customUserStore, options, membershipProvider);
return manager;
}
/// <summary>
/// Creates a BackOfficeUserManager instance with all default options and a custom BackOfficeUserManager instance
/// </summary>
/// <param name="options"></param>
/// <param name="customUserStore"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <returns></returns>
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
BackOfficeUserStore customUserStore,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig)
{
var manager = new BackOfficeUserManager(customUserStore, options, membershipProvider, contentSectionConfig);
return manager;
}
#endregion
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the overload specifying all dependencies instead")]
protected void InitUserManager(
BackOfficeUserManager manager,
MembershipProviderBase membershipProvider,
IdentityFactoryOptions<BackOfficeUserManager> options)
{
InitUserManager(manager, membershipProvider, UmbracoConfig.For.UmbracoSettings().Content, options);
}
/// <summary>
/// Initializes the user manager with the correct options
/// </summary>
/// <param name="manager"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <param name="options"></param>
/// <returns></returns>
protected void InitUserManager(
BackOfficeUserManager manager,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig,
IdentityFactoryOptions<BackOfficeUserManager> options)
{
//NOTE: This method is mostly here for backwards compat
base.InitUserManager(manager, membershipProvider, options.DataProtectionProvider, contentSectionConfig);
}
}
/// <summary>
/// Generic Back office user manager
/// </summary>
public class BackOfficeUserManager<T> : UserManager<T, int>
where T : BackOfficeIdentityUser
{
public BackOfficeUserManager(IUserStore<T, int> store)
: base(store)
{
}
#region What we support do not currently
//TODO: We could support this - but a user claims will mostly just be what is in the auth cookie
public override bool SupportsUserClaim
{
get { return false; }
}
//TODO: Support this
public override bool SupportsQueryableUsers
{
get { return false; }
}
/// <summary>
/// Developers will need to override this to support custom 2 factor auth
/// </summary>
public override bool SupportsUserTwoFactor
{
get { return false; }
}
//TODO: Support this
public override bool SupportsUserPhoneNumber
{
get { return false; }
}
#endregion
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the overload specifying all dependencies instead")]
protected void InitUserManager(
BackOfficeUserManager<T> manager,
MembershipProviderBase membershipProvider,
IDataProtectionProvider dataProtectionProvider)
{
InitUserManager(manager, membershipProvider, dataProtectionProvider, UmbracoConfig.For.UmbracoSettings().Content);
}
/// <summary>
/// Initializes the user manager with the correct options
/// </summary>
/// <param name="manager"></param>
/// <param name="membershipProvider">
/// The <see cref="MembershipProviderBase"/> for the users called UsersMembershipProvider
/// </param>
/// <param name="dataProtectionProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <returns></returns>
protected void InitUserManager(
BackOfficeUserManager<T> manager,
MembershipProviderBase membershipProvider,
IDataProtectionProvider dataProtectionProvider,
IContentSection contentSectionConfig)
{
// Configure validation logic for usernames
manager.UserValidator = new BackOfficeUserValidator<T>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new MembershipProviderPasswordValidator(membershipProvider);
//use a custom hasher based on our membership provider
manager.PasswordHasher = GetDefaultPasswordHasher(membershipProvider);
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<T, int>(dataProtectionProvider.Create("ASP.NET Identity"));
}
manager.UserLockoutEnabledByDefault = true;
manager.MaxFailedAccessAttemptsBeforeLockout = membershipProvider.MaxInvalidPasswordAttempts;
//NOTE: This just needs to be in the future, we currently don't support a lockout timespan, it's either they are locked
// or they are not locked, but this determines what is set on the account lockout date which corresponds to whether they are
// locked out or not.
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(30);
//custom identity factory for creating the identity object for which we auth against in the back office
manager.ClaimsIdentityFactory = new BackOfficeClaimsIdentityFactory<T>();
manager.EmailService = new EmailService(
contentSectionConfig.NotificationEmailAddress,
new EmailSender());
//NOTE: Not implementing these, if people need custom 2 factor auth, they'll need to implement their own UserStore to suport it
//// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
//// You can write your own provider and plug in here.
//manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
//{
// MessageFormat = "Your security code is: {0}"
//});
//manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
//{
// Subject = "Security Code",
// BodyFormat = "Your security code is: {0}"
//});
//manager.SmsService = new SmsService();
}
/// <summary>
/// Used to validate a user's session
/// </summary>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <returns></returns>
public virtual async Task<bool> ValidateSessionIdAsync(int userId, string sessionId)
{
var userSessionStore = Store as IUserSessionStore<BackOfficeIdentityUser, int>;
//if this is not set, for backwards compat (which would be super rare), we'll just approve it
if (userSessionStore == null)
return true;
return await userSessionStore.ValidateSessionIdAsync(userId, sessionId);
}
/// <summary>
/// This will determine which password hasher to use based on what is defined in config
/// </summary>
/// <returns></returns>
protected virtual IPasswordHasher GetDefaultPasswordHasher(MembershipProviderBase provider)
{
//if the current user membership provider is unkown (this would be rare), then return the default password hasher
if (provider.IsUmbracoUsersProvider() == false)
return new PasswordHasher();
//if the configured provider has legacy features enabled, then return the membership provider password hasher
if (provider.AllowManuallyChangingPassword || provider.DefaultUseLegacyEncoding)
return new MembershipProviderPasswordHasher(provider);
//we can use the user aware password hasher (which will be the default and preferred way)
return new UserAwareMembershipProviderPasswordHasher(provider);
}
/// <summary>
/// Gets/sets the default back office user password checker
/// </summary>
public IBackOfficeUserPasswordChecker BackOfficeUserPasswordChecker { get; set; }
/// <summary>
/// Helper method to generate a password for a user based on the current password validator
/// </summary>
/// <returns></returns>
public string GeneratePassword()
{
var passwordValidator = PasswordValidator as PasswordValidator;
if (passwordValidator == null)
{
var membershipPasswordHasher = PasswordHasher as IMembershipProviderPasswordHasher;
//get the real password validator, this should not be null but in some very rare cases it could be, in which case
//we need to create a default password validator to use since we have no idea what it actually is or what it's rules are
//this is an Edge Case!
passwordValidator = PasswordValidator as PasswordValidator
?? (membershipPasswordHasher != null
? new MembershipProviderPasswordValidator(membershipPasswordHasher.MembershipProvider)
: new PasswordValidator());
}
var password = Membership.GeneratePassword(
passwordValidator.RequiredLength,
passwordValidator.RequireNonLetterOrDigit ? 2 : 0);
var random = new Random();
var passwordChars = password.ToCharArray();
if (passwordValidator.RequireDigit && passwordChars.ContainsAny(Enumerable.Range(48, 58).Select(x => (char)x)))
password += Convert.ToChar(random.Next(48, 58)); // 0-9
if (passwordValidator.RequireLowercase && passwordChars.ContainsAny(Enumerable.Range(97, 123).Select(x => (char)x)))
password += Convert.ToChar(random.Next(97, 123)); // a-z
if (passwordValidator.RequireUppercase && passwordChars.ContainsAny(Enumerable.Range(65, 91).Select(x => (char)x)))
password += Convert.ToChar(random.Next(65, 91)); // A-Z
if (passwordValidator.RequireNonLetterOrDigit && passwordChars.ContainsAny(Enumerable.Range(33, 48).Select(x => (char)x)))
password += Convert.ToChar(random.Next(33, 48)); // symbols !"#$%&'()*+,-./
return password;
}
/// <summary>
/// Override to check the user approval value as well as the user lock out date, by default this only checks the user's locked out date
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
/// <remarks>
/// In the ASP.NET Identity world, there is only one value for being locked out, in Umbraco we have 2 so when checking this for Umbraco we need to check both values
/// </remarks>
public override async Task<bool> IsLockedOutAsync(int userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by id " + userId);
if (user.IsApproved == false)
return true;
return await base.IsLockedOutAsync(userId);
}
#region Overrides for password logic
/// <summary>
/// Logic used to validate a username and password
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
/// <remarks>
/// By default this uses the standard ASP.Net Identity approach which is:
/// * Get password store
/// * Call VerifyPasswordAsync with the password store + user + password
/// * Uses the PasswordHasher.VerifyHashedPassword to compare the stored password
///
/// In some cases people want simple custom control over the username/password check, for simplicity
/// sake, developers would like the users to simply validate against an LDAP directory but the user
/// data remains stored inside of Umbraco.
/// See: http://issues.umbraco.org/issue/U4-7032 for the use cases.
///
/// We've allowed this check to be overridden with a simple callback so that developers don't actually
/// have to implement/override this class.
/// </remarks>
public override async Task<bool> CheckPasswordAsync(T user, string password)
{
if (BackOfficeUserPasswordChecker != null)
{
var result = await BackOfficeUserPasswordChecker.CheckPasswordAsync(user, password);
if (user.HasIdentity == false)
{
return false;
}
//if the result indicates to not fallback to the default, then return true if the credentials are valid
if (result != BackOfficeUserPasswordCheckerResult.FallbackToDefaultChecker)
{
return result == BackOfficeUserPasswordCheckerResult.ValidCredentials;
}
}
//we cannot proceed if the user passed in does not have an identity
if (user.HasIdentity == false)
return false;
//use the default behavior
return await base.CheckPasswordAsync(user, password);
}
public override Task<IdentityResult> ChangePasswordAsync(int userId, string currentPassword, string newPassword)
{
var result = base.ChangePasswordAsync(userId, currentPassword, newPassword);
if (result.Result.Succeeded)
RaisePasswordChangedEvent(userId);
return result;
}
/// <summary>
/// Override to determine how to hash the password
/// </summary>
/// <param name="store"></param>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
protected override async Task<bool> VerifyPasswordAsync(IUserPasswordStore<T, int> store, T user, string password)
{
var userAwarePasswordHasher = PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>;
if (userAwarePasswordHasher == null)
return await base.VerifyPasswordAsync(store, user, password);
var hash = await store.GetPasswordHashAsync(user);
return userAwarePasswordHasher.VerifyHashedPassword(user, hash, password) != PasswordVerificationResult.Failed;
}
/// <summary>
/// Override to determine how to hash the password
/// </summary>
/// <param name="passwordStore"></param>
/// <param name="user"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
/// <remarks>
/// This method is called anytime the password needs to be hashed for storage (i.e. including when reset password is used)
/// </remarks>
protected override async Task<IdentityResult> UpdatePassword(IUserPasswordStore<T, int> passwordStore, T user, string newPassword)
{
var userAwarePasswordHasher = PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>;
if (userAwarePasswordHasher == null)
return await base.UpdatePassword(passwordStore, user, newPassword);
var result = await PasswordValidator.ValidateAsync(newPassword);
if (result.Succeeded == false)
return result;
await passwordStore.SetPasswordHashAsync(user, userAwarePasswordHasher.HashPassword(user, newPassword));
await UpdateSecurityStampInternal(user);
return IdentityResult.Success;
}
/// <summary>
/// This is copied from the underlying .NET base class since they decied to not expose it
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private async Task UpdateSecurityStampInternal(BackOfficeIdentityUser user)
{
if (SupportsUserSecurityStamp == false)
return;
await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp());
}
/// <summary>
/// This is copied from the underlying .NET base class since they decied to not expose it
/// </summary>
/// <returns></returns>
private IUserSecurityStampStore<BackOfficeIdentityUser, int> GetSecurityStore()
{
var store = Store as IUserSecurityStampStore<BackOfficeIdentityUser, int>;
if (store == null)
throw new NotSupportedException("The current user store does not implement " + typeof(IUserSecurityStampStore<>));
return store;
}
/// <summary>
/// This is copied from the underlying .NET base class since they decied to not expose it
/// </summary>
/// <returns></returns>
private static string NewSecurityStamp()
{
return Guid.NewGuid().ToString();
}
#endregion
public override Task<IdentityResult> SetLockoutEndDateAsync(int userId, DateTimeOffset lockoutEnd)
{
var result = base.SetLockoutEndDateAsync(userId, lockoutEnd);
// The way we unlock is by setting the lockoutEnd date to the current datetime
if (result.Result.Succeeded && lockoutEnd >= DateTimeOffset.UtcNow)
RaiseAccountLockedEvent(userId);
else
RaiseAccountUnlockedEvent(userId);
return result;
}
public override async Task<IdentityResult> ResetAccessFailedCountAsync(int userId)
{
var lockoutStore = (IUserLockoutStore<BackOfficeIdentityUser, int>)Store;
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by user id " + userId);
var accessFailedCount = await GetAccessFailedCountAsync(user.Id);
if (accessFailedCount == 0)
return IdentityResult.Success;
await lockoutStore.ResetAccessFailedCountAsync(user);
//raise the event now that it's reset
RaiseResetAccessFailedCountEvent(userId);
return await UpdateAsync(user);
}
public override Task<IdentityResult> AccessFailedAsync(int userId)
{
var result = base.AccessFailedAsync(userId);
//Slightly confusing: this will return a Success if we successfully update the AccessFailed count
if (result.Result.Succeeded)
RaiseLoginFailedEvent(userId);
return result;
}
internal void RaiseAccountLockedEvent(int userId)
{
OnAccountLocked(new IdentityAuditEventArgs(AuditEvent.AccountLocked, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseAccountUnlockedEvent(int userId)
{
OnAccountUnlocked(new IdentityAuditEventArgs(AuditEvent.AccountUnlocked, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseForgotPasswordRequestedEvent(int userId)
{
OnForgotPasswordRequested(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordRequested, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseForgotPasswordChangedSuccessEvent(int userId)
{
OnForgotPasswordChangedSuccess(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordChangedSuccess, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLoginFailedEvent(int userId)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseInvalidLoginAttemptEvent(string username)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), username, string.Format("Attempted login for username '{0}' failed", username)));
}
internal void RaiseLoginRequiresVerificationEvent(int userId)
{
OnLoginRequiresVerification(new IdentityAuditEventArgs(AuditEvent.LoginRequiresVerification, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLoginSuccessEvent(int userId)
{
OnLoginSuccess(new IdentityAuditEventArgs(AuditEvent.LoginSucces, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLogoutSuccessEvent(int userId)
{
OnLogoutSuccess(new IdentityAuditEventArgs(AuditEvent.LogoutSuccess, GetCurrentRequestIpAddress(), userId));
}
internal void RaisePasswordChangedEvent(int userId)
{
OnPasswordChanged(new IdentityAuditEventArgs(AuditEvent.PasswordChanged, GetCurrentRequestIpAddress(), userId));
}
internal void RaisePasswordResetEvent(int userId)
{
OnPasswordReset(new IdentityAuditEventArgs(AuditEvent.PasswordReset, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseResetAccessFailedCountEvent(int userId)
{
OnResetAccessFailedCount(new IdentityAuditEventArgs(AuditEvent.ResetAccessFailedCount, GetCurrentRequestIpAddress(), userId));
}
public static event EventHandler AccountLocked;
public static event EventHandler AccountUnlocked;
public static event EventHandler ForgotPasswordRequested;
public static event EventHandler ForgotPasswordChangedSuccess;
public static event EventHandler LoginFailed;
public static event EventHandler LoginRequiresVerification;
public static event EventHandler LoginSuccess;
public static event EventHandler LogoutSuccess;
public static event EventHandler PasswordChanged;
public static event EventHandler PasswordReset;
public static event EventHandler ResetAccessFailedCount;
protected virtual void OnAccountLocked(IdentityAuditEventArgs e)
{
if (AccountLocked != null) AccountLocked(this, e);
}
protected virtual void OnAccountUnlocked(IdentityAuditEventArgs e)
{
if (AccountUnlocked != null) AccountUnlocked(this, e);
}
protected virtual void OnForgotPasswordRequested(IdentityAuditEventArgs e)
{
if (ForgotPasswordRequested != null) ForgotPasswordRequested(this, e);
}
protected virtual void OnForgotPasswordChangedSuccess(IdentityAuditEventArgs e)
{
if (ForgotPasswordChangedSuccess != null) ForgotPasswordChangedSuccess(this, e);
}
protected virtual void OnLoginFailed(IdentityAuditEventArgs e)
{
if (LoginFailed != null) LoginFailed(this, e);
}
protected virtual void OnLoginRequiresVerification(IdentityAuditEventArgs e)
{
if (LoginRequiresVerification != null) LoginRequiresVerification(this, e);
}
protected virtual void OnLoginSuccess(IdentityAuditEventArgs e)
{
if (LoginSuccess != null) LoginSuccess(this, e);
}
protected virtual void OnLogoutSuccess(IdentityAuditEventArgs e)
{
if (LogoutSuccess != null) LogoutSuccess(this, e);
}
protected virtual void OnPasswordChanged(IdentityAuditEventArgs e)
{
if (PasswordChanged != null) PasswordChanged(this, e);
}
protected virtual void OnPasswordReset(IdentityAuditEventArgs e)
{
if (PasswordReset != null) PasswordReset(this, e);
}
protected virtual void OnResetAccessFailedCount(IdentityAuditEventArgs e)
{
if (ResetAccessFailedCount != null) ResetAccessFailedCount(this, e);
}
/// <summary>
/// Returns the current request IP address for logging if there is one
/// </summary>
/// <returns></returns>
protected virtual string GetCurrentRequestIpAddress()
{
//TODO: inject a service to get this value, we should not be relying on the old HttpContext.Current especially in the ASP.NET Identity world.
var httpContext = HttpContext.Current == null ? (HttpContextBase)null : new HttpContextWrapper(HttpContext.Current);
return httpContext.GetCurrentRequestIpAddress();
}
}
}
| 43.106628 | 188 | 0.641864 | [
"MIT"
] | WarwickBuz/Umbraco-CMS | src/Umbraco.Core/Security/BackOfficeUserManager.cs | 29,918 | C# |
using System.Collections.Generic;
namespace Menu.Domain.Entities
{
public class Price : EntityBase
{
public decimal PriceValue { get; set; }
public decimal PricePerGramsOrMilliliters { get; set; }
public decimal PricePerkilogramOrLiter { get; set; }
public virtual Ingredient Ingredient { get; set; }
public virtual Recipe Recipe { get; set; }
public override bool Validate(IEnumerable<string> errors)
{
throw new System.NotImplementedException();
}
}
}
| 27.3 | 65 | 0.648352 | [
"Apache-2.0"
] | GabrielColetta/MenuExpense | Menu.Domain/Entities/Price.cs | 548 | C# |
// Decompiled with JetBrains decompiler
// Type: CompanionRespec.RespecFunctions
// Assembly: CompanionRespec, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 94BDDB6C-D57A-434E-9C4A-3FE10DCDEE7A
// Assembly location: C:\Program Files (x86)\Steam\steamapps\common\Mount & Blade II Bannerlord\Modules\CompanionRespec\bin\Win64_Shipping_Client\CompanionRespec.dll
using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaleWorlds.CampaignSystem;
using TaleWorlds.Core;
using TaleWorlds.Library;
namespace CompanionRespec
{
internal static partial class Utils
{
public static void DisplayMessage(string message)
{
if (string.IsNullOrWhiteSpace(message)) return;
InformationManager.DisplayMessage(new InformationMessage(message));
}
public static void RespecHero(Hero hero)
{
if (hero == default) return;
int num1 = 0;
int num2 = 0;
DisplayMessage(string.Format("{0}", hero));
RespecPerks(hero);
DisplayMessage("Clearing focus...");
using (IEnumerator<SkillObject> enumerator = DefaultSkills.GetAllSkills().GetEnumerator())
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
int focus = hero.HeroDeveloper.GetFocus(current);
if (focus > 0)
num1 += focus;
}
}
hero.HeroDeveloper.UnspentFocusPoints += MBMath.ClampInt(num1, 0, 999);
hero.HeroDeveloper.ClearFocuses();
DisplayMessage("Clearing stats...");
for (CharacterAttributesEnum characterAttributesEnum = 0; characterAttributesEnum < CharacterAttributesEnum.End; characterAttributesEnum += 1)
{
int attributeValue = hero.GetAttributeValue(characterAttributesEnum);
if (hero == Hero.MainHero)
{
num2 += attributeValue - 2;
hero.SetAttributeValue(characterAttributesEnum, 2);
}
else
{
num2 += attributeValue - 1;
hero.SetAttributeValue(characterAttributesEnum, 1);
}
}
hero.HeroDeveloper.UnspentAttributePoints += MBMath.ClampInt(num2, 0, 999);
DisplayMessage(string.Format("Unspent: {0} stat | {1} focus", hero.HeroDeveloper.UnspentAttributePoints, hero.HeroDeveloper.UnspentFocusPoints));
}
public static void ResetPerksCheckSmithPerk(Hero hero)
{
if (hero.HeroDeveloper.GetPerkValue(DefaultPerks.Crafting.VigorousSmith))
{
// 第一排第六个
// 有力的铁匠,立刻提升一点活力
int value = hero.GetAttributeValue(CharacterAttributesEnum.Vigor) - 1;
DisplayMessage($"VigorousSmith Vigor: {value}");
if (value > 0) hero.SetAttributeValue(CharacterAttributesEnum.Vigor, value);
}
if (hero.HeroDeveloper.GetPerkValue(DefaultPerks.Crafting.StrongSmith))
{
// 第二排第六个
// 精密锻造,立刻增加一点控制
int value = hero.GetAttributeValue(CharacterAttributesEnum.Control) - 1;
DisplayMessage($"StrongSmith Control: {value}");
if (value > 0) hero.SetAttributeValue(CharacterAttributesEnum.Control, value);
}
if (hero.HeroDeveloper.GetPerkValue(DefaultPerks.Crafting.EnduringSmith))
{
// 第一排倒数第二个
// 正规铁匠,立刻提高忍耐1级
int value = hero.GetAttributeValue(CharacterAttributesEnum.Endurance) - 1;
DisplayMessage($"EnduringSmith Endurance: {value}");
if (value > 0) hero.SetAttributeValue(CharacterAttributesEnum.Endurance, value);
}
if (hero.HeroDeveloper.GetPerkValue(DefaultPerks.Crafting.WeaponMasterSmith))
{
// 第二排倒数第二个
// 击剑铁匠,单手系和双手系技能各获得1点专精点
hero.HeroDeveloper.AddFocus(DefaultSkills.OneHanded, -1, false);
hero.HeroDeveloper.AddFocus(DefaultSkills.TwoHanded, -1, false);
DisplayMessage($"WeaponMasterSmith");
}
hero.ClearPerks();
// ??? why setInitialSkillLevel
foreach (var item in DefaultSkills.GetAllSkills())
{
int skillValue = hero.GetSkillValue(item);
hero.HeroDeveloper.SetInitialSkillLevel(item, skillValue);
}
}
public static void RespecPerks(Hero hero)
{
if (hero == default) return;
DisplayMessage("Clearing perks...");
ResetPerksCheckSmithPerk(hero);
}
public static void FillUp(Hero hero) => FillUp(hero,/*DefaultSkills.MaxAssumedValue*/ 330);
public static void FillUp(Hero hero, int skillValue, bool ignorePerks = true)
{
if (hero == default) return;
try
{
DisplayMessage(string.Format("FillUp {0}", hero));
hero.HeroDeveloper.ClearFocuses();
hero.ClearAttributes();
//hero.ClearPerks();
foreach (var skill in DefaultSkills.GetAllSkills())
{
hero.SetSkillValue(skill, skillValue);
var xpValue = Campaign.Current.Models.CharacterDevelopmentModel.GetXpRequiredForSkillLevel(skillValue);
hero.HeroDeveloper.SetPropertyValue(skill, xpValue);
//var focus = hero.HeroDeveloper.GetFocus(skill);
//var changeAmount = HeroDeveloper.MaxFocusPerSkill - focus;
//hero.HeroDeveloper.AddFocus(skill, changeAmount, false);
// 因为上面调用了 ClearFocuses 这里直接给max
hero.HeroDeveloper.AddFocus(skill, HeroDeveloper.MaxFocusPerSkill, false);
}
for (var i = CharacterAttributesEnum.First; i < CharacterAttributesEnum.End; i++)
{
try
{
//hero.HeroDeveloper.AddAttribute((CharacterAttributesEnum)item, HeroDeveloper.MaxAttribute, false);
hero.SetAttributeValue(i, HeroDeveloper.MaxAttribute);
}
catch (Exception e)
{
DisplayMessage($"Attr(catch) item: {i}" + e.ToString());
}
}
if (!ignorePerks)
{
#region Perks
foreach (var item in AllPerks)
{
try
{
hero.HeroDeveloper.AddPerk(item);
}
catch (Exception e)
{
DisplayMessage($"Perk(catch) item: {item}" + e.ToString());
}
}
#endregion
}
hero.Level = 1;
hero.HeroDeveloper.UnspentAttributePoints = 0;
hero.HeroDeveloper.UnspentFocusPoints = 0;
}
catch (Exception ex)
{
DisplayMessage(ex.ToString());
}
}
public static bool CheckLegendarySmith(Hero hero)
{
return hero.HeroDeveloper.GetPerkValue(DefaultPerks.Crafting.LegendarySmith);
}
public static string CheckLegendarySmith(IEnumerable<Hero> findHeros)
=> Handle2(findHeros, nameof(DefaultPerks.Crafting.LegendarySmith), CheckLegendarySmith);
public static bool AddLegendarySmith(Hero hero)
{
if (!CheckLegendarySmith(hero))
{
hero.HeroDeveloper.AddPerk(DefaultPerks.Crafting.LegendarySmith);
return CheckLegendarySmith(hero);
}
else
{
return true;
}
}
public static string AddLegendarySmith(IEnumerable<Hero> findHeros)
=> Handle2(findHeros, nameof(DefaultPerks.Crafting.LegendarySmith), AddLegendarySmith);
public static void RespecReset(Hero hero)
{
if (hero == default) return;
DisplayMessage(string.Format("Reset {0}", hero));
hero.HeroDeveloper.ClearFocuses();
hero.ClearAttributes();
using (IEnumerator<SkillObject> enumerator = DefaultSkills.GetAllSkills().GetEnumerator())
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
hero.HeroDeveloper.SetInitialSkillLevel(current, 5);
}
}
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.OneHanded, 10);
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.TwoHanded, 10);
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.Polearm, 10);
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.Bow, 10);
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.Crossbow, 10);
hero.HeroDeveloper.SetInitialSkillLevel(DefaultSkills.Throwing, 10);
hero.ClearPerks();
HeroHelper.DetermineInitialLevel(hero);
if (hero == Hero.MainHero)
{
for (CharacterAttributesEnum characterAttributesEnum = 0; characterAttributesEnum < CharacterAttributesEnum.End; characterAttributesEnum += 1)
hero.SetAttributeValue(characterAttributesEnum, 2);
hero.HeroDeveloper.UnspentAttributePoints = 6;
hero.HeroDeveloper.UnspentFocusPoints = 13;
}
else
{
hero.HeroDeveloper.UnspentAttributePoints = 9;
hero.HeroDeveloper.UnspentFocusPoints = 5;
}
}
public static (string name, int index)[] GetNames(IEnumerable<string> names)
=> names.Select(name => NameIndexAnalysis(name.Replace('_', ' ').Trim(new char[] { '"', '“', '”' }))).ToArray();
public static Hero[] NpcHeros
{
get
{
var npcHeros = new[] {
new[] { Hero.MainHero }, // Me
Hero.MainHero.Clan.Companions.Where(x => Hero.MainHero.CompanionsInParty.Contains(x)).ToArray(), // CompanionsInParty
Hero.MainHero.Clan.Heroes.Where(x => x.PartyBelongedTo != null && x.PartyBelongedTo.IsMainParty).ToArray() // Heroes PartyBelongedTo IsMainParty
}.SelectMany(x => x).Distinct().ToArray();
return npcHeros;
}
}
public static Hero[] Search(IEnumerable<string> inputNames)
{
(string name, int index)[] names = GetNames(inputNames);
var findHeros = new Hero[names.Length];
for (int i = 0; i < names.Length; i++)
{
var name = names[i];
int currentIndex = 0;
Hero currentHero = null;
var npcHeros = NpcHeros;
foreach (var npcHero in npcHeros)
{
if (string.Equals(name.name, npcHero.Name.ToString(), StringComparison.OrdinalIgnoreCase))
{
if (currentIndex == name.index)
{
currentHero = npcHero;
break;
}
currentIndex++;
}
}
findHeros[i] = currentHero;
}
return findHeros;
}
public static string Handle(IEnumerable<Hero> findHeros, Action<Hero> action)
{
var stringBuilder = new StringBuilder();
foreach (var npcHero in findHeros)
{
if (npcHero != null)
{
action?.Invoke(npcHero);
stringBuilder.Append($"{npcHero.Name} ");
}
}
DisplayMessage(stringBuilder.ToString());
return stringBuilder.Length > 0 ? "Done" : "Not Found";
}
public static string Handle(IEnumerable<string> inputNames, Action<Hero> action)
{
var findHeros = Search(inputNames);
return Handle(findHeros, action);
}
public static string Handle2(IEnumerable<Hero> findHeros, string tag, Func<Hero, bool> func)
{
var stringBuilder_has = new StringBuilder();
var stringBuilder_not_has = new StringBuilder();
foreach (var npcHero in findHeros)
{
if (npcHero != null)
{
var has = func(npcHero);
(has ? stringBuilder_has : stringBuilder_not_has).Append($"{npcHero.Name} ");
}
}
var isDone = false;
if (stringBuilder_has.Length > 0)
{
DisplayMessage($"({bool.TrueString}){tag}");
DisplayMessage(stringBuilder_has.ToString());
isDone = true;
}
if (stringBuilder_not_has.Length > 0)
{
DisplayMessage($"({bool.FalseString}){tag}");
DisplayMessage(stringBuilder_not_has.ToString());
isDone = true;
}
return isDone ? "Done" : "Not Found";
}
}
}
| 41.978659 | 165 | 0.540707 | [
"MIT"
] | AigioL/M-B2Mod.CompanionRespec | CompanionRespec/Utils.cs | 13,975 | C# |
using Microsoft.VisualStudio.Shell;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace LigaturesLimited
{
// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(LigaturesLimitedPackage.PackageGuidString)]
public sealed class LigaturesLimitedPackage : AsyncPackage
{
public const string PackageGuidString = "20319ebb-c940-4302-82e5-e02433def57d";
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
}
}
}
| 38 | 134 | 0.797847 | [
"MIT"
] | kshetline/ligatures-limited-vs | LigaturesLimited/LigaturesLimitedPackage.cs | 836 | C# |
namespace ABC065
{
public class Program
{
static void Main(string[] args)
{
while (true)
{
QuestionB.Main(args);
}
}
}
}
| 14.928571 | 39 | 0.397129 | [
"MIT"
] | KoyashiroKohaku/AtCoder | csharp/abc/ABC065/Program.cs | 209 | C# |
//------------------------------------------------------------------------------
// <copyright file="METAHEADER.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing.Imaging {
using System.Diagnostics;
using System.Drawing;
using System;
using System.Runtime.InteropServices;
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential, Pack=2)]
public sealed class MetaHeader {
/// SECREVIEW : The ENHMETAHEADER structure is defined natively as a union with WmfHeader.
/// Extreme care should be taken if changing the layout of the corresponding managaed
/// structures to minimize the risk of buffer overruns. The affected managed classes
/// are the following: ENHMETAHEADER, MetaHeader, MetafileHeaderWmf, MetafileHeaderEmf.
/// See ASURT#82822 or changes in Metafile.cs@115636 for more information.
///
short type;
short headerSize;
short version;
int size;
short noObjects;
int maxRecord;
short noParameters;
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.Type"]/*' />
/// <devdoc>
/// Represents the type of the associated
/// <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public short Type {
get { return type; }
set { type = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.HeaderSize"]/*' />
/// <devdoc>
/// Represents the sizi, in bytes, of the
/// header file.
/// </devdoc>
public short HeaderSize {
get { return headerSize; }
set { headerSize = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.Version"]/*' />
/// <devdoc>
/// Represents the version number of the header
/// format.
/// </devdoc>
public short Version {
get { return version; }
set { version = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.Size"]/*' />
/// <devdoc>
/// Represents the sizi, in bytes, of the
/// associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public int Size {
get { return size; }
set { size = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.NoObjects"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public short NoObjects {
get { return noObjects; }
set { noObjects = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.MaxRecord"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int MaxRecord {
get { return maxRecord; }
set { maxRecord = value; }
}
/// <include file='doc\METAHEADER.uex' path='docs/doc[@for="MetaHeader.NoParameters"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public short NoParameters {
get { return noParameters; }
set { noParameters = value; }
}
}
}
| 39.175258 | 108 | 0.504737 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/commonui/System/Drawing/Advanced/METAHEADER.cs | 3,800 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using FluentBuild.Utilities;
namespace FluentBuild.AssemblyInfoBuilding
{
public class AssemblyInfoItem
{
public AssemblyInfoItem(string name, bool isQuotedValue, string value)
{
Name = name;
IsQuotedValue = isQuotedValue;
Value = value;
}
public string Name { get; set; }
public bool IsQuotedValue { get; set; }
public string Value { get; set; }
}
public interface IAssemblyInfoDetails
{
/// <summary>
/// Import a namespace. Will generate a using namespace; in C# and imports namespace in VB
/// </summary>
/// <param name="namespaces">The namespaces to import</param>
/// <remarks>Duplicate namespace imports will be automatically ignored</remarks>
/// <returns></returns>
IAssemblyInfoDetails Import(params string[] namespaces);
/// <summary>
/// Explicitly states if this assembly is visible to COM clients.
/// If the attribute is missing then the assembly is COM visible.
/// </summary>
/// <param name="visible">sets com visibility</param>
/// <returns></returns>
IAssemblyInfoDetails ComVisible(bool visible);
///<summary>
/// Sets the culture
///</summary>
///<param name="culture">The culture of the assembly</param>
///<returns></returns>
IAssemblyInfoDetails Culture(string culture);
///<summary>
/// Sets if to delay sign the assembly
///</summary>
///<param name="delaySign">Wether to delay sign the assembly</param>
///<returns></returns>
IAssemblyInfoDetails DelaySign(bool delaySign);
///<summary>
/// Sets the file version
///</summary>
///<param name="version"></param>
///<returns></returns>
IAssemblyInfoDetails FileVersion(string version);
///<summary>
/// Sets the informational version
///</summary>
///<param name="version"></param>
///<returns></returns>
IAssemblyInfoDetails InformationalVersion(string version);
///<summary>
/// Sets teh path to the Strong Named Key for an assembly
///</summary>
///<param name="path">The path to the snk file</param>
///<returns></returns>
IAssemblyInfoDetails KeyFile(string path);
///<summary>
/// Sets the KeyName
///</summary>
///<param name="name">The name of the key</param>
///<returns></returns>
IAssemblyInfoDetails KeyName(string name);
///<summary>
/// Sets the trademark attribute
///</summary>
///<param name="trademark">The value representing the trademark</param>
///<returns></returns>
IAssemblyInfoDetails Trademark(string trademark);
/// <summary>
/// States if the assembly is CLS Compliant. CLS compliant means that all classes only
/// expose features that are common accross all .NET languages.
/// </summary>
/// <remarks>
/// Things that make an assembly non-cls compliant:
/// Exposing unsigned types.
/// Unsafe types (e.g. pointers) should not be exposed.
/// Operators should not be overloaded
/// Two types or methods should not be included that differ only by case. e.g. doWork and DOWORK.
/// </remarks>
/// <param name="compliant">sets cls compliant</param>
/// <returns></returns>
IAssemblyInfoDetails ClsCompliant(bool compliant);
/// <summary>
/// Sets the assembly version.
/// </summary>
/// <param name="value">a version in the format of Major.Minor.[Build].[Revision]</param>
/// <returns></returns>
IAssemblyInfoDetails Version(string value);
/// <summary>
/// Sets the assembly version.
/// </summary>
/// <param name="value">a version object</param>
/// <returns></returns>
IAssemblyInfoDetails Version(Version value);
/// <summary>
/// Sets the title attribute of the assembly
/// </summary>
/// <param name="value">The title to use</param>
/// <returns></returns>
IAssemblyInfoDetails Title(string value);
/// <summary>
/// Sets the description attribute of the assembly
/// </summary>
/// <param name="value">The description to set</param>
/// <returns></returns>
IAssemblyInfoDetails Description(string value);
/// <summary>
/// Sets the copyright attribute of the assembly
/// </summary>
/// <param name="value">The copyright to set</param>
/// <returns></returns>
IAssemblyInfoDetails Copyright(string value);
/// <summary>
/// Sets the company attribute of the assembly
/// </summary>
/// <param name="value">The company to set</param>
/// <returns></returns>
IAssemblyInfoDetails Company(string value);
/// <summary>
/// Sets the product attribute of the assembly
/// </summary>
/// <param name="value">The product to set</param>
/// <returns></returns>
IAssemblyInfoDetails Product(string value);
///<summary>
/// Adds a custom attribute to the assemblyInfo file
///</summary>
///<param name="attributeNamespace">The namespace that the attribute exists in</param>
///<param name="name">The name of the attribute</param>
///<param name="isQuoted">Wether or not to quote the value when the file is generated</param>
///<param name="value">The value of the attribute</param>
IAssemblyInfoDetails AddCustomAttribute(string attributeNamespace, string name, bool isQuoted, string value);
/// <summary>
/// Execute the generation of the assembly info file and output it.
/// </summary>
/// <param name="artifactLocation">The destination artifact location</param>
[Obsolete("Replaced to be used with Task.CreateAssemblyInfo(). OutputTo is set with OutputPath", true)]
void OutputTo(FluentFs.Core.File artifactLocation);
/// <summary>
/// Execute the generation of the assembly info file and output it.
/// </summary>
/// <param name="filePath">The destination file path location</param>
[Obsolete("Replaced to be used with Task.CreateAssemblyInfo(). OutputTo is set with OutputPath", true)]
void OutputTo(string filePath);
IAssemblyInfoDetails OutputPath(string path);
IAssemblyInfoDetails OutputPath(FluentFs.Core.File path);
List<String> Imports { get; }
IList<AssemblyInfoItem> LineItems { get; }
}
/// <summary>
/// Sets the lines for an assembly info file
/// </summary>
internal class AssemblyInfoDetails : InternalExecutable, IAssemblyInfoDetails
{
internal readonly IAssemblyInfoBuilder AssemblyInfoBuilder;
private readonly IFileSystemHelper _fileSystemHelper;
private readonly List<String> _imports = new List<string>();
private IList<AssemblyInfoItem> _lineItems = new List<AssemblyInfoItem>();
internal string _outputPath;
public IList<AssemblyInfoItem> LineItems { get { return _lineItems; } }
public List<String> Imports { get
{
return _imports;
}}
// internal string AssemblyCopyright;
// internal string AssemblyDescription;
// internal string AssemblyTitle;
// internal Version AssemblyVersion;
// internal bool AssemblyClsCompliant;
// internal bool ClsCompliantSet;
// internal bool AssemblyComVisible;
// internal bool ComVisibleSet;
// internal string AssemblyCompany;
// internal string AssemblyProduct;
// private bool CultureSet;
// private string AssemblyCulture;
// private bool DelaySignSet;
// private bool AssemblyDelaySign;
// private bool AssemblyFileVersionSet;
// private string AssemblyFileVersion;
// private bool AssemblyInformationalVersionSet;
// private string AssemblyInformationalVersion;
// private bool AssemblyKeyFileSet;
// private string AssemblyKeyFile;
// private bool AssemblyKeyNameSet;
// private string AssemblyKeyName;
// private bool AssemblyTrademarkSet;
// private string AssemblyTrademark;
internal AssemblyInfoDetails(IAssemblyInfoBuilder assemblyInfoBuilder, IFileSystemHelper fileSystemHelper)
{
AssemblyInfoBuilder = assemblyInfoBuilder;
_fileSystemHelper = fileSystemHelper;
}
internal AssemblyInfoDetails(IAssemblyInfoBuilder assemblyInfoBuilder) : this(assemblyInfoBuilder, new FileSystemHelper())
{
}
/// <summary>
/// Import a namespace. Will generate a using namespace; in C# and imports namespace in VB
/// </summary>
/// <param name="namespaces">The namespaces to import</param>
/// <remarks>Duplicate namespace imports will be automatically ignored</remarks>
/// <returns></returns>
public IAssemblyInfoDetails Import(params string[] namespaces)
{
foreach (string import in namespaces)
ImportDropIfDuplicate(import);
return this;
}
private void ImportDropIfDuplicate(string @namespace)
{
if (!_imports.Contains(@namespace.Trim()))
_imports.Add(@namespace.Trim());
}
/// <summary>
/// Explicitly states if this assembly is visible to COM clients.
/// If the attribute is missing then the assembly is COM visible.
/// </summary>
/// <param name="visible">sets com visibility</param>
/// <returns></returns>
public IAssemblyInfoDetails ComVisible(bool visible)
{
ImportDropIfDuplicate("System.Runtime.InteropServices");
_lineItems.Add(new AssemblyInfoItem("ComVisible", false, visible.ToString().ToLower()));
return this;
}
///<summary>
/// Sets the culture
///</summary>
///<param name="culture">The culture of the assembly</param>
///<returns></returns>
public IAssemblyInfoDetails Culture(string culture)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyCulture", true, culture));
return this;
}
///<summary>
/// Sets if to delay sign the assembly
///</summary>
///<param name="delaySign">Wether to delay sign the assembly</param>
///<returns></returns>
public IAssemblyInfoDetails DelaySign(bool delaySign)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyDelaySign", false, delaySign.ToString().ToLower()));
return this;
}
///<summary>
/// Sets the file version
///</summary>
///<param name="version"></param>
///<returns></returns>
public IAssemblyInfoDetails FileVersion(string version)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyFileVersion", true, version));
return this;
}
///<summary>
/// Sets the informational version
///</summary>
///<param name="version"></param>
///<returns></returns>
public IAssemblyInfoDetails InformationalVersion(string version)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyInformationalVersion", true, version));
return this;
}
///<summary>
/// Sets teh path to the Strong Named Key for an assembly
///</summary>
///<param name="path">The path to the snk file</param>
///<returns></returns>
public IAssemblyInfoDetails KeyFile(string path)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyKeyFile", true, path));
return this;
}
///<summary>
/// Sets the KeyName
///</summary>
///<param name="name">The name of the key</param>
///<returns></returns>
public IAssemblyInfoDetails KeyName(string name)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyKeyName", true, name));
return this;
}
///<summary>
/// Sets the trademark attribute
///</summary>
///<param name="trademark">The value representing the trademark</param>
///<returns></returns>
public IAssemblyInfoDetails Trademark(string trademark)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyTrademark", true, trademark));
return this;
}
/// <summary>
/// States if the assembly is CLS Compliant. CLS compliant means that all classes only
/// expose features that are common accross all .NET languages.
/// </summary>
/// <remarks>
/// Things that make an assembly non-cls compliant:
/// Exposing unsigned types.
/// Unsafe types (e.g. pointers) should not be exposed.
/// Operators should not be overloaded
/// Two types or methods should not be included that differ only by case. e.g. doWork and DOWORK.
/// </remarks>
/// <param name="compliant">sets cls compliant</param>
/// <returns></returns>
public IAssemblyInfoDetails ClsCompliant(bool compliant)
{
ImportDropIfDuplicate("System");
_lineItems.Add(new AssemblyInfoItem("CLSCompliant", false, compliant.ToString().ToLower()));
return this;
}
/// <summary>
/// Sets the assembly version.
/// </summary>
/// <param name="value">a version in the format of Major.Minor.[Build].[Revision]</param>
/// <returns></returns>
public IAssemblyInfoDetails Version(string value)
{
return Version(new Version(value));
}
/// <summary>
/// Sets the assembly version.
/// </summary>
/// <param name="value">a version object</param>
/// <returns></returns>
public IAssemblyInfoDetails Version(Version value)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyVersionAttribute", true, value.ToString()));
return this;
}
/// <summary>
/// Sets the title attribute of the assembly
/// </summary>
/// <param name="value">The title to use</param>
/// <returns></returns>
public IAssemblyInfoDetails Title(string value)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyTitleAttribute", true, value));
return this;
}
/// <summary>
/// Sets the description attribute of the assembly
/// </summary>
/// <param name="value">The description to set</param>
/// <returns></returns>
public IAssemblyInfoDetails Description(string value)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyDescriptionAttribute", true, value));
return this;
}
/// <summary>
/// Sets the copyright attribute of the assembly
/// </summary>
/// <param name="value">The copyright to set</param>
/// <returns></returns>
public IAssemblyInfoDetails Copyright(string value)
{
ImportDropIfDuplicate("System.Reflection");
_lineItems.Add(new AssemblyInfoItem("AssemblyCopyrightAttribute", true, value));
return this;
}
/// <summary>
/// Sets the company attribute of the assembly
/// </summary>
/// <param name="value">The company to set</param>
/// <returns></returns>
public IAssemblyInfoDetails Company(string value)
{
_lineItems.Add(new AssemblyInfoItem("AssemblyCompanyAttribute", true, value));
return this;
}
/// <summary>
/// Sets the product attribute of the assembly
/// </summary>
/// <param name="value">The product to set</param>
/// <returns></returns>
public IAssemblyInfoDetails Product(string value)
{
_lineItems.Add(new AssemblyInfoItem("AssemblyProductAttribute", true, value));
return this;
}
///<summary>
/// Adds a custom attribute to the assemblyInfo file
///</summary>
///<param name="attributeNamespace">The namespace that the attribute exists in</param>
///<param name="name">The name of the attribute</param>
///<param name="isQuoted">Wether or not to quote the value when the file is generated</param>
///<param name="value">The value of the attribute</param>
public IAssemblyInfoDetails AddCustomAttribute(string attributeNamespace, string name, bool isQuoted, string value)
{
ImportDropIfDuplicate(attributeNamespace);
_lineItems.Add(new AssemblyInfoItem(name, isQuoted, value));
return this;
}
/// <summary>
/// Execute the generation of the assembly info file and output it.
/// </summary>
/// <param name="artifactLocation">The destination artifact location</param>
[Obsolete("Replaced to be used with Task.CreateAssemblyInfo(). OutputTo is set with OutputPath", true)]
public void OutputTo(FluentFs.Core.File artifactLocation)
{
OutputTo(artifactLocation.ToString());
}
/// <summary>
/// Execute the generation of the assembly info file and output it.
/// </summary>
/// <param name="filePath">The destination file path location</param>
[Obsolete("Replaced to be used with Task.CreateAssemblyInfo(). OutputTo is set with OutputPath", true)]
public void OutputTo(string filePath)
{
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
using (var sw = new StreamWriter(fs))
{
sw.Write(AssemblyInfoBuilder.Build(this));
}
}
public IAssemblyInfoDetails OutputPath(string path)
{
this._outputPath = path;
return this;
}
public IAssemblyInfoDetails OutputPath(FluentFs.Core.File path)
{
return OutputPath(path.ToString());
}
internal override void InternalExecute()
{
using (var fs = _fileSystemHelper.CreateFile(_outputPath))
using (var sw = new StreamWriter(fs))
{
sw.Write(AssemblyInfoBuilder.Build(this));
}
}
}
} | 37.837524 | 130 | 0.598967 | [
"Apache-2.0"
] | GotWoods/Fluent-Build | src/FluentBuild/AssemblyInfoBuilding/AssemblyInfoDetails.cs | 19,562 | C# |
namespace Snippet.Models.Folder
{
public record DeleteFolderInputModel(int spaceId, int folderId);
} | 26.25 | 68 | 0.790476 | [
"MIT"
] | aishang2015/SnippetDoc | api/Snippet/Models/Folder/DeleteFolderInputModel.cs | 107 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.TemplateFiltering;
using Microsoft.TemplateEngine.Cli.HelpAndUsage;
namespace Microsoft.TemplateEngine.Cli.TemplateResolution
{
/// <summary>
/// The class represents template group. Templates in single group:<br/>
/// - should same group identity
/// - should have different template identity <br/>
/// - same short name (however different short names are also supported) <br/>
/// - the templates may have different languages and types <br/>
/// - the templates should have different precedence value in case same language is used <br/>
/// - the templates in the group may have different parameters and different choices for parameter symbols defined<br/>
/// In case the template does not have group identity defined it represents separate template group with single template.
/// </summary>
internal sealed class TemplateGroup
{
/// <param name="templates">the templates of the template group.</param>
/// <exception cref="ArgumentNullException">when <paramref name="templates"/> is <see cref="null"/>.</exception>
/// <exception cref="ArgumentException">when <paramref name="templates"/> is empty or don't have same <see cref="ITemplateInfo.GroupIdentity"/> defined.</exception>
internal TemplateGroup(IEnumerable<ITemplateMatchInfo> templates)
{
_ = templates ?? throw new ArgumentNullException(paramName: nameof(templates));
if (!templates.Any())
{
throw new ArgumentException(paramName: nameof(templates), message: "The templates collection cannot be empty");
}
try
{
//all templates in the group should have same group identity
GroupIdentity = templates.Select(t => string.IsNullOrWhiteSpace(t.Info.GroupIdentity) ? null : t.Info.GroupIdentity)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Single();
}
catch (InvalidOperationException)
{
throw new ArgumentException(paramName: nameof(templates), message: "The templates should have same group identity");
}
Templates = templates.ToList();
}
/// <summary>
/// Group identity of template group. The value can be null if the template does not have group identity set.
/// </summary>
internal string? GroupIdentity { get; private set; }
/// <summary>
/// Returns the list of short names defined for templates in the group.
/// In theory, template group templates can have different short names but they are treated equally.
/// </summary>
internal IReadOnlyList<string> ShortNames
{
get
{
if (HasSingleTemplate)
{
return Templates.First().Info.ShortNameList;
}
HashSet<string> shortNames = new HashSet<string>();
foreach (ITemplateMatchInfo template in Templates)
{
shortNames.UnionWith(template.Info.ShortNameList);
}
return shortNames.ToList();
}
}
/// <summary>
/// Returns true when <see cref="GroupIdentity"/> is not <see cref="null"/> or empty.
/// </summary>
internal bool HasGroupIdentity => !string.IsNullOrWhiteSpace(GroupIdentity);
/// <summary>
/// Returns true when the template group has single template.
/// </summary>
internal bool HasSingleTemplate => Templates.Count == 1;
/// <summary>
/// Returns the enumerator to invokable templates in the group.
/// </summary>
internal IEnumerable<ITemplateMatchInfo> InvokableTemplates => Templates.Where(templates => templates.IsInvokableMatch());
/// <summary>
/// Returns the collection of templates in the group.
/// </summary>
internal IReadOnlyCollection<ITemplateMatchInfo> Templates { get; private set; }
/// <summary>
/// Returns the ambiguous <see cref="MatchKind.SingleStartsWith"/> parameters in invokable templates in the template group.
/// </summary>
/// <returns>the enumerator for ambiguous <see cref="MatchKind.SingleStartsWith"/> parameters in invokable templates in the template group.</returns>
/// <remarks>The template group is not valid when there are at least one ambiguous <see cref="MatchKind.SingleStartsWith"/> parameters in invokable templates.</remarks>
internal IEnumerable<InvalidParameterInfo> GetAmbiguousSingleStartsWithParameters()
{
var invalidParameterList = new List<InvalidParameterInfo>();
HashSet<string> singleStartsWithParamNames = new HashSet<string>();
foreach (ITemplateMatchInfo checkTemplate in InvokableTemplates)
{
//https://github.com/dotnet/templating/issues/2494
//after tab completion is implemented we no longer will be using this match kind - only exact matches will be allowed
IEnumerable<ParameterMatchInfo> singleStartParams = checkTemplate.MatchDisposition
.OfType<ParameterMatchInfo>()
#pragma warning disable CS0618 // Type or member is obsolete
.Where(x => x.Kind == MatchKind.SingleStartsWith);
#pragma warning restore CS0618 // Type or member is obsolete
foreach (var singleStartParam in singleStartParams)
{
if (!singleStartsWithParamNames.Add(singleStartParam.Name))
{
invalidParameterList.Add(new InvalidParameterInfo(
InvalidParameterInfo.Kind.AmbiguousParameterValue,
singleStartParam.InputFormat,
singleStartParam.Value,
singleStartParam.Name));
}
}
}
return invalidParameterList.Distinct();
}
/// <summary>
/// Returns the invalid template specific parameters for the template group.
/// Invalid parameters can have: invalid name, invalid value (determined only for choice parameter symbols), ambiguous value (determined only for choice parameter symbols).
/// </summary>
/// <returns>The enumerator for invalid parameters in templates in the template group.</returns>
internal IEnumerable<InvalidParameterInfo> GetInvalidParameterList()
{
List<InvalidParameterInfo> invalidParameterList = new List<InvalidParameterInfo>();
//collect the parameters which have ambiguous value match in all templates in the template group
IEnumerable<ParameterMatchInfo> ambiguousParametersForTemplates = Templates.SelectMany(template => template.MatchDisposition
.OfType<ParameterMatchInfo>()
//https://github.com/dotnet/templating/issues/2494
//after tab completion is implemented we no longer will be using this match kind - only exact matches will be allowed
#pragma warning disable CS0618 // Type or member is obsolete
.Where(x => x.Kind == MatchKind.AmbiguousValue))
#pragma warning restore CS0618 // Type or member is obsolete
.Distinct(new OrdinalIgnoreCaseMatchInfoComparer());
foreach (ParameterMatchInfo parameter in ambiguousParametersForTemplates)
{
invalidParameterList.Add(new InvalidParameterInfo(
InvalidParameterInfo.Kind.AmbiguousParameterValue,
parameter.InputFormat,
parameter.Value,
parameter.Name));
}
if (InvokableTemplates.Any())
{
//add the parameters that have single starts with match in several invokable templates in template group
return invalidParameterList.Union(GetAmbiguousSingleStartsWithParameters()).ToList();
}
//collect the parameters with invalid names for all templates in the template group
IEnumerable<ParameterMatchInfo> parametersWithInvalidNames = Templates.SelectMany(
template => template.MatchDisposition
.OfType<ParameterMatchInfo>()
.Where(x => x.Kind == MatchKind.InvalidName)).Distinct(new OrdinalIgnoreCaseMatchInfoComparer());
foreach (ParameterMatchInfo parameter in parametersWithInvalidNames)
{
if (Templates.All(
template => template.MatchDisposition
.OfType<ParameterMatchInfo>()
.Any(x => x.Kind == MatchKind.InvalidName
&& x.Name.Equals(parameter.Name, StringComparison.OrdinalIgnoreCase))))
{
invalidParameterList.Add(new InvalidParameterInfo(
InvalidParameterInfo.Kind.InvalidParameterName,
parameter.InputFormat,
parameter.Value,
parameter.Name));
}
}
//if there are templates which have a match for all template specific parameters, only they to be analyzed
var filteredTemplates = Templates.Where(template => !template.HasInvalidParameterName());
if (!filteredTemplates.Any())
{
filteredTemplates = Templates;
}
//collect the choice parameters with invalid values
IEnumerable<ParameterMatchInfo> invalidParameterValuesForTemplates = filteredTemplates.SelectMany(
template => template.MatchDisposition
.OfType<ParameterMatchInfo>()
.Where(x => x.Kind == MatchKind.InvalidValue))
.Distinct(new OrdinalIgnoreCaseMatchInfoComparer());
foreach (ParameterMatchInfo parameter in invalidParameterValuesForTemplates)
{
if (filteredTemplates.All(
template => template.MatchDisposition
.OfType<ParameterMatchInfo>()
.Any(x => x.Kind == MatchKind.InvalidValue
&& x.Name.Equals(parameter.Name, StringComparison.OrdinalIgnoreCase))))
{
invalidParameterList.Add(new InvalidParameterInfo(
InvalidParameterInfo.Kind.InvalidParameterValue,
parameter.InputFormat,
parameter.Value,
parameter.Name));
}
}
return invalidParameterList;
}
/// <summary>
/// The method returns the single invokable template with highest precedence.
/// </summary>
/// <param name="highestPrecedenceTemplate">Contains the invokable template with highest precedence.</param>
/// <param name="useDefaultLanguage">Defines if default language template should be preferred in case of ambiguity.</param>
/// <returns>
/// <see cref="true"/> when single invokable template with highest precedence can be defined.
/// <see cref="false"/> otherwise.
/// </returns>
internal bool TryGetHighestPrecedenceInvokableTemplate(out ITemplateMatchInfo? highestPrecedenceTemplate, bool useDefaultLanguage = false)
{
highestPrecedenceTemplate = null;
if (!InvokableTemplates.Any())
{
return false;
}
IEnumerable<ITemplateMatchInfo> highestPrecendenceTemplates = GetHighestPrecedenceInvokableTemplates(useDefaultLanguage);
if (highestPrecendenceTemplates.Count() == 1)
{
highestPrecedenceTemplate = highestPrecendenceTemplates.First();
return true;
}
return false;
}
/// <summary>
/// The method returns the invokable templates with highest precedence.
/// </summary>
/// <param name="useDefaultLanguage">Defines if default language template should be preferred in case of ambiguity.</param>
/// <returns>
/// the enumerator of invokable templates with highest precedence.
/// </returns>
internal IEnumerable<ITemplateMatchInfo> GetHighestPrecedenceInvokableTemplates(bool useDefaultLanguage = false)
{
IEnumerable<ITemplateMatchInfo> highestPrecedenceTemplates;
if (!InvokableTemplates.Any())
{
return new List<ITemplateMatchInfo>();
}
int highestPrecedence = InvokableTemplates.Max(t => t.Info.Precedence);
highestPrecedenceTemplates = InvokableTemplates.Where(t => t.Info.Precedence == highestPrecedence);
if (useDefaultLanguage && highestPrecedenceTemplates.Count() > 1)
{
IEnumerable<ITemplateMatchInfo> highestPrecedenceTemplatesForDefaultLanguage = highestPrecedenceTemplates.Where(t => t.HasDefaultLanguageMatch());
if (highestPrecedenceTemplatesForDefaultLanguage.Any())
{
return highestPrecedenceTemplatesForDefaultLanguage;
}
}
return highestPrecedenceTemplates;
}
/// <summary>
/// Gets the list of valid choices for <paramref name="parameter"/>.
/// </summary>
/// <param name="parameter">parameter canonical name.</param>
/// <returns>the dictionary of valid choices and descriptions.</returns>
internal IDictionary<string, ParameterChoice> GetValidValuesForChoiceParameter(string parameter)
{
Dictionary<string, ParameterChoice> validChoices = new Dictionary<string, ParameterChoice>();
foreach (ITemplateMatchInfo template in Templates)
{
if (template.Info.Tags.ContainsKey(parameter))
{
foreach (var choice in template.Info.Tags[parameter].Choices)
{
validChoices[choice.Key] = choice.Value;
}
}
}
return validChoices;
}
/// <summary>
/// Gets the list of ambiguous choices for <paramref name="parameter"/> for value <paramref name="value"/>.
/// </summary>
/// <param name="parameter">parameter canonical name.</param>
/// <param name="value">ambiguous value for the parameter to return possible choices for.</param>
/// <returns>the dictionary of possible choices and descriptions that are matching ambiguous input.</returns>
internal Dictionary<string, ParameterChoice> GetAmbiguousValuesForChoiceParameter(string parameter, string value)
{
Dictionary<string, ParameterChoice> validChoices = new Dictionary<string, ParameterChoice>();
foreach (ITemplateMatchInfo template in Templates)
{
if (template.Info.Tags.ContainsKey(parameter))
{
foreach (var choice in template.Info.Tags[parameter].Choices)
{
if (choice.Key.StartsWith(value, StringComparison.OrdinalIgnoreCase))
{
validChoices[choice.Key] = choice.Value;
}
}
}
}
return validChoices;
}
private class OrdinalIgnoreCaseMatchInfoComparer : IEqualityComparer<ParameterMatchInfo>
{
public bool Equals(ParameterMatchInfo? x, ParameterMatchInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
return x.Kind == y.Kind
&& string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(x.Value, y.Value, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(ParameterMatchInfo obj)
{
return (obj.Name.ToLowerInvariant(), obj.Value?.ToLowerInvariant(), obj.Kind).GetHashCode();
}
}
}
}
| 50.287791 | 180 | 0.591306 | [
"MIT"
] | eriawan/templating | src/Microsoft.TemplateEngine.Cli/TemplateResolution/TemplateGroup.cs | 17,299 | C# |
using System;
using LaDOSE.DTO;
namespace LaDOSE.REST.Event
{
public class UpdatedJwtEventHandler : EventArgs
{
private readonly ApplicationUserDTO msg;
public UpdatedJwtEventHandler(ApplicationUserDTO applicationUser)
{
this.msg = applicationUser;
}
public ApplicationUserDTO Message => msg;
}
} | 22.6875 | 73 | 0.672176 | [
"MIT"
] | darkstack/LaDOSE | LaDOSE.Src/LaDOSE.REST/Event/UpdatedEvent.cs | 365 | C# |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
namespace DaydreamElements.Common {
// This class is an implementation of Basetile in which the image on each tile
// zooms inward and scrolls along with the controller retical as it is hovering
// over the tile. The edges of the image are masked off if they go beyond the
// bounding rectangle of the tile.
public class MaskedTile : BaseTile {
private const string OBJ_NAME_MASKED_IMAGE = "MaskedImage";
private const float PARENT_CHANGE_THRESHOLD_PERCENT = 0.33f;
private Image maskedImage;
private GameObject maskedImageObject;
private Vector3 originalMaskedPosition; // Start position when pointer is not on tile.
private Vector3 maskedScrollOffset;
private Vector2 originalImageSize;
private Vector2 enlargedImageSize;
private float desiredPositionZ;
[Range(0.1f, 0.5f)]
[Tooltip("Image scroll amount when the pointer over the tile.")]
public float movementWeight = 0.15f;
[Range(1.1f, 2.0f)]
[Tooltip("Image scale amount when the pointer over the tile.")]
public float scaleWeight = 1.4f;
[Range(0.01f, 0.2f)]
[Tooltip("Tile forward distance when the pointer over the tile.")]
public float hoverPositionZMeters = 0.125f;
[Range(0.1f, 10.0f)]
[Tooltip("Speed used for lerping the rotation/scale/position of the tile.")]
public float interpolationSpeed = 8.0f;
protected override void Awake() {
base.Awake();
// Get current image.
Image image = GetComponent<Image>();
// Create mask.
gameObject.AddComponent<RectMask2D>();
// Save size data.
originalImageSize = image.rectTransform.sizeDelta;
enlargedImageSize = originalImageSize;
enlargedImageSize.x *= scaleWeight;
enlargedImageSize.y *= scaleWeight;
// Save position data.
originalMaskedPosition = new Vector3(originalImageSize.x / 2.0f, -originalImageSize.y / 2.0f, 0);
// Set data that varies.
maskedScrollOffset = Vector3.zero;
// Create game object for masked image.
maskedImageObject = new GameObject(OBJ_NAME_MASKED_IMAGE);
RectTransform maskedTransform = maskedImageObject.AddComponent<RectTransform>();
maskedTransform.SetParent(transform); // Set as child of this game object.
// Create maskedImage as component of child game object and initialize to base image.
maskedImage = maskedImageObject.AddComponent<Image>();
maskedImage.sprite = image.sprite;
maskedImage.color = image.color;
maskedImage.material = image.material;
image.sprite = null;
// If this object has a selectable referencing the original image,
// then we set the selectable to the masked image.
Selectable selectable = GetComponent<Selectable>();
if (selectable != null && selectable.image == image) {
selectable.image = maskedImage;
}
// Set size, scale, rotation and position.
maskedImage.rectTransform.sizeDelta = originalImageSize;
maskedImage.rectTransform.localScale = Vector3.one;
maskedImage.rectTransform.localRotation = Quaternion.identity;
maskedImage.rectTransform.anchoredPosition3D = originalMaskedPosition;
// Set masked image alignment to top-left.
Vector2 anchor = new Vector2(0, 1);
maskedImage.rectTransform.anchorMin = anchor;
maskedImage.rectTransform.anchorMax = anchor;
maskedImage.rectTransform.pivot = new Vector2(0.5f, 0.5f);
}
void Update() {
// Make sure to always ignore raycasts.
// This may be set back to true by BaseTile when the Tile becomes interactable.
maskedImage.raycastTarget = false;
UpdateScrollPosition();
UpdateFloatPosition();
UpdateScale();
}
public override void OnPointerEnter(PointerEventData eventData) {
isHovering = true;
desiredPositionZ = -hoverPositionZMeters / GetMetersToCanvasScale();
}
public override void OnPointerExit(PointerEventData eventData) {
isHovering = false;
maskedScrollOffset = Vector3.zero;
desiredPositionZ = 0.0f;
}
public override void OnGvrPointerHover(PointerEventData eventData) {
isHovering = true;
Vector3 pos = eventData.pointerCurrentRaycast.worldPosition;
RectTransform rectTransform = null;
if (maskedImageObject) {
rectTransform = maskedImageObject.GetComponent<RectTransform>();
}
if (!rectTransform || !isInteractable) {
return;
}
Rect rect = rectTransform.rect;
Vector3 localCenter = rect.center;
Vector3 worldCenter = maskedImageObject.transform.TransformPoint(localCenter);
Vector3 localMin = new Vector3(rect.min.x, rect.min.y, 0.0f);
Vector3 worldMin = maskedImageObject.transform.TransformPoint(localMin);
worldCenter -= worldMin;
pos -= worldMin;
Vector3 direction = pos - worldCenter;
maskedScrollOffset.x = movementWeight * enlargedImageSize.x * direction.x;
maskedScrollOffset.y = movementWeight * enlargedImageSize.y * direction.y;
}
private void UpdateScrollPosition() {
Vector3 desiredPosition = originalMaskedPosition;
if (isInteractable && isHovering) {
desiredPosition.x += maskedScrollOffset.x;
desiredPosition.y += maskedScrollOffset.y;
}
Vector3 position = maskedImage.rectTransform.anchoredPosition3D;
position = Vector3.Lerp(position, desiredPosition, Time.deltaTime * interpolationSpeed);
maskedImage.rectTransform.anchoredPosition3D = position;
}
private void UpdateFloatPosition() {
float finalDesiredPositionZ = desiredPositionZ;
if (!isInteractable) {
finalDesiredPositionZ = 0.0f;
}
if (finalDesiredPositionZ != transform.localPosition.z) {
Vector3 localPosition = transform.localPosition;
Vector3 desiredPosition = localPosition;
desiredPosition.z = finalDesiredPositionZ;
localPosition = Vector3.Lerp(localPosition, desiredPosition, Time.deltaTime * interpolationSpeed);
transform.localPosition = localPosition;
TiledPage page = GetPage();
if (page != null) {
float diff = Mathf.Abs(localPosition.z);
if (diff < ((PARENT_CHANGE_THRESHOLD_PERCENT * hoverPositionZMeters) / GetMetersToCanvasScale()) &&
transform.parent == page.transform) {
transform.SetParent(originalParent, true);
transform.SetAsLastSibling();
} else if (isHovering && diff >= 0 && transform.parent == originalParent) {
transform.SetParent(page.transform, true);
}
}
}
}
private void UpdateScale() {
Vector2 currentSize = maskedImage.rectTransform.sizeDelta;
Vector2 desiredSize;
if (IsInteractable && isHovering) {
desiredSize = enlargedImageSize;
} else {
desiredSize = originalImageSize;
}
currentSize = Vector2.Lerp(currentSize, desiredSize, Time.deltaTime * interpolationSpeed);
maskedImage.rectTransform.sizeDelta = currentSize;
}
}
} | 36.565421 | 109 | 0.698147 | [
"Apache-2.0"
] | Bits-HuynhBinh/DuckHuntVR | DuckShuterVR/Assets/DaydreamElements/Common/Scripts/PaginatedScrolling/PaginatedScrolling/ScrollEffects/MaskedTile.cs | 7,827 | C# |
using UnityEngine;
public class PlayerShoulderMain : MonoBehaviour
{
[TextArea(2, 4)]
public string notes = "This class only exists to act as a realiable way to let other " +
"classes find it (e.g. CrosshairJoystick).";
}
| 26.666667 | 92 | 0.691667 | [
"MIT"
] | tadadosii/2DTopDownIsometricShooterStudy | Assets/Scripts/Player/PlayerShoulderMain.cs | 242 | C# |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
namespace EmoticonGenerator
{
class Program
{
/// <summary>
/// Reads an input file for a list of emoticons and packs it into a single output PNG
/// </summary>
static void Main(string[] args)
{
string inputXml = string.Empty;
string basePath = string.Empty;
string outputPng = string.Empty;
if (ParseCommandLine(args, ref inputXml, ref basePath, ref outputPng) == false)
{
Usage();
return;
}
Console.Write("Reading and parsing input file {0}...", inputXml);
StreamReader inputFile = new StreamReader(inputXml);
string inputFileList = inputFile.ReadToEnd();
inputFile.Close();
string[] fileList = inputFileList.Split(Environment.NewLine.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("done!");
int emoticonSize = 19; // 19x19
int x = 0;
using (Bitmap pngStrip = new Bitmap(emoticonSize * fileList.Length, emoticonSize, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(pngStrip))
{
Console.Write("Packing emoticons into one strip...");
foreach (string fileName in fileList)
{
if (fileName.Trim().StartsWith(";"))
{
// skip comments
continue;
}
string filePath = Path.Combine(basePath, fileName.Trim());
if (string.CompareOrdinal(Path.GetExtension(filePath).ToLowerInvariant(), ".png") != 0)
{
filePath += ".png";
}
try
{
using (Bitmap pngFile = new Bitmap(filePath))
{
g.DrawImage(pngFile, x, 0);
x += emoticonSize;
}
}
catch (Exception e)
{
Console.WriteLine("\r\nError trying to read emoticon file {0}, {1}", filePath, e.Message);
}
}
Console.WriteLine("packed {0} emoticons!", (x / emoticonSize).ToString(CultureInfo.InvariantCulture));
}
Console.Write("Saving to {0}...", outputPng);
pngStrip.Save(outputPng, ImageFormat.Png);
Console.WriteLine("done!");
}
}
static void Usage()
{
Console.WriteLine("Usage: EmoticonGenerator -i <input file> -b <base image path> -o <output png file>");
}
static bool ParseCommandLine(string[] args, ref string inputXml, ref string basePath, ref string outputPng)
{
int countFound = 0;
try
{
for (int index = 0; index < args.Length; index++)
{
string option = args[index].Trim().ToLowerInvariant();
if (string.CompareOrdinal(option, "-i") == 0)
{
inputXml = args[++index].Trim();
countFound++;
}
else if (string.CompareOrdinal(option, "-b") == 0)
{
basePath = args[++index].Trim();
countFound++;
}
else if (string.CompareOrdinal(option, "-o") == 0)
{
outputPng = args[++index].Trim();
countFound++;
}
}
}
catch (Exception)
{
return false;
}
// 3 parameters expected
return (countFound == 3);
}
}
}
| 37.017241 | 123 | 0.435724 | [
"MIT"
] | DNSNets/OpenLiveWriter | utilities/EmoticonGenerator/Program.cs | 4,296 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
public partial class ServerDevOpsAuditingSettingsData : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(IsAzureMonitorTargetEnabled))
{
writer.WritePropertyName("isAzureMonitorTargetEnabled");
writer.WriteBooleanValue(IsAzureMonitorTargetEnabled.Value);
}
if (Optional.IsDefined(State))
{
writer.WritePropertyName("state");
writer.WriteStringValue(State.Value.ToSerialString());
}
if (Optional.IsDefined(StorageEndpoint))
{
writer.WritePropertyName("storageEndpoint");
writer.WriteStringValue(StorageEndpoint);
}
if (Optional.IsDefined(StorageAccountAccessKey))
{
writer.WritePropertyName("storageAccountAccessKey");
writer.WriteStringValue(StorageAccountAccessKey);
}
if (Optional.IsDefined(StorageAccountSubscriptionId))
{
writer.WritePropertyName("storageAccountSubscriptionId");
writer.WriteStringValue(StorageAccountSubscriptionId.Value);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static ServerDevOpsAuditingSettingsData DeserializeServerDevOpsAuditingSettingsData(JsonElement element)
{
Optional<SystemData> systemData = default;
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
Optional<bool> isAzureMonitorTargetEnabled = default;
Optional<BlobAuditingPolicyState> state = default;
Optional<string> storageEndpoint = default;
Optional<string> storageAccountAccessKey = default;
Optional<Guid> storageAccountSubscriptionId = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("systemData"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
continue;
}
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("isAzureMonitorTargetEnabled"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
isAzureMonitorTargetEnabled = property0.Value.GetBoolean();
continue;
}
if (property0.NameEquals("state"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
state = property0.Value.GetString().ToBlobAuditingPolicyState();
continue;
}
if (property0.NameEquals("storageEndpoint"))
{
storageEndpoint = property0.Value.GetString();
continue;
}
if (property0.NameEquals("storageAccountAccessKey"))
{
storageAccountAccessKey = property0.Value.GetString();
continue;
}
if (property0.NameEquals("storageAccountSubscriptionId"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
storageAccountSubscriptionId = property0.Value.GetGuid();
continue;
}
}
continue;
}
}
return new ServerDevOpsAuditingSettingsData(id, name, type, systemData, Optional.ToNullable(isAzureMonitorTargetEnabled), Optional.ToNullable(state), storageEndpoint.Value, storageAccountAccessKey.Value, Optional.ToNullable(storageAccountSubscriptionId));
}
}
}
| 42.469388 | 267 | 0.499279 | [
"MIT"
] | AhmedLeithy/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ServerDevOpsAuditingSettingsData.Serialization.cs | 6,243 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See the License.txt file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
namespace Microsoft.Configuration.ConfigurationBuilders
{
/// <summary>
/// A ConfigurationProvider that uses a directory's files as a source of values. A file's name is the key, and the contents are the value.
/// </summary>
public class KeyPerFileConfigBuilder : KeyValueConfigBuilder
{
#pragma warning disable CS1591 // No xml comments for tag literals.
public const string directoryPathTag = "directoryPath";
public const string keyDelimiterTag = "keyDelimiter";
public const string ignorePrefixTag = "ignorePrefix";
#pragma warning restore CS1591 // No xml comments for tag literals.
/// <summary>
/// Gets or sets a path to the source directory to look in for values.
/// </summary>
public string DirectoryPath { get; protected set; }
/// <summary>
/// If specified, the config builder will traverse multiple levels of the directory, building key names with this delimeter.
/// If null, the config builder only looks at the top-level of the directory. This is the default.
/// </summary>
public string KeyDelimiter { get; protected set; }
/// <summary>
/// Gets or sets a prefix string. Files that start with this prefix will be excluded.
/// Defaults to "ignore.".
/// </summary>
public string IgnorePrefix { get; protected set; }
private ConcurrentDictionary<string, string> _allValues = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Initializes the configuration builder lazily.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing builder-specific attributes specified in the configuration for this provider.</param>
protected override void LazyInitialize(string name, NameValueCollection config)
{
// Default 'Optional' to false. base.Initialize() will override if specified in config.
Optional = false;
base.LazyInitialize(name, config);
string directoryPath = UpdateConfigSettingWithAppSettings(directoryPathTag);
DirectoryPath = Utils.MapPath(directoryPath);
if (!Optional && (String.IsNullOrEmpty(DirectoryPath) || !Directory.Exists(DirectoryPath)))
{
throw new ArgumentException($"'directoryPath' does not exist.");
}
IgnorePrefix = UpdateConfigSettingWithAppSettings(ignorePrefixTag) ?? "ignore.";
// The Core KeyPerFile config provider does not do multi-level.
// If KeyDelimiter is null, do single-level. Otherwise, multi-level.
// Empty string will do multi-level with basic non-delimited concatenation in greedy mode.
// Empty string will be effectively single-level in other modes.
KeyDelimiter = config[keyDelimiterTag];
}
/// <summary>
/// Retrieves all known key/value pairs from the secrets file where the key begins with with <paramref name="prefix"/>.
/// </summary>
/// <param name="prefix">A prefix string to filter the list of potential keys retrieved from the source.</param>
/// <returns>A collection of key/value pairs.</returns>
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
ReadAllValues(DirectoryPath, "", _allValues);
return _allValues?.Where(s => s.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
}
/// <summary>
/// Looks up a single 'value' for the given 'key.'
/// </summary>
/// <param name="key">The 'key' to look up in the secrets file. (Prefix handling is not needed here.)</param>
/// <returns>The value corresponding to the given 'key' or null if no value is found.</returns>
public override string GetValue(string key)
{
string filename = key;
if (!String.IsNullOrEmpty(KeyDelimiter))
filename = filename.Replace(KeyDelimiter, Path.DirectorySeparatorChar.ToString());
if (!String.IsNullOrWhiteSpace(IgnorePrefix))
{
foreach (var pathPart in filename.Split(new char[] { Path.DirectorySeparatorChar })) {
if (pathPart.StartsWith(IgnorePrefix, StringComparison.OrdinalIgnoreCase))
return null;
}
}
return ReadValueFromFile(Path.Combine(DirectoryPath, filename));
}
private IDictionary<string, string> ReadAllValues(string root, string prefix, IDictionary<string, string> values)
{
if (values == null)
values = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DirectoryInfo di = new DirectoryInfo(root);
// Only do multi-level if KeyDelimiter is non-null.
// When doing multi-level, go depth-first, to give priority to the root level in event of a collision.
if (KeyDelimiter != null)
{
foreach (var sub in di.EnumerateDirectories())
{
if (!String.IsNullOrWhiteSpace(IgnorePrefix) && sub.Name.StartsWith(IgnorePrefix, StringComparison.OrdinalIgnoreCase))
continue;
ReadAllValues(sub.FullName, sub.Name + KeyDelimiter, values);
}
}
foreach (var file in di.EnumerateFiles())
{
if (!String.IsNullOrWhiteSpace(IgnorePrefix) && file.Name.StartsWith(IgnorePrefix, StringComparison.OrdinalIgnoreCase))
continue;
string key = prefix + file.Name;
string val = ReadValueFromFile(file.FullName);
values.Add(key, val);
}
return values;
}
private string ReadValueFromFile(string filePath)
{
if (!File.Exists(filePath))
return null;
string val = File.ReadAllText(filePath);
while (val.EndsWith(Environment.NewLine))
val = val.Substring(0, val.Length - Environment.NewLine.Length);
return val;
}
}
}
| 45.581081 | 168 | 0.629706 | [
"MIT"
] | Expecho/MicrosoftConfigurationBuilders | src/KeyPerFile/KeyPerFileConfigBuilder.cs | 6,748 | C# |
//#define BT_DEBUG_ENABLE
using System;
using System.Collections.Generic;
using Saro.BT.Utility;
namespace Saro.BT
{
public sealed class BehaviorIterator
{
private readonly FixedSizeStack<int> traversal;
private readonly Queue<int> requestedTraversals;
private readonly BehaviorTree tree;
public Action onDone;
public bool IsRunning => traversal.Count != 0;
public int CurrentIndex => traversal.Count == 0 ? BTNode.kInvalidOrder : traversal.Peek();
public int LevelOffset { get; }
public BTNode.EStatus? LastChildExitStatus { get; private set; }
public BTNode.EStatus LastExecutedStatus { get; private set; }
public int FirstInTraversal => traversal.GetValueAt(0);
public BehaviorIterator(BehaviorTree tree, int levelOffset)
{
this.tree = tree;
LevelOffset = levelOffset;
var maxTraversalLen = this.tree.Height + 1;
traversal = new FixedSizeStack<int>(maxTraversalLen);
requestedTraversals = new Queue<int>(maxTraversalLen);
}
public void Tick()
{
CallOnEnterOnQueuedNodes();
var index = traversal.Peek();
var node = tree.Nodes[index];
var status = node.Run();
LastExecutedStatus = status;
#if UNITY_EDITOR
node.StatusEditorResult = (BTNode.EStatusEditor)status;
#endif
if (status != BTNode.EStatus.Running)
{
PopNode();
OnChildExit(node, status);
}
if (traversal.Count == 0)
{
onDone?.Invoke();
__debug("iterator done!");
}
}
private BTNode PopNode()
{
var index = traversal.Pop();
var node = tree.Nodes[index];
if (node.IsComposite())
{
for (int i = 0; i < node.ChildCount(); i++)
{
node.GetChildAt(i).OnCompositeParentExit();
}
}
node.OnExit();
__debug($"exit *{LastExecutedStatus}* <color=green>{node.name}: {node.preOrderIndex}</color>");
__debug($"------traversal pop: {string.Join(",", traversal)}");
return node;
}
private void CallOnEnterOnQueuedNodes()
{
while (requestedTraversals.Count != 0)
{
var i = requestedTraversals.Dequeue();
var node = tree.Nodes[i];
node.OnEnter();
__debug($"enter <color=green>{node.name}: {node.preOrderIndex}</color>");
#if UNITY_EDITOR
node.OnBreakpoint();
#endif
OnChildEnter(node);
}
}
private void OnChildEnter(BTNode node)
{
if (node.Parent != null)
{
LastChildExitStatus = null;
node.Parent.OnChildEnter(node.childOrder);
}
}
private void OnChildExit(BTNode node, BTNode.EStatus status)
{
if (node.Parent != null)
{
node.Parent.OnChildExit(node.childOrder, status);
LastChildExitStatus = status;
}
}
public void Traverse(BTNode child)
{
var i = child.preOrderIndex;
traversal.Push(i);
requestedTraversals.Enqueue(i);
#if UNITY_EDITOR
child.StatusEditorResult = BTNode.EStatusEditor.Running;
#endif
}
public void AbortRunningChildBranch(BTNode parent, int abortBranchIndex)
{
if (IsRunning && parent != null)
{
var terminatingIndex = parent.preOrderIndex;
while (traversal.Count != 0 && traversal.Peek() != terminatingIndex)
{
StepBackAbort();
}
if (parent.IsComposite())
{
parent.OnAbort(abortBranchIndex);
}
requestedTraversals.Clear();
Traverse(parent.GetChildAt(abortBranchIndex));
__debug($"<color=red>abort</color> *{parent.name}: {parent.preOrderIndex}* branch index: {abortBranchIndex}");
__debug($"------traversal abort: {string.Join(",", traversal)}");
}
}
private void StepBackAbort()
{
var node = PopNode();
#if UNITY_EDITOR
node.StatusEditorResult = BTNode.EStatusEditor.Aborted;
#endif
}
internal void Interrupt(BTNode subtree)
{
if (subtree != null)
{
var parentIndex = subtree.Parent != null ? subtree.Parent.preOrderIndex : BTNode.kInvalidOrder;
while (traversal.Count != 0 && traversal.Peek() != parentIndex)
{
var node = PopNode();
#if UNITY_EDITOR
node.StatusEditorResult = BTNode.EStatusEditor.Interruption;
#endif
}
requestedTraversals.Clear();
}
}
[System.Diagnostics.Conditional("BT_DEBUG_ENABLE")]
private static void __debug(string msg)
{
UnityEngine.Debug.LogError("[BT] " + msg);
}
}
}
| 27.690722 | 126 | 0.525875 | [
"MIT"
] | Sarofc/BehaviorTree-Unity | Runtime/Core/BehaviorIterator.cs | 5,374 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public interface IPrivateOverriddenImplementation
{
object OverriddenProperty { get; set; }
}
} | 40.75 | 68 | 0.761503 | [
"MIT"
] | Chimpaneez/LiveSplit | LiveSplit/Libs/JSON.Net/Source/Src/Newtonsoft.Json.Tests/TestObjects/IPrivateOverriddenImplementation.cs | 1,306 | C# |
namespace MeetAndGo.Model.SearchObject
{
public class UserSearchObject
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int? RoleId { get; set; }
}
}
| 25 | 45 | 0.586667 | [
"MIT"
] | emin-alajbegovic/Meet-Go | MeetAndGo/MeetAndGo.Model/SearchObject/UserSearchObject.cs | 302 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.