content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace API.Zahnraddimensionierungsprogramm.GruppeJ { /// <summary> /// Interaktionslogik für Window2.xaml /// </summary> public partial class Window2 : Window { public Window2() { InitializeComponent(); } private bool Zahlprüfung(string Zahlcheck) { try { double doublezahl = double.Parse(Zahlcheck); return true; } catch (FormatException) { return false; } } private double d; private double z; private void m_calc_btn_Click(object sender, RoutedEventArgs e) { string Zahlencheck = d_calc.Text; if (Zahlprüfung(Zahlencheck) == true) { d = Convert.ToDouble(d_calc.Text); if (d < 0) { MessageBox.Show("Fehler: Der Teilkreisdurchmesser darf nicht unter 0 liegen. Bitte Eingabe korrigieren"); } } else { MessageBox.Show("Bitte Eingabe zum Teilkreisdurchmesser überprüfen"); } Zahlencheck = z_calc.Text; if (Zahlprüfung(Zahlencheck) == true) { z = Convert.ToDouble(z_calc.Text); if (z < 0) { MessageBox.Show("Fehler: Die Zähnezahl darf nicht unter 0 liegen. Bitte Eingabe korrigieren"); } } else { MessageBox.Show("Fehler: Bitte Eingabe zur Zähnezahl überprüfen"); } m_calc.Content = d / z; } } }
26.961039
125
0.5342
[ "MIT" ]
maxeuken/HSP-Sprint-1
API.Zahnraddimensionierungsprogramm.GruppeJ/API.Zahnraddimensionierungsprogramm.GruppeJ/Window2.xaml.cs
2,088
C#
using lib12.Mathematics.Extensions; using Shouldly; using Xunit; namespace lib12.Tests.Mathematics { public class IntExtensionTests { [Fact] public void to_bool_returns_false_if_given_zero() { 0.ToBool().ShouldBeFalse(); } [Fact] public void to_bool_returns_true_if_given_non_zero() { 12.ToBool().ShouldBeTrue(); } } }
20.047619
60
0.60095
[ "MIT" ]
kkalinowski/lib12
lib12.Tests/Mathematics/IntExtensionTests.cs
423
C#
// // SecureMimeTests.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2020 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using NUnit.Framework; using Org.BouncyCastle.Cms; using Org.BouncyCastle.X509; using Org.BouncyCastle.Pkcs; using MimeKit; using MimeKit.Cryptography; using X509Certificate = Org.BouncyCastle.X509.X509Certificate; namespace UnitTests.Cryptography { public abstract class SecureMimeTestsBase { //const string ExpiredCertificateMessage = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file.\r\n"; const string ExpiredCertificateMessage = "The certificate is revoked.\r\n"; const string UntrustedRootCertificateMessage = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.\r\n"; const string ThunderbirdFingerprint = "354ea4dcf98166639b58ec5df06a65de0cd8a95c"; const string MimeKitFingerprint = "ba4403cd3d876ae8cd261575820330086cc3cbc8"; const string ThunderbirdName = "fejj@gnome.org"; static readonly DateTime MimeKitCreationDate = new DateTime (2019, 11, 05, 03, 00, 15); static readonly DateTime MimeKitExpirationDate = new DateTime (2029, 11, 02, 03, 00, 15); readonly X509Certificate MimeKitCertificate; static readonly string[] StartComCertificates = { "StartComCertificationAuthority.crt", "StartComClass1PrimaryIntermediateClientCA.crt" }; protected virtual bool IsEnabled { get { return true; } } protected abstract SecureMimeContext CreateContext (); protected SecureMimeTestsBase () { if (!IsEnabled) return; using (var ctx = CreateContext ()) { var dataDir = Path.Combine ("..", "..", "TestData", "smime"); string path; if (ctx is TemporarySecureMimeContext) CryptographyContext.Register (() => CreateContext ()); else CryptographyContext.Register (ctx.GetType ()); var chain = LoadPkcs12CertificateChain (Path.Combine (dataDir, "smime.pfx"), "no.secret"); MimeKitCertificate = chain[0]; if (ctx is WindowsSecureMimeContext) { var windows = (WindowsSecureMimeContext) ctx; var parser = new X509CertificateParser (); using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComCertificationAuthority.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.AuthRoot, certificate); } using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComClass1PrimaryIntermediateClientCA.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.CertificateAuthority, certificate); } // import the root & intermediate certificates from the smime.pfx file var store = StoreName.AuthRoot; for (int i = chain.Length - 1; i > 0; i--) { windows.Import (store, chain[i]); store = StoreName.CertificateAuthority; } } else { foreach (var filename in StartComCertificates) { path = Path.Combine (dataDir, filename); using (var stream = File.OpenRead (path)) { if (ctx is DefaultSecureMimeContext) { ((DefaultSecureMimeContext) ctx).Import (stream, true); } else { var parser = new X509CertificateParser (); foreach (X509Certificate certificate in parser.ReadCertificates (stream)) ctx.Import (certificate); } } } // import the root & intermediate certificates from the smime.pfx file for (int i = chain.Length - 1; i > 0; i--) { if (ctx is DefaultSecureMimeContext) { ((DefaultSecureMimeContext) ctx).Import (chain[i], true); } else { ctx.Import (chain[i]); } } } path = Path.Combine (dataDir, "smime.pfx"); ctx.Import (path, "no.secret"); // import a second time to cover the case where the certificate & private key already exist Assert.DoesNotThrow (() => ctx.Import (path, "no.secret")); } } public static X509Certificate LoadCertificate (string path) { using (var stream = File.OpenRead (path)) { var parser = new X509CertificateParser (); return parser.ReadCertificate (stream); } } public static X509Certificate[] LoadPkcs12CertificateChain (string fileName, string password) { using (var stream = File.OpenRead (fileName)) { var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); if (!entry.Key.IsPrivate) continue; var certificates = new X509Certificate[chain.Length]; for (int i = 0; i < chain.Length; i++) certificates[i] = chain[i].Certificate; return certificates; } } return new X509Certificate[0]; } } [Test] public void TestArgumentExceptions () { var stream = new MemoryStream (); Assert.Throws<ArgumentNullException> (() => new ApplicationPkcs7Signature ((MimeEntityConstructorArgs) null)); Assert.Throws<ArgumentNullException> (() => new ApplicationPkcs7Mime ((MimeEntityConstructorArgs) null)); Assert.Throws<ArgumentNullException> (() => new ApplicationPkcs7Signature ((Stream) null)); // Accept Assert.Throws<ArgumentNullException> (() => new ApplicationPkcs7Mime (SecureMimeType.SignedData, stream).Accept (null)); Assert.Throws<ArgumentNullException> (() => new ApplicationPkcs7Signature (stream).Accept (null)); Assert.Throws<ArgumentOutOfRangeException> (() => SecureMimeContext.GetDigestOid (DigestAlgorithm.None)); Assert.Throws<NotSupportedException> (() => SecureMimeContext.GetDigestOid (DigestAlgorithm.DoubleSha)); Assert.Throws<NotSupportedException> (() => SecureMimeContext.GetDigestOid (DigestAlgorithm.Haval5160)); Assert.Throws<NotSupportedException> (() => SecureMimeContext.GetDigestOid (DigestAlgorithm.Tiger192)); using (var ctx = CreateContext ()) { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret"); var mailbox = new MailboxAddress ("Unit Tests", "example@mimekit.net"); var recipients = new CmsRecipientCollection (); DigitalSignatureCollection signatures; MimeEntity entity; Assert.IsFalse (ctx.Supports ("text/plain"), "Should not support text/plain"); Assert.IsFalse (ctx.Supports ("application/octet-stream"), "Should not support application/octet-stream"); Assert.IsTrue (ctx.Supports ("application/pkcs7-mime"), "Should support application/pkcs7-mime"); Assert.IsTrue (ctx.Supports ("application/x-pkcs7-mime"), "Should support application/x-pkcs7-mime"); Assert.IsTrue (ctx.Supports ("application/pkcs7-signature"), "Should support application/pkcs7-signature"); Assert.IsTrue (ctx.Supports ("application/x-pkcs7-signature"), "Should support application/x-pkcs7-signature"); Assert.AreEqual ("application/pkcs7-signature", ctx.SignatureProtocol); Assert.AreEqual ("application/pkcs7-mime", ctx.EncryptionProtocol); Assert.AreEqual ("application/pkcs7-mime", ctx.KeyExchangeProtocol); Assert.Throws<ArgumentNullException> (() => ctx.Supports (null)); Assert.Throws<ArgumentNullException> (() => ctx.CanSign (null)); Assert.Throws<ArgumentNullException> (() => ctx.CanEncrypt (null)); Assert.Throws<ArgumentNullException> (() => ctx.Compress (null)); Assert.Throws<ArgumentNullException> (() => ctx.Decompress (null)); Assert.Throws<ArgumentNullException> (() => ctx.DecompressTo (null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.DecompressTo (stream, null)); Assert.Throws<ArgumentNullException> (() => ctx.Decrypt (null)); Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (stream, null)); Assert.Throws<ArgumentNullException> (() => ctx.EncapsulatedSign (null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.EncapsulatedSign (signer, null)); Assert.Throws<ArgumentNullException> (() => ctx.EncapsulatedSign (null, DigestAlgorithm.Sha256, stream)); Assert.Throws<ArgumentNullException> (() => ctx.EncapsulatedSign (mailbox, DigestAlgorithm.Sha256, null)); Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((CmsRecipientCollection) null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (recipients, null)); Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((IEnumerable<MailboxAddress>) null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (new MailboxAddress[0], null)); Assert.Throws<ArgumentException> (() => ctx.Encrypt (new MailboxAddress[0], stream)); Assert.Throws<ArgumentNullException> (() => ctx.Export (null)); Assert.Throws<ArgumentNullException> (() => ctx.GetDigestAlgorithm (null)); Assert.Throws<ArgumentNullException> (() => ctx.Import ((Stream) null)); Assert.Throws<ArgumentNullException> (() => ctx.Import ((Stream) null, "password")); Assert.Throws<ArgumentNullException> (() => ctx.Import (stream, null)); Assert.Throws<ArgumentNullException> (() => ctx.Import ((string) null, "password")); Assert.Throws<ArgumentNullException> (() => ctx.Import ("fileName", null)); Assert.Throws<ArgumentNullException> (() => ctx.Import ((X509Crl) null)); Assert.Throws<ArgumentNullException> (() => ctx.Import ((X509Certificate) null)); Assert.Throws<ArgumentNullException> (() => ctx.Sign (null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.Sign (signer, null)); Assert.Throws<ArgumentNullException> (() => ctx.Sign (null, DigestAlgorithm.Sha256, stream)); Assert.Throws<ArgumentNullException> (() => ctx.Sign (mailbox, DigestAlgorithm.Sha256, null)); Assert.Throws<ArgumentNullException> (() => ctx.Verify (null, stream)); Assert.Throws<ArgumentNullException> (() => ctx.Verify (stream, null)); Assert.Throws<ArgumentNullException> (() => ctx.Verify (null, out signatures)); Assert.Throws<ArgumentNullException> (() => ctx.Verify (null, out entity)); Assert.Throws<ArgumentNullException> (async () => await ctx.VerifyAsync (null, stream)); Assert.Throws<ArgumentNullException> (async () => await ctx.VerifyAsync (stream, null)); entity = new MimePart { Content = new MimeContent (stream) }; Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create ((SecureMimeContext) null, signer, entity)); Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, (CmsSigner) null, entity)); Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, signer, null)); Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create ((CmsSigner) null, entity)); Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (signer, null)); } } [Test] public virtual void TestCanSignAndEncrypt () { var valid = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var invalid = new MailboxAddress ("Joe Nobody", "joe@nobody.com"); using (var ctx = CreateContext ()) { Assert.IsFalse (ctx.CanSign (invalid), "{0} should not be able to sign.", invalid); Assert.IsFalse (ctx.CanEncrypt (invalid), "{0} should not be able to encrypt.", invalid); Assert.IsTrue (ctx.CanSign (valid), "{0} should be able to sign.", valid); Assert.IsTrue (ctx.CanEncrypt (valid), "{0} should be able to encrypt.", valid); using (var content = new MemoryStream ()) { Assert.Throws<CertificateNotFoundException> (() => ctx.Encrypt (new[] { invalid }, content)); Assert.Throws<CertificateNotFoundException> (() => ctx.Sign (invalid, DigestAlgorithm.Sha1, content)); Assert.Throws<CertificateNotFoundException> (() => ctx.EncapsulatedSign (invalid, DigestAlgorithm.Sha1, content)); } } } [Test] public void TestDigestAlgorithmMappings () { using (var ctx = CreateContext ()) { foreach (DigestAlgorithm digestAlgo in Enum.GetValues (typeof (DigestAlgorithm))) { if (digestAlgo == DigestAlgorithm.None || digestAlgo == DigestAlgorithm.DoubleSha) continue; // make sure that the name & enum values map back and forth correctly var micalg = ctx.GetDigestAlgorithmName (digestAlgo); var algorithm = ctx.GetDigestAlgorithm (micalg); Assert.AreEqual (digestAlgo, algorithm); // make sure that the oid and enum values map back and forth correctly try { var oid = SecureMimeContext.GetDigestOid (digestAlgo); SecureMimeContext.TryGetDigestAlgorithm (oid, out algorithm); Assert.AreEqual (digestAlgo, algorithm); } catch (NotSupportedException) { } } Assert.Throws<NotSupportedException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.DoubleSha)); Assert.Throws<ArgumentOutOfRangeException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.None)); Assert.AreEqual (DigestAlgorithm.None, ctx.GetDigestAlgorithm ("blahblahblah")); Assert.IsFalse (SecureMimeContext.TryGetDigestAlgorithm ("blahblahblah", out DigestAlgorithm algo)); } } [Test] public void TestSecureMimeCompression () { var original = new TextPart ("plain"); original.Text = "This is some text that we'll end up compressing..."; var compressed = ApplicationPkcs7Mime.Compress (original); Assert.AreEqual (SecureMimeType.CompressedData, compressed.SecureMimeType, "S/MIME type did not match."); var decompressed = compressed.Decompress (); Assert.IsInstanceOf<TextPart> (decompressed, "Decompressed part is not the expected type."); Assert.AreEqual (original.Text, ((TextPart) decompressed).Text, "Decompressed content is not the same as the original."); } [Test] public void TestSecureMimeCompressionWithContext () { var original = new TextPart ("plain"); original.Text = "This is some text that we'll end up compressing..."; using (var ctx = CreateContext ()) { var compressed = ApplicationPkcs7Mime.Compress (ctx, original); Assert.AreEqual (SecureMimeType.CompressedData, compressed.SecureMimeType, "S/MIME type did not match."); var decompressed = compressed.Decompress (ctx); Assert.IsInstanceOf<TextPart> (decompressed, "Decompressed part is not the expected type."); Assert.AreEqual (original.Text, ((TextPart) decompressed).Text, "Decompressed content is not the same as the original."); using (var stream = new MemoryStream ()) { using (var decoded = new MemoryStream ()) { compressed.Content.DecodeTo (decoded); decoded.Position = 0; ctx.DecompressTo (decoded, stream); } stream.Position = 0; decompressed = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (decompressed, "Decompressed part is not the expected type."); Assert.AreEqual (original.Text, ((TextPart) decompressed).Text, "Decompressed content is not the same as the original."); } } } protected virtual EncryptionAlgorithm[] GetEncryptionAlgorithms (IDigitalSignature signature) { return ((SecureMimeDigitalSignature) signature).EncryptionAlgorithms; } [Test] public virtual void TestSecureMimeEncapsulatedSigning () { var cleartext = new TextPart ("plain") { Text = "This is some text that we'll end up signing..." }; var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var signed = ApplicationPkcs7Mime.Sign (self, DigestAlgorithm.Sha1, cleartext); MimeEntity extracted; Assert.AreEqual (SecureMimeType.SignedData, signed.SecureMimeType, "S/MIME type did not match."); var signatures = signed.Verify (out extracted); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); Assert.AreEqual (MimeKitCreationDate, signature.SignerCertificate.CreationDate, "CreationDate"); Assert.AreEqual (MimeKitExpirationDate, signature.SignerCertificate.ExpirationDate, "ExpirationDate"); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.PublicKeyAlgorithm); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { using (var ctx = CreateContext ()) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); } void AssertValidSignatures (SecureMimeContext ctx, DigitalSignatureCollection signatures) { foreach (var signature in signatures) { try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Seed)) Assert.AreEqual (EncryptionAlgorithm.Seed, algorithms[i++], "Expected SEED capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia256)) Assert.AreEqual (EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia192)) Assert.AreEqual (EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia128)) Assert.AreEqual (EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Cast5)) Assert.AreEqual (EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Idea)) Assert.AreEqual (EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability"); //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability"); //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability"); //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability"); //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability"); } } [Test] public virtual void TestSecureMimeEncapsulatedSigningWithContext () { var cleartext = new TextPart ("plain") { Text = "This is some text that we'll end up signing..." }; var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); using (var ctx = CreateContext ()) { var signed = ApplicationPkcs7Mime.Sign (ctx, self, DigestAlgorithm.Sha1, cleartext); MimeEntity extracted; Assert.AreEqual (SecureMimeType.SignedData, signed.SecureMimeType, "S/MIME type did not match."); var signatures = signed.Verify (ctx, out extracted); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); AssertValidSignatures (ctx, signatures); using (var signedData = signed.Content.Open ()) { using (var stream = ctx.Verify (signedData, out signatures)) extracted = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); AssertValidSignatures (ctx, signatures); } } } [Test] public virtual void TestSecureMimeEncapsulatedSigningWithCmsSigner () { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret", SubjectIdentifierType.SubjectKeyIdentifier); var cleartext = new TextPart ("plain") { Text = "This is some text that we'll end up signing..." }; var signed = ApplicationPkcs7Mime.Sign (signer, cleartext); MimeEntity extracted; Assert.AreEqual (SecureMimeType.SignedData, signed.SecureMimeType, "S/MIME type did not match."); var signatures = signed.Verify (out extracted); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); foreach (var signature in signatures) { try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { using (var ctx = CreateContext ()) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); } } [Test] public virtual void TestSecureMimeEncapsulatedSigningWithContextAndCmsSigner () { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret", SubjectIdentifierType.SubjectKeyIdentifier); var cleartext = new TextPart ("plain") { Text = "This is some text that we'll end up signing..." }; using (var ctx = CreateContext ()) { var signed = ApplicationPkcs7Mime.Sign (ctx, signer, cleartext); MimeEntity extracted; Assert.AreEqual (SecureMimeType.SignedData, signed.SecureMimeType, "S/MIME type did not match."); var signatures = signed.Verify (ctx, out extracted); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); AssertValidSignatures (ctx, signatures); using (var signedData = signed.Content.Open ()) { using (var stream = ctx.Verify (signedData, out signatures)) extracted = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (extracted, "Extracted part is not the expected type."); Assert.AreEqual (cleartext.Text, ((TextPart) extracted).Text, "Extracted content is not the same as the original."); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); AssertValidSignatures (ctx, signatures); } } } [Test] public virtual void TestSecureMimeSigningWithCmsSigner () { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret"); var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." }; var multipart = MultipartSigned.Create (signer, body); Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children."); var protocol = multipart.ContentType.Parameters["protocol"]; Assert.AreEqual ("application/pkcs7-signature", protocol, "The multipart/signed protocol does not match."); Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); var signatures = multipart.Verify (); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; using (var ctx = CreateContext ()) { if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeSigningWithContextAndCmsSigner () { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret"); var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." }; using (var ctx = CreateContext ()) { var multipart = MultipartSigned.Create (ctx, signer, body); Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children."); var protocol = multipart.ContentType.Parameters["protocol"]; Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match."); Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); var signatures = multipart.Verify (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Seed)) Assert.AreEqual (EncryptionAlgorithm.Seed, algorithms[i++], "Expected SEED capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia256)) Assert.AreEqual (EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia192)) Assert.AreEqual (EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia128)) Assert.AreEqual (EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Cast5)) Assert.AreEqual (EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Idea)) Assert.AreEqual (EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability"); //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability"); //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability"); //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability"); //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeSigningWithRsaSsaPss () { var signer = new CmsSigner (Path.Combine ("..", "..", "TestData", "smime", "smime.pfx"), "no.secret") { RsaSignaturePadding = RsaSignaturePadding.Pss }; var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." }; using (var ctx = CreateContext ()) { MultipartSigned multipart; try { multipart = MultipartSigned.Create (signer, body); } catch (NotSupportedException) { if (!(ctx is WindowsSecureMimeContext)) Assert.Fail ("RSASSA-PSS should be supported."); return; } Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children."); var protocol = multipart.ContentType.Parameters["protocol"]; Assert.AreEqual ("application/pkcs7-signature", protocol, "The multipart/signed protocol does not match."); Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); var signatures = multipart.Verify (); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeMessageSigning () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." }; var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var message = new MimeMessage { Subject = "Test of signing with S/MIME" }; message.From.Add (self); message.Body = body; using (var ctx = CreateContext ()) { Assert.IsTrue (ctx.CanSign (self)); message.Sign (ctx); Assert.IsInstanceOf<MultipartSigned> (message.Body, "The message body should be a multipart/signed."); var multipart = (MultipartSigned) message.Body; Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children."); var protocol = multipart.ContentType.Parameters["protocol"]; Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match."); Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); var signatures = multipart.Verify (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual (self.Name, signature.SignerCertificate.Name); Assert.AreEqual (self.Address, signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Seed)) Assert.AreEqual (EncryptionAlgorithm.Seed, algorithms[i++], "Expected SEED capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia256)) Assert.AreEqual (EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia192)) Assert.AreEqual (EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia128)) Assert.AreEqual (EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Cast5)) Assert.AreEqual (EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Idea)) Assert.AreEqual (EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability"); //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability"); //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability"); //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability"); //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual async Task TestSecureMimeMessageSigningAsync () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." }; var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var message = new MimeMessage { Subject = "Test of signing with S/MIME" }; message.From.Add (self); message.Body = body; using (var ctx = CreateContext ()) { Assert.IsTrue (ctx.CanSign (self)); message.Sign (ctx); Assert.IsInstanceOf<MultipartSigned> (message.Body, "The message body should be a multipart/signed."); var multipart = (MultipartSigned) message.Body; Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children."); var protocol = multipart.ContentType.Parameters["protocol"]; Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match."); Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); var signatures = await multipart.VerifyAsync (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual (self.Name, signature.SignerCertificate.Name); Assert.AreEqual (self.Address, signature.SignerCertificate.Email); Assert.AreEqual (MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Seed)) Assert.AreEqual (EncryptionAlgorithm.Seed, algorithms[i++], "Expected SEED capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia256)) Assert.AreEqual (EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia192)) Assert.AreEqual (EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia128)) Assert.AreEqual (EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Cast5)) Assert.AreEqual (EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Idea)) Assert.AreEqual (EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability"); //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability"); //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability"); //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability"); //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeVerifyThunderbird () { MimeMessage message; using (var file = File.OpenRead (Path.Combine ("..", "..", "TestData", "smime", "thunderbird-signed.txt"))) { var parser = new MimeParser (file, MimeFormat.Default); message = parser.ParseMessage (); } using (var ctx = CreateContext ()) { Assert.IsInstanceOf<MultipartSigned> (message.Body, "The message body should be a multipart/signed."); var multipart = (MultipartSigned) message.Body; var protocol = multipart.ContentType.Parameters["protocol"]?.Trim (); Assert.IsTrue (ctx.Supports (protocol), "The multipart/signed protocol is not supported."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature."); // Note: this fails in WindowsSecureMimeContext var signatures = multipart.Verify (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var sender = message.From.Mailboxes.FirstOrDefault (); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual (ThunderbirdName, signature.SignerCertificate.Name); Assert.AreEqual (sender.Address, signature.SignerCertificate.Email); Assert.AreEqual (ThunderbirdFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[0], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[1], "Expected AES-128 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[2], "Expected Triple-DES capability"); Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[3], "Expected RC2-128 capability"); Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[4], "Expected RC2-64 capability"); Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[5], "Expected DES capability"); Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[6], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { if (Path.DirectorySeparatorChar == '/') Assert.IsInstanceOf<ArgumentException> (ex.InnerException); else Assert.AreEqual (ExpiredCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeMessageEncryption () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." }; var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var message = new MimeMessage { Subject = "Test of encrypting with S/MIME" }; message.From.Add (self); message.To.Add (self); message.Body = body; using (var ctx = CreateContext ()) { Assert.IsTrue (ctx.CanEncrypt (self)); message.Encrypt (ctx); Assert.IsInstanceOf<ApplicationPkcs7Mime> (message.Body, "The message body should be an application/pkcs7-mime part."); var encrypted = (ApplicationPkcs7Mime) message.Body; Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); var decrypted = encrypted.Decrypt (ctx); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type."); Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original."); } } [Test] public virtual void TestSecureMimeEncryption () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." }; var recipients = new CmsRecipientCollection (); recipients.Add (new CmsRecipient (MimeKitCertificate, SubjectIdentifierType.SubjectKeyIdentifier)); var encrypted = ApplicationPkcs7Mime.Encrypt (recipients, body); Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); var decrypted = encrypted.Decrypt (); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type."); Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original."); } [Test] public virtual void TestSecureMimeEncryptionWithContext () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." }; using (var ctx = CreateContext ()) { var recipients = new CmsRecipientCollection (); if (ctx is WindowsSecureMimeContext) recipients.Add (new CmsRecipient (MimeKitCertificate.AsX509Certificate2 (), SubjectIdentifierType.SubjectKeyIdentifier)); else recipients.Add (new CmsRecipient (MimeKitCertificate, SubjectIdentifierType.SubjectKeyIdentifier)); var encrypted = ApplicationPkcs7Mime.Encrypt (ctx, recipients, body); Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); using (var stream = new MemoryStream ()) { ctx.DecryptTo (encrypted.Content.Open (), stream); stream.Position = 0; var decrypted = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type."); Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original."); } } } [Test] public virtual void TestSecureMimeEncryptionWithAlgorithm () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." }; using (var ctx = CreateContext ()) { var recipients = new CmsRecipientCollection (); if (ctx is WindowsSecureMimeContext) recipients.Add (new CmsRecipient (MimeKitCertificate.AsX509Certificate2 (), SubjectIdentifierType.SubjectKeyIdentifier)); else recipients.Add (new CmsRecipient (MimeKitCertificate, SubjectIdentifierType.SubjectKeyIdentifier)); foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) { foreach (var recipient in recipients) recipient.EncryptionAlgorithms = new EncryptionAlgorithm[] { algorithm }; var enabled = ctx.IsEnabled (algorithm); ApplicationPkcs7Mime encrypted; // Note: these are considered weaker than 3DES and so we need to disable 3DES to use them switch (algorithm) { case EncryptionAlgorithm.Idea: case EncryptionAlgorithm.Des: case EncryptionAlgorithm.RC2128: case EncryptionAlgorithm.RC264: case EncryptionAlgorithm.RC240: ctx.Disable (EncryptionAlgorithm.TripleDes); break; } if (!enabled) { // make sure the algorithm is enabled ctx.Enable (algorithm); } try { encrypted = ApplicationPkcs7Mime.Encrypt (ctx, recipients, body); } catch (NotSupportedException ex) { if (ctx is WindowsSecureMimeContext) { switch (algorithm) { case EncryptionAlgorithm.Camellia128: case EncryptionAlgorithm.Camellia192: case EncryptionAlgorithm.Camellia256: case EncryptionAlgorithm.Blowfish: case EncryptionAlgorithm.Twofish: case EncryptionAlgorithm.Cast5: case EncryptionAlgorithm.Idea: case EncryptionAlgorithm.Seed: break; default: Assert.Fail ("{0} does not support {1}: {2}", ctx.GetType ().Name, algorithm, ex.Message); break; } } else { if (algorithm != EncryptionAlgorithm.Twofish) Assert.Fail ("{0} does not support {1}: {2}", ctx.GetType ().Name, algorithm, ex.Message); } continue; } catch (Exception ex) { Assert.Fail ("{0} does not support {1}: {2}", ctx.GetType ().Name, algorithm, ex.Message); continue; } finally { if (!enabled) { ctx.Enable (EncryptionAlgorithm.TripleDes); ctx.Disable (algorithm); } } Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); using (var stream = new MemoryStream ()) { ctx.DecryptTo (encrypted.Content.Open (), stream); stream.Position = 0; var decrypted = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type."); Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original."); } } } } [TestCase (DigestAlgorithm.Sha1)] [TestCase (DigestAlgorithm.Sha256)] [TestCase (DigestAlgorithm.Sha384)] [TestCase (DigestAlgorithm.Sha512)] public virtual void TestSecureMimeEncryptionWithRsaesOaep (DigestAlgorithm hashAlgorithm) { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." }; using (var ctx = CreateContext ()) { var recipients = new CmsRecipientCollection (); var recipient = new CmsRecipient (MimeKitCertificate, SubjectIdentifierType.IssuerAndSerialNumber); recipient.EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.Aes128 }; recipient.RsaEncryptionPadding = RsaEncryptionPadding.CreateOaep (hashAlgorithm); recipients.Add (recipient); ApplicationPkcs7Mime encrypted; try { encrypted = ApplicationPkcs7Mime.Encrypt (ctx, recipients, body); } catch (NotSupportedException) { if (!(ctx is WindowsSecureMimeContext)) Assert.Fail ("RSAES-OAEP should be supported."); return; } Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); using (var stream = new MemoryStream ()) { ctx.DecryptTo (encrypted.Content.Open (), stream); stream.Position = 0; var decrypted = MimeEntity.Load (stream); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type."); Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original."); } } } [Test] public void TestSecureMimeDecryptThunderbird () { var p12 = Path.Combine ("..", "..", "TestData", "smime", "gnome.p12"); MimeMessage message; if (!File.Exists (p12)) return; using (var file = File.OpenRead (Path.Combine ("..", "..", "TestData", "smime", "thunderbird-encrypted.txt"))) { var parser = new MimeParser (file, MimeFormat.Default); message = parser.ParseMessage (); } using (var ctx = CreateContext ()) { var encrypted = (ApplicationPkcs7Mime) message.Body; MimeEntity decrypted = null; using (var file = File.OpenRead (p12)) { ctx.Import (file, "no.secret"); } var type = encrypted.ContentType.Parameters["smime-type"]; Assert.AreEqual ("enveloped-data", type, "Unexpected smime-type parameter."); try { decrypted = encrypted.Decrypt (ctx); } catch (Exception ex) { Console.WriteLine (ex); Assert.Fail ("Failed to decrypt thunderbird message: {0}", ex); } // The decrypted part should be a multipart/mixed with a text/plain part and an image attachment, // very much like the thunderbird-signed.txt message. Assert.IsInstanceOf<Multipart> (decrypted, "Expected the decrypted part to be a Multipart."); var multipart = (Multipart) decrypted; Assert.IsInstanceOf<TextPart> (multipart[0], "Expected the first part of the decrypted multipart to be a TextPart."); Assert.IsInstanceOf<MimePart> (multipart[1], "Expected the second part of the decrypted multipart to be a MimePart."); } } [Test] public virtual void TestSecureMimeSignAndEncrypt () { var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." }; var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", MimeKitFingerprint); var message = new MimeMessage { Subject = "Test of signing and encrypting with S/MIME" }; ApplicationPkcs7Mime encrypted; message.From.Add (self); message.To.Add (self); message.Body = body; using (var ctx = CreateContext ()) { message.SignAndEncrypt (ctx); Assert.IsInstanceOf<ApplicationPkcs7Mime> (message.Body, "The message body should be an application/pkcs7-mime part."); encrypted = (ApplicationPkcs7Mime) message.Body; Assert.AreEqual (SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match."); } using (var ctx = CreateContext ()) { var decrypted = encrypted.Decrypt (ctx); // The decrypted part should be a multipart/signed Assert.IsInstanceOf<MultipartSigned> (decrypted, "Expected the decrypted part to be a multipart/signed."); var signed = (MultipartSigned) decrypted; Assert.IsInstanceOf<TextPart> (signed[0], "Expected the first part of the multipart/signed to be a multipart."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (signed[1], "Expected second part of the multipart/signed to be a pkcs7-signature."); var extracted = (TextPart) signed[0]; Assert.AreEqual (body.Text, extracted.Text, "The decrypted text part's text does not match the original."); var signatures = signed.Verify (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual (self.Name, signature.SignerCertificate.Name); Assert.AreEqual (self.Address, signature.SignerCertificate.Email); Assert.AreEqual (self.Fingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Seed)) Assert.AreEqual (EncryptionAlgorithm.Seed, algorithms[i++], "Expected SEED capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia256)) Assert.AreEqual (EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia192)) Assert.AreEqual (EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Camellia128)) Assert.AreEqual (EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Cast5)) Assert.AreEqual (EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability"); if (ctx.IsEnabled (EncryptionAlgorithm.Idea)) Assert.AreEqual (EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability"); //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability"); //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability"); //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability"); //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public void TestSecureMimeDecryptVerifyThunderbird () { var p12 = Path.Combine ("..", "..", "TestData", "smime", "gnome.p12"); MimeMessage message; if (!File.Exists (p12)) return; using (var file = File.OpenRead (Path.Combine ("..", "..", "TestData", "smime", "thunderbird-signed-encrypted.txt"))) { var parser = new MimeParser (file, MimeFormat.Default); message = parser.ParseMessage (); } using (var ctx = CreateContext ()) { var encrypted = (ApplicationPkcs7Mime) message.Body; MimeEntity decrypted = null; using (var file = File.OpenRead (p12)) { ctx.Import (file, "no.secret"); } var type = encrypted.ContentType.Parameters["smime-type"]; Assert.AreEqual ("enveloped-data", type, "Unexpected smime-type parameter."); try { decrypted = encrypted.Decrypt (ctx); } catch (Exception ex) { Console.WriteLine (ex); Assert.Fail ("Failed to decrypt thunderbird message: {0}", ex); } // The decrypted part should be a multipart/signed Assert.IsInstanceOf<MultipartSigned> (decrypted, "Expected the decrypted part to be a multipart/signed."); var signed = (MultipartSigned) decrypted; // The first part of the multipart/signed should be a multipart/mixed with a text/plain part and 2 image attachments, // very much like the thunderbird-signed.txt message. Assert.IsInstanceOf<Multipart> (signed[0], "Expected the first part of the multipart/signed to be a multipart."); Assert.IsInstanceOf<ApplicationPkcs7Signature> (signed[1], "Expected second part of the multipart/signed to be a pkcs7-signature."); var multipart = (Multipart) signed[0]; Assert.IsInstanceOf<TextPart> (multipart[0], "Expected the first part of the decrypted multipart to be a TextPart."); Assert.IsInstanceOf<MimePart> (multipart[1], "Expected the second part of the decrypted multipart to be a MimePart."); Assert.IsInstanceOf<MimePart> (multipart[2], "Expected the third part of the decrypted multipart to be a MimePart."); var signatures = signed.Verify (ctx); Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures."); var sender = message.From.Mailboxes.FirstOrDefault (); var signature = signatures[0]; if (!(ctx is WindowsSecureMimeContext) || Path.DirectorySeparatorChar == '\\') Assert.AreEqual (ThunderbirdName, signature.SignerCertificate.Name); Assert.AreEqual (sender.Address, signature.SignerCertificate.Email); Assert.AreEqual (ThunderbirdFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); var algorithms = GetEncryptionAlgorithms (signature); Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[0], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[1], "Expected AES-128 capability"); Assert.AreEqual (EncryptionAlgorithm.TripleDes, algorithms[2], "Expected Triple-DES capability"); Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[3], "Expected RC2-128 capability"); Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[4], "Expected RC2-64 capability"); Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[5], "Expected DES capability"); Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[6], "Expected RC2-40 capability"); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { if (Path.DirectorySeparatorChar == '/') Assert.IsInstanceOf<ArgumentException> (ex.InnerException); else Assert.AreEqual (ExpiredCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } } } [Test] public virtual void TestSecureMimeImportExport () { var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var mailboxes = new List<MailboxAddress> (); // we're going to export our public certificate so that we can email it to someone // so that they can then encrypt their emails to us. mailboxes.Add (self); using (var ctx = CreateContext ()) { var certsonly = ctx.Export (mailboxes); Assert.IsInstanceOf<ApplicationPkcs7Mime> (certsonly, "The exported mime part is not of the expected type."); var pkcs7mime = (ApplicationPkcs7Mime) certsonly; Assert.AreEqual (SecureMimeType.CertsOnly, pkcs7mime.SecureMimeType, "S/MIME type did not match."); using (var imported = new TemporarySecureMimeContext ()) { pkcs7mime.Import (imported); Assert.AreEqual (1, imported.certificates.Count, "Unexpected number of imported certificates."); Assert.IsFalse (imported.keys.Count > 0, "One or more of the certificates included the private key."); } } } } [TestFixture] public class SecureMimeTests : SecureMimeTestsBase { readonly TemporarySecureMimeContext ctx = new TemporarySecureMimeContext { CheckCertificateRevocation = true }; protected override SecureMimeContext CreateContext () { return ctx; } } [TestFixture] public class SecureMimeSqliteTests : SecureMimeTestsBase { class MySecureMimeContext : DefaultSecureMimeContext { public MySecureMimeContext () : base ("smime.db", "no.secret") { CheckCertificateRevocation = true; } } protected override SecureMimeContext CreateContext () { return new MySecureMimeContext (); } static SecureMimeSqliteTests () { if (File.Exists ("smime.db")) File.Delete ("smime.db"); } } #if false [TestFixture, Explicit] public class SecureMimeNpgsqlTests : SecureMimeTestsBase { protected override SecureMimeContext CreateContext () { var user = Environment.GetEnvironmentVariable ("USER"); var builder = new StringBuilder (); builder.Append ("server=localhost;"); builder.Append ("database=smime.npg;"); builder.AppendFormat ("user id={0}", user); var db = new NpgsqlCertificateDatabase (builder.ToString (), "no.secret"); return new DefaultSecureMimeContext (db); } } #endif [TestFixture] public class WindowsSecureMimeTests : SecureMimeTestsBase { protected override bool IsEnabled { get { return Path.DirectorySeparatorChar == '\\'; } } protected override SecureMimeContext CreateContext () { return new WindowsSecureMimeContext (); } protected override EncryptionAlgorithm[] GetEncryptionAlgorithms (IDigitalSignature signature) { return ((WindowsSecureMimeDigitalSignature) signature).EncryptionAlgorithms; } [Test] public override void TestCanSignAndEncrypt () { if (Path.DirectorySeparatorChar != '\\') return; base.TestCanSignAndEncrypt (); } [Test] public override void TestSecureMimeEncapsulatedSigning () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncapsulatedSigning (); } [Test] public override void TestSecureMimeEncapsulatedSigningWithContext () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncapsulatedSigningWithContext (); } [Test] public override void TestSecureMimeEncapsulatedSigningWithCmsSigner () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncapsulatedSigningWithCmsSigner (); } [Test] public override void TestSecureMimeEncapsulatedSigningWithContextAndCmsSigner () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncapsulatedSigningWithContextAndCmsSigner (); } [Test] public override void TestSecureMimeSigningWithCmsSigner () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeSigningWithCmsSigner (); } [Test] public override void TestSecureMimeSigningWithContextAndCmsSigner () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeSigningWithContextAndCmsSigner (); } [Test] public override void TestSecureMimeSigningWithRsaSsaPss () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeSigningWithRsaSsaPss (); } [Test] public override void TestSecureMimeMessageSigning () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeMessageSigning (); } [Test] public override async Task TestSecureMimeMessageSigningAsync () { if (Path.DirectorySeparatorChar != '\\') return; await base.TestSecureMimeMessageSigningAsync (); } [Test] public override void TestSecureMimeVerifyThunderbird () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeVerifyThunderbird (); } [Test] public override void TestSecureMimeMessageEncryption () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeMessageEncryption (); } [Test] public override void TestSecureMimeEncryption () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncryption (); } [Test] public override void TestSecureMimeEncryptionWithContext () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncryptionWithContext (); } [Test] public override void TestSecureMimeEncryptionWithAlgorithm () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncryptionWithAlgorithm (); } [TestCase (DigestAlgorithm.Sha1)] [TestCase (DigestAlgorithm.Sha256)] [TestCase (DigestAlgorithm.Sha384)] [TestCase (DigestAlgorithm.Sha512)] public override void TestSecureMimeEncryptionWithRsaesOaep (DigestAlgorithm hashAlgorithm) { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeEncryptionWithRsaesOaep (hashAlgorithm); } [Test] public override void TestSecureMimeSignAndEncrypt () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeSignAndEncrypt (); } [Test] public override void TestSecureMimeImportExport () { if (Path.DirectorySeparatorChar != '\\') return; base.TestSecureMimeImportExport (); } } }
42.392
193
0.716071
[ "MIT" ]
EssentialNRG/MimeKit
UnitTests/Cryptography/SecureMimeTests.cs
68,889
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Limpl { public interface IReadOnlyScanner<T> { T LookAhead(int k); T Current {get;} T Next {get;} bool End {get;} int Position {get;} } public interface IScanner<T> : IReadOnlyScanner<T> { void Initialize(IEnumerator<T> input); bool MoveNext(); T Consume(); } /// <summary>Extension methods for IScanner and IReadOnlyScanner</summary> public static class Scanner { public static string Scan(this IReadOnlyScanner<char> scanner, int length) { var sb = new StringBuilder(); for(var i = 0; i < length; ++i) sb.Append(scanner.LookAhead(i)); Debug.Assert(sb.Length==length); var s = sb.ToString(); return s; } } public class Scanner<T> : IScanner<T>, IEnumerator<T> { readonly List<T> buffer = new List<T>(); IEnumerator<T> enumerator; const int uninitializedPosition = -3; const int initializedPosition = -1; T current; int position = uninitializedPosition; public Scanner() {} public Scanner(IEnumerable<T> input) { Initialize(input.GetEnumerator()); } public T Current {get {return current;}} public T Next {get {return LookAhead(1);}} public bool End {get; private set; } public int Position {get {return position;}} public virtual void Initialize(IEnumerator<T> input) { enumerator = input ?? throw new ArgumentNullException(nameof(input)); position = initializedPosition; End = false; } public virtual T Consume() { var c = current; MoveNext(); return c; } public virtual bool MoveNext() { if (enumerator == null) throw new InvalidOperationException("Call Initialize() first"); if (buffer.Count>0) { current = buffer[0]; buffer.RemoveAt(0); position++; return true; } if (enumerator.MoveNext()) { current = enumerator.Current; position++; return true; } current = default(T); this.End = true; return false; } public virtual T LookAhead(int k) { if (k==0) return current; while (k > buffer.Count) { if (!enumerator.MoveNext()) return default(T); buffer.Add(enumerator.Current); } return buffer[k-1]; } void IDisposable.Dispose(){} object System.Collections.IEnumerator.Current{ get { return this.Current; }} void System.Collections.IEnumerator.Reset(){throw new NotSupportedException();} } }
22.290323
83
0.592258
[ "Apache-2.0" ]
vanillity/limpl
Limpl.dll/Parsing/Scanner.cs
2,766
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the docdb-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DocDB.Model { /// <summary> /// Detailed information about a DB cluster parameter group. /// </summary> public partial class DBClusterParameterGroup { private string _dbClusterParameterGroupArn; private string _dbClusterParameterGroupName; private string _dbParameterGroupFamily; private string _description; /// <summary> /// Gets and sets the property DBClusterParameterGroupArn. /// <para> /// The Amazon Resource Name (ARN) for the DB cluster parameter group. /// </para> /// </summary> public string DBClusterParameterGroupArn { get { return this._dbClusterParameterGroupArn; } set { this._dbClusterParameterGroupArn = value; } } // Check to see if DBClusterParameterGroupArn property is set internal bool IsSetDBClusterParameterGroupArn() { return this._dbClusterParameterGroupArn != null; } /// <summary> /// Gets and sets the property DBClusterParameterGroupName. /// <para> /// Provides the name of the DB cluster parameter group. /// </para> /// </summary> public string DBClusterParameterGroupName { get { return this._dbClusterParameterGroupName; } set { this._dbClusterParameterGroupName = value; } } // Check to see if DBClusterParameterGroupName property is set internal bool IsSetDBClusterParameterGroupName() { return this._dbClusterParameterGroupName != null; } /// <summary> /// Gets and sets the property DBParameterGroupFamily. /// <para> /// Provides the name of the DB parameter group family that this DB cluster parameter /// group is compatible with. /// </para> /// </summary> public string DBParameterGroupFamily { get { return this._dbParameterGroupFamily; } set { this._dbParameterGroupFamily = value; } } // Check to see if DBParameterGroupFamily property is set internal bool IsSetDBParameterGroupFamily() { return this._dbParameterGroupFamily != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// Provides the customer-specified description for this DB cluster parameter group. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } } }
32.561404
103
0.628772
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DocDB/Generated/Model/DBClusterParameterGroup.cs
3,712
C#
/* * 房间模式的用户头像 */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RoomPlayer : MonoBehaviour { public Image _vipIcon; public Text _vipLevel; public Text _winRate; public Image _headBg; public Image _head; public Image _ownerImg; public Text _name; public Text _multiple; public GameObject _vipEffect; private int _local; private bool _isOwner; public GameObject _gameWaitVipPos; public enum eRoomPlayerType{ ROOM_WIAT,// 房间玩家 GAME_WAIT,//游戏等待时玩家 }; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnDestroy(){ removeAllEvent(); } void OnEnable(){ addAllEvent(); } void OnDisable(){    removeAllEvent(); } //--------------------------一些操作------------------------------------------------------ void addAllEvent(){ //LobbyEvent.EM().AddEvent(LobbyEvent.EVENT.UPDATE_USER_INFO,onUpdataUserInfo); } void removeAllEvent(){ //LobbyEvent.EM().RemoveEvent(LobbyEvent.EVENT.UPDATE_USER_INFO); } public void updateRoomPlayer(eRoomPlayerType type,int local,int vip,float winRate,string head,bool isOwner,string name){ int vipLevel = CommonUtil.Util.getVipLevel (vip); _vipIcon.sprite = CommonUtil.Util.getSprite (CommonDefine.ResPath.VIP_ICON + vipLevel); _vipLevel.text = "" + vipLevel; if (vipLevel >= 3) { _vipEffect.gameObject.SetActive (true); } else { _vipEffect.gameObject.SetActive (false); } _local = local; _name.text = name; _headBg.sprite = CommonUtil.Util.getSpriteByLocal (local, CommonDefine.ResPath.ROOM_HEAD_BG); if (head.Contains ("http")) { //网路图片 } else { _head.sprite = CommonUtil.Util.getSprite (CommonDefine.ResPath.ROOM_HEAD); } if (type == eRoomPlayerType.ROOM_WIAT) { _winRate.text = "胜率" + winRate + "%"; _multiple.gameObject.SetActive (false); _ownerImg.gameObject.SetActive (isOwner); _isOwner = isOwner; } else if(type == eRoomPlayerType.GAME_WAIT){ // _winRate.gameObject.SetActive(false); _multiple.gameObject.SetActive (false); _ownerImg.gameObject.SetActive (false); //vip信息需要移动到头像下方 _vipIcon.transform.position = _gameWaitVipPos.transform.position; } } public void updateMultiple(int m){ _multiple.gameObject.SetActive (true); _multiple.text = "x"+m+"倍"; } public bool getIsOwner(){ return _isOwner; } public void updatePlayerReady(){ _headBg.sprite = CommonUtil.Util.getSpriteByLocal (_local, CommonDefine.ResPath.ROOM_READY_HEAD_BG); } }
23.190909
121
0.701294
[ "MIT" ]
iniwap/LianQiClient
Assets/App/View/Lobby/RoomPlayer.cs
2,640
C#
//BODY FORMAT: /// Header Byte (Specifies Format) /// Code Section /// SEH Sections using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Emit; using DataDynamics.PageFX.Common.CodeModel; using DataDynamics.PageFX.Common.CodeModel.Statements; using DataDynamics.PageFX.Common.Collections; using DataDynamics.PageFX.Common.IO; using DataDynamics.PageFX.Common.Services; using DataDynamics.PageFX.Common.TypeSystem; using DataDynamics.PageFX.Core.Metadata; using DataDynamics.PageFX.Core.Translation; namespace DataDynamics.PageFX.Core.IL { /// <summary> /// Reads method body /// </summary> internal sealed class MethodBody : IClrMethodBody { private readonly IMethod _method; private readonly int _maxStackSize; private IVariableCollection _vars; private readonly IReadOnlyList<TryCatchBlock> _protectedBlocks; private readonly ILStream _code; [Flags] private enum GenericFlags : byte { HasGenericVars = 1, HasGenericInstructions = 2, HasGenericExceptions = 4 } private GenericFlags _genericFlags; public MethodBody(IMethod method, IMethodContext context, BufferedBinaryReader reader) { if (method == null) throw new ArgumentNullException("method"); if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); _method = method; int lsb = reader.ReadUInt8(); var flags = (MethodBodyFlags)lsb; _maxStackSize = 8; var format = flags & MethodBodyFlags.FormatMask; List<SEHBlock> sehBlocks = null; switch (format) { case MethodBodyFlags.FatFormat: { byte msb = reader.ReadUInt8(); int dwordMultipleSize = (msb & 0xF0) >> 4; Debug.Assert(dwordMultipleSize == 3); // the fat header is 3 dwords _maxStackSize = reader.ReadUInt16(); int codeSize = reader.ReadInt32(); int localSig = reader.ReadInt32(); flags = (MethodBodyFlags)((msb & 0x0F) << 8 | lsb); _code = ReadCode(method, context, reader, codeSize); if ((flags & MethodBodyFlags.MoreSects) != 0) { sehBlocks = ReadSehBlocks(reader); } bool hasGenericVars; _vars = context.ResolveLocalVariables(method, localSig, out hasGenericVars); if (hasGenericVars) _genericFlags |= GenericFlags.HasGenericVars; } break; case MethodBodyFlags.TinyFormat: case MethodBodyFlags.TinyFormat1: { int codeSize = (lsb >> 2); _code = ReadCode(method, context, reader, codeSize); } break; default: throw new NotSupportedException("Not supported method body format!"); } TranslateOffsets(); if (sehBlocks != null) { _protectedBlocks = TranslateSehBlocks(method, context, sehBlocks, _code); } context.LinkDebugInfo(this); } #region Public Properties public IMethod Method { get { return _method; } } public int MaxStackSize { get { return _maxStackSize; } } public IVariableCollection LocalVariables { get { return _vars ?? (_vars = new VariableCollection()); } } public IStatementCollection Statements { get; set; } /// <summary> /// Provides translator that can be used to translate this method body using specific <see cref="ICodeProvider"/>. /// </summary> /// <returns><see cref="ITranslator"/></returns> public ITranslator CreateTranslator() { return new Translator(); } public bool HasProtectedBlocks { get { return _protectedBlocks != null && _protectedBlocks.Count > 0; } } public IReadOnlyList<TryCatchBlock> ProtectedBlocks { get { return _protectedBlocks; } } public ILStream Code { get { return _code; } } /// <summary> /// Gets all calls that can be invocated in the method. /// </summary> /// <returns></returns> public IMethod[] GetCalls() { if (_code == null) return new IMethod[0]; return _code.Where<Instruction>(x => x.FlowControl == FlowControl.Call).Select(x => x.Method).ToArray(); } public bool HasGenerics { get { return _genericFlags != 0; } } public bool HasGenericVars { get { return (_genericFlags & GenericFlags.HasGenericVars) != 0; } } public bool HasGenericInstructions { get { return (_genericFlags & GenericFlags.HasGenericInstructions) != 0; } } public bool HasGenericExceptions { get { return (_genericFlags & GenericFlags.HasGenericExceptions) != 0; } } //Number of compilations public int InstanceCount { get; set; } public ControlFlowGraph ControlFlowGraph { get; set; } #endregion public void SetSequencePoints(IEnumerable<SequencePoint> points) { if (points == null) return; var code = Code; foreach (var p in points) { if (p == null) continue; var instr = code.FindByOffset(p.Offset); if (instr != null) instr.SequencePoint = p; } } #region Private Members private ILStream ReadCode(IMethod method, IMethodContext context, byte[] code) { return ReadCode(method, context, new BufferedBinaryReader(code), code.Length); } private ILStream ReadCode(IMethod method, IMethodContext context, BufferedBinaryReader reader, int codeSize) { var list = new ILStream(); var startPos = reader.Position; int offset = 0; while (offset < codeSize) { var pos = reader.Position; var instr = ReadInstruction(method, context, reader, startPos); var size = reader.Position - pos; offset += (int)size; instr.Index = list.Count; list.Add(instr); if (!HasGenericInstructions && instr.IsGenericContext) _genericFlags |= GenericFlags.HasGenericInstructions; } return list; } private static Instruction ReadInstruction(IMethod method, IMethodContext context, BufferedBinaryReader reader, long startPosition) { var instr = new Instruction { Offset = (int)(reader.Position - startPosition), OpCode = OpCodes.Nop }; byte op = reader.ReadUInt8(); OpCode? opCode; if (op != CIL.MultiBytePrefix) { opCode = CIL.GetShortOpCode(op); } else { op = reader.ReadUInt8(); opCode = CIL.GetLongOpCode(op); } if (!opCode.HasValue) throw new BadImageFormatException(string.Format("The format of instruction with code {0} is invalid", op)); instr.OpCode = opCode.Value; //Read operand switch (instr.OpCode.OperandType) { case OperandType.InlineI: instr.Value = reader.ReadInt32(); break; case OperandType.ShortInlineI: instr.Value = (int)reader.ReadSByte(); break; case OperandType.InlineI8: instr.Value = reader.ReadInt64(); break; case OperandType.InlineR: instr.Value = reader.ReadDouble(); break; case OperandType.ShortInlineR: instr.Value = reader.ReadSingle(); break; case OperandType.InlineBrTarget: { int offset = reader.ReadInt32(); instr.Value = (int)(offset + reader.Position - startPosition); } break; case OperandType.ShortInlineBrTarget: { int offset = reader.ReadSByte(); instr.Value = (int)(offset + reader.Position - startPosition); } break; case OperandType.InlineSwitch: { int casesCount = reader.ReadInt32(); var switchBranches = new int[casesCount]; for (int k = 0; k < casesCount; k++) switchBranches[k] = reader.ReadInt32(); int shift = (int)(reader.Position - startPosition); for (int k = 0; k < casesCount; k++) switchBranches[k] += shift; instr.Value = switchBranches; } break; case OperandType.InlineVar: instr.Value = (int)reader.ReadUInt16(); break; case OperandType.ShortInlineVar: instr.Value = reader.ReadByte(); break; case OperandType.InlineString: { int token = reader.ReadInt32(); instr.Value = context.ResolveMetadataToken(method, token); } break; case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineSig: case OperandType.InlineTok: case OperandType.InlineType: { int token = reader.ReadInt32(); instr.MetadataToken = token; object val = context.ResolveMetadataToken(method, token); if (val is ITypeMember) { } if (val == null) { #if DEBUG if (DebugHooks.BreakInvalidMetadataToken) { Debugger.Break(); val = context.ResolveMetadataToken(method, token); } #endif throw new BadTokenException(token); } instr.Value = val; } break; case OperandType.InlineNone: // no operand break; case OperandType.InlinePhi: throw new BadImageFormatException(@"Obsolete. The InlinePhi operand is reserved and should not be used!"); } return instr; } #region ReadSehBlocks [Flags] private enum SectionFlags { EHTable = 0x01, OptILTable = 0x02, FatFormat = 0x40, MoreSects = 0x80, } private static List<SEHBlock> ReadSehBlocks(BufferedBinaryReader reader) { const int FatSize = 24; const int TinySize = 12; var blocks = new List<SEHBlock>(); bool next = true; while (next) { // Goto 4 byte boundary (each section has to start at 4 byte boundary) reader.Align4(); uint header = reader.ReadUInt32(); var sf = (SectionFlags)(header & 0xFF); int size = (int)(header >> 8); //in bytes if ((sf & SectionFlags.OptILTable) != 0) { } else if ((sf & SectionFlags.FatFormat) == 0) { // tiny header size &= 0xFF; // 1 byte size (filter out the padding) int n = size / TinySize; for (int i = 0; i < n; ++i) { var block = new SEHBlock(reader, false); blocks.Add(block); } } else { //make sure this is an exception block , otherwise skip if ((sf & SectionFlags.EHTable) != 0) { int n = size / FatSize; for (int i = 0; i < n; ++i) { var block = new SEHBlock(reader, true); blocks.Add(block); } } else { reader.Position += size; } } next = (sf & SectionFlags.MoreSects) != 0; } return blocks; } #endregion #region TranslateOffsets //Translates branch offsets to instruction indicies void TranslateOffsets() { var list = Code; //#if DEBUG // CIL.UpdateCoverage(list); //#endif list.TranslateOffsets(); } #endregion #region TranslateSehBlocks private HandlerBlock CreateHandlerBlock(IMethod method, IMethodContext context, IInstructionList code, SEHBlock block) { switch (block.Type) { case SEHFlags.Catch: { int token = block.Value; var type = context.ResolveType(method, token); if (!HasGenericExceptions && type.IsGenericContext()) _genericFlags |= GenericFlags.HasGenericExceptions; var h = new HandlerBlock(BlockType.Catch) { ExceptionType = type }; return h; } case SEHFlags.Filter: { var h = new HandlerBlock(BlockType.Filter) { FilterIndex = code.GetOffsetIndex(block.Value) }; return h; } case SEHFlags.Finally: return new HandlerBlock(BlockType.Finally); case SEHFlags.Fault: return new HandlerBlock(BlockType.Fault); default: throw new IndexOutOfRangeException(); } } private static Block FindParent(IEnumerable<TryCatchBlock> list, Block block) { return list.FirstOrDefault(parent => parent != block && (block.EntryIndex >= parent.EntryIndex && block.ExitIndex <= parent.ExitIndex)); } private static void SetupInstructions(ILStream code, Block block) { foreach (var kid in block.Kids) { SetupInstructions(code, kid); } var tryBlock = block as TryCatchBlock; if (tryBlock != null) { foreach (var h in tryBlock.Handlers.Cast<HandlerBlock>()) { SetupInstructions(code, h); } } block.SetupInstructions(code); } private static int GetIndex(ILStream code, int offset, int length) { int index = code.GetOffsetIndex(offset + length); if (index == code.Count - 1) { return index; } index--; return index >= 0 ? index : code.Count - 1; } private static TryCatchBlock CreateTryBlock(ILStream code, int tryOffset, int tryLength) { int entryIndex = code.GetOffsetIndex(tryOffset); int exitIndex = GetIndex(code, tryOffset, tryLength); var tryBlock = new TryCatchBlock { EntryPoint = code[entryIndex], ExitPoint = code[exitIndex] }; return tryBlock; } private IReadOnlyList<TryCatchBlock> TranslateSehBlocks(IMethod method, IMethodContext context, IList<SEHBlock> blocks, ILStream code) { var list = new List<TryCatchBlock>(); var handlers = new BlockList(); TryCatchBlock tryBlock = null; int n = blocks.Count; for (int i = 0; i < n; ++i) { var block = blocks[i]; tryBlock = EnshureTryBlock(blocks, i, tryBlock, code, block, list); var handler = CreateHandlerBlock(method, context, code, block); int entryIndex = code.GetOffsetIndex(block.HandlerOffset); int exitIndex = GetIndex(code, block.HandlerOffset, block.HandlerLength); handler.EntryPoint = code[entryIndex]; handler.ExitPoint = code[exitIndex]; tryBlock.Handlers.Add(handler); handlers.Add(handler); } //set parents for (int i = 0; i < list.Count; ++i) { var block = list[i]; var parent = FindParent(list, block); if (parent != null) { parent.Add(block); list.RemoveAt(i); --i; } } foreach (var block in list) { SetupInstructions(code, block); } return list.AsReadOnlyList(); } private static TryCatchBlock EnshureTryBlock(IList<SEHBlock> blocks, int i, TryCatchBlock tryBlock, ILStream code, SEHBlock block, ICollection<TryCatchBlock> list) { if (tryBlock == null) { tryBlock = CreateTryBlock(code, block.TryOffset, block.TryLength); list.Add(tryBlock); } else { var prev = blocks[i - 1]; if (prev.TryOffset != block.TryOffset || prev.TryLength != block.TryLength) { tryBlock = CreateTryBlock(code, block.TryOffset, block.TryLength); list.Add(tryBlock); } } return tryBlock; } #endregion #endregion public override string ToString() { return _method.DeclaringType.FullName + "." + _method.Name; } /// <summary> /// IL method body flags /// </summary> [Flags] private enum MethodBodyFlags { None = 0, /// <summary> /// Small Code /// </summary> SmallFormat = 0x00, /// <summary> /// Tiny code format (use this code if the code size is even) /// </summary> TinyFormat = 0x02, /// <summary> /// Fat code format /// </summary> FatFormat = 0x03, /// <summary> /// Use this code if the code size is odd /// </summary> TinyFormat1 = 0x06, /// <summary> /// Mask for extract code type /// </summary> FormatMask = 0x07, /// <summary> /// Runtime call default constructor on all local vars /// </summary> InitLocals = 0x10, /// <summary> /// There is another attribute after this one /// </summary> MoreSects = 0x08, } } }
32.224299
172
0.47907
[ "MIT" ]
GrapeCity/pagefx
source/libs/Core/IL/MethodBody.cs
20,688
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.DirectX.UnitTests; /// <summary>Provides validation of the <see cref="ID2D1ComputeInfo" /> struct.</summary> public static unsafe partial class ID2D1ComputeInfoTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ID2D1ComputeInfo" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ID2D1ComputeInfo).GUID, Is.EqualTo(IID_ID2D1ComputeInfo)); } /// <summary>Validates that the <see cref="ID2D1ComputeInfo" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ID2D1ComputeInfo>(), Is.EqualTo(sizeof(ID2D1ComputeInfo))); } /// <summary>Validates that the <see cref="ID2D1ComputeInfo" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ID2D1ComputeInfo).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ID2D1ComputeInfo" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ID2D1ComputeInfo), Is.EqualTo(8)); } else { Assert.That(sizeof(ID2D1ComputeInfo), Is.EqualTo(4)); } } }
35.352941
145
0.689407
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/DirectX/um/d2d1effectauthor/ID2D1ComputeInfoTests.cs
1,805
C#
// ====================================================================== // // Copyright (C) 2018-2068 湖南心莱信息科技有限公司 // All rights reserved // // filename : FromMessageBase.cs // description : // // created by codelove1314@live.cn at 2021-02-09 10:48:27 // Blog:http://www.cnblogs.com/codelove/ // GitHub : https://github.com/xin-lai // Home:http://xin-lai.com // // ======================================================================= namespace Magicodes.Wx.PublicAccount.Sdk.AspNet.ServerMessages.From { using Magicodes.Wx.Sdk.Core.Helper; using System; using System.Xml.Serialization; /// <summary> /// Defines the <see cref="FromMessageBase" /> /// </summary> [XmlRoot("xml")] [Serializable] public abstract class FromMessageBase : IFromMessage { /// <summary> /// Gets or sets the ToUserName /// 开发者微信号 /// </summary> [XmlElement("ToUserName")] public string ToUserName { get; set; } /// <summary> /// Gets or sets the FromUserName /// 发送方帐号(一个OpenID) /// </summary> [XmlElement("FromUserName")] public string FromUserName { get; set; } /// <summary> /// Gets or sets the CreateTimestamp /// </summary> [XmlElement("CreateTime")] internal long CreateTimestamp { get; set; } /// <summary> /// Gets the CreateDateTime /// 创建时间 /// </summary> [XmlIgnore] public DateTime CreateDateTime => CreateTimestamp > 0 ? CreateTimestamp.ConvertToDateTime() : default(DateTime); /// <summary> /// Gets or sets the Type /// 消息类型 /// </summary> [XmlElement("MsgType")] public FromMessageTypes Type { get; set; } /// <summary> /// Gets or sets the MessageId /// 消息id,64位整型 /// </summary> [XmlElement("MsgId")] public string MessageId { get; set; } } }
29.242857
120
0.507572
[ "MIT" ]
xin-lai/Magicodes.Wx.Sdk
src/Magicodes.Wx.PublicAccount.Sdk.AspNet/ServerMessages/From/FromMessageBase.cs
2,137
C#
namespace bgTeam.ProduceMessages { public interface IDictionaryConfig { string EntityType { get; set; } string EntityKey { get; set; } string Description { get; set; } string DateFormatStart { get; set; } int? DateChangeOffset { get; set; } int? GroupOrderBy { get; set; } string GroupName { get; set; } int Pool { get; set; } string SqlString { get; } } }
18.75
44
0.562222
[ "MIT" ]
101stounarm101/bgTeam.Core
src/bgTeam.Core.Esb/ProduceMessages/IDictionaryConfig.cs
452
C#
using SecKill.Model; using System.Threading.Tasks; namespace SecKill.Helper { internal static class TaskException { public static void LogExcetion(this Task task) { task.ContinueWith(t => { var aggException = t.Exception.Flatten(); foreach (var ex in aggException.InnerExceptions) { LogModel.UpdateLogStr(ex.Message); } }, TaskContinuationOptions.OnlyOnFaulted); } } }
25.095238
64
0.550285
[ "MIT" ]
SinnoSong/SecKill
SecKill/Helper/TaskException.cs
529
C#
using Abp.Application.Navigation; using Abp.Localization; using Xn.Authorization; namespace Xn.Web.Startup { /// <summary> /// This class defines menus for the application. /// </summary> public class XnNavigationProvider : NavigationProvider { public override void SetNavigation(INavigationProviderContext context) { context.Manager.MainMenu .AddItem( new MenuItemDefinition( PageNames.Home, L("HomePage"), url: "", icon: "home", requiresAuthentication: true ) ).AddItem( new MenuItemDefinition( PageNames.Tenants, L("Tenants"), url: "Tenants", icon: "business", requiredPermissionName: PermissionNames.Pages_Tenants ) ).AddItem( new MenuItemDefinition( PageNames.Users, L("Users"), url: "Users", icon: "people", requiredPermissionName: PermissionNames.Pages_Users ) ).AddItem( new MenuItemDefinition( PageNames.Roles, L("Roles"), url: "Roles", icon: "local_offer", requiredPermissionName: PermissionNames.Pages_Roles ) ) .AddItem( new MenuItemDefinition( PageNames.About, L("About"), url: "About", icon: "info" ) ) .AddItem( new MenuItemDefinition( PageNames.Company, L("Công Ty"), url: "company", icon: "account_balance" ) ) .AddItem( new MenuItemDefinition( PageNames.Nhap, L("Nhập Hàng"), url: "nhap", icon: "account_balance" ) ) .AddItem( new MenuItemDefinition( PageNames.Report, L("Báo Cáo"), url: "report", icon: "insert_chart" ) ) .AddItem( new MenuItemDefinition( PageNames.Xuat, L("Xuất Hàng"), url: "xuat", icon: "account_balance" ) ) .AddItem( new MenuItemDefinition( PageNames.Company, L("Nhà Cung Cấp"), url: "ncc", icon: "account_balance" ) ) .AddItem( new MenuItemDefinition( PageNames.Company, L("Angular"), url: "angular", icon: "account_balance" ) ).AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "MultiLevelMenu", L("MultiLevelMenu"), icon: "menu" ).AddItem( new MenuItemDefinition( "AspNetBoilerplate", new FixedLocalizableString("ASP.NET Boilerplate") ).AddItem( new MenuItemDefinition( "AspNetBoilerplateHome", new FixedLocalizableString("Home"), url: "https://aspnetboilerplate.com?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateTemplates", new FixedLocalizableString("Templates"), url: "https://aspnetboilerplate.com/Templates?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateSamples", new FixedLocalizableString("Samples"), url: "https://aspnetboilerplate.com/Samples?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateDocuments", new FixedLocalizableString("Documents"), url: "https://aspnetboilerplate.com/Pages/Documents?ref=abptmpl" ) ) ).AddItem( new MenuItemDefinition( "AspNetZero", new FixedLocalizableString("ASP.NET Zero") ).AddItem( new MenuItemDefinition( "AspNetZeroHome", new FixedLocalizableString("Home"), url: "https://aspnetzero.com?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetZeroDescription", new FixedLocalizableString("Description"), url: "https://aspnetzero.com/?ref=abptmpl#description" ) ).AddItem( new MenuItemDefinition( "AspNetZeroFeatures", new FixedLocalizableString("Features"), url: "https://aspnetzero.com/?ref=abptmpl#features" ) ).AddItem( new MenuItemDefinition( "AspNetZeroPricing", new FixedLocalizableString("Pricing"), url: "https://aspnetzero.com/?ref=abptmpl#pricing" ) ).AddItem( new MenuItemDefinition( "AspNetZeroFaq", new FixedLocalizableString("Faq"), url: "https://aspnetzero.com/Faq?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetZeroDocuments", new FixedLocalizableString("Documents"), url: "https://aspnetzero.com/Documents?ref=abptmpl" ) ) ) ); } private static ILocalizableString L(string name) { return new LocalizableString(name, XnConsts.LocalizationSourceName); } } }
41.473404
96
0.361934
[ "MIT" ]
nguyen2504/XnBoiler
aspnet-core/src/Xn.Web.Mvc/Startup/XnNavigationProvider.cs
7,811
C#
using System.Data.Entity; namespace Smi.DataAccess { public interface IAccountDbContext { IDatabase Database { get; } DbSet<Account> Account { get; set; } DbSet<AccountOwners> AccountOwners { get; set; } DbSet<Users> Users { get; set; } } }
24.75
57
0.599327
[ "MIT" ]
mishrsud/CSharpApplicationSamples
CustomSqlWithEntityFramework/SqlWithEf/src/Smi.DataAccess/IAccountDbContext.cs
299
C#
using System; using System.Threading.Tasks; using Amplified.Monads.Internal.Extensions; using JetBrains.Annotations; namespace Amplified.Monads.Extensions { public static class MaybeMapAsync { public static AsyncMaybe<TResult> MapAsync<T, TResult>( this Maybe<T> source, [InstantHandle, NotNull] Func<T, Task<TResult>> mapper) { return source.Match( some => mapper(some).Then(Maybe<TResult>.Some), none => Task.FromResult(Maybe<TResult>.None()) ).ToAsyncMaybe(); } } }
29.25
67
0.620513
[ "MIT" ]
Nillerr/Amplified.Monads.Maybe
Amplified.Monads.Maybe/src/Extensions/Maybe/Async/MaybeMapAsync.cs
585
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.Commands.Automation.Model; using System; using System.Management.Automation; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Automation.Cmdlet { /// <summary> /// Gets azure automation job stream record for a given job. /// </summary> [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "AutomationJobOutputRecord")] [OutputType(typeof(JobStreamRecord))] public class GetAzureAutomationJobOutputRecord : AzureAutomationBaseCmdlet { /// <summary> /// Gets or sets the job id /// </summary> [Parameter(Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "The job Id")] public Guid JobId { get; set; } /// <summary> /// Gets or sets the job stream record id /// </summary> [Alias("StreamRecordId")] [Parameter(Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "The stream record id")] [ValidateNotNullOrEmpty] public string Id { get; set; } /// <summary> /// Execute this cmdlet. /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] protected override void AutomationProcessRecord() { var ret = this.AutomationClient.GetJobStreamRecord(this.ResourceGroupName, this.AutomationAccountName, this.JobId, this.Id); this.GenerateCmdletOutput(ret); } } }
43.888889
137
0.607595
[ "MIT" ]
3quanfeng/azure-powershell
src/Automation/Automation/Cmdlet/GetAzureAutomationJobOutputRecord.cs
2,319
C#
using Infrastructure.Enumeration; using System; using System.Collections.Generic; using System.Text; namespace eShop.Payment.Payment { public class Status : Enumeration<Status, string> { public static Status Submitted = new Status("SUBMITTED", "Submitted", "Payment has been submitted"); public static Status Settled = new Status("SETTLED", "Settled", "Paymnet fully completed"); public static Status Cancelled = new Status("CANCELLED", "Cancelled", "The payment was cancelled"); public Status(string value, string displayName, string description) : base(value, displayName) { this.Description = description; } public string Description { get; private set; } } }
33.954545
108
0.688086
[ "MIT" ]
charlessolar/eShopOnContainersDDD
src/Contexts/Payment/Language/Payment/Status.cs
749
C#
using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Honeti; using NumberConversions; using UnityEngine; using UnityEngine.UI; using SilknowMap; using UnityEngine.UI.Extensions; using Debug = UnityEngine.Debug; public class TimeSlider : MonoBehaviour { public Slider slider; public Text sliderText; public GameObject missingDataText; [SerializeField] private List<TimeElement> currentValues; // Start is called before the first frame update private void OnEnable() { slider.onValueChanged.RemoveAllListeners(); slider.onValueChanged.AddListener(HandleValueChanged); sliderText.text = I18N.instance.gameLang == LanguageCode.EN ? NumericConversions.AddOrdinal((int) slider.value) : NumericConversions.ArabicToRoman((int) slider.value); if (currentValues == null) currentValues = new List<TimeElement>(); } public void initSliderOnShow() { if (currentValues.Count < 1) { missingDataText.SetActive(true); slider.gameObject.SetActive(false); return; } missingDataText.SetActive(false); slider.gameObject.SetActive(true); HandleValueChanged(slider.value); } private void HandleValueChanged(float value) { var crono = Stopwatch.StartNew(); UpdateTimeFrame(value); //Debug.Log($"UpdateTimeFrame {crono.ElapsedMilliseconds * 0.001f} segundos"); //sliderText.text = slider.value.ToString(CultureInfo.InvariantCulture); sliderText.text = I18N.instance.gameLang == LanguageCode.EN ? NumericConversions.AddOrdinal((int) slider.value) : NumericConversions.ArabicToRoman((int) slider.value); } private void UpdateTimeFrame(float value) { var crono = Stopwatch.StartNew(); var selectedCentury = currentValues.Find(t => t.century == (int) value); //Debug.Log($"currentValues.Find {crono.ElapsedMilliseconds * 0.001f} segundos"); if (selectedCentury != null) { //Debug.LogFormat("Llamo a ActivateTimeFrame from:{0} to {1}",selectedCentury.@from,selectedCentury.to); crono = Stopwatch.StartNew(); SilkMap.instance.map.activateTimeFrame(selectedCentury.@from, selectedCentury.to); //Debug.Log($"activateTimeFrame {crono.ElapsedMilliseconds * 0.001f} segundos"); AnalyticsMonitor.instance.sendEvent("Timeline_Update", new Dictionary<string, object> {{"from", selectedCentury.@from}, {"to", selectedCentury.to}}); } else { var timeElement = APIManager.instance.timeValues.First(t => t.Value.century == (int) value).Value; //Debug.LogFormat("OCULTAR: Llamo a ActivateTimeFrame from:{0} to {1}",timeElement.@from,timeElement.to); SilkMap.instance.map.activateTimeFrame(timeElement.@from, timeElement.to); } } public void SetPropertyValues(Property timeProp) { var values = timeProp.getPossibleValues(); if (currentValues == null) currentValues = new List<TimeElement>(); else currentValues.Clear(); if (values.Count < 1) return; foreach (var val in values) { if (APIManager.instance.timeValues.TryGetValue(val, out var timeElement)) currentValues.Add(timeElement); } currentValues = currentValues.OrderBy(t => t.century).ToList(); slider.minValue = currentValues.Min(t => t.century); slider.maxValue = currentValues.Max(t => t.century); } }
35.285714
118
0.65803
[ "Apache-2.0" ]
silknow/silkmap
Assets/scripts/TimeSlider.cs
3,707
C#
namespace GraphQLTest.Models { public class Address { public string City { get; set; } public string Street { get; set; } } }
17.222222
42
0.580645
[ "MIT" ]
saeedeldah/GraphQL
GraphQLTest/GraphQLTest/Models/Address.cs
157
C#
// // System.Net.NetworkInformation.IcmpV6Statistics // // Authors: // Gonzalo Paniagua Javier (gonzalo@novell.com) // Atsushi Enomoto (atsushi@ximian.com) // // Copyright (c) 2006-2007 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Collections.Specialized; using System.Globalization; using System.Runtime.InteropServices; namespace System.Net.NetworkInformation { public abstract class IcmpV6Statistics { protected IcmpV6Statistics () { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } class MibIcmpV6Statistics : IcmpV6Statistics { StringDictionary dic; public MibIcmpV6Statistics (StringDictionary dic) { this.dic = dic; } long Get (string name) { return dic [name] != null ? long.Parse (dic [name], NumberFormatInfo.InvariantInfo) : 0; } public override long DestinationUnreachableMessagesReceived { get { return Get ("InDestUnreachs"); } } public override long DestinationUnreachableMessagesSent { get { return Get ("OutDestUnreachs"); } } public override long EchoRepliesReceived { get { return Get ("InEchoReplies"); } } public override long EchoRepliesSent { get { return Get ("OutEchoReplies"); } } public override long EchoRequestsReceived { get { return Get ("InEchos"); } } public override long EchoRequestsSent { get { return Get ("OutEchos"); } } public override long ErrorsReceived { get { return Get ("InErrors"); } } public override long ErrorsSent { get { return Get ("OutErrors"); } } public override long MembershipQueriesReceived { get { return Get ("InGroupMembQueries"); } } public override long MembershipQueriesSent { get { return Get ("OutGroupMembQueries"); } } public override long MembershipReductionsReceived { get { return Get ("InGroupMembReductiions"); } } public override long MembershipReductionsSent { get { return Get ("OutGroupMembReductiions"); } } public override long MembershipReportsReceived { get { return Get ("InGroupMembRespons"); } } public override long MembershipReportsSent { get { return Get ("OutGroupMembRespons"); } } public override long MessagesReceived { get { return Get ("InMsgs"); } } public override long MessagesSent { get { return Get ("OutMsgs"); } } public override long NeighborAdvertisementsReceived { get { return Get ("InNeighborAdvertisements"); } } public override long NeighborAdvertisementsSent { get { return Get ("OutNeighborAdvertisements"); } } public override long NeighborSolicitsReceived { get { return Get ("InNeighborSolicits"); } } public override long NeighborSolicitsSent { get { return Get ("OutNeighborSolicits"); } } public override long PacketTooBigMessagesReceived { get { return Get ("InPktTooBigs"); } } public override long PacketTooBigMessagesSent { get { return Get ("OutPktTooBigs"); } } public override long ParameterProblemsReceived { get { return Get ("InParmProblems"); } } public override long ParameterProblemsSent { get { return Get ("OutParmProblems"); } } public override long RedirectsReceived { get { return Get ("InRedirects"); } } public override long RedirectsSent { get { return Get ("OutRedirects"); } } public override long RouterAdvertisementsReceived { get { return Get ("InRouterAdvertisements"); } } public override long RouterAdvertisementsSent { get { return Get ("OutRouterAdvertisements"); } } public override long RouterSolicitsReceived { get { return Get ("InRouterSolicits"); } } public override long RouterSolicitsSent { get { return Get ("OutRouterSolicits"); } } public override long TimeExceededMessagesReceived { get { return Get ("InTimeExcds"); } } public override long TimeExceededMessagesSent { get { return Get ("OutTimeExcds"); } } } class IcmpV6MessageTypes { public const int DestinationUnreachable = 1; public const int PacketTooBig = 2; public const int TimeExceeded = 3; public const int ParameterProblem = 4; public const int EchoRequest = 128; public const int EchoReply = 129; public const int GroupMembershipQuery = 130; public const int GroupMembershipReport = 131; public const int GroupMembershipReduction = 132; public const int RouterSolicitation = 133; public const int RouterAdvertisement = 134; public const int NeighborSolicitation = 135; public const int NeighborAdvertisement = 136; public const int Redirect = 137; public const int RouterRenumbering = 138; } class Win32IcmpV6Statistics : IcmpV6Statistics { Win32_MIBICMPSTATS_EX iin, iout; public Win32IcmpV6Statistics (Win32_MIB_ICMP_EX info) { iin = info.InStats; iout = info.OutStats; } public override long DestinationUnreachableMessagesReceived { get { return iin.Counts [IcmpV6MessageTypes.DestinationUnreachable]; } } public override long DestinationUnreachableMessagesSent { get { return iout.Counts [IcmpV6MessageTypes.DestinationUnreachable]; } } public override long EchoRepliesReceived { get { return iin.Counts [IcmpV6MessageTypes.EchoReply]; } } public override long EchoRepliesSent { get { return iout.Counts [IcmpV6MessageTypes.EchoReply]; } } public override long EchoRequestsReceived { get { return iin.Counts [IcmpV6MessageTypes.EchoRequest]; } } public override long EchoRequestsSent { get { return iout.Counts [IcmpV6MessageTypes.EchoRequest]; } } public override long ErrorsReceived { get { return iin.Errors; } } public override long ErrorsSent { get { return iout.Errors; } } public override long MembershipQueriesReceived { get { return iin.Counts [IcmpV6MessageTypes.GroupMembershipQuery]; } } public override long MembershipQueriesSent { get { return iout.Counts [IcmpV6MessageTypes.GroupMembershipQuery]; } } public override long MembershipReductionsReceived { get { return iin.Counts [IcmpV6MessageTypes.GroupMembershipReduction]; } } public override long MembershipReductionsSent { get { return iout.Counts [IcmpV6MessageTypes.GroupMembershipReduction]; } } public override long MembershipReportsReceived { get { return iin.Counts [IcmpV6MessageTypes.GroupMembershipReport]; } } public override long MembershipReportsSent { get { return iout.Counts [IcmpV6MessageTypes.GroupMembershipReport]; } } public override long MessagesReceived { get { return iin.Msgs; } } public override long MessagesSent { get { return iout.Msgs; } } public override long NeighborAdvertisementsReceived { get { return iin.Counts [IcmpV6MessageTypes.NeighborAdvertisement]; } } public override long NeighborAdvertisementsSent { get { return iout.Counts [IcmpV6MessageTypes.NeighborAdvertisement]; } } public override long NeighborSolicitsReceived { get { return iin.Counts [IcmpV6MessageTypes.NeighborSolicitation]; } } public override long NeighborSolicitsSent { get { return iout.Counts [IcmpV6MessageTypes.NeighborSolicitation]; } } public override long PacketTooBigMessagesReceived { get { return iin.Counts [IcmpV6MessageTypes.PacketTooBig]; } } public override long PacketTooBigMessagesSent { get { return iout.Counts [IcmpV6MessageTypes.PacketTooBig]; } } public override long ParameterProblemsReceived { get { return iin.Counts [IcmpV6MessageTypes.ParameterProblem]; } } public override long ParameterProblemsSent { get { return iout.Counts [IcmpV6MessageTypes.ParameterProblem]; } } public override long RedirectsReceived { get { return iin.Counts [IcmpV6MessageTypes.Redirect]; } } public override long RedirectsSent { get { return iout.Counts [IcmpV6MessageTypes.Redirect]; } } public override long RouterAdvertisementsReceived { get { return iin.Counts [IcmpV6MessageTypes.RouterAdvertisement]; } } public override long RouterAdvertisementsSent { get { return iout.Counts [IcmpV6MessageTypes.RouterAdvertisement]; } } public override long RouterSolicitsReceived { get { return iin.Counts [IcmpV6MessageTypes.RouterSolicitation]; } } public override long RouterSolicitsSent { get { return iout.Counts [IcmpV6MessageTypes.RouterSolicitation]; } } public override long TimeExceededMessagesReceived { get { return iin.Counts [IcmpV6MessageTypes.TimeExceeded]; } } public override long TimeExceededMessagesSent { get { return iout.Counts [IcmpV6MessageTypes.TimeExceeded]; } } } struct Win32_MIB_ICMP_EX { public Win32_MIBICMPSTATS_EX InStats; public Win32_MIBICMPSTATS_EX OutStats; } struct Win32_MIBICMPSTATS_EX { public uint Msgs; public uint Errors; [MarshalAs (UnmanagedType.ByValArray, SizeConst = 256)] public uint [] Counts; } } #endif
35.091185
91
0.748029
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/class/System/System.Net.NetworkInformation/IcmpV6Statistics.cs
11,545
C#
using UnityEngine; namespace InsaneOne.Core { /// <summary>Used to handle OnTrigger* event in separated class. </summary> public interface ITriggerEnterHandler { void TriggerEnterAction(Collider entered); } }
23.4
79
0.709402
[ "MIT" ]
InsaneOneHub/Core
InsaneOne/Core/Sources/Interfaces/ITriggerEnterHandler.cs
236
C#
//----------------------------------------------------------------------- // <copyright file="SunnyWeatherSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using System.Threading; using Akka.Actor; using Akka.Cluster.TestKit; using Akka.Configuration; using Akka.Remote.TestKit; using Akka.Util; using FluentAssertions; using MultiNodeFactAttribute = Akka.MultiNode.TestAdapter.MultiNodeFactAttribute; namespace Akka.Cluster.Tests.MultiNode { public class SunnyWeatherNodeConfig : MultiNodeConfig { public RoleName First { get; set; } public RoleName Second { get; set; } public RoleName Third { get; set; } public RoleName Fourth { get; set; } public RoleName Fifth { get; set; } public SunnyWeatherNodeConfig() { First = Role("first"); Second = Role("second"); Third = Role("third"); Fourth = Role("fourth"); Fifth = Role("fifth"); CommonConfig = ConfigurationFactory.ParseString(@" akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" akka.loggers = [""Akka.TestKit.TestEventListener, Akka.TestKit""] akka.loglevel = INFO akka.remote.log-remote-lifecycle-events = off akka.cluster.failure-detector.monitored-by-nr-of-members = 3 "); } } public class SunnyWeatherSpec : MultiNodeClusterSpec { private class Listener : UntypedActor { private readonly AtomicReference<SortedSet<Member>> _unexpected; public Listener(AtomicReference<SortedSet<Member>> unexpected) { _unexpected = unexpected; } protected override void OnReceive(object message) { message.Match() .With<ClusterEvent.IMemberEvent>(evt => { _unexpected.Value.Add(evt.Member); }) .With<ClusterEvent.CurrentClusterState>(() => { // ignore }); } } private readonly SunnyWeatherNodeConfig _config; public SunnyWeatherSpec() : this(new SunnyWeatherNodeConfig()) { } protected SunnyWeatherSpec(SunnyWeatherNodeConfig config) : base(config, typeof(SunnyWeatherSpec)) { _config = config; } [MultiNodeFact] public void SunnyWeatherSpecs() { Normal_cluster_must_be_healthy(); } public void Normal_cluster_must_be_healthy() { // start some AwaitClusterUp(_config.First, _config.Second, _config.Third); RunOn(() => { Log.Debug("3 joined"); }, _config.First, _config.Second, _config.Third); // add a few more AwaitClusterUp(Roles.ToArray()); Log.Debug("5 joined"); var unexpected = new AtomicReference<SortedSet<Member>>(new SortedSet<Member>()); Cluster.Subscribe(Sys.ActorOf(Props.Create(() => new Listener(unexpected))), new[] { typeof(ClusterEvent.IMemberEvent) }); foreach (var n in Enumerable.Range(1, 30)) { EnterBarrier("period-" + n); unexpected.Value.Should().BeEmpty(); AwaitMembersUp(Roles.Count); AssertLeaderIn(Roles); if (n % 5 == 0) { Log.Debug("Passed period [{0}]", n); } Thread.Sleep(1000); } EnterBarrier("after"); } } }
31.744186
106
0.528449
[ "Apache-2.0" ]
BearerPipelineTest/akka.net
src/core/Akka.Cluster.Tests.MultiNode/SunnyWeatherSpec.cs
4,097
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute(Namespace="urn:hl7-org:v3")] public partial class CV_ObservationType : CV { private static System.Xml.Serialization.XmlSerializer serializer; private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(CV_ObservationType)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current CV_ObservationType object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an CV_ObservationType object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output CV_ObservationType object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out CV_ObservationType obj, out System.Exception exception) { exception = null; obj = default(CV_ObservationType); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out CV_ObservationType obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static CV_ObservationType Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((CV_ObservationType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current CV_ObservationType object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an CV_ObservationType object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output CV_ObservationType object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out CV_ObservationType obj, out System.Exception exception) { exception = null; obj = default(CV_ObservationType); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out CV_ObservationType obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static CV_ObservationType LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this CV_ObservationType object /// </summary> public virtual CV_ObservationType Clone() { return ((CV_ObservationType)(this.MemberwiseClone())); } #endregion } }
46.057895
1,368
0.589418
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/CV_ObservationType.cs
8,751
C#
using Xrm.Models.Interfaces; namespace Xrm.Domain.Events { public class InfiniteLoopEvent1 : IEvent { } }
12.1
44
0.68595
[ "MIT" ]
GlobalSolutions365/XrmProjectTemplateCQS
Xrm.Domain/Events/InfiniteLoopEvent1.cs
123
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// MybankCreditLoantradeLoanarRepayModel Data Structure. /// </summary> [Serializable] public class MybankCreditLoantradeLoanarRepayModel : AopObject { /// <summary> /// 贷款客户在网商的会员ID /// </summary> [XmlElement("cust_iprole_id")] public string CustIproleId { get; set; } /// <summary> /// 还款日,精确到日,格式为yyyyMMdd,必须是当天 /// </summary> [XmlElement("date")] public string Date { get; set; } /// <summary> /// 贷款合约号 /// </summary> [XmlElement("loan_ar_no")] public string LoanArNo { get; set; } /// <summary> /// 还款本金金额,单位默认为元,支持小数点两位,为了便于传输用合作方将数值型转换为字符串型 /// </summary> [XmlElement("prin_amt")] public string PrinAmt { get; set; } /// <summary> /// 外部流水号格式:日期(8位)+序列号(8位),序列号是数字,如00000001(必须是16位且符合该格式) /// </summary> [XmlElement("request_id")] public string RequestId { get; set; } } }
26.604651
67
0.534091
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/MybankCreditLoantradeLoanarRepayModel.cs
1,368
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace npva.Chart { /// <summary> /// 論理座標で場所を決める文字列ラベル /// </summary> class AxisDependantString : IDrawableObject { /// <summary> /// 軸を指定してオブジェクトを作成 /// </summary> /// <param name="axisX">依存軸X</param> /// <param name="axisY">依存軸Y</param> public AxisDependantString(Axis axisX, Axis axisY) { AxisX = axisX; AxisY = axisY; } /// <summary>依存軸X</summary> Axis AxisX; /// <summary>依存軸Y</summary> Axis AxisY; /// <summary> /// 表示位置X /// </summary> public double LogicalX { get; set; } /// <summary> /// 表示位置Y /// </summary> public double LogicalY { get; set; } /// <summary> /// 表示する文字列 /// </summary> public string Message { get; set; } /// <summary> /// ラベル及び線の色 /// </summary> public Color Color = Color.Gray; /// <summary> /// 座標に対する文字列の水平位置 /// </summary> public StringAlignment HolizontalAlign { get; set; } = StringAlignment.Near; /// <summary> /// 座標に対する文字列の垂直位置 /// </summary> public StringAlignment VerticalAlign { get; set; } = StringAlignment.Near; /// <summary> /// 水平線を引くか /// </summary> public bool DrawHolizontalLine { get; set; } = false; /// <summary> /// 垂直線を引くか /// </summary> public bool DrawVerticalLine { get; set; } = false; /// <summary> /// 描画処理の実施 /// </summary> /// <param name="context"></param> public void Draw(IDrawContext context) { //位置決め var x = AxisX.LogicalValueToPhysicalValue(LogicalX, context.PlotArea.Location); var y = AxisY.LogicalValueToPhysicalValue(LogicalY, context.PlotArea.Location); //ラベル context.DrawString(x, y, 16, Color, Message, HolizontalAlign, VerticalAlign); //水平線 if (DrawHolizontalLine) { context.DrawLine(new PointF(context.PlotArea.Left, y), new PointF(context.PlotArea.Right, y), 1, Color); } //垂直線 if (DrawVerticalLine) { context.DrawLine(new PointF(x, context.PlotArea.Top), new PointF(x, context.PlotArea.Bottom), 1, Color); } } } }
28.141304
120
0.521823
[ "MIT" ]
lordhollow/NPVA
npva/Chart/AxisDependantString.cs
2,849
C#
namespace WebApiHttpBatchServer.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
26.666667
75
0.78125
[ "MIT" ]
georgeolson/angular-http-batcher
servers/WebApi2/WebApiHttpBatchServer/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
160
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("SoonLearning.Math_Fast.SYSS300.QCSS9DS2_221")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SoonLearning.Math_Fast.SYSS300.QCSS9DS2_221")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] //若要开始生成可本地化的应用程序,请在 //<PropertyGroup> 中的 .csproj 文件中 //设置 <UICulture>CultureYouAreCodingWith</UICulture>。例如,如果您在源文件中 //使用的是美国英语,请将 <UICulture> 设置为 en-US。然后取消 //对以下 NeutralResourceLanguage 特性的注释。更新 //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //主题特定资源词典所处位置 //(在页面或应用程序资源词典中 // 未找到某个资源的情况下使用) ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 //(在页面、应用程序或任何主题特定资源词典中 // 未找到某个资源的情况下使用) )] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27.357143
91
0.742167
[ "MIT" ]
LigangSun/AppCenter
source/Apps/Math_Fast_SYSS300/221_230/SoonLearning.Math_Fast.SYSS300.QCSS9DS2_221/Properties/AssemblyInfo.cs
2,197
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ThePLeagueDomain.Models.Schedule; using ThePLeagueDomain.ViewModels.Schedule; namespace ThePLeagueDomain.Converters.Schedule { public class GameTimeConverter { #region Methods public static GameTimeViewModel Convert(GameTime gameTime) { GameTimeViewModel model = new GameTimeViewModel(); model.GamesTime = (Int64)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds; model.GameDayId = gameTime.GameDayId; model.Id = gameTime.Id; return model; } public static List<GameTimeViewModel> ConvertList(IEnumerable<GameTime> gameTimes) { return gameTimes.Select(gameTime => { GameTimeViewModel model = new GameTimeViewModel(); model.GamesTime = (Int64)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds; model.Id = gameTime.Id; model.GameDayId = gameTime.GameDayId; return model; }).ToList(); } #endregion } }
29.125
99
0.633476
[ "MIT" ]
omikolaj/the-p-league-api
ThePLeagueDomain/Converters/Schedule/GameTimeConverter.cs
1,167
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Formula1.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Formula1.iOS")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.756757
84
0.743737
[ "MIT" ]
Bhekinkosi12/XamarinFormsLayoutChallenges
Formula1/Formula1/Formula1.iOS/Properties/AssemblyInfo.cs
1,400
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100c_116a-a9b6ee12")] public void Method_100c_116a() { ii(0x100c_116a, 5); push(0x38); /* push 0x38 */ ii(0x100c_116f, 5); call(Definitions.sys_check_available_stack_size, 0xa_4bde);/* call 0x10165d52 */ ii(0x100c_1174, 1); push(ebx); /* push ebx */ ii(0x100c_1175, 1); push(ecx); /* push ecx */ ii(0x100c_1176, 1); push(edx); /* push edx */ ii(0x100c_1177, 1); push(esi); /* push esi */ ii(0x100c_1178, 1); push(edi); /* push edi */ ii(0x100c_1179, 1); push(ebp); /* push ebp */ ii(0x100c_117a, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100c_117c, 6); sub(esp, 0x1c); /* sub esp, 0x1c */ ii(0x100c_1182, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x100c_1185, 6); mov(ax, memw[ds, 0x101c_8172]); /* mov ax, [0x101c8172] */ ii(0x100c_118b, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */ ii(0x100c_118e, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100c_1191, 3); mov(eax, memd[ds, eax + 4]); /* mov eax, [eax+0x4] */ ii(0x100c_1194, 3); mov(memd[ss, ebp - 28], eax); /* mov [ebp-0x1c], eax */ ii(0x100c_1197, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100c_119a, 3); mov(eax, memd[ds, eax + 8]); /* mov eax, [eax+0x8] */ ii(0x100c_119d, 3); mov(memd[ss, ebp - 24], eax); /* mov [ebp-0x18], eax */ l_0x100c_11a0: ii(0x100c_11a0, 3); dec(memd[ss, ebp - 12]); /* dec dword [ebp-0xc] */ ii(0x100c_11a3, 5); cmp(memw[ss, ebp - 12], -1 /* 0xff */);/* cmp word [ebp-0xc], 0xffff */ ii(0x100c_11a8, 2); if(jz(0x100c_1201, 0x57)) goto l_0x100c_1201;/* jz 0x100c1201 */ ii(0x100c_11aa, 3); mov(eax, memd[ss, ebp - 28]); /* mov eax, [ebp-0x1c] */ ii(0x100c_11ad, 4); add(memd[ss, ebp - 28], 4); /* add dword [ebp-0x1c], 0x4 */ ii(0x100c_11b1, 2); mov(eax, memd[ds, eax]); /* mov eax, [eax] */ ii(0x100c_11b3, 3); mov(memd[ss, ebp - 20], eax); /* mov [ebp-0x14], eax */ ii(0x100c_11b6, 3); mov(eax, memd[ss, ebp - 24]); /* mov eax, [ebp-0x18] */ ii(0x100c_11b9, 4); add(memd[ss, ebp - 24], 4); /* add dword [ebp-0x18], 0x4 */ ii(0x100c_11bd, 2); mov(eax, memd[ds, eax]); /* mov eax, [eax] */ ii(0x100c_11bf, 3); mov(memd[ss, ebp - 16], eax); /* mov [ebp-0x10], eax */ ii(0x100c_11c2, 6); mov(ax, memw[ds, 0x101c_8174]); /* mov ax, [0x101c8174] */ ii(0x100c_11c8, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ l_0x100c_11cb: ii(0x100c_11cb, 3); dec(memd[ss, ebp - 8]); /* dec dword [ebp-0x8] */ ii(0x100c_11ce, 5); cmp(memw[ss, ebp - 8], -1 /* 0xff */);/* cmp word [ebp-0x8], 0xffff */ ii(0x100c_11d3, 2); if(jz(0x100c_11ff, 0x2a)) goto l_0x100c_11ff;/* jz 0x100c11ff */ ii(0x100c_11d5, 3); mov(eax, memd[ss, ebp - 20]); /* mov eax, [ebp-0x14] */ ii(0x100c_11d8, 3); movsx(eax, memw[ds, eax]); /* movsx eax, word [eax] */ ii(0x100c_11db, 2); test(eax, eax); /* test eax, eax */ ii(0x100c_11dd, 2); if(jge(0x100c_11ef, 0x10)) goto l_0x100c_11ef;/* jge 0x100c11ef */ ii(0x100c_11df, 3); mov(eax, memd[ss, ebp - 20]); /* mov eax, [ebp-0x14] */ ii(0x100c_11e2, 5); mov(memw[ds, eax], 0); /* mov word [eax], 0x0 */ ii(0x100c_11e7, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x100c_11ea, 5); mov(memw[ds, eax], 0); /* mov word [eax], 0x0 */ l_0x100c_11ef: ii(0x100c_11ef, 3); mov(eax, memd[ss, ebp - 20]); /* mov eax, [ebp-0x14] */ ii(0x100c_11f2, 4); add(memd[ss, ebp - 20], 2); /* add dword [ebp-0x14], 0x2 */ ii(0x100c_11f6, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x100c_11f9, 4); add(memd[ss, ebp - 16], 2); /* add dword [ebp-0x10], 0x2 */ ii(0x100c_11fd, 2); jmp(0x100c_11cb, -0x34); goto l_0x100c_11cb;/* jmp 0x100c11cb */ l_0x100c_11ff: ii(0x100c_11ff, 2); jmp(0x100c_11a0, -0x61); goto l_0x100c_11a0;/* jmp 0x100c11a0 */ l_0x100c_1201: ii(0x100c_1201, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100c_1203, 1); pop(ebp); /* pop ebp */ ii(0x100c_1204, 1); pop(edi); /* pop edi */ ii(0x100c_1205, 1); pop(esi); /* pop esi */ ii(0x100c_1206, 1); pop(edx); /* pop edx */ ii(0x100c_1207, 1); pop(ecx); /* pop ecx */ ii(0x100c_1208, 1); pop(ebx); /* pop ebx */ ii(0x100c_1209, 1); ret(); /* ret */ } } }
76.802632
114
0.444064
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100c-116a.cs
5,837
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataMigration.V20180715Preview.Outputs { [OutputType] public sealed class MigrateSqlServerSqlDbTaskPropertiesResponse { /// <summary> /// Key value pairs of client data to attach meta data information to task /// </summary> public readonly ImmutableDictionary<string, string>? ClientData; /// <summary> /// Array of command properties. /// </summary> public readonly ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> Commands; /// <summary> /// Array of errors. This is ignored if submitted. /// </summary> public readonly ImmutableArray<Outputs.ODataErrorResponse> Errors; /// <summary> /// Task input /// </summary> public readonly Outputs.MigrateSqlServerSqlDbTaskInputResponse? Input; /// <summary> /// Task output. This is ignored if submitted. /// </summary> public readonly ImmutableArray<Union<Outputs.MigrateSqlServerSqlDbTaskOutputDatabaseLevelResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputDatabaseLevelValidationResultResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputErrorResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputMigrationLevelResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputTableLevelResponse, Outputs.MigrateSqlServerSqlDbTaskOutputValidationResultResponse>>>>>> Output; /// <summary> /// The state of the task. This is ignored if submitted. /// </summary> public readonly string State; /// <summary> /// Task type. /// </summary> public readonly string TaskType; [OutputConstructor] private MigrateSqlServerSqlDbTaskPropertiesResponse( ImmutableDictionary<string, string>? clientData, ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> commands, ImmutableArray<Outputs.ODataErrorResponse> errors, Outputs.MigrateSqlServerSqlDbTaskInputResponse? input, ImmutableArray<Union<Outputs.MigrateSqlServerSqlDbTaskOutputDatabaseLevelResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputDatabaseLevelValidationResultResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputErrorResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputMigrationLevelResponse, Union<Outputs.MigrateSqlServerSqlDbTaskOutputTableLevelResponse, Outputs.MigrateSqlServerSqlDbTaskOutputValidationResultResponse>>>>>> output, string state, string taskType) { ClientData = clientData; Commands = commands; Errors = errors; Input = input; Output = output; State = state; TaskType = taskType; } } }
45.788732
462
0.716087
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/DataMigration/V20180715Preview/Outputs/MigrateSqlServerSqlDbTaskPropertiesResponse.cs
3,251
C#
using System; using System.IO; using Enumerations; using System.Collections.Generic; using System.Runtime.InteropServices; namespace LeptonicaSharp { public partial class _All { // flipdetect.c (242, 1) // pixOrientCorrect(pixs, minupconf, minratio, pupconf, pleftconf, protation, debug) as Pix // pixOrientCorrect(PIX *, l_float32, l_float32, l_float32 *, l_float32 *, l_int32 *, l_int32) as PIX * /// <summary> /// (1) Simple top-level function to detect if Roman text is in /// reading orientation, and to rotate the image accordingly if not.<para/> /// /// (2) Returns a copy if no rotation is needed.<para/> /// /// (3) See notes for pixOrientDetect() and pixOrientDecision(). /// Use 0.0 for default values for %minupconf and %minratio<para/> /// /// (4) Optional output of intermediate confidence results and /// the rotation performed on pixs. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixOrientCorrect/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text, 150 - 300 ppi</param> /// <param name="minupconf">[in] - minimum value for which a decision can be made</param> /// <param name="minratio">[in] - minimum conf ratio required for a decision</param> /// <param name="pupconf">[out][optional] - use NULL to skip</param> /// <param name="pleftconf">[out][optional] - use NULL to skip</param> /// <param name="protation">[out][optional] - use NULL to skip</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>pixd may be rotated by 90, 180 or 270 null on error</returns> public static Pix pixOrientCorrect( Pix pixs, Single minupconf, Single minratio, out Single pupconf, out Single pleftconf, out int protation, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} IntPtr _Result = Natives.pixOrientCorrect(pixs.Pointer, minupconf, minratio, out pupconf, out pleftconf, out protation, (int) debug); if (_Result == IntPtr.Zero) {return null;} return new Pix(_Result); } // flipdetect.c (370, 1) // pixOrientDetect(pixs, pupconf, pleftconf, mincount, debug) as int // pixOrientDetect(PIX *, l_float32 *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) See "Measuring document image skew and orientation" /// Dan S. Bloomberg, Gary E. Kopec and Lakshmi Dasari /// IS[and]T/SPIE EI'95, Conference 2422: Document Recognition II /// pp 302-316, Feb 6-7, 1995, San Jose, CA<para/> /// /// (2) upconf is the normalized difference between up ascenders /// and down ascenders. The image is analyzed without rotation /// for being rightside-up or upside-down. Set [and]upconf to null /// to skip this operation.<para/> /// /// (3) leftconf is the normalized difference between up ascenders /// and down ascenders in the image after it has been /// rotated 90 degrees clockwise. With that rotation, ascenders /// projecting to the left in the source image will project up /// in the rotated image. We compute this by rotating 90 degrees /// clockwise and testing for up and down ascenders. Set /// [and]leftconf to null to skip this operation.<para/> /// /// (4) Note that upconf and leftconf are not linear measures of /// confidence, e.g., in a range between 0 and 100. They /// measure how far you are out on the tail of a (presumably) /// normal distribution. For example, a confidence of 10 means /// that it is nearly certain that the difference did not /// happen at random. However, these values must be interpreted /// cautiously, taking into consideration the estimated prior /// for a particular orientation or mirror flip. The up-down /// signal is very strong if applied to text with ascenders /// up and down, and relatively weak for text at 90 degrees, /// but even at 90 degrees, the difference can look significant. /// For example, suppose the ascenders are oriented horizontally, /// but the test is done vertically. Then upconf can /// be is smaller -MIN_CONF_FOR_UP_DOWN, suggesting the text may be /// upside-down. However, if instead the test were done /// horizontally, leftconf will be very much larger /// (in absolute value), giving the correct orientation.<para/> /// /// (5) If you compute both upconf and leftconf, and there is /// sufficient signal, the following table determines the /// cw angle necessary to rotate pixs so that the text is /// rightside-up: /// 0 deg : upconf is greater is greater 1, abs(upconf) is greater is greater abs(leftconf) /// 90 deg : leftconf is greater is greater 1, abs(leftconf) is greater is greater abs(upconf) /// 180 deg : upconf is smaller is smaller -1, abs(upconf) is greater is greater abs(leftconf) /// 270 deg : leftconf is smaller is smaller -1, abs(leftconf) is greater is greater abs(upconf)<para/> /// /// (6) One should probably not interpret the direction unless /// there are a sufficient number of counts for both orientations, /// in which case neither upconf nor leftconf will be 0.0.<para/> /// /// (7) Uses rasterop implementation of HMT. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixOrientDetect/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text, 150 - 300 ppi</param> /// <param name="pupconf">[out][optional] - may be NULL</param> /// <param name="pleftconf">[out][optional] - may be NULL</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixOrientDetect( Pix pixs, out Single pupconf, out Single pleftconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixOrientDetect(pixs.Pointer, out pupconf, out pleftconf, mincount, (int) debug); return _Result; } // flipdetect.c (431, 1) // makeOrientDecision(upconf, leftconf, minupconf, minratio, porient, debug) as int // makeOrientDecision(l_float32, l_float32, l_float32, l_float32, l_int32 *, l_int32) as l_ok /// <summary> /// (1) This can be run after pixOrientDetect()<para/> /// /// (2) Both upconf and leftconf must be nonzero otherwise the /// orientation cannot be determined.<para/> /// /// (3) The abs values of the input confidences are compared to /// minupconf.<para/> /// /// (4) The abs value of the largest of (upconf/leftconf) and /// (leftconf/upconf) is compared with minratio.<para/> /// /// (5) Input 0.0 for the default values for minupconf and minratio.<para/> /// /// (6) The return value of orient is interpreted thus: /// L_TEXT_ORIENT_UNKNOWN: not enough evidence to determine /// L_TEXT_ORIENT_UP: text rightside-up /// L_TEXT_ORIENT_LEFT: landscape, text up facing left /// L_TEXT_ORIENT_DOWN: text upside-down /// L_TEXT_ORIENT_RIGHT: landscape, text up facing right /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/makeOrientDecision/*"/> /// <param name="upconf">[in] - nonzero</param> /// <param name="leftconf">[in] - nonzero</param> /// <param name="minupconf">[in] - minimum value for which a decision can be made</param> /// <param name="minratio">[in] - minimum conf ratio required for a decision</param> /// <param name="porient">[out] - text orientation enum {0,1,2,3,4}</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int makeOrientDecision( Single upconf, Single leftconf, Single minupconf, Single minratio, out int porient, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { int _Result = Natives.makeOrientDecision( upconf, leftconf, minupconf, minratio, out porient, (int) debug); return _Result; } // flipdetect.c (510, 1) // pixUpDownDetect(pixs, pconf, mincount, debug) as int // pixUpDownDetect(PIX *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) Special (typical, slightly faster) case, where the pixels /// identified through the HMT (hit-miss transform) are not /// clipped by a truncated word mask pixm. See pixOrientDetect() /// and pixUpDownDetectGeneral() for details.<para/> /// /// (2) The returned confidence is the normalized difference /// between the number of detected up and down ascenders, /// assuming that the text is either rightside-up or upside-down /// and not rotated at a 90 degree angle. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixUpDownDetect/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text, 150 - 300 ppi</param> /// <param name="pconf">[out] - confidence that text is rightside-up</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixUpDownDetect( Pix pixs, out Single pconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixUpDownDetect(pixs.Pointer, out pconf, mincount, (int) debug); return _Result; } // flipdetect.c (558, 1) // pixUpDownDetectGeneral(pixs, pconf, mincount, npixels, debug) as int // pixUpDownDetectGeneral(PIX *, l_float32 *, l_int32, l_int32, l_int32) as l_ok /// <summary> /// (1) See pixOrientDetect() for other details.<para/> /// /// (2) %conf is the normalized difference between the number of /// detected up and down ascenders, assuming that the text /// is either rightside-up or upside-down and not rotated /// at a 90 degree angle.<para/> /// /// (3) The typical mode of operation is %npixels == 0. /// If %npixels is greater 0, this removes HMT matches at the /// beginning and ending of "words." This is useful for /// pages that may have mostly digits, because if npixels == 0, /// leading "1" and "3" digits can register as having /// ascenders or descenders, and "7" digits can match descenders. /// Consequently, a page image of only digits may register /// as being upside-down.<para/> /// /// (4) We want to count the number of instances found using the HMT. /// An expensive way to do this would be to count the /// number of connected components. A cheap way is to do a rank /// reduction cascade that reduces each component to a single /// pixel, and results (after two or three 2x reductions) /// in one pixel for each of the original components. /// After the reduction, you have a much smaller pix over /// which to count pixels. We do only 2 reductions, because /// this function is designed to work for input pix between /// 150 and 300 ppi, and an 8x reduction on a 150 ppi image /// is going too far -- components will get merged. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixUpDownDetectGeneral/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text, 150 - 300 ppi</param> /// <param name="pconf">[out] - confidence that text is rightside-up</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="npixels">[in] - number of pixels removed from each side of word box</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixUpDownDetectGeneral( Pix pixs, out Single pconf, int mincount, int npixels, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixUpDownDetectGeneral(pixs.Pointer, out pconf, mincount, npixels, (int) debug); return _Result; } // flipdetect.c (699, 1) // pixOrientDetectDwa(pixs, pupconf, pleftconf, mincount, debug) as int // pixOrientDetectDwa(PIX *, l_float32 *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) Same interface as for pixOrientDetect(). See notes /// there for usage.<para/> /// /// (2) Uses auto-gen'd code for the Sels defined at the /// top of this file, with some renaming of functions. /// The auto-gen'd code is in fliphmtgen.c, and can /// be generated by a simple executable see prog/flipselgen.c.<para/> /// /// (3) This runs about 2.5 times faster than the pixOrientDetect(). /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixOrientDetectDwa/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text</param> /// <param name="pupconf">[out][optional] - may be NULL</param> /// <param name="pleftconf">[out][optional] - may be NULL</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixOrientDetectDwa( Pix pixs, out Single pupconf, out Single pleftconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixOrientDetectDwa(pixs.Pointer, out pupconf, out pleftconf, mincount, (int) debug); return _Result; } // flipdetect.c (752, 1) // pixUpDownDetectDwa(pixs, pconf, mincount, debug) as int // pixUpDownDetectDwa(PIX *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) Faster (DWA) version of pixUpDownDetect().<para/> /// /// (2) This is a special case (but typical and slightly faster) of /// pixUpDownDetectGeneralDwa(), where the pixels identified /// through the HMT (hit-miss transform) are not clipped by /// a truncated word mask pixm. See pixUpDownDetectGeneral() /// for usage and other details.<para/> /// /// (3) The returned confidence is the normalized difference /// between the number of detected up and down ascenders, /// assuming that the text is either rightside-up or upside-down /// and not rotated at a 90 degree angle. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixUpDownDetectDwa/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text, 150 - 300 ppi</param> /// <param name="pconf">[out] - confidence that text is rightside-up</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixUpDownDetectDwa( Pix pixs, out Single pconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixUpDownDetectDwa(pixs.Pointer, out pconf, mincount, (int) debug); return _Result; } // flipdetect.c (777, 1) // pixUpDownDetectGeneralDwa(pixs, pconf, mincount, npixels, debug) as int // pixUpDownDetectGeneralDwa(PIX *, l_float32 *, l_int32, l_int32, l_int32) as l_ok /// <summary> /// (1) See the notes in pixUpDownDetectGeneral() for usage. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixUpDownDetectGeneralDwa/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text</param> /// <param name="pconf">[out] - confidence that text is rightside-up</param> /// <param name="mincount">[in] - min number of up + down use 0 for default</param> /// <param name="npixels">[in] - number of pixels removed from each side of word box</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixUpDownDetectGeneralDwa( Pix pixs, out Single pconf, int mincount, int npixels, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixUpDownDetectGeneralDwa(pixs.Pointer, out pconf, mincount, npixels, (int) debug); return _Result; } // flipdetect.c (934, 1) // pixMirrorDetect(pixs, pconf, mincount, debug) as int // pixMirrorDetect(PIX *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) For this test, it is necessary that the text is horizontally /// oriented, with ascenders going up.<para/> /// /// (2) conf is the normalized difference between the number of /// right and left facing characters with ascenders. /// Left-facing are {d} right-facing are {b, h, k}. /// At least that was the expectation. In practice, we can /// really just say that it is the normalized difference in /// hits using two specific hit-miss filters, textsel1 and textsel2, /// after the image has been suitably pre-filtered so that /// these filters are effective. See (4) for what's really happening.<para/> /// /// (3) A large positive conf value indicates normal text, whereas /// a large negative conf value means the page is mirror reversed.<para/> /// /// (4) The implementation is a bit tricky. The general idea is /// to fill the x-height part of characters, but not the space /// between them, before doing the HMT. This is done by /// finding pixels added using two different operations -- a /// horizontal close and a vertical dilation -- and adding /// the intersection of these sets to the original. It turns /// out that the original intuition about the signal was largely /// in error: much of the signal for right-facing characters /// comes from the lower part of common x-height characters, like /// the e and c, that remain open after these operations. /// So it's important that the operations to close the x-height /// parts of the characters are purposely weakened sufficiently /// to allow these characters to remain open. The wonders /// of morphology! /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixMirrorDetect/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text</param> /// <param name="pconf">[out] - confidence that text is not LR mirror reversed</param> /// <param name="mincount">[in] - min number of left + right use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixMirrorDetect( Pix pixs, out Single pconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixMirrorDetect(pixs.Pointer, out pconf, mincount, (int) debug); return _Result; } // flipdetect.c (1025, 1) // pixMirrorDetectDwa(pixs, pconf, mincount, debug) as int // pixMirrorDetectDwa(PIX *, l_float32 *, l_int32, l_int32) as l_ok /// <summary> /// (1) We assume the text is horizontally oriented, with /// ascenders going up.<para/> /// /// (2) See notes in pixMirrorDetect(). /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixMirrorDetectDwa/*"/> /// <param name="pixs">[in] - 1 bpp, deskewed, English text</param> /// <param name="pconf">[out] - confidence that text is not LR mirror reversed</param> /// <param name="mincount">[in] - min number of left + right use 0 for default</param> /// <param name="debug">[in] - 1 for debug output 0 otherwise</param> /// <returns>0 if OK, 1 on error</returns> public static int pixMirrorDetectDwa( Pix pixs, out Single pconf, int mincount, Enumerations.DebugOnOff debug = DebugOnOff.DebugOn) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} int _Result = Natives.pixMirrorDetectDwa(pixs.Pointer, out pconf, mincount, (int) debug); return _Result; } } }
47.26652
145
0.656088
[ "BSD-2-Clause" ]
Phreak87/LeptonicaSharp
CS_LIB/Functions/flipdetect.cs
21,459
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Reflection; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Moq; using Xunit; namespace Microsoft.EntityFrameworkCore.Tests.Metadata.Conventions.Internal { public class ConventionDispatcherTest { [InlineData(false)] [InlineData(true)] [Theory] public void OnEntityTypeAdded_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalEntityTypeBuilder entityTypeBuilder = null; var convention = new Mock<IEntityTypeConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b => { Assert.NotNull(b); entityTypeBuilder = new InternalEntityTypeBuilder(b.Metadata, b.ModelBuilder); return entityTypeBuilder; }); conventions.EntityTypeAddedConventions.Add(convention.Object); var nullConvention = new Mock<IEntityTypeConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b => { Assert.Same(entityTypeBuilder, b); return null; }); conventions.EntityTypeAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IEntityTypeConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b => { Assert.False(true); return null; }); conventions.EntityTypeAddedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); if (useBuilder) { Assert.Null(builder.Entity(typeof(Order), ConfigurationSource.Convention)); } else { Assert.Null(builder.Metadata.AddEntityType(typeof(Order), ConfigurationSource.Convention)); } Assert.NotNull(entityTypeBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnBaseEntityTypeSet_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalEntityTypeBuilder entityTypeBuilder = null; var convention = new Mock<IBaseTypeConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<EntityType>())) .Returns<InternalEntityTypeBuilder, EntityType>((b, t) => { Assert.NotNull(b); Assert.Null(t); entityTypeBuilder = b; return true; }); conventions.BaseEntityTypeSetConventions.Add(convention.Object); var nullConvention = new Mock<IBaseTypeConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<EntityType>())) .Returns<InternalEntityTypeBuilder, EntityType>((b, t) => { Assert.Null(t); Assert.Same(entityTypeBuilder, b); return false; }); conventions.BaseEntityTypeSetConventions.Add(nullConvention.Object); var extraConvention = new Mock<IBaseTypeConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<EntityType>())) .Returns<InternalEntityTypeBuilder, EntityType>((b, t) => { Assert.False(true); return false; }); conventions.BaseEntityTypeSetConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)) .Entity(typeof(SpecialOrder), ConfigurationSource.Convention); if (useBuilder) { Assert.NotNull(builder.HasBaseType(typeof(Order), ConfigurationSource.Convention)); } else { builder.Metadata.HasBaseType(builder.Metadata.Model.AddEntityType(typeof(Order)), ConfigurationSource.Convention); } Assert.NotNull(entityTypeBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnEntityTypeMemberIgnored_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalEntityTypeBuilder entityTypeBuilder = null; var convention = new Mock<IEntityTypeMemberIgnoredConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<string>())) .Returns<InternalEntityTypeBuilder, string>((b, t) => { Assert.NotNull(b); Assert.Equal("A", t); entityTypeBuilder = b; return true; }); conventions.EntityTypeMemberIgnoredConventions.Add(convention.Object); var nullConvention = new Mock<IEntityTypeMemberIgnoredConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<string>())) .Returns<InternalEntityTypeBuilder, string>((b, t) => { Assert.Equal("A", t); Assert.Same(entityTypeBuilder, b); return false; }); conventions.EntityTypeMemberIgnoredConventions.Add(nullConvention.Object); var extraConvention = new Mock<IEntityTypeMemberIgnoredConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<string>())) .Returns<InternalEntityTypeBuilder, string>((b, t) => { Assert.False(true); return false; }); conventions.EntityTypeMemberIgnoredConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)).Entity(typeof(SpecialOrder), ConfigurationSource.Convention); if (useBuilder) { Assert.NotNull(builder.Ignore("A", ConfigurationSource.Convention)); } else { builder.Metadata.Ignore("A", ConfigurationSource.Convention); } Assert.NotNull(entityTypeBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnPropertyAdded_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalPropertyBuilder propertyBuilder = null; var convention = new Mock<IPropertyConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.NotNull(b); Assert.Equal("OrderId", b.Metadata.Name); propertyBuilder = new InternalPropertyBuilder(b.Metadata, b.ModelBuilder); return propertyBuilder; }); conventions.PropertyAddedConventions.Add(convention.Object); var nullConvention = new Mock<IPropertyConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.Same(propertyBuilder, b); return null; }); conventions.PropertyAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IPropertyConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.False(true); return null; }); conventions.PropertyAddedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); if (useBuilder) { Assert.Null(entityBuilder.Property("OrderId", typeof(int), ConfigurationSource.Convention)); } else { Assert.Null(entityBuilder.Metadata.AddProperty("OrderId", typeof(int))); } Assert.NotNull(propertyBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnPropertyAdded_calls_apply_on_conventions_in_order_for_non_shadow_property(bool useBuilder) { var conventions = new ConventionSet(); InternalPropertyBuilder propertyBuilder = null; var convention = new Mock<IPropertyConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.NotNull(b); Assert.Equal("OrderId", b.Metadata.Name); propertyBuilder = new InternalPropertyBuilder(b.Metadata, b.ModelBuilder); return propertyBuilder; }); conventions.PropertyAddedConventions.Add(convention.Object); var nullConvention = new Mock<IPropertyConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.Same(propertyBuilder, b); return null; }); conventions.PropertyAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IPropertyConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b => { Assert.False(true); return null; }); conventions.PropertyAddedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); if (useBuilder) { Assert.Null(entityBuilder.Property(Order.OrderIdProperty, ConfigurationSource.Convention)); } else { Assert.Null(entityBuilder.Metadata.AddProperty(Order.OrderIdProperty)); } Assert.NotNull(propertyBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnForeignKeyAdded_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalRelationshipBuilder relationshipBuilder = null; var convention = new Mock<IForeignKeyConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.NotNull(b); relationshipBuilder = new InternalRelationshipBuilder(b.Metadata, b.ModelBuilder); return relationshipBuilder; }); conventions.ForeignKeyAddedConventions.Add(convention.Object); var nullConvention = new Mock<IForeignKeyConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.Same(relationshipBuilder, b); return null; }); conventions.ForeignKeyAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IForeignKeyConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.False(true); return null; }); conventions.ForeignKeyAddedConventions.Add(extraConvention.Object); var modelBuilder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = modelBuilder.Entity(typeof(Order), ConfigurationSource.Convention); entityBuilder.PrimaryKey(new[] { "OrderId" }, ConfigurationSource.Convention); if (useBuilder) { Assert.Null(entityBuilder.Relationship(entityBuilder, ConfigurationSource.Convention)); } else { Assert.Null(entityBuilder.Metadata.AddForeignKey( entityBuilder.Property("Id", typeof(int), ConfigurationSource.Convention).Metadata, entityBuilder.Metadata.FindPrimaryKey(), entityBuilder.Metadata, ConfigurationSource.Convention)); } Assert.NotNull(relationshipBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnKeyAdded_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalKeyBuilder keyBuilder = null; var convention = new Mock<IKeyConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b => { Assert.NotNull(b); keyBuilder = new InternalKeyBuilder(b.Metadata, b.ModelBuilder); return keyBuilder; }); conventions.KeyAddedConventions.Add(convention.Object); var nullConvention = new Mock<IKeyConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b => { Assert.Same(keyBuilder, b); return null; }); conventions.KeyAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IKeyConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b => { Assert.False(true); return null; }); conventions.KeyAddedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); if (useBuilder) { Assert.Null(entityBuilder.HasKey(new List<string> { "OrderId" }, ConfigurationSource.Convention)); } else { var property = entityBuilder.Property("OrderId", ConfigurationSource.Convention).Metadata; property.IsNullable = false; Assert.Null(entityBuilder.Metadata.AddKey(property)); } Assert.NotNull(keyBuilder); } [Fact] public void OnKeyRemoved_calls_apply_on_conventions_in_order() { var conventions = new ConventionSet(); InternalKeyBuilder keyBuilder = null; var convention = new Mock<IKeyRemovedConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<Key>())) .Callback<InternalEntityTypeBuilder, Key>((b, k) => { Assert.NotNull(b); Assert.NotNull(k); keyBuilder = new InternalKeyBuilder(k, b.ModelBuilder); }); conventions.KeyRemovedConventions.Add(convention.Object); var extraConvention = new Mock<IKeyRemovedConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<Key>())) .Callback<InternalEntityTypeBuilder, Key>((b, k) => { Assert.NotNull(b); Assert.NotNull(k); Assert.NotNull(keyBuilder); }); conventions.KeyRemovedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); var key = entityBuilder.HasKey(new List<string> { "OrderId" }, ConfigurationSource.Convention).Metadata; Assert.Same(key, entityBuilder.Metadata.RemoveKey(key.Properties)); Assert.NotNull(keyBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnPrimaryKeySet_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalKeyBuilder internalKeyBuilder = null; var convention = new Mock<IPrimaryKeyConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>(), It.IsAny<Key>())) .Returns<InternalKeyBuilder, Key>((b, t) => { Assert.NotNull(b); Assert.Null(t); internalKeyBuilder = b; return true; }); conventions.PrimaryKeySetConventions.Add(convention.Object); var nullConvention = new Mock<IPrimaryKeyConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>(), It.IsAny<Key>())) .Returns<InternalKeyBuilder, Key>((b, t) => { Assert.Null(t); Assert.Same(internalKeyBuilder, b); return false; }); conventions.PrimaryKeySetConventions.Add(nullConvention.Object); var extraConvention = new Mock<IPrimaryKeyConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>(), It.IsAny<Key>())) .Returns<InternalKeyBuilder, Key>((b, t) => { Assert.False(true); return false; }); conventions.PrimaryKeySetConventions.Add(extraConvention.Object); var entityBuilder = new InternalModelBuilder(new Model(conventions)) .Entity(typeof(Order), ConfigurationSource.Convention); entityBuilder.HasKey(new[] { "OrderId" }, ConfigurationSource.Convention); if (useBuilder) { Assert.NotNull(entityBuilder.PrimaryKey(new[] { "OrderId" }, ConfigurationSource.Convention)); } else { Assert.NotNull(entityBuilder.Metadata.SetPrimaryKey( entityBuilder.Property("OrderId", ConfigurationSource.Convention).Metadata)); } Assert.NotNull(internalKeyBuilder); } [Fact] public void OnForeignKeyRemoved_calls_apply_on_conventions_in_order() { var conventions = new ConventionSet(); var foreignKeyRemoved = false; var convention = new Mock<IForeignKeyRemovedConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<ForeignKey>())) .Callback(() => foreignKeyRemoved = true); conventions.ForeignKeyRemovedConventions.Add(convention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); var foreignKey = entityBuilder.Metadata.AddForeignKey( new[] { entityBuilder.Property("FK", typeof(int), ConfigurationSource.Convention).Metadata }, entityBuilder.HasKey(new[] { "OrderId" }, ConfigurationSource.Convention).Metadata, entityBuilder.Metadata); Assert.NotNull(entityBuilder.Metadata.RemoveForeignKey(foreignKey.Properties, foreignKey.PrincipalKey, foreignKey.PrincipalEntityType)); Assert.True(foreignKeyRemoved); } [InlineData(false)] [InlineData(true)] [Theory] public void OnNavigationAdded_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalRelationshipBuilder relationshipBuilder = null; var orderIgnored = false; var orderDetailsIgnored = false; var convention = new Mock<INavigationConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>(), It.IsAny<Navigation>())).Returns((InternalRelationshipBuilder b, Navigation n) => { Assert.NotNull(b); relationshipBuilder = new InternalRelationshipBuilder(b.Metadata, b.ModelBuilder); return relationshipBuilder; }); conventions.NavigationAddedConventions.Add(convention.Object); var nullConvention = new Mock<INavigationConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>(), It.IsAny<Navigation>())).Returns((InternalRelationshipBuilder b, Navigation n) => { Assert.Same(relationshipBuilder, b); if (n.Name == "Order") { orderIgnored = true; } if (n.Name == "OrderDetails") { orderDetailsIgnored = true; } return null; }); conventions.NavigationAddedConventions.Add(nullConvention.Object); var extraConvention = new Mock<INavigationConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>(), It.IsAny<Navigation>())).Returns((InternalRelationshipBuilder b, Navigation n) => { Assert.False(true); return null; }); conventions.NavigationAddedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var principalEntityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); var dependentEntityBuilder = builder.Entity(typeof(OrderDetails), ConfigurationSource.Convention); if (useBuilder) { Assert.Null(dependentEntityBuilder.Relationship(principalEntityBuilder, OrderDetails.OrderProperty, Order.OrderDetailsProperty, ConfigurationSource.Convention)); } else { var fk = dependentEntityBuilder.Relationship(principalEntityBuilder, ConfigurationSource.Convention) .IsUnique(true, ConfigurationSource.Convention) .Metadata; Assert.Null(fk.HasDependentToPrincipal(OrderDetails.OrderProperty)); } Assert.True(orderIgnored); Assert.False(orderDetailsIgnored); Assert.NotNull(relationshipBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnNavigationRemoved_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalEntityTypeBuilder dependentEntityTypeBuilderFromConvention = null; InternalEntityTypeBuilder principalEntityBuilderFromConvention = null; var convention = new Mock<INavigationRemovedConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<string>())).Returns((InternalEntityTypeBuilder s, InternalEntityTypeBuilder t, string n) => { dependentEntityTypeBuilderFromConvention = s; principalEntityBuilderFromConvention = t; Assert.Equal(nameof(OrderDetails.Order), n); return false; }); conventions.NavigationRemovedConventions.Add(convention.Object); var extraConvention = new Mock<INavigationRemovedConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<string>())).Returns((InternalEntityTypeBuilder s, InternalEntityTypeBuilder t, string n) => { Assert.False(true); return false; }); conventions.NavigationRemovedConventions.Add(extraConvention.Object); var builder = new InternalModelBuilder(new Model(conventions)); var principalEntityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention); var dependentEntityBuilder = builder.Entity(typeof(OrderDetails), ConfigurationSource.Convention); var relationshipBuilder = dependentEntityBuilder.Relationship(principalEntityBuilder, nameof(OrderDetails.Order), nameof(Order.OrderDetails), ConfigurationSource.Convention); if (useBuilder) { Assert.NotNull(relationshipBuilder.DependentToPrincipal((string)null, ConfigurationSource.Convention)); } else { Assert.NotNull(relationshipBuilder.Metadata.HasDependentToPrincipal((string)null, ConfigurationSource.Convention)); } Assert.Same(dependentEntityTypeBuilderFromConvention, dependentEntityBuilder); Assert.Same(principalEntityBuilderFromConvention, principalEntityBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnPrincipalKeySet_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); InternalRelationshipBuilder relationshipBuilder = null; var convention = new Mock<IPrincipalEndConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.NotNull(b); relationshipBuilder = new InternalRelationshipBuilder(b.Metadata, b.ModelBuilder); return relationshipBuilder; }); conventions.PrincipalEndSetConventions.Add(convention.Object); var nullConvention = new Mock<IPrincipalEndConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.Same(relationshipBuilder, b); return null; }); conventions.PrincipalEndSetConventions.Add(nullConvention.Object); var extraConvention = new Mock<IPrincipalEndConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b => { Assert.False(true); return null; }); conventions.PrincipalEndSetConventions.Add(extraConvention.Object); var modelBuilder = new InternalModelBuilder(new Model(conventions)); var entityBuilder = modelBuilder.Entity(typeof(Order), ConfigurationSource.Convention); entityBuilder.PrimaryKey(new[] { "OrderId" }, ConfigurationSource.Convention); var dependentEntityBuilder = modelBuilder.Entity(typeof(OrderDetails), ConfigurationSource.Convention); if (useBuilder) { Assert.Null( dependentEntityBuilder .Relationship(entityBuilder, ConfigurationSource.Convention) .HasPrincipalKey(entityBuilder.Metadata.FindPrimaryKey().Properties, ConfigurationSource.Convention)); } else { Assert.Null(dependentEntityBuilder.Metadata.AddForeignKey( dependentEntityBuilder.Property("Id", typeof(int), ConfigurationSource.Convention).Metadata, entityBuilder.Metadata.FindPrimaryKey(), entityBuilder.Metadata, ConfigurationSource.Convention)); } Assert.NotNull(relationshipBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void InitializingModel_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); var nullConventionCalled = false; InternalModelBuilder modelBuilder = null; var convention = new Mock<IModelConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { Assert.NotNull(b); modelBuilder = new InternalModelBuilder(b.Metadata); return b; }); conventions.ModelInitializedConventions.Add(convention.Object); var nullConvention = new Mock<IModelConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { nullConventionCalled = true; return null; }); conventions.ModelInitializedConventions.Add(nullConvention.Object); var extraConvention = new Mock<IModelConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { Assert.False(true); return null; }); conventions.ModelInitializedConventions.Add(extraConvention.Object); if (useBuilder) { Assert.NotNull(new ModelBuilder(conventions)); } else { Assert.NotNull(new Model(conventions)); } Assert.True(nullConventionCalled); Assert.NotNull(modelBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void ValidatingModel_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); var nullConventionCalled = false; InternalModelBuilder modelBuilder = null; var convention = new Mock<IModelConvention>(); convention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { Assert.NotNull(b); modelBuilder = new InternalModelBuilder(b.Metadata); return b; }); conventions.ModelBuiltConventions.Add(convention.Object); var nullConvention = new Mock<IModelConvention>(); nullConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { nullConventionCalled = true; return null; }); conventions.ModelBuiltConventions.Add(nullConvention.Object); var extraConvention = new Mock<IModelConvention>(); extraConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b => { Assert.False(true); return null; }); conventions.ModelBuiltConventions.Add(extraConvention.Object); Assert.Null(useBuilder ? new InternalModelBuilder(new Model(conventions)).Validate() : new Model(conventions).Validate()); Assert.True(nullConventionCalled); Assert.NotNull(modelBuilder); } [InlineData(false)] [InlineData(true)] [Theory] public void OnPropertyNullableChanged_calls_apply_on_conventions_in_order(bool useBuilder) { var conventions = new ConventionSet(); var convention1 = new PropertyNullableConvention(false); var convention2 = new PropertyNullableConvention(true); var convention3 = new PropertyNullableConvention(false); conventions.PropertyNullableChangedConventions.Add(convention1); conventions.PropertyNullableChangedConventions.Add(convention2); conventions.PropertyNullableChangedConventions.Add(convention3); var builder = new ModelBuilder(conventions); var propertyBuilder = builder.Entity<Order>().Property(e => e.Name); if (useBuilder) { propertyBuilder.IsRequired(); } else { propertyBuilder.Metadata.IsNullable = false; } Assert.Equal(new bool?[] { false }, convention1.Calls); Assert.Equal(new bool?[] { false }, convention2.Calls); Assert.Empty(convention3.Calls); propertyBuilder = builder.Entity<Order>().Property(e => e.Name); if (useBuilder) { propertyBuilder.IsRequired(false); } else { propertyBuilder.Metadata.IsNullable = true; } Assert.Equal(new bool?[] { false, true }, convention1.Calls); Assert.Equal(new bool?[] { false, true }, convention2.Calls); Assert.Empty(convention3.Calls); propertyBuilder = builder.Entity<Order>().Property(e => e.Name); if (useBuilder) { propertyBuilder.IsRequired(false); } else { propertyBuilder.Metadata.IsNullable = true; } Assert.Equal(new bool?[] { false, true }, convention1.Calls); Assert.Equal(new bool?[] { false, true }, convention2.Calls); Assert.Empty(convention3.Calls); propertyBuilder = builder.Entity<Order>().Property(e => e.Name); if (useBuilder) { propertyBuilder.IsRequired(); } else { propertyBuilder.Metadata.IsNullable = false; } Assert.Equal(new bool?[] { false, true, false }, convention1.Calls); Assert.Equal(new bool?[] { false, true, false }, convention2.Calls); Assert.Empty(convention3.Calls); } private class PropertyNullableConvention : IPropertyNullableConvention { public readonly List<bool?> Calls = new List<bool?>(); private readonly bool _terminate; public PropertyNullableConvention(bool terminate) { _terminate = terminate; } public bool Apply(InternalPropertyBuilder propertyBuilder) { Calls.Add(propertyBuilder.Metadata.IsNullable); return !_terminate; } } private class Order { public static readonly PropertyInfo OrderIdProperty = typeof(Order).GetProperty(nameof(OrderId)); public static readonly PropertyInfo OrderDetailsProperty = typeof(Order).GetProperty(nameof(OrderDetails)); public int OrderId { get; set; } public string Name { get; set; } public virtual OrderDetails OrderDetails { get; set; } } private class SpecialOrder : Order { } private class OrderDetails { public static readonly PropertyInfo OrderProperty = typeof(OrderDetails).GetProperty(nameof(Order)); public int Id { get; set; } public virtual Order Order { get; set; } } } }
42.89977
225
0.586567
[ "Apache-2.0" ]
davidroth/EntityFrameworkCore
test/Microsoft.EntityFrameworkCore.Tests/Metadata/Conventions/Internal/ConventionDispatcherTest.cs
37,237
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTLib3 { public static partial class Collections { public static TValue[] HSelectByKeys<TKey, TValue>(this Dictionary<TKey, TValue> dict, params TKey[] keys) { List<TValue> values = new List<TValue>(); foreach(TKey key in keys) values.Add(dict[key]); return values.ToArray(); } } }
25.578947
115
0.590535
[ "MIT" ]
htna/HCsbLib
HCsbLib/HCsbLib/HTLib3/Core/Collection/Collections.HSelectByKeys.cs
488
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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Completion; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SpellCheck { internal abstract class AbstractSpellCheckCodeFixProvider<TSimpleName> : CodeFixProvider where TSimpleName : SyntaxNode { protected abstract bool IsGeneric(TSimpleName nameNode); protected abstract bool IsGeneric(CompletionItem completionItem); protected abstract SyntaxToken CreateIdentifier(TSimpleName nameNode, string newName); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var span = context.Span; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = syntaxRoot.FindNode(span); if (node == null || node.Span != span) { return; } SemanticModel semanticModel = null; foreach (var name in node.DescendantNodesAndSelf().OfType<TSimpleName>()) { // Only bother with identifiers that are at least 3 characters long. // We don't want to be too noisy as you're just starting to type something. var nameText = name.GetFirstToken().ValueText; if (nameText?.Length >= 3) { semanticModel = semanticModel ?? await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = semanticModel.GetSymbolInfo(name, cancellationToken); if (symbolInfo.Symbol == null) { await CreateSpellCheckCodeIssueAsync(context, name, nameText, cancellationToken).ConfigureAwait(false); } } } } private async Task CreateSpellCheckCodeIssueAsync(CodeFixContext context, TSimpleName nameNode, string nameText, CancellationToken cancellationToken) { var document = context.Document; var completionList = await CompletionService.GetCompletionListAsync( document, nameNode.SpanStart, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo(), cancellationToken: cancellationToken).ConfigureAwait(false); if (completionList == null) { return; } var completionRules = CompletionService.GetCompletionRules(document); var onlyConsiderGenerics = IsGeneric(nameNode); var results = new MultiDictionary<double, string>(); using (var editDistance = new EditDistance(nameText)) { foreach (var item in completionList.Items) { if (onlyConsiderGenerics && !IsGeneric(item)) { continue; } var candidateText = item.FilterText; double matchCost; if (!editDistance.IsCloseMatch(candidateText, out matchCost)) { continue; } var insertionText = completionRules.GetTextChange(item).NewText; results.Add(matchCost, insertionText); } } var matches = results.OrderBy(kvp => kvp.Key) .SelectMany(kvp => kvp.Value.Order()) .Where(t => t != nameText) .Take(3) .Select(n => CreateCodeAction(nameNode, nameText, n, document)); context.RegisterFixes(matches, context.Diagnostics); } private SpellCheckCodeAction CreateCodeAction(TSimpleName nameNode, string oldName, string newName, Document document) { return new SpellCheckCodeAction( string.Format(FeaturesResources.ChangeTo, oldName, newName), c => Update(document, nameNode, newName, c), equivalenceKey: newName); } private async Task<Document> Update(Document document, TSimpleName nameNode, string newName, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceToken(nameNode.GetFirstToken(), CreateIdentifier(nameNode, newName)); return document.WithSyntaxRoot(newRoot); } private class SpellCheckCodeAction : CodeAction.DocumentChangeAction { public SpellCheckCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
44.066667
165
0.608926
[ "Apache-2.0" ]
0x53A/roslyn
src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs
5,290
C#
namespace LogJoint.Postprocessing { internal class NeverRunState : PostprocessorOutputRecordState { public NeverRunState(Context ctx) : base(ctx) { } public override LogSourcePostprocessorState GetData() { return ctx.owner.BuildData(LogSourcePostprocessorState.Status.NeverRun); } public override bool? PostprocessorNeedsRunning => true; public override PostprocessorOutputRecordState Refresh() { return this; } }; }
23.1
76
0.742424
[ "MIT" ]
rkapl123/logjoint
trunk/model/postprocessing/manager/states/NeverRunState.cs
464
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 connect-2017-08-08.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.Connect.Model { /// <summary> /// Container for the parameters to the CreateUser operation. /// Creates a user account for the specified Amazon Connect instance. /// </summary> public partial class CreateUserRequest : AmazonConnectRequest { private string _directoryUserId; private string _hierarchyGroupId; private UserIdentityInfo _identityInfo; private string _instanceId; private string _password; private UserPhoneConfig _phoneConfig; private string _routingProfileId; private List<string> _securityProfileIds = new List<string>(); private Dictionary<string, string> _tags = new Dictionary<string, string>(); private string _username; /// <summary> /// Gets and sets the property DirectoryUserId. /// <para> /// The identifier of the user account in the directory used for identity management. /// If Amazon Connect cannot access the directory, you can specify this identifier to /// authenticate users. If you include the identifier, we assume that Amazon Connect cannot /// access the directory. Otherwise, the identity information is used to authenticate /// users from your directory. /// </para> /// /// <para> /// This parameter is required if you are using an existing directory for identity management /// in Amazon Connect when Amazon Connect cannot access your directory to authenticate /// users. If you are using SAML for identity management and include this parameter, an /// error is returned. /// </para> /// </summary> public string DirectoryUserId { get { return this._directoryUserId; } set { this._directoryUserId = value; } } // Check to see if DirectoryUserId property is set internal bool IsSetDirectoryUserId() { return this._directoryUserId != null; } /// <summary> /// Gets and sets the property HierarchyGroupId. /// <para> /// The identifier of the hierarchy group for the user. /// </para> /// </summary> public string HierarchyGroupId { get { return this._hierarchyGroupId; } set { this._hierarchyGroupId = value; } } // Check to see if HierarchyGroupId property is set internal bool IsSetHierarchyGroupId() { return this._hierarchyGroupId != null; } /// <summary> /// Gets and sets the property IdentityInfo. /// <para> /// The information about the identity of the user. /// </para> /// </summary> public UserIdentityInfo IdentityInfo { get { return this._identityInfo; } set { this._identityInfo = value; } } // Check to see if IdentityInfo property is set internal bool IsSetIdentityInfo() { return this._identityInfo != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The identifier of the Amazon Connect instance. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property Password. /// <para> /// The password for the user account. A password is required if you are using Amazon /// Connect for identity management. Otherwise, it is an error to include a password. /// </para> /// </summary> public string Password { get { return this._password; } set { this._password = value; } } // Check to see if Password property is set internal bool IsSetPassword() { return this._password != null; } /// <summary> /// Gets and sets the property PhoneConfig. /// <para> /// The phone settings for the user. /// </para> /// </summary> [AWSProperty(Required=true)] public UserPhoneConfig PhoneConfig { get { return this._phoneConfig; } set { this._phoneConfig = value; } } // Check to see if PhoneConfig property is set internal bool IsSetPhoneConfig() { return this._phoneConfig != null; } /// <summary> /// Gets and sets the property RoutingProfileId. /// <para> /// The identifier of the routing profile for the user. /// </para> /// </summary> [AWSProperty(Required=true)] public string RoutingProfileId { get { return this._routingProfileId; } set { this._routingProfileId = value; } } // Check to see if RoutingProfileId property is set internal bool IsSetRoutingProfileId() { return this._routingProfileId != null; } /// <summary> /// Gets and sets the property SecurityProfileIds. /// <para> /// The identifier of the security profile for the user. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=10)] public List<string> SecurityProfileIds { get { return this._securityProfileIds; } set { this._securityProfileIds = value; } } // Check to see if SecurityProfileIds property is set internal bool IsSetSecurityProfileIds() { return this._securityProfileIds != null && this._securityProfileIds.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// One or more tags. /// </para> /// </summary> [AWSProperty(Min=1, Max=50)] public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property Username. /// <para> /// The user name for the account. For instances not using SAML for identity management, /// the user name can include up to 20 characters. If you are using SAML for identity /// management, the user name can include up to 64 characters from [a-zA-Z0-9_-.\@]+. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public string Username { get { return this._username; } set { this._username = value; } } // Check to see if Username property is set internal bool IsSetUsername() { return this._username != null; } } }
33.02008
105
0.580151
[ "Apache-2.0" ]
joshongithub/aws-sdk-net
sdk/src/Services/Connect/Generated/Model/CreateUserRequest.cs
8,222
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using Microsoft.AspNetCore.Components; using Microsoft.MobileBlazorBindings.Core; using Microsoft.MobileBlazorBindings.Elements.Handlers; using System; using System.Threading.Tasks; using XF = Xamarin.Forms; namespace Microsoft.MobileBlazorBindings.Elements { public partial class TimePicker : View { static TimePicker() { ElementHandlerRegistry.RegisterElementHandler<TimePicker>( renderer => new TimePickerHandler(renderer, new XF.TimePicker())); } [Parameter] public double? CharacterSpacing { get; set; } /// <summary> /// TGets a value that indicates whether the font for the searchbar text is bold, italic, or neither. /// </summary> [Parameter] public XF.FontAttributes? FontAttributes { get; set; } /// <summary> /// Gets or sets the font family for the picker text. /// </summary> [Parameter] public string FontFamily { get; set; } /// <summary> /// Gets or sets the size of the font for the text in the picker. /// </summary> /// <value> /// A <see langword="double" /> that indicates the size of the font. /// </value> [Parameter] public double? FontSize { get; set; } /// <summary> /// The format of the time to display to the user. This is a bindable property. /// </summary> /// <value> /// A valid time format string. /// </value> [Parameter] public string Format { get; set; } /// <summary> /// Gets or sets the text color. /// </summary> [Parameter] public XF.Color? TextColor { get; set; } /// <summary> /// Gets or sets the displayed time. This is a bindable property. /// </summary> /// <value> /// The <see cref="T:System.TimeSpan" /> displayed in the TimePicker. /// </value> [Parameter] public TimeSpan? Time { get; set; } public new XF.TimePicker NativeControl => ((TimePickerHandler)ElementHandler).TimePickerControl; protected override void RenderAttributes(AttributesBuilder builder) { base.RenderAttributes(builder); if (CharacterSpacing != null) { builder.AddAttribute(nameof(CharacterSpacing), AttributeHelper.DoubleToString(CharacterSpacing.Value)); } if (FontAttributes != null) { builder.AddAttribute(nameof(FontAttributes), (int)FontAttributes.Value); } if (FontFamily != null) { builder.AddAttribute(nameof(FontFamily), FontFamily); } if (FontSize != null) { builder.AddAttribute(nameof(FontSize), AttributeHelper.DoubleToString(FontSize.Value)); } if (Format != null) { builder.AddAttribute(nameof(Format), Format); } if (TextColor != null) { builder.AddAttribute(nameof(TextColor), AttributeHelper.ColorToString(TextColor.Value)); } if (Time != null) { builder.AddAttribute(nameof(Time), AttributeHelper.TimeSpanToString(Time.Value)); } RenderAdditionalAttributes(builder); } partial void RenderAdditionalAttributes(AttributesBuilder builder); } }
36.412371
119
0.58154
[ "MIT" ]
CipherLab/MobileBlazorBindings
src/Microsoft.MobileBlazorBindings/Elements/TimePicker.generated.cs
3,532
C#
namespace Pickle { public enum ObjectSourceType { Asset = 1 << 0, Scene = 1 << 1 } }
12.666667
32
0.482456
[ "MIT" ]
AlexMeesters/Pickle
Runtime/ObjectSourceType.cs
116
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * 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 ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Mail.Server.Core.Dao.Interfaces; using ASC.Mail.Server.Core.DbSchema; using ASC.Mail.Server.Core.DbSchema.Interfaces; using ASC.Mail.Server.Core.DbSchema.Tables; using ASC.Mail.Server.Core.Entities; namespace ASC.Mail.Server.Core.Dao { public class DkimDao : BaseDao, IDkimDao { protected static ITable table = new MailServerTableFactory().Create<DkimTable>(); public DkimDao(IDbManager dbManager) : base(table, dbManager) { } public int Save(Dkim dkim) { var query = new SqlInsert(DkimTable.TABLE_NAME, true) .InColumnValue(DkimTable.Columns.ID, dkim.Id) .InColumnValue(DkimTable.Columns.DOMAIN_NAME, dkim.DomainName) .InColumnValue(DkimTable.Columns.SELECTOR, dkim.Selector) .InColumnValue(DkimTable.Columns.PRIVATE_KEY, dkim.PrivateKey) .InColumnValue(DkimTable.Columns.PUBLIC_KEY, dkim.PublicKey); var id = Db.ExecuteScalar<int>(query); return id; } public int Remove(string domain) { var query = new SqlDelete(DkimTable.TABLE_NAME) .Where(DkimTable.Columns.DOMAIN_NAME, domain); var result = Db.ExecuteNonQuery(query); return result; } } }
33.3
89
0.668669
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Mail.Server/ASC.Mail.Server/Core/Dao/DkimDao.cs
1,998
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(6590)] [Attributes(9)] public class LteB7C1RxGain { [ElementsCount(16)] [ElementType("uint16")] [Description("")] public ushort[] Value { get; set; } } }
19.52381
44
0.597561
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/LteB7C1RxGainI.cs
410
C#
//------------------------------------------------------------------------------ // Generated by the DevExpress.Blazor package. // To prevent this operation, add the DxExtendStartupHost property to the project and set this property to False. // // XAF.ExposureNotification.Blazor.Server.csproj: // // <Project Sdk="Microsoft.NET.Sdk.Web"> // <PropertyGroup> // <TargetFramework>netcoreapp3.1</TargetFramework> // <DxExtendStartupHost>False</DxExtendStartupHost> // </PropertyGroup> //------------------------------------------------------------------------------ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; [assembly: HostingStartup(typeof(XAF.ExposureNotification.Blazor.Server.DevExpressHostingStartup))] namespace XAF.ExposureNotification.Blazor.Server { public partial class DevExpressHostingStartup : IHostingStartup { void IHostingStartup.Configure(IWebHostBuilder builder) { builder.ConfigureServices((serviceCollection) => { serviceCollection.AddDevExpressBlazor(); }); } } }
39.714286
113
0.63759
[ "MIT" ]
egarim/xamarin.exposurenotification
XAF.ExposureNotification.Blazor.Server/Startup.DevExpress.cs
1,112
C#
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MinhaAppVisualStudio { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.64
76
0.698052
[ "MIT" ]
ferjesusjs8/Formacao_FullstackDeveloper_DevIo_NetAngular
Iniciando_Com_AspNetCore/MinhaAppVisualStudio/MinhaAppVisualStudio/Program.cs
618
C#
/* * author:symbolspace * e-mail:symbolspace@outlook.com */ /// <summary> /// 字符串随机类,辅助生成一些随机的字符串序列。 /// </summary> public static class StringRandomizer { #region methods #region Next /// <summary> /// 生成指定长度的字符串(任何字符)。 /// </summary> /// <param name="length">长度。</param> /// <returns>返回生成的字符串序列。</returns> public static string Next(int length) { return Next(length, true, true, true, true); } /// <summary> /// 生成指定长度的字符串。 /// </summary> /// <param name="length">长度。</param> /// <param name="allowNumber">允许数字。</param> /// <param name="allowSmallword">允许小写字母。</param> /// <param name="allowBigword">允许大小字母。</param> /// <returns>返回生成的字符串序列。</returns> public static string Next(int length, bool allowNumber, bool allowSmallword, bool allowBigword) { return Next(length, allowNumber, false, allowSmallword, allowBigword); } /// <summary> /// 生成指定长度的字符串。 /// </summary> /// <param name="length">长度。</param> /// <param name="allowNumber">允许数字。</param> /// <param name="allowSign">允许特殊符号。</param> /// <param name="allowSmallword">允许小写字母。</param> /// <param name="allowBigword">允许大小字母。</param> /// <returns>返回生成的字符串序列。</returns> public static string Next(int length, bool allowNumber, bool allowSign, bool allowSmallword, bool allowBigword) { //定义 System.Random ranA = new System.Random(); int intResultRound = 0; int intA = 0; string strB = ""; while (intResultRound < length) { //生成随机数A,表示生成类型 //1=数字,2=符号,3=小写字母,4=大写字母 intA = ranA.Next(1, 5); //如果随机数A=1,则运行生成数字 //生成随机数A,范围在0-10 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 1 && allowNumber) { intA = ranA.Next(0, 10); strB = intA.ToString() + strB; intResultRound = intResultRound + 1; continue; } //如果随机数A=2,则运行生成符号 //生成随机数A,表示生成值域 //1:33-47值域,2:58-64值域,3:91-96值域,4:123-126值域 if (intA == 2 && allowSign == true) { intA = ranA.Next(1, 5); //如果A=1 //生成随机数A,33-47的Ascii码 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 1) { intA = ranA.Next(33, 48); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } //如果A=2 //生成随机数A,58-64的Ascii码 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 2) { intA = ranA.Next(58, 65); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } //如果A=3 //生成随机数A,91-96的Ascii码 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 3) { intA = ranA.Next(91, 97); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } //如果A=4 //生成随机数A,123-126的Ascii码 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 4) { intA = ranA.Next(123, 127); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } } //如果随机数A=3,则运行生成小写字母 //生成随机数A,范围在97-122 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 3 && allowSmallword == true) { intA = ranA.Next(97, 123); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } //如果随机数A=4,则运行生成大写字母 //生成随机数A,范围在65-90 //把随机数A,转成字符 //生成完,位数+1,字符串累加,结束本次循环 if (intA == 4 && allowBigword == true) { intA = ranA.Next(65, 89); strB = ((char)intA).ToString() + strB; intResultRound = intResultRound + 1; continue; } } return strB; } #endregion #endregion }
29.237179
117
0.459987
[ "MIT" ]
symbolspace/Symbol
src/Symbol/.global/StringRandomizer.cs
5,613
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(6921)] [Attributes(9)] public class Wcdma1500Im2IValue { [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Value { get; set; } } }
19.863636
40
0.613272
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/Wcdma1500Im2IValueI.cs
437
C#
/* * Copyright 2004,2006 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: WindowPreference.cs,v 1.2 2011/10/27 23:21:55 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Drawing; using System.Text.RegularExpressions; using System.Globalization; using Poderosa.Util; using Poderosa.Plugins; using Poderosa.Sessions; using Poderosa.Preferences; using Poderosa.View; using Poderosa.Commands; namespace Poderosa.Forms { //friendly interface実装 internal class CoreServicePreferenceAdapter : SnapshotAwarePreferenceBase, ICoreServicePreference { //見た目調整 private IStringPreferenceItem _viewSplitModifier; //マウスでの分割 private IBoolPreferenceItem _showsToolBar; private IStringPreferenceItem _language; private IIntPreferenceItem _caretInterval; private IBoolPreferenceItem _autoCopyByLeftButton; //TerminalEmulatorから引越ししてきた private IIntPreferenceItem _splitLimitCount; //ダーティフラグとキャッシュ private bool _viewSplitModifierChecked; private Keys _viewSplitModifierKey; public CoreServicePreferenceAdapter(IPreferenceFolder folder) : base(folder) { } public override void DefineItems(IPreferenceBuilder builder) { _viewSplitModifier = builder.DefineStringValue(_folder, "viewSplitModifier", "None", null); _showsToolBar = builder.DefineBoolValue(_folder, "showsToolBar", true, null); _caretInterval = builder.DefineIntValue(_folder, "caretInterval", 300, PreferenceValidatorUtil.PositiveIntegerValidator); _autoCopyByLeftButton = builder.DefineBoolValue(_folder, "autoCopyByLeftButton", false, null); _language = builder.DefineStringValue(_folder, "language", GetNativeLanguage().ToString(), null); _splitLimitCount = builder.DefineIntValue(_folder, "splitLimitCount", 16, PreferenceValidatorUtil.IntRangeValidator(1, 50)); } public CoreServicePreferenceAdapter Import(CoreServicePreferenceAdapter src) { _viewSplitModifier = ConvertItem(src._viewSplitModifier); _showsToolBar = ConvertItem(src._showsToolBar); _language = ConvertItem(src._language); _caretInterval = ConvertItem(src._caretInterval); _autoCopyByLeftButton = ConvertItem(src._autoCopyByLeftButton); _splitLimitCount = ConvertItem(src._splitLimitCount); return this; } public bool ShowsToolBar { get { return _showsToolBar.Value; } set { _showsToolBar.Value = value; } } public int CaretInterval { get { return _caretInterval.Value; } set { _caretInterval.Value = value; } } public bool AutoCopyByLeftButton { get { return _autoCopyByLeftButton.Value; } set { _autoCopyByLeftButton.Value = value; } } public int SplitLimitCount { get { return _splitLimitCount.Value; } set { _splitLimitCount.Value = value; } } public Keys ViewSplitModifier { get { if (!_viewSplitModifierChecked) { _viewSplitModifierChecked = true; try { _viewSplitModifierKey = WinFormsUtil.ParseModifier(_viewSplitModifier.Value); } catch (Exception ex) { RuntimeUtil.ReportException(ex); _viewSplitModifierKey = Keys.None; //ここはOnMouseMoveから繰り返しチェックを受けるので、下手な値が入っていて繰り返しエラーが起きるのをさける } } return _viewSplitModifierKey; } set { _viewSplitModifier.Value = value.ToString(); _viewSplitModifierChecked = false; } } //フラグクリア public void ClearSplitModifierCheckedFlag() { _viewSplitModifierChecked = false; } public Language Language { get { return ParseUtil.ParseEnum<Language>(_language.Value, Language.English); } set { _language.Value = value.ToString(); } } private Language GetNativeLanguage() { IPoderosaCulture c = WindowManagerPlugin.Instance.PoderosaWorld.Culture; return c.InitialCulture.Name.StartsWith("ja") ? Language.Japanese : Language.English; } public static CultureInfo LangToCulture(Language lang) { if (lang == Language.Japanese) return CultureInfo.GetCultureInfo("ja-JP"); else return CultureInfo.InvariantCulture; } } internal class WindowPreference : IPreferenceSupplier, IWindowPreference { private IPreferenceFolder _originalFolder; private IPreferenceFolderArray _windowArrayPreference; private IPreferenceFolder _windowTemplatePreference; //以下、ウィンドウ毎 private IStringPreferenceItem _windowPositionPreference; private IStringPreferenceItem _windowSplitFormatPreference; private IStringPreferenceItem _toolBarFormatPreference; private IIntPreferenceItem _tabRowCountPreference; private CoreServicePreferenceAdapter _adapter; private class ChangeListener : IPreferenceChangeListener { private CoreServicePreferenceAdapter _adapter; public ChangeListener(CoreServicePreferenceAdapter adapter) { _adapter = adapter; } public void OnPreferenceImport(IPreferenceFolder oldvalues, IPreferenceFolder newvalues) { ICoreServicePreference nv = (ICoreServicePreference)newvalues.QueryAdapter(typeof(ICoreServicePreference)); WindowManagerPlugin.Instance.ReloadPreference(nv); _adapter.ClearSplitModifierCheckedFlag(); //言語が変わっていたら... Language lang = nv.Language; if (lang != ((ICoreServicePreference)oldvalues.QueryAdapter(typeof(ICoreServicePreference))).Language) { Debug.WriteLine("Change Language"); WindowManagerPlugin.Instance.PoderosaWorld.Culture.SetCulture(CoreServicePreferenceAdapter.LangToCulture(lang)); } } } #region IPreferenceSupplier public string PreferenceID { get { return WindowManagerPlugin.PLUGIN_ID; } } public void InitializePreference(IPreferenceBuilder builder, IPreferenceFolder folder) { _originalFolder = folder; _adapter = new CoreServicePreferenceAdapter(folder); _adapter.DefineItems(builder); AboutBoxUtil.InitPreference(builder, folder); _windowTemplatePreference = builder.DefineFolderArray(folder, this, "mainwindow"); _windowArrayPreference = folder.FindChildFolderArray("mainwindow"); Debug.Assert(_windowArrayPreference != null); _windowPositionPreference = builder.DefineStringValue(_windowTemplatePreference, "position", "", null); _windowSplitFormatPreference = builder.DefineStringValue(_windowTemplatePreference, "format", "", null); _toolBarFormatPreference = builder.DefineStringValue(_windowTemplatePreference, "toolbar", "", null); _tabRowCountPreference = builder.DefineIntValue(_windowTemplatePreference, "tabrowcount", 1, null); //add listener folder.AddChangeListener(new ChangeListener(_adapter)); } public IPreferenceFolderArray WindowArray { get { return _windowArrayPreference; } } public int WindowCount { get { return _windowArrayPreference.Folders.Length; } } public string WindowPositionAt(int index) { IPreferenceFolderArray a = _windowArrayPreference; return a.ConvertItem(a.Folders[index], _windowPositionPreference).AsString().Value; } public string WindowSplitFormatAt(int index) { IPreferenceFolderArray a = _windowArrayPreference; return a.ConvertItem(a.Folders[index], _windowSplitFormatPreference).AsString().Value; } public string ToolBarFormatAt(int index) { IPreferenceFolderArray a = _windowArrayPreference; return a.ConvertItem(a.Folders[index], _toolBarFormatPreference).AsString().Value; } public int TabRowCountAt(int index) { IPreferenceFolderArray a = _windowArrayPreference; return a.ConvertItem(a.Folders[index], _tabRowCountPreference).AsInt().Value; } public object QueryAdapter(IPreferenceFolder folder, Type type) { if (type == typeof(ICoreServicePreference)) return folder == _originalFolder ? _adapter : new CoreServicePreferenceAdapter(folder).Import(_adapter); else if (type == typeof(IWindowPreference)) { Debug.Assert(folder == _originalFolder); //IWindowPreferenceについてはSnapshotサポートせず return this; } else return null; } public string GetDescription(IPreferenceItem item) { return ""; } public void ValidateFolder(IPreferenceFolder folder, IPreferenceValidationResult output) { } #endregion public ICoreServicePreference OriginalPreference { get { return _adapter; } } public void FormatWindowPreference(MainWindow f) { IPreferenceFolder element = _windowArrayPreference.CreateNewFolder(); FormWindowState st = f.WindowState; Rectangle rc = st == FormWindowState.Normal ? f.DesktopBounds : f.RestoreBounds; //Normal時にはRestoreBound取得できない、注意 _windowArrayPreference.ConvertItem(element, _windowPositionPreference).AsString().Value = String.Format("({0}{1},{2},{3},{4})", st == FormWindowState.Maximized ? "Max," : "", rc.Left, rc.Top, rc.Width, rc.Height); //TODO PreferenceItemのテンプレートをViewManager側に移動したほうが汎用的 ISplittableViewManager vm = (ISplittableViewManager)f.ViewManager.GetAdapter(typeof(ISplittableViewManager)); if (vm != null) _windowArrayPreference.ConvertItem(element, _windowSplitFormatPreference).AsString().Value = vm.FormatSplitInfo(); _windowArrayPreference.ConvertItem(element, _toolBarFormatPreference).AsString().Value = f.ToolBar.FormatLocations(); _windowArrayPreference.ConvertItem(element, _tabRowCountPreference).AsInt().Value = f.DocumentTabFeature.TabRowCount; } } }
39.65493
139
0.639407
[ "Apache-2.0" ]
FNKGino/poderosa
Core/WindowPreference.cs
11,564
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using Charlotte.Commons; using Charlotte.Tests; namespace Charlotte { class Program { static void Main(string[] args) { ProcMain.CUIMain(new Program().Main2); } private void Main2(ArgsReader ar) { if (ProcMain.DEBUG) { Main3(); } else { Main4(); } Common.OpenOutputDirIfCreated(); } private void Main3() { // -- choose one -- //Main4(); //new Test0001().Test01(); //new Test0002().Test01(); //new Test0002().Test02(); //new Test0002().Test03(); //new Test0003().Test01(); new Test0004().Test01(); // -- Common.Pause(); } private void Main4() { // none } } }
15.155172
41
0.630262
[ "MIT" ]
soleil-taruto/wb
t20210325/Claes20200001/Claes20200001/Program.cs
881
C#
using System; using System.Collections.Generic; using UnityEngine; using System.IO; public class Wav { private const long DataChunkHeader = 0x61746164; private Stream _stream; private BinaryReader _reader; private Header _header; private List<DataChunk> _chunks; private int _chunkIndex; private int _sampleIndex; private AudioClip _clip; public AudioClip Clip => _clip; public static AudioClip Load(string clipName, bool streamData, Stream stream) { var wav = new Wav(clipName, streamData, stream); return wav.Clip; } public Wav(string clipName, bool streamData, Stream stream) { _stream = stream; _reader = new BinaryReader(stream); _header = ReadHeader(_reader); if (_header.format != 1) { Debug.LogWarning("Only PCM wav is implemented (" + clipName + ")"); return; } if (_header.bitsPerSample != 16) { Debug.LogWarning("Only 16bit wav is implemented (" + clipName + ")"); return; } _chunks = ScanDataChunks(_reader, _header); int lengthSamples = 0; foreach (var chunk in _chunks) { lengthSamples += chunk.blockCount; } _clip = AudioClip.Create(clipName, lengthSamples, _header.channels, (int)_header.sampleRate, streamData, ReadCallback, SetPositionCallback); } private void ReadCallback(float[] data) { int i = 0; while (i < data.Length && _chunkIndex < _chunks.Count) { var chunk = _chunks[_chunkIndex]; int samplesAvailable = chunk.sampleCount + chunk.sampleOffset - _sampleIndex; int samplesToRead = Math.Min(data.Length - i, samplesAvailable); for (int j = 0; j < samplesToRead; ++j, ++i) { data[i] = ReadSample(_reader); } _sampleIndex += samplesToRead; if (i < data.Length) ++_chunkIndex; } } private void SetPositionCallback(int pos) { for (_chunkIndex = 0; _chunkIndex < _chunks.Count; ++_chunkIndex) { var chunk = _chunks[_chunkIndex]; if (pos >= chunk.sampleOffset && pos < chunk.sampleOffset + chunk.sampleCount) { _stream.Position = chunk.position + (pos - chunk.sampleOffset) * _header.blockAlign; break; } } _sampleIndex = pos; } struct Header { public uint riffHeader; // "riff" public uint size; public uint wavHeader; // "WAVE" public uint formatSectionHeader; // "fmt " public uint fmtSize; public ushort format; // PCM = 1, otherwise something compressed public ushort channels; public uint sampleRate; public uint bytePerSec; public ushort blockAlign; public ushort bitsPerSample; } struct DataChunk { public int position; public int sampleOffset; public int sampleCount; public int blockCount; } private static Header ReadHeader(BinaryReader reader) { var header = new Header(); header.riffHeader = reader.ReadUInt32(); header.size = reader.ReadUInt32(); header.wavHeader = reader.ReadUInt32(); header.formatSectionHeader = reader.ReadUInt32(); header.fmtSize = reader.ReadUInt32(); header.format = reader.ReadUInt16(); header.channels = reader.ReadUInt16(); header.sampleRate = reader.ReadUInt32(); header.bytePerSec = reader.ReadUInt32(); header.blockAlign = reader.ReadUInt16(); header.bitsPerSample = reader.ReadUInt16(); return header; } private static float ReadSample(BinaryReader reader) { byte byte1 = reader.ReadByte(); byte byte2 = reader.ReadByte(); return BytesToFloat(byte1, byte2); } private static float BytesToFloat(byte byte1, byte byte2) { // convert two bytes to one short (little endian) short s = (short)((byte2 << 8) | byte1); // convert to range from -1 to (just below) 1 return s / 32768.0F; } private static List<DataChunk> ScanDataChunks(BinaryReader reader, Header header) { long startPosition = reader.BaseStream.Position; var chunks = new List<DataChunk>(); int sampleOffset = 0; try { while (true) { long dataHeader = reader.ReadUInt32(); uint dataSize = reader.ReadUInt32(); if (dataHeader == DataChunkHeader) // Skipping PAD and other chunks { int blockCount = (int) dataSize / header.blockAlign; int sampleCount = blockCount * header.channels; chunks.Add(new DataChunk() { position = (int) reader.BaseStream.Position, sampleOffset = sampleOffset, sampleCount = sampleCount, blockCount = blockCount, }); sampleOffset += sampleCount; } reader.BaseStream.Seek(dataSize, SeekOrigin.Current); } } catch (IOException) { } reader.BaseStream.Position = startPosition; return chunks; } }
31.214689
148
0.568326
[ "MIT" ]
Coco10086/Diablerie
Assets/Scripts/Diablerie/Engine/IO/Wav.cs
5,527
C#
/* * Copyright 2013-2015 Vitalii Fedorchenko (nrecosite.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the NReco Recommender software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * making recommendations in a web application, shipping NReco Recommender with a closed * source product. * * For more information, please contact: support@nrecosite.com * * Parts of this code are based on Apache Mahout ("Taste") that was licensed under the * Apache 2.0 License (see http://www.apache.org/licenses/LICENSE-2.0). * * Unless required by applicable law or agreed to in writing, software distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.IO; using NReco.CF; namespace NReco.CF.Taste.Impl.Common { /// @see FastByIDMap public sealed class FastIDSet : ICloneable, IEnumerable<long> { private static float DEFAULT_LOAD_FACTOR = 1.5f; /// Dummy object used to represent a key that has been removed. private static long REMOVED = long.MaxValue; private static long NULL = Int64.MinValue; private long[] keys; private float loadFactor; private int numEntries; private int numSlotsUsed; /// Creates a new {@link FastIDSet} with default capacity. public FastIDSet() : this(2) { } public FastIDSet(long[] initialKeys) : this(initialKeys.Length) { AddAll(initialKeys); } public FastIDSet(int size) : this(size, DEFAULT_LOAD_FACTOR) { } public FastIDSet(int size, float loadFactor) { //Preconditions.checkArgument(size >= 0, "size must be at least 0"); //Preconditions.checkArgument(loadFactor >= 1.0f, "loadFactor must be at least 1.0"); this.loadFactor = loadFactor; int max = (int) (RandomUtils.MAX_INT_SMALLER_TWIN_PRIME / loadFactor); //Preconditions.checkArgument(size < max, "size must be less than %d", max); int hashSize = RandomUtils.nextTwinPrime((int) (loadFactor * size)); keys = new long[hashSize]; ArrayFill(keys, NULL); } private FastIDSet(FastIDSet copyFrom) { keys = copyFrom.keys; loadFactor = copyFrom.loadFactor; numEntries = copyFrom.numEntries; numSlotsUsed = copyFrom.numSlotsUsed; } void ArrayFill<T>(T[] a, T val) { for (int i = 0; i < a.Length; i++) a[i] = val; } /// @see #findForAdd(long) private int find(long key) { int theHashCode = (int) key & 0x7FFFFFFF; // make sure it's positive long[] keys = this.keys; int hashSize = keys.Length; int jump = 1 + theHashCode % (hashSize - 2); int index = theHashCode % hashSize; long currentKey = keys[index]; while (currentKey != NULL && key != currentKey) { // note: true when currentKey == REMOVED index -= index < jump ? jump - hashSize : jump; currentKey = keys[index]; } return index; } /// @see #find(long) private int findForAdd(long key) { int theHashCode = (int) key & 0x7FFFFFFF; // make sure it's positive long[] keys = this.keys; int hashSize = keys.Length; int jump = 1 + theHashCode % (hashSize - 2); int index = theHashCode % hashSize; long currentKey = keys[index]; while (currentKey != NULL && currentKey != REMOVED && key != currentKey) { index -= index < jump ? jump - hashSize : jump; currentKey = keys[index]; } if (currentKey != REMOVED) { return index; } // If we're adding, it's here, but, the key might have a value already later int addIndex = index; while (currentKey != NULL && key != currentKey) { index -= index < jump ? jump - hashSize : jump; currentKey = keys[index]; } return key == currentKey ? index : addIndex; } public int Count() { return numEntries; } public bool IsEmpty() { return numEntries == 0; } public bool Contains(long key) { return key != NULL && key != REMOVED && keys[find(key)] != NULL; } public bool Add(long key) { if (key == NULL || key == REMOVED) throw new ArgumentException(); //Preconditions.checkArgument(key != NULL && key != REMOVED); // If less than half the slots are open, let's clear it up if (numSlotsUsed * loadFactor >= keys.Length) { // If over half the slots used are actual entries, let's grow if (numEntries * loadFactor >= numSlotsUsed) { growAndRehash(); } else { // Otherwise just rehash to clear REMOVED entries and don't grow Rehash(); } } // Here we may later consider implementing Brent's variation described on page 532 int index = findForAdd(key); long keyIndex = keys[index]; if (keyIndex != key) { keys[index] = key; numEntries++; if (keyIndex == NULL) { numSlotsUsed++; } return true; } return false; } public IEnumerator<long> GetEnumerator() { for (int position=0; position<keys.Length; position++) { if (keys[position] != NULL && keys[position] != REMOVED) { yield return keys[position]; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public long[] ToArray() { long[] result = new long[numEntries]; for (int i = 0, position = 0; i < result.Length; i++) { while (keys[position] == NULL || keys[position] == REMOVED) { position++; } result[i] = keys[position++]; } return result; } public bool Remove(long key) { if (key == NULL || key == REMOVED) { return false; } int index = find(key); if (keys[index] == NULL) { return false; } else { keys[index] = REMOVED; numEntries--; return true; } } public bool AddAll(long[] c) { bool changed = false; foreach (long k in c) { if (Add(k)) { changed = true; } } return changed; } public bool AddAll(FastIDSet c) { bool changed = false; foreach (long k in c.keys) { if (k != NULL && k != REMOVED && Add(k)) { changed = true; } } return changed; } public bool RemoveAll(long[] c) { bool changed = false; foreach (long o in c) { if (Remove(o)) { changed = true; } } return changed; } public bool RemoveAll(FastIDSet c) { bool changed = false; foreach (long k in c.keys) { if (k != NULL && k != REMOVED && Remove(k)) { changed = true; } } return changed; } public bool RetainAll(FastIDSet c) { bool changed = false; for (int i = 0; i < keys.Length; i++) { long k = keys[i]; if (k != NULL && k != REMOVED && !c.Contains(k)) { keys[i] = REMOVED; numEntries--; changed = true; } } return changed; } public void Clear() { numEntries = 0; numSlotsUsed = 0; ArrayFill(keys, NULL); } private void growAndRehash() { if (keys.Length * loadFactor >= RandomUtils.MAX_INT_SMALLER_TWIN_PRIME) { throw new InvalidOperationException("Can't grow any more"); } rehash(RandomUtils.nextTwinPrime((int) (loadFactor * keys.Length))); } public void Rehash() { rehash(RandomUtils.nextTwinPrime((int) (loadFactor * numEntries))); } private void rehash(int newHashSize) { long[] oldKeys = keys; numEntries = 0; numSlotsUsed = 0; keys = new long[newHashSize]; ArrayFill(keys, NULL); foreach (long key in oldKeys) { if (key != NULL && key != REMOVED) { Add(key); } } } /// Convenience method to quickly compute just the size of the intersection with another {@link FastIDSet}. /// /// @param other /// {@link FastIDSet} to intersect with /// @return number of elements in intersection public int IntersectionSize(FastIDSet other) { int count = 0; foreach (long key in other.keys) { if (key != NULL && key != REMOVED && keys[find(key)] != NULL) { count++; } } return count; } public object Clone() { return new FastIDSet(this); } public override int GetHashCode() { int hash = 0; long[] keys = this.keys; foreach (long key in keys) { if (key != NULL && key != REMOVED) { hash = 31 * hash + ((int) (key >> 32) ^ (int) key); } } return hash; } public override bool Equals(Object other) { if (!(other is FastIDSet)) { return false; } FastIDSet otherMap = (FastIDSet) other; long[] otherKeys = otherMap.keys; int length = keys.Length; int otherLength = otherKeys.Length; int max = Math.Min(length, otherLength); int i = 0; while (i < max) { long key = keys[i]; long otherKey = otherKeys[i]; if (key == NULL || key == REMOVED) { if (otherKey != NULL && otherKey != REMOVED) { return false; } } else { if (key != otherKey) { return false; } } i++; } while (i < length) { long key = keys[i]; if (key != NULL && key != REMOVED) { return false; } i++; } while (i < otherLength) { long key = otherKeys[i]; if (key != NULL && key != REMOVED) { return false; } i++; } return true; } public override string ToString() { if (IsEmpty()) { return "[]"; } var result = new System.Text.StringBuilder(); result.Append('['); foreach (long key in keys) { if (key != NULL && key != REMOVED) { result.Append(key).Append(','); } } result[result.Length - 1] = ']'; return result.ToString(); } } }
27.074667
110
0.60199
[ "Apache-2.0" ]
andy840119/recommender
src/NReco.Recommender/taste/impl/common/FastIDSet.cs
10,153
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace KubernetesService.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// HTTPIngressPath associates a path regex with a backend. Incoming urls /// matching the path are forwarded to the backend. /// </summary> public partial class Iok8sapiextensionsv1beta1HTTPIngressPath { /// <summary> /// Initializes a new instance of the /// Iok8sapiextensionsv1beta1HTTPIngressPath class. /// </summary> public Iok8sapiextensionsv1beta1HTTPIngressPath() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// Iok8sapiextensionsv1beta1HTTPIngressPath class. /// </summary> /// <param name="backend">Backend defines the referenced service /// endpoint to which the traffic will be forwarded to.</param> /// <param name="path">Path is an extended POSIX regex as defined by /// IEEE Std 1003.1, (i.e this follows the egrep/unix syntax, not the /// perl syntax) matched against the path of an incoming request. /// Currently it can contain characters disallowed from the /// conventional "path" part of a URL as defined by RFC 3986. Paths /// must begin with a '/'. If unspecified, the path defaults to a catch /// all sending traffic to the backend.</param> public Iok8sapiextensionsv1beta1HTTPIngressPath(Iok8sapiextensionsv1beta1IngressBackend backend, string path = default(string)) { Backend = backend; Path = path; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets backend defines the referenced service endpoint to /// which the traffic will be forwarded to. /// </summary> [JsonProperty(PropertyName = "backend")] public Iok8sapiextensionsv1beta1IngressBackend Backend { get; set; } /// <summary> /// Gets or sets path is an extended POSIX regex as defined by IEEE Std /// 1003.1, (i.e this follows the egrep/unix syntax, not the perl /// syntax) matched against the path of an incoming request. Currently /// it can contain characters disallowed from the conventional "path" /// part of a URL as defined by RFC 3986. Paths must begin with a '/'. /// If unspecified, the path defaults to a catch all sending traffic to /// the backend. /// </summary> [JsonProperty(PropertyName = "path")] public string Path { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Backend == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Backend"); } if (Backend != null) { Backend.Validate(); } } } }
37.945055
135
0.607588
[ "MIT" ]
tonnyeremin/kubernetes_gen
KubernetesService/Source/CSharp_Kubernetes/Models/Iok8sapiextensionsv1beta1HTTPIngressPath.cs
3,453
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ActorModel.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ActorModel.Tests")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bd0574f1-4e34-46fb-944e-0d208691e188")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.837838
84
0.747857
[ "MIT" ]
Hassan822/Akka-Testing
ActorModel/ActorModel.Tests/Properties/AssemblyInfo.cs
1,403
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Moq; using System.Data.Entity; using RoboBraille.WebApi.Models; using System.Collections.Generic; using System.Text; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net.Http; using RoboBraille.WebApi.Controllers; namespace RoboBraille.WebApi.Test { [TestClass] public class TestHtmlToText { [TestMethod] public async Task TestPostHtmlToText() { //init var mockJobs = new Mock<DbSet<Job>>(); var mockServiceUsers = new Mock<DbSet<ServiceUser>>(); var mockContext = new Mock<RoboBrailleDataContext>(); // arrange var users = new List<ServiceUser> { new ServiceUser { EmailAddress = "test@test.eu", UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"), ApiKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"), FromDate = new DateTime(2015, 1, 1), ToDate = new DateTime(2020, 1, 1), UserName = "TestUser", Jobs = null } }.AsQueryable(); HTMLToTextJob htj = new HTMLToTextJob() { Id = Guid.NewGuid(), FileContent = new byte[512], UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"), FileExtension = ".pdf", FileName = "test", MimeType = "application/pdf", Status = JobStatus.Started, SubmitTime = DateTime.Now, DownloadCounter = 0, InputFileHash = new byte[8], }; HTMLToTextJob htj2 = new HTMLToTextJob() { Id = Guid.NewGuid(), FileContent = new byte[256], UserId = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"), FileExtension = ".txt", FileName = "test2", MimeType = "text/plain", Status = JobStatus.Done, SubmitTime = DateTime.Now, DownloadCounter = 2, InputFileHash = new byte[2] }; var jobs = new List<HTMLToTextJob> { htj2 }.AsQueryable(); mockJobs.As<IDbAsyncEnumerable<Job>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<Job>(jobs.GetEnumerator())); mockJobs.As<IQueryable<Job>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<Job>(jobs.Provider)); mockJobs.As<IQueryable<Job>>().Setup(m => m.Expression).Returns(jobs.Expression); mockJobs.As<IQueryable<Job>>().Setup(m => m.ElementType).Returns(jobs.ElementType); mockJobs.As<IQueryable<Job>>().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator()); mockServiceUsers.As<IDbAsyncEnumerable<ServiceUser>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<ServiceUser>(users.GetEnumerator())); mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<ServiceUser>(users.Provider)); mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Expression).Returns(users.Expression); mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.ElementType).Returns(users.ElementType); mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator()); mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object); mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object); var repo = new HTMLToTextRepository(mockContext.Object); var request = new HttpRequestMessage(); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\""); var serviceController = new HTMLToTextController(repo); serviceController.Request = request; //call await serviceController.Post(htj); //test mockJobs.Verify(m => m.Add(It.IsAny<Job>()), Times.Once()); mockContext.Verify(m => m.SaveChanges(), Times.Exactly(1)); //twice if it is synced //mockContext.Verify(m => m.SaveChanges(), Times.Exactly(2)); } } }
45.970297
258
0.600043
[ "Apache-2.0" ]
sensusaps/RoboBraille.Web.API
RoboBraille.WebApi.Test/TestControllers/TestHtmlToText.cs
4,645
C#
using Oxide.Core.Libraries; using Oxide.Core.Libraries.Covalence; using System; namespace Oxide.Game.Hurtworld.Libraries { public class Server : Library { #region Initialization internal static readonly BanManager BanManager = BanManager.Instance; internal static readonly ChatManagerServer ChatManager = ChatManagerServer.Instance; internal static readonly ConsoleManager ConsoleManager = ConsoleManager.Instance; #endregion Initialization #region Administration /// <summary> /// Bans the player for the specified reason and duration /// </summary> /// <param name="id"></param> /// <param name="reason"></param> /// <param name="duration"></param> public void Ban(string id, string reason, TimeSpan duration = default(TimeSpan)) { if (!IsBanned(id)) BanManager.AddBan(Convert.ToUInt64(id)); } /// <summary> /// Gets if the player is banned /// </summary> /// <param name="id"></param> public bool IsBanned(string id) => BanManager.IsBanned(Convert.ToUInt64(id)); /// <summary> /// Unbans the player /// </summary> /// <param name="id"></param> public void Unban(string id) { if (IsBanned(id)) BanManager.RemoveBan(Convert.ToUInt64(id)); } #endregion Administration #region Chat and Commands /// <summary> /// Broadcasts the specified chat message and prefix to all players /// </summary> /// <param name="message"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Broadcast(string message, string prefix, params object[] args) { message = string.Format(Formatter.ToUnity(message), args); var formatted = prefix != null ? $"{prefix} {message}" : message; #if ITEMV2 ChatManager.SendChatMessage(new ServerChatMessage(formatted)); #else ChatManager.RPC("RelayChat", uLink.RPCMode.Others, formatted); #endif ConsoleManager.SendLog($"[Chat] {message}"); } /// <summary> /// Broadcasts the specified chat message to all players /// </summary> /// <param name="message"></param> public void Broadcast(string message) => Broadcast(message, null); /// <summary> /// Runs the specified server command /// </summary> /// <param name="command"></param> /// <param name="args"></param> public void Command(string command, params object[] args) { ConsoleManager.ExecuteCommand($"{command} {string.Join(" ", Array.ConvertAll(args, x => x.ToString()))}"); } #endregion Chat and Commands } }
33.174419
118
0.589905
[ "MIT" ]
CryptoJones/Oxide
Games/Oxide.Hurtworld/Libraries/Server.cs
2,855
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; public class Item { public enum ItemType { Carrot, Apple, Meat, } public ItemType itemType; public int amount = 0; public Sprite getSprite() { Debug.Log((int)itemType); switch (itemType) { case ItemType.Apple: return ItemAssets.instance.appleSprite; case ItemType.Carrot: return ItemAssets.instance.carrotSprite; case ItemType.Meat: return ItemAssets.instance.meatSprite; default: Assert.IsTrue(false); return ItemAssets.instance.appleSprite; } } public string getInfo() { switch (itemType) { case ItemType.Apple: return "Apple"; case ItemType.Carrot: return "Carrot"; case ItemType.Meat: return "Meat"; default: Assert.IsTrue(false); return "UNKNOWN"; } } }
24.8
76
0.693548
[ "Apache-2.0" ]
zacharyselk/Test-Project
Test Project/Assets/Scripts/Item.cs
868
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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 Castle.Windsor.Tests.Facilities.TypedFactory.Delegates { using System; public class UsesFooAndDelegate { private readonly Func<int, Foo> myFooFactory; private int counter; public UsesFooAndDelegate(Func<int, Foo> myFooFactory, Foo foo) { Foo = foo; this.myFooFactory = myFooFactory; counter = 0; } public Foo Foo { get; private set; } public Foo GetFoo() { return myFooFactory(++counter); } } }
29.236842
76
0.70207
[ "Apache-2.0" ]
castleproject-deprecated/Castle.Windsor-READONLY
src/Castle.Windsor.Tests/Facilities/TypedFactory/Delegates/UsesFooAndDelegate.cs
1,111
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WPF_Demo_Area.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WPF_Demo_Area.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.652778
179
0.603665
[ "MIT" ]
Y-Manoj-Kumar/WindowsPresentationFoundation
WPF Demo Area/Properties/Resources.Designer.cs
2,785
C#
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Logging; namespace Google { /// <summary> /// Class defining the context in which this library is run. /// Allows to set up custom loggers and other bindings. /// </summary> public static class ApplicationContext { private static ILogger logger; /// <summary> /// Returns the logger used within this ApplicationContext. /// </summary> /// <remarks>Will create a Log4NetLogger if no logger was registered previously</remarks> public static ILogger Logger { get { // Register the default null-logger if no other one was set. return logger ?? (logger = new NullLogger()); } } /// <summary> /// Registers a logger with this ApplicationContext. /// </summary> /// <exception cref="InvalidOperationException">Thrown if a logger was already registered.</exception> public static void RegisterLogger(ILogger loggerToRegister) { if (logger != null && !(logger is NullLogger)) { throw new InvalidOperationException("A logger was already registered with this context."); } logger = loggerToRegister; } } }
33.77193
111
0.625974
[ "Apache-2.0" ]
Victhor94/loggencsg
vendors/gapi/Src/GoogleApis/ApplicationContext.cs
1,927
C#
using System; using System.Collections.Generic; using System.Linq; using DoubleEntry.Common.Exceptions; namespace DoubleEntry.Broker { public class EventBroker : IEventBroker { private readonly IEventBrokerRepository _repository; public EventBroker(IEventBrokerRepository repository) { _repository = repository; } public IList<BaseEvent> EventsCommitted { get; set; } = new List<BaseEvent>(); public IList<BaseEvent> EventsToCommit { get; set; } = new List<BaseEvent>(); public void CommitEvents(IList<BaseEvent> events) { foreach (var @event in EventsToCommit) { CheckDuplicatedBeforeCommit(); } _repository.InsertEvents(events); } public void CheckDuplicatedBeforeCommit() { foreach (var @event in EventsToCommit) { if (EventsCommitted.Any(x => x.Exists(@event))) throw new DuplicatedEventException(); } } public IEnumerable<BaseEvent> GetAllEvents() { return _repository.ReadEvents(DateTime.MinValue); } public IEnumerable<BaseEvent> GetEventsBasedOnType(Type eventType) { return _repository.ReadEvents(eventType); } } }
27.755102
86
0.6
[ "MIT" ]
kyogeti/double-entry-exploring
src/DoubleEntry.Broker/EventBroker.cs
1,362
C#
using Hellang.Middleware.ProblemDetails; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using RPG.Data.Context; using RPG.Data.Repository.AuthRepository; using RPG.Data.Repository.CharacterRepository; using RPG.Data.Repository.WeaponRepository; using RPG.Services.AuthService; using RPG.Services.CharacterService; using RPG.Services.CharacterSkillService; using System.Text; namespace RPG.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAutoMapper(typeof(Data.Profiles.MapperProfile).Assembly); services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefultConnection")) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) ); services.AddProblemDetails(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII .GetBytes(Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false }; }); //Repose services.AddScoped<ICharacterRepository, CharacterRepository>(); services.AddScoped<IAuthRepository, AuthRepository>(); services.AddScoped<IWeaponRepository, WeaponRepository>(); //Services services.AddScoped<ICharacterService, CharacterService>(); services.AddScoped<IAuthService, AuthService>(); services.AddScoped<ICharacterSkillService, CharacterSkillService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseProblemDetails(); //app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
33.920455
92
0.636851
[ "MIT" ]
HusseinShukri/DotNET-RPG
RPG/RPG.API/.vshistory/Startup.cs/2021-08-29_14_28_31_700.cs
2,987
C#
using System; using ASTRA.EMSG.Business.Reporting; namespace ASTRA.EMSG.Business.Reports.BenchmarkauswertungInventarkennwerten { [Serializable] public class BenchmarkauswertungInventarkennwertenParameter : BenchmarkauswertungParameter { } }
25.7
94
0.81323
[ "BSD-3-Clause" ]
astra-emsg/ASTRA.EMSG
Master/ASTRA.EMSG.Business/Reports/BenchmarkauswertungInventarkennwerten/BenchmarkauswertungInventarkennwertenParameter.cs
257
C#
//----------------------------------------------------------------------- // <copyright file="AbstractDispatcher.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Threading; using Akka.Actor; using Akka.Configuration; using Akka.Dispatch.SysMsg; using Akka.Event; namespace Akka.Dispatch { /// <summary> /// Contextual information that's useful for dispatchers /// </summary> public interface IDispatcherPrerequisites { /// <summary> /// The <see cref="EventStream"/> that belongs to the current <see cref="ActorSystem"/>. /// </summary> EventStream EventStream { get; } /// <summary> /// The <see cref="IScheduler"/> that belongs to the current <see cref="ActorSystem"/>. /// </summary> IScheduler Scheduler { get; } /// <summary> /// The <see cref="Settings"/> for the current <see cref="ActorSystem"/>. /// </summary> Settings Settings { get; } /// <summary> /// The list of registered <see cref="Mailboxes"/> for the current <see cref="ActorSystem"/>. /// </summary> Mailboxes Mailboxes { get; } } /// <summary> /// The default set of contextual data needed for <see cref="MessageDispatcherConfigurator"/>s /// </summary> public sealed class DefaultDispatcherPrerequisites : IDispatcherPrerequisites { /// <summary> /// Default constructor... /// </summary> public DefaultDispatcherPrerequisites(EventStream eventStream, IScheduler scheduler, Settings settings, Mailboxes mailboxes) { Mailboxes = mailboxes; Settings = settings; Scheduler = scheduler; EventStream = eventStream; } public EventStream EventStream { get; private set; } public IScheduler Scheduler { get; private set; } public Settings Settings { get; private set; } public Mailboxes Mailboxes { get; private set; } } /// <summary> /// Base class used for hooking new <see cref="MessageDispatcher"/> types into <see cref="Dispatchers"/> /// </summary> public abstract class MessageDispatcherConfigurator { /// <summary> /// Takes a <see cref="Config"/> object, usually passed in via <see cref="Settings.Config"/> /// </summary> protected MessageDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) { Prerequisites = prerequisites; Config = config; } /// <summary> /// System-wide configuration /// </summary> public Config Config { get; private set; } /// <summary> /// The system prerequisites needed for this dispatcher to do its job /// </summary> public IDispatcherPrerequisites Prerequisites { get; private set; } /// <summary> /// Returns a <see cref="Dispatcher"/> instance. /// /// Whether or not this <see cref="MessageDispatcherConfigurator"/> returns a new instance /// or returns a reference to an existing instance is an implementation detail of the /// underlying implementation. /// </summary> /// <returns></returns> public abstract MessageDispatcher Dispatcher(); } /// <summary> /// Used to create instances of the <see cref="ThreadPoolDispatcher"/>. /// /// <remarks> /// Always returns the same instance, since the <see cref="ThreadPool"/> is global. /// This is also the default dispatcher for all actors. /// </remarks> /// </summary> class ThreadPoolDispatcherConfigurator : MessageDispatcherConfigurator { public ThreadPoolDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { _instance = new ThreadPoolDispatcher(this); } //cached instance private readonly ThreadPoolDispatcher _instance; public override MessageDispatcher Dispatcher() { /* * Always want to return the same instance of the ThreadPoolDispatcher */ return _instance; } } /// <summary> /// Used to create instances of the <see cref="TaskDispatcher"/>. /// /// <remarks> /// Always returns the same instance. /// </remarks> /// </summary> class TaskDispatcherConfigurator : MessageDispatcherConfigurator { public TaskDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { _instance = new TaskDispatcher(this); } private readonly TaskDispatcher _instance; public override MessageDispatcher Dispatcher() { return _instance; } } /// <summary> /// Used to create instances of the <see cref="CurrentSynchronizationContextDispatcher"/>. /// /// <remarks> /// Always returns the a new instance. /// </remarks> /// </summary> class CurrentSynchronizationContextDispatcherConfigurator : MessageDispatcherConfigurator { public CurrentSynchronizationContextDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { } public override MessageDispatcher Dispatcher() { return new CurrentSynchronizationContextDispatcher(this); } } /// <summary> /// Class responsible for pushing messages from an actor's mailbox into its /// receive methods. Comes in many different flavors. /// </summary> public abstract class MessageDispatcher { /// <summary> /// The default throughput /// </summary> public const int DefaultThroughput = 100; /// <summary> /// The configurator used to configure this message dispatcher. /// </summary> public MessageDispatcherConfigurator Configurator { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="MessageDispatcher" /> class. /// </summary> protected MessageDispatcher(MessageDispatcherConfigurator configurator) { Configurator = configurator; Throughput = DefaultThroughput; } /// <summary> /// The ID for this dispatcher. /// </summary> public string Id { get; set; } /// <summary> /// Gets or sets the throughput deadline time. /// </summary> /// <value>The throughput deadline time.</value> public long? ThroughputDeadlineTime { get; set; } /// <summary> /// Gets or sets the throughput. /// </summary> /// <value>The throughput.</value> public int Throughput { get; set; } /// <summary> /// Schedules the specified run. /// </summary> /// <param name="run">The run.</param> public abstract void Schedule(Action run); /// <summary> /// Dispatches a user-defined message from a mailbox to an <see cref="ActorCell"/> /// </summary> public virtual void Dispatch(ActorCell cell, Envelope envelope) { cell.Invoke(envelope); } /// <summary> /// Dispatches a <see cref="ISystemMessage"/> from a mailbox to an <see cref="ActorCell"/> /// </summary> public virtual void SystemDispatch(ActorCell cell, Envelope envelope) { cell.SystemInvoke(envelope); } /// <summary> /// Attaches the dispatcher to the <see cref="ActorCell"/> /// /// <remarks> /// Practically, doesn't do very much right now - dispatchers aren't responsible for creating /// mailboxes in Akka.NET /// </remarks> /// </summary> /// <param name="cell">The ActorCell belonging to the actor who's attaching to this dispatcher.</param> public virtual void Attach(ActorCell cell) { } /// <summary> /// Detaches the dispatcher to the <see cref="ActorCell"/> /// /// <remarks> /// Only really used in dispatchers with 1:1 relationship with dispatcher. /// </remarks> /// </summary> /// <param name="cell">The ActorCell belonging to the actor who's deatching from this dispatcher.</param> public virtual void Detach(ActorCell cell) { } } }
33.889313
151
0.588017
[ "Apache-2.0" ]
codemaveric/akka.net
src/core/Akka/Dispatch/AbstractDispatcher.cs
8,881
C#
using UWPX_UI_Context.Classes.DataTemplates.Controls; using Windows.UI.Xaml.Media; namespace UWPX_UI_Context.Classes.DataContext.Controls { public class ImObservatoryBadgeControlContext { //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\ #region --Attributes-- public readonly ImObservatoryBadgeControlDataTemplate MODEL = new ImObservatoryBadgeControlDataTemplate(); #endregion //--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public void UpdateView(string rating) { // Badge color: switch (rating.ToLowerInvariant()) { case "a": MODEL.BadgeBrush = new SolidColorBrush(UiUtils.HexStringToColor("#5cb85c")); break; case "b": case "c": case "d": MODEL.BadgeBrush = new SolidColorBrush(UiUtils.HexStringToColor("#f0ad4e")); break; case "e": case "f": MODEL.BadgeBrush = new SolidColorBrush(UiUtils.HexStringToColor("#d9534f")); break; default: MODEL.BadgeBrush = new SolidColorBrush(UiUtils.HexStringToColor("#818181")); break; } } #endregion #region --Misc Methods (Private)-- #endregion #region --Misc Methods (Protected)-- #endregion //--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- #endregion } }
33.362319
144
0.385317
[ "MPL-2.0" ]
LibreHacker/UWPX-Client
UWPX_UI_Context/Classes/DataContext/Controls/ImObservatoryBadgeControlContext.cs
2,304
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inbox2.Platform.Interfaces.Enumerations { public static class DownloadStates { public const int None = 0; public const int Initial = 10; public const int Downloading = 20; public const int Downloaded = 30; public const int DoNotDownload = 100; } }
23.3125
50
0.726542
[ "BSD-3-Clause" ]
Klaudit/inbox2_desktop
Code/Platform/Interfaces/Enumerations/DownloadStates.cs
375
C#
//Write a program that finds the maximal increasing sequence in an array. using System; class MaximalIncreasingSequence { static void Main() { string[] input = Console.ReadLine().Split(','); int[] numbers = new int[input.Length]; for (int i = 0; i < input.Length; i++) { numbers[i] = int.Parse(input[i]); } int count = 1; int endIndex = 0; int sequenceLenght = 0; int[] sequence = new int[input.Length]; for (int i = 0; i < numbers.Length - 1; i++) { if (numbers[i] < numbers[i + 1]) { count++; } else { if (sequenceLenght < count) { sequenceLenght = count; endIndex = i; } count = 1; } } if (sequenceLenght < count) { sequenceLenght = count; endIndex = numbers.Length - 1; } for (int i = endIndex - sequenceLenght + 1; i <= endIndex; i++) { if (i == endIndex) { Console.WriteLine("{0}", numbers[i]); } else { Console.Write("{0},", numbers[i]); } } } }
23.649123
74
0.409496
[ "MIT" ]
milkokochev/Telerik
C#2/HomeWorks/01. Arrays/Maximal increasing sequence/MaximalIncreasingSequence.cs
1,350
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace LilyPathDemo { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main () { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
22.045455
65
0.6
[ "MIT" ]
jaquadro/LilyPath
LilyPathDemo/Program.cs
487
C#
using UnityEngine; using System; public class menu_crewmate_controller : MonoBehaviour { public Color[] colorList; public SpriteRenderer[] crewmates; public double[] randomCrewmate; public int[] randomCrewmateOut; void Start () { selectCrewmate(); } void selectCrewmate() { randomCrewmate[0] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmate[1] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmate[2] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmate[3] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmate[4] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmate[5] = System.Math.Round(UnityEngine.Random.Range(0f, 5f)); randomCrewmateOut[0] = (int)randomCrewmate[0]; randomCrewmateOut[1] = (int)randomCrewmate[1]; randomCrewmateOut[2] = (int)randomCrewmate[2]; randomCrewmateOut[3] = (int)randomCrewmate[3]; randomCrewmateOut[4] = (int)randomCrewmate[4]; randomCrewmateOut[5] = (int)randomCrewmate[5]; checkDoubles(); } void checkDoubles() { if (randomCrewmateOut[0] == randomCrewmateOut[1] || randomCrewmateOut[0] == randomCrewmateOut[2] || randomCrewmateOut[0] == randomCrewmateOut[3] || randomCrewmateOut[0] == randomCrewmateOut[4] || randomCrewmateOut[0] == randomCrewmateOut[5]) { selectCrewmate(); } else if (randomCrewmateOut[1] == randomCrewmateOut[0] || randomCrewmateOut[1] == randomCrewmateOut[2] || randomCrewmateOut[1] == randomCrewmateOut[3] || randomCrewmateOut[1] == randomCrewmateOut[4] || randomCrewmateOut[1] == randomCrewmateOut[5]) { selectCrewmate(); } else if (randomCrewmateOut[2] == randomCrewmateOut[0] || randomCrewmateOut[2] == randomCrewmateOut[1] || randomCrewmateOut[2] == randomCrewmateOut[3] || randomCrewmateOut[2] == randomCrewmateOut[4] || randomCrewmateOut[2] == randomCrewmateOut[5]) { selectCrewmate(); } else if (randomCrewmateOut[3] == randomCrewmateOut[0] || randomCrewmateOut[3] == randomCrewmateOut[1] || randomCrewmateOut[3] == randomCrewmateOut[2] || randomCrewmateOut[3] == randomCrewmateOut[4] || randomCrewmateOut[3] == randomCrewmateOut[5]) { selectCrewmate(); } else if (randomCrewmateOut[4] == randomCrewmateOut[0] || randomCrewmateOut[4] == randomCrewmateOut[1] || randomCrewmateOut[4] == randomCrewmateOut[2] || randomCrewmateOut[4] == randomCrewmateOut[3] || randomCrewmateOut[4] == randomCrewmateOut[5]) { selectCrewmate(); } else if (randomCrewmateOut[5] == randomCrewmateOut[0] || randomCrewmateOut[5] == randomCrewmateOut[1] || randomCrewmateOut[5] == randomCrewmateOut[2] || randomCrewmateOut[5] == randomCrewmateOut[3] || randomCrewmateOut[5] == randomCrewmateOut[4]) { selectCrewmate(); } else { setColor(); } } void setColor() { crewmates[randomCrewmateOut[0]].color = colorList[0]; crewmates[randomCrewmateOut[1]].color = colorList[1]; crewmates[randomCrewmateOut[2]].color = colorList[2]; crewmates[randomCrewmateOut[3]].color = colorList[3]; crewmates[randomCrewmateOut[4]].color = colorList[4]; crewmates[randomCrewmateOut[5]].color = colorList[5]; } }
41.853333
248
0.722842
[ "Apache-2.0" ]
Homebrew-Ports/Among-Us-for-the-3ds
Assets/Scripts/menu/menu_crewmate_controller.cs
3,141
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Advertisements; public class InitializeAds : MonoBehaviour { string gameId = "3528723"; bool testMode = true; void Start() { Advertisement.Initialize(gameId, testMode); } }
18.8125
51
0.714286
[ "MIT" ]
westmacgames/speedcube
Assets/Scripts/Advertising/InitializeAds.cs
303
C#
using PhilipDaubmeier.CompactTimeSeries; using PhilipDaubmeier.GraphIoT.Core.Aggregation; using PhilipDaubmeier.GraphIoT.Core.ViewModel; using PhilipDaubmeier.GraphIoT.Graphite.Model; using System; using System.Collections.Generic; using System.Linq; namespace PhilipDaubmeier.GraphIoT.Graphite.Parser.Query { public class QueryOptimizer { private readonly HashSet<ResampleFunctionExpression?> _resampleFuncs = new(); private readonly List<Aggregator> _nonOptimizableResampler = new() { Aggregator.Median, Aggregator.Minimum, Aggregator.Maximum, Aggregator.Diff, Aggregator.Stddev, Aggregator.Count, Aggregator.Range, Aggregator.Multiply, Aggregator.Last }; public readonly Parser _parser; public GraphDataSource DataSource { get; set; } = new GraphDataSource(new List<IGraphCollectionViewModel>()); public QueryOptimizer(Parser parser) => (_parser, DataSource) = (parser, parser.DataSource); public IEnumerable<IGraphiteGraph> ParseAndOptimize(IEnumerable<string> target) { var expressions = target.Select(t => _parser.Parse(t)); Optimize(expressions); return expressions.SelectMany(x => x.Graphs); } public void Optimize(IEnumerable<IGraphiteExpression> expressions) { foreach (var expression in expressions) TraverseAst(expression, Enumerable.Empty<IGraphiteExpression>()); // if AST contains one or more queries without any additional // resampling steps there is nothing to optimize if (_resampleFuncs.Contains(null)) return; // no optimization potential if desired resolution is not lower than the original var originalResolution = DataSource.Span; var minReamplingRate = _resampleFuncs.Where(x => x != null).Min(x => x!.Spacing); if (minReamplingRate <= originalResolution.Duration) return; // no optimization potential if all the resampling functions contain non-optimizable aggregator functions if (_resampleFuncs.All(x => x is null || _nonOptimizableResampler.Contains(x.Func))) return; // optimize by loading lower resolution source data DataSource.Span = new TimeSeriesSpan(originalResolution.Begin, originalResolution.End, minReamplingRate); } private bool TraverseAst(IGraphiteExpression expression, IEnumerable<IGraphiteExpression> parents) { return expression switch { IFunctionExpression funcExpr => TraverseAst(funcExpr.InnerExpression, parents.Prepend(expression)), SourceExpression _ => AddSource(parents), _ => throw new Exception("Unknown expression type found in AST.") }; } private bool AddSource(IEnumerable<IGraphiteExpression> parents) { _resampleFuncs.Add(parents.Select(x => x as ResampleFunctionExpression).FirstOrDefault()); return true; } } }
39.654321
117
0.651619
[ "MIT" ]
philipdaubmeier/GraphIoT
src/GraphIoT.Graphite/Parser/Query/QueryOptimizer.cs
3,214
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.UI.Views { // Metadata.xml XPath class reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ui.views']/class[@name='TabletCardRecognitionHolderLinearLayout']" [global::Android.Runtime.Register ("com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ui/views/TabletCardRecognitionHolderLinearLayout", DoNotGenerateAcw=true)] public partial class TabletCardRecognitionHolderLinearLayout : global::Android.Widget.LinearLayout { static readonly JniPeerMembers _members = new XAPeerMembers ("com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ui/views/TabletCardRecognitionHolderLinearLayout", typeof (TabletCardRecognitionHolderLinearLayout)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected TabletCardRecognitionHolderLinearLayout (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ui.views']/class[@name='TabletCardRecognitionHolderLinearLayout']/constructor[@name='TabletCardRecognitionHolderLinearLayout' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register (".ctor", "(Landroid/content/Context;)V", "")] public unsafe TabletCardRecognitionHolderLinearLayout (global::Android.Content.Context context) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); } } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ui.views']/class[@name='TabletCardRecognitionHolderLinearLayout']/constructor[@name='TabletCardRecognitionHolderLinearLayout' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='android.util.AttributeSet']]" [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "")] public unsafe TabletCardRecognitionHolderLinearLayout (global::Android.Content.Context context, global::Android.Util.IAttributeSet attrs) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;Landroid/util/AttributeSet;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); __args [1] = new JniArgumentValue ((attrs == null) ? IntPtr.Zero : ((global::Java.Lang.Object) attrs).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); global::System.GC.KeepAlive (attrs); } } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ui.views']/class[@name='TabletCardRecognitionHolderLinearLayout']/constructor[@name='TabletCardRecognitionHolderLinearLayout' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='android.util.AttributeSet'] and parameter[3][@type='int']]" [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V", "")] public unsafe TabletCardRecognitionHolderLinearLayout (global::Android.Content.Context context, global::Android.Util.IAttributeSet attrs, int defStyle) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [3]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); __args [1] = new JniArgumentValue ((attrs == null) ? IntPtr.Zero : ((global::Java.Lang.Object) attrs).Handle); __args [2] = new JniArgumentValue (defStyle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); global::System.GC.KeepAlive (attrs); } } } }
60.311321
422
0.767558
[ "MIT" ]
amr-Magdy-PT/xamarin-paytabs-binding
android/CardScanBindingLib/obj/Debug/generated/src/Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.UI.Views.TabletCardRecognitionHolderLinearLayout.cs
6,393
C#
using System.Text.RegularExpressions; using Dalamud.Game.Chat; using Dalamud.Game.Chat.SeStringHandling; using Dalamud.Plugin; using ImGuiNET; namespace AetherSense.Triggers { public class ChatTrigger : TriggerBase { private string regexPattern = ""; private int duration = 1000; private bool wasPreviousMessageYou = false; private bool onlyYou = true; public int Duration { get => this.duration; set => this.duration = value; } public bool OnlyYou { get => this.onlyYou; set => onlyYou = value; } public string RegexPattern { get => this.regexPattern; set => this.regexPattern = value; } public override void Attach() { base.Attach(); Plugin.DalamudPluginInterface.Framework.Gui.Chat.OnChatMessage += this.OnChatMessage; } public override void Detach() { base.Detach(); Plugin.DalamudPluginInterface.Framework.Gui.Chat.OnChatMessage -= this.OnChatMessage; } public override void OnEditorGui() { ImGui.SameLine(); ImGui.Checkbox("Only Self", ref this.onlyYou); if (ImGui.IsItemHovered()) ImGui.SetTooltip("This trigger will only work if the proceding line in the log begins with 'You', eg. 'You cast' or 'You use'"); ImGui.InputText("Regex", ref this.regexPattern, 100); if (ImGui.IsItemHovered()) ImGui.SetTooltip("A regex-format string to check each chat message with."); ImGui.InputInt("Duration", ref this.duration); if (ImGui.IsItemHovered()) ImGui.SetTooltip("The duration to run the selected pattern for when this trigger runs."); } private void OnChatMessage(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) { if (this.Pattern == null) return; this.OnChatMessage(sender.TextValue, message.TextValue); } public void OnChatMessage(string sender, string message) { // Don't process any chat messages if the plugin is globally disabled if (!Plugin.Configuration.Enabled) return; bool isSystem = string.IsNullOrEmpty(sender); if (this.OnlyYou) { bool currentMessageWasYou = (isSystem && (message.StartsWith("You") || message.StartsWith("Vous") || message.StartsWith("Du"))); if (!this.wasPreviousMessageYou) { this.wasPreviousMessageYou = currentMessageWasYou; return; } } // Add the sender back into the message before regex. if (!isSystem) message = sender + ": " + message; if (!Regex.IsMatch(message, this.RegexPattern)) return; PluginLog.Information($"Triggered: {this.Name} with chat message: \"{message}\""); this.Pattern.RunFor(this.Duration); } } }
26.039604
132
0.698859
[ "BSD-3-Clause" ]
yuyuisyuyu/AetherSense
AetherSense/Triggers/ChatTrigger.cs
2,632
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDriveItemVersionRequest. /// </summary> public partial interface IDriveItemVersionRequest : IBaseRequest { /// <summary> /// Creates the specified DriveItemVersion using POST. /// </summary> /// <param name="driveItemVersionToCreate">The DriveItemVersion to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DriveItemVersion.</returns> System.Threading.Tasks.Task<DriveItemVersion> CreateAsync(DriveItemVersion driveItemVersionToCreate, CancellationToken cancellationToken = default); /// <summary> /// Creates the specified DriveItemVersion using POST and returns a <see cref="GraphResponse{DriveItemVersion}"/> object. /// </summary> /// <param name="driveItemVersionToCreate">The DriveItemVersion to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DriveItemVersion}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<DriveItemVersion>> CreateResponseAsync(DriveItemVersion driveItemVersionToCreate, CancellationToken cancellationToken = default); /// <summary> /// Deletes the specified DriveItemVersion. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default); /// <summary> /// Deletes the specified DriveItemVersion and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets the specified DriveItemVersion. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DriveItemVersion.</returns> System.Threading.Tasks.Task<DriveItemVersion> GetAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets the specified DriveItemVersion and returns a <see cref="GraphResponse{DriveItemVersion}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DriveItemVersion}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<DriveItemVersion>> GetResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Updates the specified DriveItemVersion using PATCH. /// </summary> /// <param name="driveItemVersionToUpdate">The DriveItemVersion to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated DriveItemVersion.</returns> System.Threading.Tasks.Task<DriveItemVersion> UpdateAsync(DriveItemVersion driveItemVersionToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Updates the specified DriveItemVersion using PATCH and returns a <see cref="GraphResponse{DriveItemVersion}"/> object. /// </summary> /// <param name="driveItemVersionToUpdate">The DriveItemVersion to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{DriveItemVersion}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<DriveItemVersion>> UpdateResponseAsync(DriveItemVersion driveItemVersionToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Updates the specified DriveItemVersion using PUT. /// </summary> /// <param name="driveItemVersionToUpdate">The DriveItemVersion object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task<DriveItemVersion> PutAsync(DriveItemVersion driveItemVersionToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Updates the specified DriveItemVersion using PUT and returns a <see cref="GraphResponse{DriveItemVersion}"/> object. /// </summary> /// <param name="driveItemVersionToUpdate">The DriveItemVersion object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse{DriveItemVersion}"/> to await.</returns> System.Threading.Tasks.Task<GraphResponse<DriveItemVersion>> PutResponseAsync(DriveItemVersion driveItemVersionToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDriveItemVersionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDriveItemVersionRequest Expand(Expression<Func<DriveItemVersion, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDriveItemVersionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDriveItemVersionRequest Select(Expression<Func<DriveItemVersion, object>> selectExpression); } }
58.053435
179
0.672584
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDriveItemVersionRequest.cs
7,605
C#
using EfCore.InMemoryHelpers; using EntityFrameworkCore.Cacheable; using Master40.DB.Data.Helper; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; namespace Master40.DB.Data.Context { public class InMemoryContext : ProductionDomainContext { public InMemoryContext(DbContextOptions<MasterDBContext> options) : base(options: options) { } /* protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); /* modelBuilder.Entity<ArticleType>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Article>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<ArticleBom>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<ArticleToBusinessPartner>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<BusinessPartner>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<DemandToProvider>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Kpi>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Machine>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<MachineTool>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<MachineGroup>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Order>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<OrderPart>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<ProductionOrder>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<ProductionOrderBom>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<ProductionOrderWorkSchedule>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Purchase>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<PurchasePart>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Stock>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<Unit>().Property(p => p.Id).ValueGeneratedNever(); modelBuilder.Entity<WorkSchedule>().Property(p => p.Id).ValueGeneratedNever(); } */ public static ProductionDomainContext CreateInMemoryContext() { // In-memory database only exists while the connection is open var options = new DbContextOptionsBuilder<MasterDBContext>(); options.UseSecondLevelCache(); InMemoryContext _inMemmoryContext = InMemoryContextBuilder.Build<InMemoryContext>(builder: options); _inMemmoryContext.Database.EnsureCreated(); return _inMemmoryContext; } public static ProductionDomainContext CreateInMemoryContext_Old() { // In-memory database only exists while the connection is open var connectionStringBuilder = new SqliteConnectionStringBuilder {DataSource = ":memory:"}; var connection = new SqliteConnection(connectionString: connectionStringBuilder.ToString()); // create OptionsBuilder with InMemmory Context var builder = new DbContextOptionsBuilder<MasterDBContext>(); builder.UseSqlite(connection: connection); //builder.UseSecondLevelCache(); var c = new ProductionDomainContext(options: builder.Options); c.Database.OpenConnection(); c.Database.EnsureCreated(); return c; } public static void LoadData(ProductionDomainContext source, ProductionDomainContext target) { foreach (var item in source.ArticleTypes) { target.ArticleTypes.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.Units) { target.Units.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ResourceSkills) { target.ResourceSkills.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ResourceTools) { target.ResourceTools.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.Resources) { target.Resources.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ResourceSetups) { target.ResourceSetups.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.Articles) { target.Articles.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.Stocks) { target.Stocks.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.Operations) { target.Operations.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ArticleBoms) { target.ArticleBoms.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.BusinessPartners) { target.BusinessPartners.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ArticleToBusinessPartners) { target.ArticleToBusinessPartners.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.CustomerOrders) { target.CustomerOrders.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.CustomerOrderParts) { target.CustomerOrderParts.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.ProductionOrders) { target.ProductionOrders.Add(entity: item.CopyProperties()); } target.SaveChanges(); } public static void SaveData(ResultContext source, ResultContext target) { foreach (var item in source.Kpis) { target.Kpis.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.SimulationOperations) { target.SimulationOperations.Add(entity: item.CopyProperties()); } target.SaveChanges(); foreach (var item in source.StockExchanges) { target.StockExchanges.Add(entity: item.CopyProperties()); } target.SaveChanges(); } } }
39.203209
112
0.593098
[ "Apache-2.0" ]
pascalschumann/Master-4.0
Master40.DB/Data/Context/InMemoryContext.cs
7,333
C#
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // // The Original Code is from http://gps3.codeplex.com/ version 3.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Globalization; using System.Text; #if !PocketPC using System.ComponentModel; #endif namespace DotSpatial.Positioning { /// <summary> /// Represents an address used to identify a unique Bluetooth device. /// </summary> /// <remarks>Each Bluetooth device has a unique address, in the form of a six-byte address.</remarks> public struct BluetoothAddress : IFormattable, IEquatable<BluetoothAddress> { /// <summary> /// /// </summary> private readonly byte[] _bytes; #region Constructors /// <summary> /// Creates a new instance from the specified byte array. /// </summary> /// <param name="address">The address.</param> public BluetoothAddress(byte[] address) { if (address == null) throw new ArgumentNullException("address"); if (address.Length != 8 && address.Length != 6) { throw new ArgumentOutOfRangeException("address", "The length of a Bluetooth address must be 6 or 8 bytes."); } _bytes = address; } /// <summary> /// Creates a new instance using the specified unsigned 64-bit integer. /// </summary> /// <param name="address">The address.</param> [CLSCompliant(false)] public BluetoothAddress(ulong address) { _bytes = BitConverter.GetBytes(address); } /// <summary> /// Creates a new instance using the specified 64-bit integer. /// </summary> /// <param name="address">The address.</param> public BluetoothAddress(long address) { _bytes = BitConverter.GetBytes(address); } /// <summary> /// Creates a new instance using the specified string. /// </summary> /// <param name="address">The address.</param> public BluetoothAddress(string address) { string[] values = address.Split(':'); if (values.Length != 6) throw new ArgumentException("When creating a BluetoothAddress object from a string, the string must be six bytes, in hexadecimal, separated by a colon (e.g. 00:00:00:00:00:00)"); _bytes = new byte[6]; for (int index = 0; index < 6; index++) _bytes[5 - index] = Convert.ToByte(values[index], 16); } #endregion Constructors #region Public Properties #if !PocketPC /// <summary> /// Returns the bytes of the address. /// </summary> [Category("Data")] [Description("Returns the bytes of the address.")] [Browsable(true)] #endif public byte[] Address { get { return _bytes; } } #endregion Public Properties #region Public Methods /// <summary> /// Returns the address as a 64-bit integer. /// </summary> /// <returns></returns> public long ToInt64() { /* Bluetooth addresses are 6 bytes, but are typically passed as a long (e.g. two extra bytes). * So, make an 8-byte array. */ byte[] bytes = new byte[8]; Array.Copy(_bytes, bytes, 6); return BitConverter.ToInt64(bytes, 0); } #endregion Public Methods #region Overrides /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return _bytes.GetHashCode(); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is BluetoothAddress) return Equals((BluetoothAddress)obj); return false; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } #endregion Overrides #region Static Methods /// <summary> /// Converts the specified string into an address. /// </summary> /// <param name="address">The address.</param> /// <returns></returns> public static BluetoothAddress Parse(string address) { return new BluetoothAddress(address); } #endregion Static Methods #region Conversions /// <summary> /// Bluetooth Address /// </summary> /// <param name="address">The address.</param> /// <returns>The result of the conversion.</returns> public static explicit operator BluetoothAddress(string address) { return new BluetoothAddress(address); } /// <summary> /// Bluetooth address /// </summary> /// <param name="address">The address.</param> /// <returns>The result of the conversion.</returns> public static explicit operator BluetoothAddress(long address) { return new BluetoothAddress(address); } /// <summary> /// Bluetooth address /// </summary> /// <param name="address">The address.</param> /// <returns>The result of the conversion.</returns> [CLSCompliant(false)] public static explicit operator BluetoothAddress(ulong address) { return new BluetoothAddress(address); } /// <summary> /// Bluetooth address /// </summary> /// <param name="address">The address.</param> /// <returns>The result of the conversion.</returns> public static explicit operator string(BluetoothAddress address) { return address.ToString(); } #endregion Conversions #region IFormattable Members /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param> /// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public string ToString(string format, IFormatProvider formatProvider) { string separator; if (string.IsNullOrEmpty(format)) { separator = string.Empty; } else { switch (format.ToUpper(CultureInfo.InvariantCulture)) { case "8": case "N": separator = string.Empty; break; case "G": case "C": separator = ":"; break; case "P": separator = "."; break; default: throw new FormatException("Invalid format specified - must be either \"N\", \"C\", \"P\", \"\" or null."); } } StringBuilder result = new StringBuilder(18); if (format == "8") { result.Append(_bytes[7].ToString("X2") + separator); result.Append(_bytes[6].ToString("X2") + separator); } result.Append(_bytes[5].ToString("X2") + separator); result.Append(_bytes[4].ToString("X2") + separator); result.Append(_bytes[3].ToString("X2") + separator); result.Append(_bytes[2].ToString("X2") + separator); result.Append(_bytes[1].ToString("X2") + separator); result.Append(_bytes[0].ToString("X2")); return result.ToString(); } #endregion IFormattable Members #region IEquatable<BluetoothAddress> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns> public bool Equals(BluetoothAddress other) { // compare the address byte-by-byte for (int index = 0; index < 6; index++) if (_bytes[index] != other.Address[index]) return false; // If we get here, all bytes match return true; } #endregion IEquatable<BluetoothAddress> Members } }
36.066225
234
0.528186
[ "Apache-2.0" ]
1stResponder/pinpoint
DotSpatial.Positioning/BluetoothAddress.cs
10,894
C#
/**** * Created by: Akram Taghavi-Burrs * Date Created: Feb 23, 2022 * * Last Edited by: Jacob Sharp * Date Last Edited: March 7, 2022 * * Description: GameManager object for the entire game ****/ /** Import Libraries **/ using System; //C# library for system properties using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //libraries for accessing scenes public class GameManager : MonoBehaviour { /*** VARIABLES ***/ #region GameManager Singleton static private GameManager gm; //refence GameManager static public GameManager GM { get { return gm; } } //public access to read only gm //Check to make sure only one gm of the GameManager is in the scene void CheckGameManagerIsInScene() { //Check if instnace is null if (gm == null) { gm = this; //set gm to this gm of the game object Debug.Log(gm); } else //else if gm is not null a Game Manager must already exsist { Destroy(this.gameObject); //In this case you need to delete this gm } DontDestroyOnLoad(this); //Do not delete the GameManager when scenes load Debug.Log(gm); }//end CheckGameManagerIsInScene() #endregion [Header("GENERAL SETTINGS")] public string gameTitle = "Untitled Game"; //name of the game public string gameCredits = "Made by Me"; //game creator(s) public string copyrightDate = "Copyright " + thisDay; //date cretaed [Header("GAME SETTINGS")] [Tooltip("Will the high score be recoreded")] public bool recordBestMoves = false; //is best moves recorded //[SerializeField] //Access to private variables in editor private int[] defaultBestMoves; static public int[] bestMoves; // the default best moves public int BestMoves { get { return bestMoves[SceneManager.GetActiveScene().buildIndex]; } set { bestMoves[SceneManager.GetActiveScene().buildIndex] = value; } } //access to private variable best moves [get/set methods] [Space(10)] static public int moves; //score value public int Moves { get { return moves; } set { moves = value; } }//access to private variable moves [get/set methods] [Space(10)] public string winMessage = "You Win!"; //Message if player wins [HideInInspector] public string endMsg ;//the end screen message, depends on winning outcome [Header("SCENE SETTINGS")] [Tooltip("Name of the start scene")] public string startScene; [Tooltip("Name of the game over scene")] public string gameOverScene; [Tooltip("Count and name of each Game Level (scene)")] public string[] gameLevels; //names of levels [HideInInspector] public int gameLevelsCount; //what level we are on private int loadLevel; //what level from the array to load public static string currentSceneName; //the current scene name; [Header("FOR TESTING")] public bool nextLevel = false; //test for next level //Game State Varaiables [HideInInspector] public enum gameStates { Idle, Playing, Death, GameOver, BeatLevel };//enum of game states [HideInInspector] public gameStates gameState = gameStates.Idle;//current game state //Timer Varaibles private float currentTime; //sets current time for timer private bool gameStarted = false; //test if games has started //Win/Loose conditon [SerializeField] //to test in inspector private bool playerWon = true; //reference to system time private static string thisDay = System.DateTime.Now.ToString("yyyy"); //today's date as string /*** MEHTODS ***/ //Awake is called when the game loads (before Start). Awake only once during the lifetime of the script instance. void Awake() { //runs the method to check for the GameManager CheckGameManagerIsInScene(); //store the current scene currentSceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; //create the best moves array with an index for each scene bestMoves = new int[gameLevels.Length + 2]; defaultBestMoves = new int[] { 0, 9, 12, 41, 32, 41, 26, 39, 40, 0 }; //Get the saved best moves GetBestMoves(); }//end Awake() // Update is called once per frame private void Update() { //if ESC is pressed , exit game //if (Input.GetKey("escape")) { ExitGame(); } // if R is pressed, restart the room if (Input.GetKey("r")) { moves = 0; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } //Check for next level if (nextLevel) { NextLevel(); } //Check Score //CheckMoves(); }//end Update //LOAD THE GAME FOR THE FIRST TIME OR RESTART public void StartGame() { //SET ALL GAME LEVEL VARIABLES FOR START OF GAME gameLevelsCount = 1; //set the count for the game levels loadLevel = gameLevelsCount - 1; //the level from the array if (!nextLevel) { SceneManager.LoadScene(gameLevels[loadLevel]); //load first game level PlayerPrefs.SetInt("Current Level", gameLevelsCount); } gameState = gameStates.Playing; //set the game state to playing moves = 0; //set starting score /* //set High Score if (recordBestMoves) //if we are recording highscore { //if the high score, is less than the default high score if (highScore <= defaultHighScore) { highScore = defaultHighScore; //set the high score to defulat PlayerPrefs.SetInt("HighScore", highScore); //update high score PlayerPref }//end if (highScore <= defaultHighScore) }//end if (recordHighScore) */ endMsg = winMessage; //set the end message default playerWon = true; //set player winning condition to false }//end StartGame() //EXIT THE GAME public void ExitGame() { Application.Quit(); Debug.Log("Exited Game"); }//end ExitGame() //GO TO THE GAME OVER SCENE public void GameOver() { gameState = gameStates.GameOver; //set the game state to gameOver //if(playerWon) { endMsg = winMessage; } else { endMsg = looseMessage; } //set the end message SceneManager.LoadScene(gameOverScene); //load the game over scene Debug.Log("Gameover"); } //GO TO THE NEXT LEVEL public void NextLevel() { if (!nextLevel) { CheckMoves(); // update best moves if necessary } nextLevel = false; //reset the next level moves = 0; //as long as our level count is not more than the amount of levels if (gameLevelsCount < gameLevels.Length) { gameLevelsCount++; //add to level count for next level loadLevel = gameLevelsCount - 1; //find the next level in the array PlayerPrefs.SetInt("Current Level", gameLevelsCount); Debug.Log(loadLevel); Debug.Log(gameLevels[loadLevel]); SceneManager.LoadScene(gameLevels[loadLevel]); //load next level }else{ //if we have run out of levels go to game over GameOver(); } //end if (gameLevelsCount <= gameLevels.Length) }//end NextLevel() // LOAD A PARTICULAR LEVEL public void LoadGame() { nextLevel = true; StartGame(); // initialize game stats gameLevelsCount = PlayerPrefs.GetInt("Current Level") - 1; // set level NextLevel(); } void CheckMoves() { //This method manages the score on update. Right now it just checks if we are greater than the high score. //if the score is more than the high score if (moves < BestMoves) { BestMoves = moves; //set the best moves to current moves PlayerPrefs.SetInt("BestMoves Scene " + SceneManager.GetActiveScene().buildIndex, BestMoves); //set the playerPref for best moves in that scene }//end if(score > highScore) }//end CheckMoves() void GetBestMoves() {//Get the saved highscore for (int i = 0; i < bestMoves.Length; i++) { //if the PlayerPref alredy exists for the high score if (PlayerPrefs.HasKey("BestMoves Scene " + i)) { //Debug.Log("Has Key"); bestMoves[i] = PlayerPrefs.GetInt("BestMoves Scene " + i); //set the high score to the saved high score if (bestMoves[i] == 0) { PlayerPrefs.SetInt("BestMoves Scene " + i, defaultBestMoves[i]); //set the playerPref to default best moves bestMoves[i] = defaultBestMoves[i]; } }//end if (PlayerPrefs.HasKey("HighScore")) else { PlayerPrefs.SetInt("BestMoves Scene " + i, defaultBestMoves[i]); //set the playerPref to default best moves bestMoves[i] = defaultBestMoves[i]; } } }//end GetBestMoves() }
33.230216
223
0.620048
[ "MIT" ]
jhsharp/PuzzleGame
PuzzleGameUnity/Assets/Scripts/Management/Managers/GameManager.cs
9,238
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using OpenRiaServices.Hosting; using OpenRiaServices.Server; using OpenRiaServices.Server.Test.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace OpenRiaServices.Tools.Test { /// <summary> /// Summary description for domain service code gen /// </summary> [TestClass] public class CodeGenSharedEntitiesTests { // Tests the following // 1. An entity shared across 2 domain services just works. // 2. Entity type, property and enumerable exposed once from each domain service are code gen'ed. // 3. Entity type, property and enumerable exposed by both domain services are code gen'ed. // 4. Entity type, property and enumerable exposed by no domain services are not code gen'ed. [TestMethod] [Description("Two DomainServices with shared entities succeeds")] public void CodeGen_SharedEntity_EntityShapingByTwoDomainServices_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_EntityShaping_ExposeAandBDomainService), typeof(SharedScenarios_EntityShaping_ExposeBAndCDomainService), }; // Generated property getter, classes, and enumerables for A, B and C exists string[] codeContains = new string[] { "public sealed partial class SharedScenarios_LeafEntityA : Entity", "public sealed partial class SharedScenarios_LeafEntityB : Entity", "public sealed partial class SharedScenarios_LeafEntityC : Entity", "public SharedScenarios_LeafEntityA A", "public SharedScenarios_LeafEntityB B", "public SharedScenarios_LeafEntityC C", "public EntitySet<SharedScenarios_LeafEntityA> SharedScenarios_LeafEntityAs", "public EntitySet<SharedScenarios_LeafEntityB> SharedScenarios_LeafEntityBs", "public EntitySet<SharedScenarios_LeafEntityC> SharedScenarios_LeafEntityCs", }; // D does not exist string[] codeNotContains = new string[] { "SharedScenarios_LeafEntityD", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, codeNotContains); } // Tests the following // 1. An entity shared across 3 domain services just works. // 2. Entity type, property and enumerable exposed once from each domain service are code gen'ed. // 3. Entity type, property and enumerable exposed by no domain services are not code gen'ed. [TestMethod] [Description("Three DomainServices with shared entities exposed succeeds")] public void CodeGen_SharedEntity_EntityShapingByThreeDomainServices_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_EntityShaping_ExposeADomainService), typeof(SharedScenarios_EntityShaping_ExposeBDomainService), typeof(SharedScenarios_EntityShaping_ExposeCDomainService), }; // Generated property getter, classes, and enumerables for A, B and C exists string[] codeContains = new string[] { "public sealed partial class SharedScenarios_LeafEntityA : Entity", "public sealed partial class SharedScenarios_LeafEntityB : Entity", "public sealed partial class SharedScenarios_LeafEntityC : Entity", "public SharedScenarios_LeafEntityA A", "public SharedScenarios_LeafEntityB B", "public SharedScenarios_LeafEntityC C", "public EntitySet<SharedScenarios_LeafEntityA> SharedScenarios_LeafEntityAs", "public EntitySet<SharedScenarios_LeafEntityB> SharedScenarios_LeafEntityBs", "public EntitySet<SharedScenarios_LeafEntityC> SharedScenarios_LeafEntityCs", }; // D does not exist string[] codeNotContains = new string[] { "SharedScenarios_LeafEntityD", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, codeNotContains); } // Tests the following // 1. All include/exclude attributed properties are generated correctly on a shared entity. // 2. Regular shaping takes over when include/exclude does not specify. [TestMethod] [Description("Two DomainServices with shared entities shaped by [Include] and [Exclude] succeeds")] public void CodeGen_SharedEntity_EntityShapingWithIncludeAndExclude_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_IncludeExcludeShaping_ExposeBDomainService), typeof(SharedScenarios_IncludeExcludeShaping_ExposeBAndCDomainService), }; // Generated classes for A, B, and C exist // Generated property getter for A and C exists // Generated enumerables for B and C exist string[] codeContains = new string[] { "public sealed partial class SharedScenarios_LeafEntityA : Entity", "public sealed partial class SharedScenarios_LeafEntityB : Entity", "public sealed partial class SharedScenarios_LeafEntityC : Entity", "public SharedScenarios_LeafEntityA A", "public SharedScenarios_LeafEntityC C", "public EntitySet<SharedScenarios_LeafEntityB> SharedScenarios_LeafEntityBs", "public EntitySet<SharedScenarios_LeafEntityC> SharedScenarios_LeafEntityCs", }; // Generated property getter for B does not exist // Generated enumerable fo A does not exist // D does not exist string[] codeNotContains = new string[] { "public SharedScenarios_LeafEntityB B", "public EntitySet<SharedScenarios_LeafEntityA> SharedScenarios_LeafEntityAs", "SharedScenarios_LeafEntityD", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, codeNotContains); } // Tests the following // 1. An entity with composition shared across two domain services just works. // 2. Composed entity is generated correctly. [TestMethod] [Description("Two DomainServices exposing a shared entities and its [Composition] member succeeds")] public void CodeGen_SharedEntity_EntityShapingWithComposition_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_CompositionShaping_ExposeBDomainService1), typeof(SharedScenarios_CompositionShaping_ExposeBDomainService2), }; // Generated class and property getter for B exists string[] codeContains = new string[] { "public sealed partial class SharedScenarios_LeafEntityB : Entity", "public SharedScenarios_LeafEntityB B", }; // Generated enumerable for B does not exist // A does not exist string[] codeNotContains = new string[] { "public EntitySet<SharedScenarios_LeafEntityB> SharedScenarios_LeafEntityBs", "SharedScenarios_LeafEntityA", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, codeNotContains); } // Tests the following // 1. An entity shared via inheritance across two domain services just works. // 2. Code generation does not generate unspecified inheritance heirarchies. [TestMethod] [Description("Two DomainServices with shared entities via inheritance succeeds")] public void CodeGen_SharedEntity_EntityShapingWithEvenInheritance_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_InheritanceShaping_ExposeXDomainService), typeof(SharedScenarios_InheritanceShaping_ExposeX2DomainService), }; // Generated classes and enumerables for X and Z exist // Z inherits from X directly string[] codeContains = new string[] { "public partial class SharedScenarios_InheritanceShaping_X : Entity", "public sealed partial class SharedScenarios_InheritanceShaping_Z : SharedScenarios_InheritanceShaping_X", "public EntitySet<SharedScenarios_InheritanceShaping_X> SharedScenarios_InheritanceShaping_Xes", }; // Z's entity set does not exist // Y does not exist string[] codeNotContains = new string[] { "EntitySet<SharedScenarios_InheritanceShaping_Z>", "SharedScenarios_InheritanceShaping_Y", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, codeNotContains); } // Tests than an entity shared via uneven inheritance across two domain services will fail. [TestMethod] [Description("Two DomainServices with shared entities via inheritance succeeds")] public void CodeGen_SharedEntity_EntityShapingWithUnevenInheritance_Fails() { Type[] domainServices = new Type[] { typeof(SharedScenarios_InheritanceShaping_ExposeXDomainService), typeof(SharedScenarios_InheritanceShaping_ExposeZDomainService), }; string[] errors = new string[] { string.Format(Resource.EntityCodeGen_SharedEntityMustBeLeastDerived, typeof(SharedScenarios_InheritanceShaping_X), typeof(SharedScenarios_InheritanceShaping_ExposeXDomainService), typeof(SharedScenarios_InheritanceShaping_Z), typeof(SharedScenarios_InheritanceShaping_ExposeZDomainService), typeof(SharedScenarios_InheritanceShaping_Z)), }; TestHelper.GenerateCodeAssertFailure("C#", domainServices, errors); } // Tests the following // 1. 2 DomainServices expose 2 different named update methods on the same entity just works. // 2. Verify the entity contains both named update methods. [TestMethod] [Description("Two DomainServices share an entity and each expose a named update method succeeds")] public void CodeGen_SharedEntity_TwoNamedUpdateMethods_Succeeds() { Type[] domainServices = new Type[] { typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate1DomainService), typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate2DomainService), }; // Named update methods, other methods and guard properties exist for both methods string[] codeContains = new string[] { "base.InvokeAction(\"ChangeA1\", intProp);", "base.InvokeAction(\"ChangeA2\", boolProp);", "OnChangeA1Invoking", "OnChangeA2Invoking", "OnChangeA1Invoked", "OnChangeA2Invoked", "IsChangeA1Invoked", "IsChangeA2Invoked", "CanChangeA1", "CanChangeA2", }; CodeGenHelper.BaseSuccessTest(domainServices, codeContains, null); } // Tests the following // 1. 2 DomainServices expose 2 overloaded named update methods with different parameters. // 2. Verify this generates a build error. [TestMethod] [Description("Two DomainServices expose overloaded named update methods on the same entity fails")] public void CodeGen_SharedEntity_TwoNamedUpdateMethodOverloads_Fails() { Type[] domainServices = new Type[] { typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate1DomainService), typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate1OverloadDomainService), }; string[] errors = new string[] { string.Format(Resource.EntityCodeGen_DuplicateCustomMethodName, "ChangeA1", typeof(SharedScenarios_LeafEntityA), typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate1DomainService), typeof(SharedScenarios_NamedUpdate_ExposeNamedUpdate1OverloadDomainService)), }; TestHelper.GenerateCodeAssertFailure("C#", domainServices, errors); } } #region Leaf entities public class SharedScenarios_LeafEntityA { [Key] public int IdA { get; set; } } public class SharedScenarios_LeafEntityB { [Key] public int IdB { get; set; } } public class SharedScenarios_LeafEntityC { [Key] public int IdC { get; set; } } public class SharedScenarios_LeafEntityD { [Key] public int IdD { get; set; } } #endregion #region Entity shaping public class SharedScenarios_EntityShaping_FourPropertyEntity { [Key] public int Id { get; set; } public int IdA { get; set; } public int IdB { get; set; } public int IdC { get; set; } public int IdD { get; set; } [Association("Top_A", "IdA", "IdA")] public SharedScenarios_LeafEntityA A { get; set; } [Association("Top_B", "IdB", "IdB")] public SharedScenarios_LeafEntityB B { get; set; } [Association("Top_C", "IdC", "IdC")] public SharedScenarios_LeafEntityC C { get; set; } [Association("Top_D", "IdD", "IdD")] public SharedScenarios_LeafEntityD D { get; set; } } // --- For basic shared entity test. // Top level entity exposes A, B, C, and D // DS1 exposes top level entity, A and B // DS2 exposes top level entity, B and C // Verify that A, B and C entities are code gen'ed correctly, // and top level entity has only 3 properties. [EnableClientAccess] public class SharedScenarios_EntityShaping_ExposeAandBDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_EntityShaping_FourPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityA> GetA() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } } [EnableClientAccess] public class SharedScenarios_EntityShaping_ExposeBAndCDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_EntityShaping_FourPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityC> GetC() { return null; } } // --- For a slightly more complex shared entity test. // Top level entity exposes A, B, C, and D // DS1 exposes top level entity and A // DS2 exposes top level entity and B // DS3 exposes top level entity and C // Verify that A, B and C entities are code gen'ed correctly, // and top level entity has only 3 properties. [EnableClientAccess] public class SharedScenarios_EntityShaping_ExposeADomainService : DomainService { [Query] public IEnumerable<SharedScenarios_EntityShaping_FourPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityA> GetA() { return null; } } [EnableClientAccess] public class SharedScenarios_EntityShaping_ExposeBDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_EntityShaping_FourPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } } [EnableClientAccess] public class SharedScenarios_EntityShaping_ExposeCDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_EntityShaping_FourPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityC> GetC() { return null; } } // --- Ensure shared entities continue to work with [Include] and [Exclude] attributes // Top level entity exposes [Inclue]A, [Exclue]B, C, D // DS1 exposes top level entity, B and C // DS2 exposes top level entity and C // Verify that A, B and C entities are code gen'ed correctly, // and top level entity has only 2 properties. public class SharedScenarios_IncludeExcludeShaping_ThreePropertyEntity { [Key] public int Id { get; set; } public int IdA { get; set; } public int IdB { get; set; } public int IdC { get; set; } public int IdD { get; set; } [Association("Top_A", "IdA", "IdA")] [Include] public SharedScenarios_LeafEntityA A { get; set; } [Association("Top_B", "IdB", "IdB")] [Exclude] public SharedScenarios_LeafEntityB B { get; set; } [Association("Top_C", "IdC", "IdC")] public SharedScenarios_LeafEntityC C { get; set; } [Association("Top_D", "IdD", "IdD")] public SharedScenarios_LeafEntityD D { get; set; } } [EnableClientAccess] public class SharedScenarios_IncludeExcludeShaping_ExposeBAndCDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_IncludeExcludeShaping_ThreePropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityC> GetC() { return null; } } [EnableClientAccess] public class SharedScenarios_IncludeExcludeShaping_ExposeBDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_IncludeExcludeShaping_ThreePropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } } // --- Ensure shared entities continue to work with [Composition] // Top level entity exposes A, [Composition]B // DS1 exposes top level entity and B // DS2 exposes top level entity and B // Verify that B entity is code gen'ed correctly, // and top level entity has only 1 property. public class SharedScenarios_CompositionShaping_TwoPropertyEntity { [Key] public int Id { get; set; } public int IdA { get; set; } public int IdB { get; set; } [Association("Top_A", "IdA", "IdA")] public SharedScenarios_LeafEntityA A { get; set; } [Association("Top_B", "IdB", "IdB")] [Composition] public SharedScenarios_LeafEntityB B { get; set; } } [EnableClientAccess] public class SharedScenarios_CompositionShaping_ExposeBDomainService1 : DomainService { [Query] public IEnumerable<SharedScenarios_CompositionShaping_TwoPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } } [EnableClientAccess] public class SharedScenarios_CompositionShaping_ExposeBDomainService2 : DomainService { [Query] public IEnumerable<SharedScenarios_CompositionShaping_TwoPropertyEntity> GetProperty() { return null; } [Query] public IEnumerable<SharedScenarios_LeafEntityB> GetB() { return null; } } // --- Ensure shared entities continue to work with inheritance // Z derives from Y derives from X // DS1 exposes X // DS2 exposes Z // Declare only Z a known type and verify that X derives from Z [KnownType(typeof(SharedScenarios_InheritanceShaping_Z))] public class SharedScenarios_InheritanceShaping_X { [Key] public int Id { get; set; } } public class SharedScenarios_InheritanceShaping_Y : SharedScenarios_InheritanceShaping_X { } public class SharedScenarios_InheritanceShaping_Z : SharedScenarios_InheritanceShaping_Y { } [EnableClientAccess] public class SharedScenarios_InheritanceShaping_ExposeXDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_InheritanceShaping_X> GetProperty() { return null; } } [EnableClientAccess] public class SharedScenarios_InheritanceShaping_ExposeX2DomainService : DomainService { [Query] public IEnumerable<SharedScenarios_InheritanceShaping_X> GetProperty() { return null; } } // --- Ensure shared entities continue to work with inheritance // Z derives from Y derives from X // DS1 exposes X // DS2 exposes Z // Declare only Z a known type and verify that X derives from Z [EnableClientAccess] public class SharedScenarios_InheritanceShaping_ExposeZDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_InheritanceShaping_Z> GetProperty() { return null; } } #endregion #region Named updates // --- Ensure shared entities expose named updates from multiple sources // DS1 exposes Named Update 1 // DS2 exposes Named Update 2 // Verify both named updates appear on the Entity [EnableClientAccess] public class SharedScenarios_NamedUpdate_ExposeNamedUpdate1DomainService : DomainService { [Query] public IEnumerable<SharedScenarios_LeafEntityA> GetProperty() { return null; } [EntityAction] public void ChangeA1(SharedScenarios_LeafEntityA a, int intProp) { } } [EnableClientAccess] public class SharedScenarios_NamedUpdate_ExposeNamedUpdate2DomainService : DomainService { [Query] public IEnumerable<SharedScenarios_LeafEntityA> GetProperty() { return null; } [EntityAction] public void ChangeA2(SharedScenarios_LeafEntityA a, bool boolProp) { } } // --- Ensure named updates with conflicting names cause a build error // DS1 exposes Named Update (int) // DS2 exposes Named Update (int, bool) // Verify error occurs [EnableClientAccess] public class SharedScenarios_NamedUpdate_ExposeNamedUpdate1OverloadDomainService : DomainService { [Query] public IEnumerable<SharedScenarios_LeafEntityA> GetProperty() { return null; } [EntityAction] public void ChangeA1(SharedScenarios_LeafEntityA a, int intProp, bool boolProp) { } } #endregion }
39.328231
130
0.655265
[ "Apache-2.0" ]
erikoijwall/OpenRiaServices
src/OpenRiaServices.Tools/Test/CodeGenSharedEntitiesTests.cs
23,127
C#
using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Sereno.Domain.Entity; namespace Sereno.STS.UI.Pages.Account { [AllowAnonymous] public class ConfirmEmailChangeModel : PageModel { private readonly UserManager<User> _userManager; private readonly SignInManager<User> _signInManager; public ConfirmEmailChangeModel(UserManager<User> userManager, SignInManager<User> signInManager) { this._userManager = userManager; this._signInManager = signInManager; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync(string userId, string email, string code) { if (userId == null || email == null || code == null) { return this.RedirectToPage("/Index"); } var user = await this._userManager.FindByIdAsync(userId); if (user == null) { return this.NotFound($"Unable to load user with ID '{userId}'."); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await this._userManager.ChangeEmailAsync(user, email, code); if (!result.Succeeded) { this.StatusMessage = "Error changing email."; return this.Page(); } // In our UI email and user name are one and the same, so when we update the email // we need to update the user name. var setUserNameResult = await this._userManager.SetUserNameAsync(user, email); if (!setUserNameResult.Succeeded) { this.StatusMessage = "Error changing user name."; return this.Page(); } await this._signInManager.RefreshSignInAsync(user); this.StatusMessage = "Thank you for confirming your email change."; return this.Page(); } } }
34.888889
104
0.61283
[ "MIT" ]
sergiomcalzada/sereno
src/Sereno.STS.UI/Pages/Account/ConfirmEmailChange.cshtml.cs
2,200
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace JupiterCapstone.Models { public class SubCategory { public SubCategory() { Products = new HashSet<Product>(); } [Key] public string Id { get; set; } [Required(ErrorMessage ="Subcategory name cannot be left blank")] [MaxLength(32, ErrorMessage ="Subcategory name cannot be longer than 32 characters")] public string SubCategoryName { get; set; } public bool? IsDeleted { get; set; } public DateTime CreatedDateTime { get; set; } = DateTime.Now; public DateTime LastModified { get; set; } public virtual Category Category { get; set; } public string CategoryId { get; set; } public string SubCategoryImage { get; set; } public virtual IEnumerable<Product> Products { get; set; } } }
32.666667
93
0.647959
[ "MIT" ]
kenelight4u/CAPSTONE-TEAM-JUPITER
SRC/JupiterCapstone/Models/SubCategory.cs
982
C#
using System; using System.Collections.Generic; using System.Data.Entity; using VendingMachineApp.DataAccess.Entities; namespace VendingMachineApp.DataAccess.EF { internal sealed class DatabaseInitializer : CreateDatabaseIfNotExists<VendingMachineDbContext> { protected override void Seed(VendingMachineDbContext context) { var vendingMachine = new VendingMachineEntity { Coins = new List<VendingMachineWalletEntity> { new VendingMachineWalletEntity { FaceValue = 1, Count = 100 }, new VendingMachineWalletEntity { FaceValue = 2, Count = 100 }, new VendingMachineWalletEntity { FaceValue = 5, Count = 100 }, new VendingMachineWalletEntity { FaceValue = 10, Count = 100 }, } }; var user = new UserEntity { Coins = new List<UserWalletEntity> { new UserWalletEntity { FaceValue = 1, Count = 10 }, new UserWalletEntity { FaceValue = 2, Count = 30 }, new UserWalletEntity { FaceValue = 5, Count = 20 }, new UserWalletEntity { FaceValue = 10, Count = 15 }, } }; var goods = new List<GoodsEntity> { new GoodsEntity { Id = Guid.NewGuid(), Name = "Чай", Count = 10, Price = 13, VendingMachine = vendingMachine }, new GoodsEntity { Id = Guid.NewGuid(), Name = "Кофе", Count = 20, Price = 18, VendingMachine = vendingMachine }, new GoodsEntity { Id = Guid.NewGuid(), Name = "Кофе с молоком", Count = 20, Price = 21, VendingMachine = vendingMachine }, new GoodsEntity { Id = Guid.NewGuid(), Name = "Сок", Count = 15, Price = 35, VendingMachine = vendingMachine } }; context.Set<VendingMachineEntity>().Add(vendingMachine); context.Set<UserEntity>().Add(user); context.Set<GoodsEntity>().AddRange(goods); context.SaveChanges(); } } }
33.554545
98
0.326741
[ "MIT" ]
DrunkyBard/VendingMachine
src/VendingMachine/DataAccess/EF/DatabaseInitializer.cs
3,715
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x901c-f62f58b4")] public void Method_0000_901c() { ii(0x901c, 4); enter(0x40, 0); /* enter 0x40, 0x0 */ ii(0x9020, 3); mov(ax, memw[ds, 0x11da]); /* mov ax, [0x11da] */ ii(0x9023, 4); mov(dx, memw[ds, 0x11dc]); /* mov dx, [0x11dc] */ ii(0x9027, 3); add(ax, 0x40); /* add ax, 0x40 */ ii(0x902a, 3); adc(dx, 0); /* adc dx, 0x0 */ ii(0x902d, 1); push(dx); /* push dx */ ii(0x902e, 1); push(ax); /* push ax */ ii(0x902f, 3); call(0xbd7a, 0x2d48); /* call 0xbd7a */ ii(0x9032, 1); pop(bx); /* pop bx */ ii(0x9033, 1); pop(bx); /* pop bx */ ii(0x9034, 2); push(0x40); /* push 0x40 */ ii(0x9036, 3); lea(ax, memw[ss, bp - 64]); /* lea ax, [bp-0x40] */ ii(0x9039, 1); push(ax); /* push ax */ ii(0x903a, 3); call(0xbd92, 0x2d55); /* call 0xbd92 */ ii(0x903d, 1); pop(bx); /* pop bx */ ii(0x903e, 1); pop(bx); /* pop bx */ ii(0x903f, 3); push(0xe73); /* push 0xe73 */ ii(0x9042, 3); lea(ax, memw[ss, bp - 64]); /* lea ax, [bp-0x40] */ ii(0x9045, 1); push(ax); /* push ax */ ii(0x9046, 3); call(0xbefa, 0x2eb1); /* call 0xbefa */ ii(0x9049, 1); pop(bx); /* pop bx */ ii(0x904a, 1); pop(bx); /* pop bx */ ii(0x904b, 2); or(ax, ax); /* or ax, ax */ ii(0x904d, 2); if(jnz(0x905f, 0x10)) goto l_0x905f; /* jnz 0x905f */ ii(0x904f, 3); push(0xe7b); /* push 0xe7b */ ii(0x9052, 3); lea(ax, memw[ss, bp - 64]); /* lea ax, [bp-0x40] */ ii(0x9055, 1); push(ax); /* push ax */ ii(0x9056, 3); call(0xbefa, 0x2ea1); /* call 0xbefa */ ii(0x9059, 1); pop(bx); /* pop bx */ ii(0x905a, 1); pop(bx); /* pop bx */ ii(0x905b, 2); or(ax, ax); /* or ax, ax */ ii(0x905d, 2); if(jz(0x9072, 0x13)) goto l_0x9072; /* jz 0x9072 */ l_0x905f: ii(0x905f, 3); mov(ax, memw[ds, 0x11f4]); /* mov ax, [0x11f4] */ ii(0x9062, 4); mov(dx, memw[ds, 0x11f6]); /* mov dx, [0x11f6] */ ii(0x9066, 3); mov(memw[ds, 0x11da], ax); /* mov [0x11da], ax */ ii(0x9069, 4); mov(memw[ds, 0x11dc], dx); /* mov [0x11dc], dx */ ii(0x906d, 3); mov(ax, 1); /* mov ax, 0x1 */ ii(0x9070, 1); leave(); /* leave */ ii(0x9071, 1); ret(); return; /* ret */ l_0x9072: ii(0x9072, 2); sub(ax, ax); /* sub ax, ax */ ii(0x9074, 1); leave(); /* leave */ ii(0x9075, 1); ret(); /* ret */ } } }
69.603448
95
0.325985
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-0000-901c.cs
4,037
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.Dts.V20180330.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeRegionConfRequest : AbstractModel { /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { } } }
29.108108
83
0.687094
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Dts/V20180330/Models/DescribeRegionConfRequest.cs
1,077
C#
namespace DeemZ.Services.UserServices { using System.Collections.Generic; using System.Threading.Tasks; using DeemZ.Models.FormModels.User; using DeemZ.Models.ViewModels.User; public interface IUserService { IEnumerable<T> GetAllUsers<T>(string searchTerm = null, int page = 1, int quantity = 20); Task<int> GetUserTakenCourses(string uid); Task<T> GetUserById<T>(string uid); bool GetUserById(string uid); Task<bool> IsInRoleAsync(string uid, string role); Task EditUser(string uid, EditUserFormModel user); Task AddUserToRole(string uid, string role); Task RemoveUserFromRole(string uid, string role); bool IsEmailFree(string uid, string email); bool IsUsernameFree(string uid, string userName); Task<IndexUserViewModel> GetIndexInformaiton(string uid, bool isAdmin); bool GetUserByUserName(string username); Task<string> GetUserIdByUserName(string username); Task SetProfileImg(string id, string url, string publidId); Task DeleteUserProfileImg(string userId); } }
42.961538
97
0.700985
[ "MIT" ]
Berat-Dzhevdetov/DeemZ
DeemZ/DeemZ.Services/UserServices/IUserService.cs
1,119
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Pencil42.PakjesDienst.Db; using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; namespace Pencil42.PakjesDienst.Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSignalR(); services.Configure<PakjesQueueSettings>(Configuration.GetSection(PakjesQueueSettings.SectionName)); services.AddSingleton<IHostedService, QueueListener>(); var connection = Configuration.GetConnectionString(Constants.ConnectionStrings.Pakjes); services.AddDbContext<PakjesContext>(options => options.UseSqlServer(connection)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddDebug(); loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseMvc(); app.UseSignalR(routes => { routes.MapHub<PakjesHub>("/pakjes"); }); } } }
31.909091
111
0.65622
[ "MIT" ]
hugoham/workshop-netcore
src/Pencil42.PakjesDienst.Web/Startup.cs
2,106
C#
using System; using Microsoft.Extensions.Logging; using Xunit.Abstractions; namespace BackgroundProcessing.Core.Tests { /// <summary> /// <see cref="ILogger{TCategoryName}"/> implementation that outputs to xunit <see cref="ITestOutputHelper"/>. /// </summary> /// <typeparam name="T">The service type.</typeparam> public sealed class XunitLogger<T> : ILogger<T> { private ITestOutputHelper _output; public XunitLogger(ITestOutputHelper output) { _output = output; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { _output.WriteLine(state.ToString()); } public bool IsEnabled(LogLevel logLevel) { return true; } public IDisposable BeginScope<TState>(TState state) { return new NoopDisposable(); } private class NoopDisposable : IDisposable { public void Dispose() { } } } }
25.860465
145
0.597122
[ "Apache-2.0" ]
nventive/BackgroundProcessing
BackgroundProcessing.Core.Tests/XunitLogger.cs
1,114
C#
using System; using System.IO; using System.Diagnostics; using System.Reflection; using SharpTools; namespace SharpTools { public static class Program { public static string FixExtension(string path) { //core3 creates exes in win and no extension in unix //core2 creats dlls everywhere if (Platform.IsWindows()) { return Path.ChangeExtension(path, ".exe"); } if (Platform.IsMacOS()) { return Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)); } if (Platform.IsLinux()) { return Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)); } return path; } public static string[] Run(string arguments) { //A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'C:\Program Files\dotnet'. //Problem is SharpTools.Test.Console.runtimeconfig.json is not being copied to output folder //It gets generated in SharpTools.Test.Console/bin/Debug/netcoreapp3.0 but not carried to SharpTools.Test/bin/Debug/netcoreapp3.0 var rtcExecuting = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".runtimeconfig.json"); //SharpTools.Test.Console var rtcCalling = Path.ChangeExtension(Assembly.GetCallingAssembly().Location, ".runtimeconfig.json"); //SharpTools.Test if (!File.Exists(rtcExecuting)) File.Copy(rtcCalling, rtcExecuting); var p = new Process(); p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.Arguments = arguments; //Gets DLL extension! //C:\Users\samuel\Documents\github\SharpTools\SharpTools.Test\bin\Debug\netcoreapp3.0\SharpTools.Test.Console.dll p.StartInfo.FileName = FixExtension(Assembly.GetExecutingAssembly().Location); //Console.WriteLine(p.StartInfo.FileName); p.Start(); p.WaitForExit(); var output = p.StandardOutput.ReadToEnd(); return output.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); } [STAThread] private static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments..."); Console.ReadKey(); } else { switch (args[0]) { case "Executable": RunExecutable(args); break; case "GlobalMutex": RunGlobalMutext(args); break; case "Logger": RunLogger(args); break; } } } private static void RunExecutable(string[] args) { Console.WriteLine(Executable.VersionString()); Console.WriteLine(Executable.BuildDateTime().ToString()); Console.WriteLine(Executable.Filename()); Console.WriteLine(Executable.DirectoryPath()); Console.WriteLine(Executable.FullPath()); Console.WriteLine(Executable.Relative("file")); Console.WriteLine(Executable.Relative("folder", "file")); } private static void RunGlobalMutext(string[] args) { var mutex = new GlobalMutex(args[1], () => { Console.WriteLine("Mutex Busy"); }); mutex.Run(() => { Console.WriteLine("Mutex Free"); }); } private static void RunLogger(string[] args) { using (var runner = new LogRunner(new PatternLogFormatter("{LEVEL} {NAME} {MESSAGE}"))) { runner.AddAppender(new ConsoleLogAppender()); var logger = new Logger(runner, "N$AME"); logger.Debug("Message {0}", 1); logger.Info("Message {0}", 2); logger.Warn("Message {0}", 3); logger.Error("Message {0}", 4); logger.Success("Message {0}", 5); } } } }
39.681416
153
0.555308
[ "MIT" ]
JTOne123/SharpTools
SharpTools.Test.Console/Program.cs
4,484
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the docdb-2014-10-31.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.DocDB { /// <summary> /// Configuration for accessing Amazon DocDB service /// </summary> public partial class AmazonDocDBConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.102.26"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonDocDBConfig() { this.AuthenticationServiceName = "rds"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "rds"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2014-10-31"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.8125
103
0.582082
[ "Apache-2.0" ]
dwainew/aws-sdk-net
sdk/src/Services/DocDB/Generated/AmazonDocDBConfig.cs
2,065
C#
// Taken from https://github.com/xunit/samples.xunit/blob/master/UseCulture/UseCultureAttribute.cs using System; using System.Globalization; using System.Reflection; using System.Threading; using Xunit.Sdk; /// <summary> /// Apply this attribute to your test method to replace the /// <see cref="Thread.CurrentThread" /> <see cref="CultureInfo.CurrentCulture" /> and /// <see cref="CultureInfo.CurrentUICulture" /> with another culture. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class UseCultureAttribute : BeforeAfterTestAttribute { readonly Lazy<CultureInfo> culture; readonly Lazy<CultureInfo> uiCulture; CultureInfo originalCulture; CultureInfo originalUICulture; /// <summary> /// Replaces the culture and UI culture of the current thread with /// <paramref name="culture" /> /// </summary> /// <param name="culture">The name of the culture.</param> /// <remarks> /// <para> /// This constructor overload uses <paramref name="culture" /> for both /// <see cref="Culture" /> and <see cref="UICulture" />. /// </para> /// </remarks> public UseCultureAttribute(string culture) : this(culture, culture) { } /// <summary> /// Replaces the culture and UI culture of the current thread with /// <paramref name="culture" /> and <paramref name="uiCulture" /> /// </summary> /// <param name="culture">The name of the culture.</param> /// <param name="uiCulture">The name of the UI culture.</param> public UseCultureAttribute(string culture, string uiCulture) { this.culture = new Lazy<CultureInfo>(() => new CultureInfo(culture, false)); this.uiCulture = new Lazy<CultureInfo>(() => new CultureInfo(uiCulture, false)); } /// <summary> /// Gets the culture. /// </summary> public CultureInfo Culture { get { return culture.Value; } } /// <summary> /// Gets the UI culture. /// </summary> public CultureInfo UICulture { get { return uiCulture.Value; } } /// <summary> /// Stores the current <see cref="Thread.CurrentPrincipal" /> /// <see cref="CultureInfo.CurrentCulture" /> and <see cref="CultureInfo.CurrentUICulture" /> /// and replaces them with the new cultures defined in the constructor. /// </summary> /// <param name="methodUnderTest">The method under test</param> public override void Before(MethodInfo methodUnderTest) { originalCulture = Thread.CurrentThread.CurrentCulture; originalUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = Culture; Thread.CurrentThread.CurrentUICulture = UICulture; } /// <summary> /// Restores the original <see cref="CultureInfo.CurrentCulture" /> and /// <see cref="CultureInfo.CurrentUICulture" /> to <see cref="Thread.CurrentPrincipal" /> /// </summary> /// <param name="methodUnderTest">The method under test</param> public override void After(MethodInfo methodUnderTest) { Thread.CurrentThread.CurrentCulture = originalCulture; Thread.CurrentThread.CurrentUICulture = originalUICulture; } }
40.35
107
0.679678
[ "BSD-2-Clause" ]
chtoucas/Narvalo.NET
tests/TestCommon/UseCultureAttribute.cs
3,230
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. */ /* * Created on May 15, 2005 * */ namespace NPOI.SS.Formula.Functions { public class Sign : OneArg { public override double Evaluate(double d) { return MathX.Sign(d); } } }
33.666667
74
0.720792
[ "Apache-2.0" ]
0xAAE/npoi
main/SS/Formula/Functions/Sign.cs
1,010
C#
using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.Linq; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Interfaces.Logging; using BuildXL.Cache.ContentStore.Utils; using BuildXL.Cache.Monitor.App.Analysis; using Kusto.Data.Common; namespace BuildXL.Cache.Monitor.App.Rules { internal class CheckpointSizeRule : KustoRuleBase { public class Configuration : KustoRuleConfiguration { public Configuration(KustoRuleConfiguration kustoRuleConfiguration) : base(kustoRuleConfiguration) { } /// <summary> /// Time to take for analysis /// </summary> public TimeSpan LookbackPeriod { get; set; } = TimeSpan.FromDays(1); /// <summary> /// Time to take for detection /// </summary> public TimeSpan AnomalyDetectionHorizon { get; set; } = TimeSpan.FromHours(1); /// <summary> /// Maximum amount that a checkpoint can grow or decrease in size with respect to previous one /// </summary> public double MaximumPercentualDifference { get; set; } = 0.5; /// <summary> /// Minimum valid size. A checkpoint smaller than this triggers a fatal error. /// </summary> public string MinimumValidSize { get; set; } = "1KB"; public long MinimumValidSizeBytes => MinimumValidSize.ToSize(); /// <summary> /// Maximum valid size. A checkpoint larger than this triggers a fatal error. /// </summary> public string MaximumValidSize { get; set; } = "120GB"; public long MaximumValidSizeBytes => MaximumValidSize.ToSize(); /// <summary> /// Minimum percentage of data needed to estimate the maximum/minimum ranges /// </summary> public double MinimumTrainingPercentOfData { get; set; } = 0.75; /// <summary> /// Maximum amount that a checkpoint can grow or decrease in size with respect to lookback period /// </summary> public double MaximumGrowthWrtToLookback { get; set; } = 0.2; } private readonly Configuration _configuration; public override string Identifier => $"{nameof(CheckpointSizeRule)}:{_configuration.Environment}/{_configuration.Stamp}"; public CheckpointSizeRule(Configuration configuration) : base(configuration) { Contract.RequiresNotNull(configuration); _configuration = configuration; } #pragma warning disable CS0649 private class Result { public DateTime PreciseTimeStamp; public long TotalSize; } #pragma warning restore CS0649 public override async Task Run(RuleContext context) { var now = _configuration.Clock.UtcNow; var query = $@" let end = now(); let start = end - {CslTimeSpanLiteral.AsCslString(_configuration.LookbackPeriod)}; table(""{_configuration.CacheTableName}"") | where PreciseTimeStamp between (start .. end) | where Stamp == ""{_configuration.Stamp}"" | where Service == ""{Constants.MasterServiceName}"" | where Message has ""CreateCheckpointAsync stop"" | project PreciseTimeStamp, Message | parse Message with * ""SizeMb=["" SizeMb:double ""]"" * | project PreciseTimeStamp, TotalSize=tolong(SizeMb * 1000000) | sort by PreciseTimeStamp asc"; var results = (await QueryKustoAsync<Result>(context, query)).ToList(); if (results.Count == 0) { _configuration.Logger.Error($"No checkpoints have been produced for at least {_configuration.LookbackPeriod}"); return; } var detectionHorizon = now - _configuration.AnomalyDetectionHorizon; results .Select(r => (double)r.TotalSize) .OverPercentualDifference(_configuration.MaximumPercentualDifference) .Where(evaluation => results[evaluation.Index].PreciseTimeStamp >= detectionHorizon) .PerformOnLast(index => { var result = results[index]; var previousResult = results[index - 1]; Emit(context, "SizeDerivative", Severity.Warning, $"Checkpoint size went from `{previousResult.TotalSize.ToSizeExpression()}` to `{result.TotalSize.ToSizeExpression()}`, which is higher than the threshold of `{_configuration.MaximumPercentualDifference * 100.0}%`", $"Checkpoint size went from `{previousResult.TotalSize.ToSizeExpression()}` to `{result.TotalSize.ToSizeExpression()}`", eventTimeUtc: result.PreciseTimeStamp); }); var training = new List<Result>(); var prediction = new List<Result>(); results.SplitBy(r => r.PreciseTimeStamp <= detectionHorizon, training, prediction); if (prediction.Count == 0) { _configuration.Logger.Error($"No checkpoints have been produced for at least {_configuration.AnomalyDetectionHorizon}"); return; } prediction .Select(p => p.TotalSize) .NotInRange(_configuration.MinimumValidSizeBytes, _configuration.MaximumValidSizeBytes) .PerformOnLast(index => { var result = prediction[index]; Emit(context, "SizeValidRange", Severity.Warning, $"Checkpoint size `{result.TotalSize.ToSizeExpression()}` out of valid range [`{_configuration.MinimumValidSize}`, `{_configuration.MaximumValidSize}`]", eventTimeUtc: result.PreciseTimeStamp); }); if (training.Count < _configuration.MinimumTrainingPercentOfData * results.Count) { return; } var lookbackSizes = training.Select(r => r.TotalSize); var expectedMin = (long)Math.Floor((1 - _configuration.MaximumGrowthWrtToLookback) * lookbackSizes.Min()); var expectedMax = (long)Math.Ceiling((1 + _configuration.MaximumGrowthWrtToLookback) * lookbackSizes.Max()); prediction .Select(p => p.TotalSize) .NotInRange(expectedMin, expectedMax) .PerformOnLast(index => { var result = prediction[index]; Emit(context, "SizeExpectedRange", Severity.Warning, $"Checkpoint size `{result.TotalSize.ToSizeExpression()}` out of expected range [`{expectedMin.ToSizeExpression()}`, `{expectedMax.ToSizeExpression()}`]", eventTimeUtc: result.PreciseTimeStamp); }); } } }
45.273292
240
0.577034
[ "MIT" ]
Bhaskers-Blu-Org2/BuildXL
Public/Src/Cache/Monitor/App/Rules/CheckpointSizeRule.cs
7,291
C#
using System; using System.Collections.Generic; using System.Data.Objects; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.Caching; namespace System { public static class LinqExtensions { public static IQueryable<T> Search<T>(this IQueryable<T> model, string keyword) { if (!string.IsNullOrEmpty(keyword)) { var where = model.GetType().GetGenericArguments()[0].GetProperties().Where(item => item.PropertyType == typeof(string)).Aggregate("1!=1 ", (current, item) => current + " or " + item.Name + ".Contains(@0)"); int intKeyword; if (int.TryParse(keyword, out intKeyword)) { where = model.GetType().GetGenericArguments()[0].GetProperties().Where(item => item.PropertyType == typeof(int)).Aggregate(where, (current, item) => current + " or " + item.Name + "==" + intKeyword); } decimal decimalKeyword; if (decimal.TryParse(keyword, out decimalKeyword)) { where = model.GetType().GetGenericArguments()[0].GetProperties().Where(item => item.PropertyType == typeof(decimal)).Aggregate(where, (current, item) => current + " or " + item.Name + "==" + decimalKeyword); } bool boolKeyword; if (bool.TryParse(keyword, out boolKeyword)) { where = model.GetType().GetGenericArguments()[0].GetProperties().Where(item => item.PropertyType == typeof(bool)).Aggregate(where, (current, item) => current + " or " + item.Name + "==" + boolKeyword); } // model = model.Where(where, keyword); } return model; } public static IEnumerable<T> Cache<T>(this IQueryable<T> model) where T : class { var cacheId = model.ToTraceString(); var item = (IEnumerable<T>)MemoryCache.Default.Get(cacheId); if (item == null) { item = model.ToList(); var policy = new CacheItemPolicy { //该缓存指定时间内未使用 自动移除 SlidingExpiration = TimeSpan.FromHours(1) }; // policy.ChangeMonitors.Add(MemoryCache.Default.CreateCacheEntryChangeMonitor(new[] { cacheId })); MemoryCache.Default.Add(cacheId, item, policy); } else { Trace.WriteLine("从缓存读取:" + cacheId); } return item; } private static string ToTraceString<T>(this IQueryable<T> query) { var internalQueryField = query.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).First(f => f.Name.Equals("_internalQuery")); var internalQuery = internalQueryField.GetValue(query); var objectQueryField = internalQuery.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).First(f => f.Name.Equals("_objectQuery")); var objectQuery = objectQueryField.GetValue(internalQuery) as ObjectQuery<T>; return objectQuery.ToTraceStringWithParameters(); } private static string ToTraceStringWithParameters<T>(this ObjectQuery<T> query) { var traceString = query.ToTraceString() + "\n"; traceString = query.Parameters.Aggregate(traceString, (current, parameter) => current + ("-- @" + parameter.Name + ": '" + parameter.Value + "' (Type =" + parameter.ParameterType.Name + ")\n")); return traceString; } public static CacheEntryChangeMonitor policyChangeMonitors { get; set; } } public static class DistinctExtensions { public static IEnumerable<T> Distinct<T, TV>(this IEnumerable<T> source, Func<T, TV> keySelector) { return source.Distinct(new CommonEqualityComparer<T, TV>(keySelector)); } public static IEnumerable<T> Distinct<T, TV>(this IEnumerable<T> source, Func<T, TV> keySelector, IEqualityComparer<TV> comparer) { return source.Distinct(new CommonEqualityComparer<T, TV>(keySelector, comparer)); } } // Distinct(p => p.Name, StringComparer.CurrentCultureIgnoreCase) public class CommonEqualityComparer<T, TV> : IEqualityComparer<T> { private readonly Func<T, TV> _keySelector; private readonly IEqualityComparer<TV> _comparer; public CommonEqualityComparer(Func<T, TV> keySelector, IEqualityComparer<TV> comparer) { _keySelector = keySelector; _comparer = comparer; } public CommonEqualityComparer(Func<T, TV> keySelector) : this(keySelector, EqualityComparer<TV>.Default) { } public bool Equals(T x, T y) { return _comparer.Equals(_keySelector(x), _keySelector(y)); } public int GetHashCode(T obj) { return _comparer.GetHashCode(_keySelector(obj)); } } }
36.678571
227
0.589873
[ "Apache-2.0" ]
Sopcce/.Net-Common-Utility
Sop.Common.Helper/Extensions/LinqExtensions.cs
5,179
C#
using System; using EasyRabbitMQ.Infrastructure; using EasyRabbitMQ.Logging; using EasyRabbitMQ.Publish; using EasyRabbitMQ.Serialization; using EasyRabbitMQ.Subscribe; namespace EasyRabbitMQ.Configuration { public class EasyRabbitMQConfigurer { private readonly IContainer _container = new SuperSimpleIoC(); internal EasyRabbitMQConfigurer(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); ComponentRegistration.Register(_container); _container.Resolve<IConfiguration>().ConnectionString = connectionString; } public EasyRabbitMQConfigurer Use(ISerializer serializer) { if (serializer == null) throw new ArgumentNullException(nameof(serializer)); _container.Register(() => serializer); return this; } public EasyRabbitMQConfigurer Use(IHandlerActivator handlerActivator) { if (handlerActivator == null) throw new ArgumentNullException(nameof(handlerActivator)); _container.Register(() => handlerActivator); return this; } public EasyRabbitMQConfigurer Use(ILoggerFactory loggerFactory) { if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); LogManager.LoggerFactory = loggerFactory; return this; } public IPublisher AsPublisher() { return _container.Resolve<IPublisher>(); } public ISubscriber AsSubscriber() { return _container.Resolve<ISubscriber>(); } } }
28.180328
114
0.659104
[ "Apache-2.0" ]
simonbaas/EasyRabbitMQ
src/EasyRabbitMQ/Configuration/EasyRabbitMQConfigurer.cs
1,721
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MdTranslator.Wpf.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.666667
151
0.582633
[ "MIT" ]
felpasl/MdTranslate
src/MdTranslate.Wpf/Properties/Settings.Designer.cs
1,073
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace PartyPartUsers.Models { [Table("users")] public class User { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long? user_id { get; set; } public string name { get; set; } public string login { get; set; } public string email { get; set; } public string password { get; set; } public string? telegram_id { get; set; } } }
29.277778
61
0.639469
[ "Apache-2.0" ]
Party-Part/party-part-users
PartyPartUsers/PartyPartUsers/Models/User.cs
527
C#
using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; using System; namespace Xrm.DataManager.Framework.Tests { public class RemoveAsyncTasksDataJob : PickAndProcessDataJobBase//FullProcessDataJobBase//PickAndProcessDataJobBase { public RemoveAsyncTasksDataJob(JobSettings jobSettings, JobProcessParameters parameters) : base(jobSettings, parameters) { } public override string GetName() => "RemoveAsyncTasksDataJob - Remove system jobs"; public override QueryExpression GetQuery(Guid callerId) { var query = new QueryExpression("asyncoperation"); query.ColumnSet.AddColumn("statecode"); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 3); query.Criteria.AddCondition("recurrencepattern", ConditionOperator.Null); query.AddOrder("createdon", OrderType.Descending); query.ColumnSet.AllColumns = false; query.NoLock = true; return query; } public override void ProcessRecord(JobExecutionContext context) { var proxy = context.Proxy; var record = context.Record; try { proxy.Delete(record.LogicalName, record.Id); } catch { } } } }
30.840909
128
0.627119
[ "MIT" ]
AymericM78/Xrm.DataManager.Framework
Xrm.DataManager.Framework.Tests/DataJobs/RemoveAsyncTasksDataJob.cs
1,359
C#
using GameStore.Services.Articles.Models; namespace GameStore.Services.Articles { public class ArticleServiceModel : IArticleModel { public int Id { get; set; } public string Content { get; set; } public string Title { get; set; } public string CreatedOn { get; set; } public string ImageUrl { get; set; } public string TrailerUrl { get; set; } public string ShortDescription { get; set; } public int Rating { get; set; } } }
18.5
52
0.606178
[ "MIT" ]
MarianAtanasovv/ASP.NET-Core-Project-Gaming-Store
GameStore/GameStore/Services/Articles/Models/ArticleServiceModel.cs
520
C#
using System.Reflection; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly : AssemblyTitle("CommandLine.dll")] [assembly : AssemblyDescription("Automatic parsing and validation of command line arguments.")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("")] [assembly : AssemblyProduct("")] [assembly : AssemblyCopyright("Copyright(c) 2003 Roger McFarlane.All rights reserved.")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly : AssemblyVersion("1.0.000.0000")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly : AssemblyDelaySign(false)] [assembly : AssemblyKeyFile("")] [assembly : AssemblyKeyName("")]
44.142857
95
0.705502
[ "BSD-3-Clause" ]
jozefizso/xsd2db
Common/CommandLineParser/AssemblyInfo.cs
2,472
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.dataworks_public; using Aliyun.Acs.dataworks_public.Transform; using Aliyun.Acs.dataworks_public.Transform.V20200518; namespace Aliyun.Acs.dataworks_public.Model.V20200518 { public class ListNodeIORequest : RpcAcsRequest<ListNodeIOResponse> { public ListNodeIORequest() : base("dataworks-public", "2020-05-18", "ListNodeIO") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.dataworks_public.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.dataworks_public.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string projectEnv; private long? nodeId; private string ioType; public string ProjectEnv { get { return projectEnv; } set { projectEnv = value; DictionaryUtil.Add(BodyParameters, "ProjectEnv", value); } } public long? NodeId { get { return nodeId; } set { nodeId = value; DictionaryUtil.Add(BodyParameters, "NodeId", value.ToString()); } } public string IoType { get { return ioType; } set { ioType = value; DictionaryUtil.Add(BodyParameters, "IoType", value); } } public override bool CheckShowJsonItemName() { return false; } public override ListNodeIOResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListNodeIOResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
27.53
146
0.681075
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-dataworks-public/Dataworks_public/Model/V20200518/ListNodeIORequest.cs
2,753
C#
using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Skybrud.Umbraco.GridData.Json.Converters; namespace Skybrud.Umbraco.GridData.Values { /// <summary> /// Class representing the HTML value of a control. /// </summary> [JsonConverter(typeof(GridControlValueStringConverter))] public class GridControlHtmlValue : GridControlTextValue { #region Properties /// <summary> /// Gets an instance of <code>HtmlString</code> representing the text value. /// </summary> [JsonIgnore] public HtmlString HtmlValue { get; private set; } #endregion #region Constructors protected GridControlHtmlValue(GridControl control, JToken token) : base(control, token) { HtmlValue = new HtmlString(Value); } #endregion #region Static methods /// <summary> /// Gets a text value from the specified <code>JToken</code>. /// </summary> /// <param name="control">The parent control.</param> /// <param name="token">The instance of <code>JToken</code> to be parsed.</param> public new static GridControlTextValue Parse(GridControl control, JToken token) { return token == null ? null : new GridControlHtmlValue(control, token); } #endregion } }
29.085106
98
0.631309
[ "MIT" ]
nvisage-gf/Skybrud.Umbraco.GridData
src/Skybrud.Umbraco.GridData/Values/GridControlHtmlValue.cs
1,369
C#
using System.Collections.Generic; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using Newtonsoft.Json.Linq; using SmartFormat.Core.Parsing; using SmartFormat.Extensions; namespace SmartFormat.Performance { /* BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042 AMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores .NET Core SDK=5.0.202 [Host] : .NET Core 5.0.5 (CoreCLR 5.0.521.16609, CoreFX 5.0.521.16609), X64 RyuJIT .NET Core 5.0 : .NET Core 5.0.5 (CoreCLR 5.0.521.16609, CoreFX 5.0.521.16609), X64 RyuJIT Job=.NET Core 5.0 Runtime=.NET Core 5.0 | Method | N | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------- |------ |------------:|----------:|----------:|----------:|------:|------:|------------:| | DirectMemberAccess | 1000 | 261.5 us | 5.13 us | 8.71 us | 20.9961 | - | - | 171.88 KB | | SfWithStringSource | 1000 | 1,792.1 us | 9.97 us | 9.32 us | 167.9688 | - | - | 1382.81 KB | | SfCacheReflection | 1000 | 2,026.1 us | 20.62 us | 19.29 us | 179.6875 | - | - | 1476.56 KB | |SfNoCacheReflection | 1000 | 13,091.9 us | 129.38 us | 121.02 us | 781.2500 | - | - | 6468.75 KB | | | | | | | | | | | | DirectMemberAccess | 10000 | 2,519.2 us | 49.85 us | 53.34 us | 207.0313 | - | - | 1718.75 KB | | SfWithStringSource | 10000 | 17,886.7 us | 151.64 us | 141.84 us | 1687.5000 | - | - | 13828.13 KB | | SfCacheReflection | 10000 | 20,918.6 us | 166.88 us | 156.10 us | 1781.2500 | - | - | 14765.63 KB | |SfNoCacheReflection | 10000 |130,049.2 us |1,231.06us |1,027.99us | 7750.0000 | - | - | 64687.81 KB | * Legends * N : Value of the 'N' parameter Mean : Arithmetic mean of all measurements Error : Half of 99.9% confidence interval StdDev : Standard deviation of all measurements Ratio : Mean of the ratio distribution ([Current]/[Baseline]) RatioSD : Standard deviation of the ratio distribution ([Current]/[Baseline]) Gen 0 : GC Generation 0 collects per 1000 operations Gen 1 : GC Generation 1 collects per 1000 operations Gen 2 : GC Generation 2 collects per 1000 operations Allocated : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B) 1 us : 1 Microsecond (0.000001 sec) */ [SimpleJob(RuntimeMoniker.Net50)] [MemoryDiagnoser] // [RPlotExporter] public class ReflectionVsStringSourceTests { private const string _formatString = "Address: {0.ToUpper} {1.ToLower}, {2.Trim}"; private readonly SmartFormatter _reflectionSourceFormatter; private readonly SmartFormatter _stringSourceFormatter; private readonly Address _address = new(); public ReflectionVsStringSourceTests() { _reflectionSourceFormatter = new SmartFormatter(); _reflectionSourceFormatter.AddExtensions( new ReflectionSource(), new DefaultSource() ); _reflectionSourceFormatter.AddExtensions( new DefaultFormatter() ); _stringSourceFormatter = new SmartFormatter(); _stringSourceFormatter.AddExtensions( new StringSource(), new DefaultSource() ); _stringSourceFormatter.AddExtensions( new DefaultFormatter() ); var parsedFormat = _stringSourceFormatter.Parser.ParseFormat(_formatString); _formatCache = parsedFormat; } [Params(1000, 10000)] public int N; private readonly Format _formatCache; [GlobalSetup] public void Setup() { } [Benchmark] public void DirectMemberAccess() { for (var i = 0; i < N; i++) { _ = string.Format("Address: {0} {1}, {2}", _address.City.ZipCode.ToUpper(), _address.City.Name.ToLower(), _address.City.AreaCode.Trim()); } } [Benchmark] public void SfCacheReflectionSource() { for (var i = 0; i < N; i++) { _ = _reflectionSourceFormatter.Format(_formatCache, _address.City.ZipCode, _address.City.Name, _address.City.AreaCode); } } [Benchmark] public void SfWithStringSource() { for (var i = 0; i < N; i++) { _ = _stringSourceFormatter.Format(_formatCache,_address.City.ZipCode, _address.City.Name, _address.City.AreaCode); } } public class Address { public CityDetails City { get; set; } = new CityDetails(); public PersonDetails Person { get; set; } = new PersonDetails(); public Dictionary<string, object> ToDictionary() { var d = new Dictionary<string, object> { { nameof(City), City.ToDictionary() }, { nameof(Person), Person.ToDictionary() } }; return d; } public JObject ToJson() { return JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(this)); } public class CityDetails { public string Name { get; set; } = "New York"; public string ZipCode { get; set; } = "00501"; public string AreaCode { get; set; } = "631"; public Dictionary<string, string> ToDictionary() { return new() { {nameof(Name), Name}, {nameof(ZipCode), ZipCode}, {nameof(AreaCode), AreaCode} }; } } public class PersonDetails { public string FirstName { get; set; } = "John"; public string LastName { get; set; } = "Doe"; public Dictionary<string, string> ToDictionary() { return new() { {nameof(FirstName), FirstName}, {nameof(LastName), LastName} }; } } } } }
37.628571
110
0.515718
[ "MIT" ]
axuno/SmartFormat.NET
src/Performance/ReflectionVsStringSourceTests.cs
6,587
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace ScintillaNet.Configuration { [Serializable] public class ConfigFile : ConfigItem { [NonSerialized] protected ConfigFile[] includedFiles; [XmlArray("includes")] [XmlArrayItem("include")] public include[] includes; [NonSerialized] public string filename; protected virtual Scintilla ChildScintilla => null; public virtual Scintilla MasterScintilla => _parent == this ? ChildScintilla : _parent.MasterScintilla; public virtual void addIncludedFile(ConfigFile file) { var configFiles = new ConfigFile[includedFiles.Length + 1]; includedFiles.CopyTo(configFiles, 0); configFiles[includedFiles.Length] = file; includedFiles = configFiles; } public override void init(ConfigurationUtility utility, ConfigFile theParent) { includedFiles = Array.Empty<ConfigFile>(); base.init(utility, theParent); if (includes is null) includes = Array.Empty<include>(); foreach (var include in includes) include.init(utility, _parent); foreach (var include in includes) { var configFile = (ConfigFile)utility.LoadConfiguration(GetType(), include.file, _parent); addIncludedFile(configFile); } CollectScintillaNodes(null); } public virtual void CollectScintillaNodes(List<ConfigItem> list) { if (_parent == this) { if (list != null) return; list = new List<ConfigItem>(); ChildScintilla?.CollectScintillaNodes(list); } else if (list is null) return; if (includedFiles != null) { foreach (var cf in includedFiles) { if (cf is null) continue; if (cf.ChildScintilla != null) list.Add(cf.ChildScintilla); cf.ChildScintilla?.CollectScintillaNodes(list); if( cf.includedFiles != null && cf.includedFiles.Length > 0) cf.CollectScintillaNodes(list); } } if (_parent == this) { ChildScintilla.includedFiles = new ConfigFile[list.Count]; list.CopyTo(ChildScintilla.includedFiles); } } } }
35.452055
113
0.556414
[ "MIT" ]
Acidburn0zzz/flashdevelop
PluginCore/ScintillaNet/Configuration/ConfigFile.cs
2,516
C#
using System; using System.Data.Common; using System.Diagnostics; using Judger.Core.Database.Internal.DbOperator; using Judger.Core.Database.Internal.Entity; using Judger.Models; using Judger.Models.Database; using Judger.Models.Judge; namespace Judger.Core.Database.Internal { /// <summary> /// 数据库单组用例评测器 /// </summary> public class SingleCaseJudger { /// <summary> /// 对查询字段是否大小写敏感 /// </summary> private readonly bool _caseSensitive; public SingleCaseJudger(JudgeContext context, BaseDbOperator dbOperator) { JudgeTask = context.Task; UserOperator = dbOperator; _caseSensitive = ((DbLangConfig) context.LangConfig).CaseSensitive; } private JudgeTask JudgeTask { get; } private BaseDbOperator UserOperator { get; } /// <summary> /// 评测一组用例 /// </summary> /// <param name="stdDbData">标准输出</param> /// <param name="stdQueryData">标准查询</param> /// <returns>单组评测结果</returns> public SingleJudgeResult Judge(DbData stdDbData, DbQueryData stdQueryData) { Stopwatch watch = new Stopwatch(); DbQueryData usrQuery; DbData usrOutput; try { watch.Start(); DbDataReader reader = UserOperator.ExecuteQuery(JudgeTask.SourceCode, JudgeTask.TimeLimit); usrQuery = BaseDbOperator.ReadQueryData(reader); usrOutput = UserOperator.ReadDbData(); } catch (Exception ex) { return new SingleJudgeResult { ResultCode = JudgeResultCode.RuntimeError, JudgeDetail = ex.Message, TimeCost = 0 }; } finally { watch.Stop(); } CompareResult result = CompareAnswer(stdDbData, stdQueryData, usrOutput, usrQuery); JudgeResultCode resultCode = result == CompareResult.Accepted ? JudgeResultCode.Accepted : JudgeResultCode.WrongAnswer; return new SingleJudgeResult { ResultCode = resultCode, TimeCost = (int) watch.ElapsedMilliseconds }; } private CompareResult CompareAnswer(DbData stdOutput, DbQueryData stdQuery, DbData usrOutput, DbQueryData usrQuery) { if (stdOutput != null && CompareDbData(stdOutput, usrOutput) == CompareResult.WrongAnswer) return CompareResult.WrongAnswer; if (stdQuery != null && CompareQuery(stdQuery, usrQuery) == CompareResult.WrongAnswer) return CompareResult.WrongAnswer; return CompareResult.Accepted; } private CompareResult CompareDbData(DbData stdOutput, DbData usrOutput) { if (stdOutput.TablesData.Length != usrOutput.TablesData.Length) return CompareResult.WrongAnswer; int tableCount = stdOutput.TablesData.Length; for (int i = 0; i < tableCount; i++) { if (!CmpString(stdOutput.TablesData[i].Name, usrOutput.TablesData[i].Name)) return CompareResult.WrongAnswer; if (CompareQuery(stdOutput.TablesData[i], usrOutput.TablesData[i]) == CompareResult.WrongAnswer) return CompareResult.WrongAnswer; } return CompareResult.Accepted; } private CompareResult CompareQuery(DbQueryData stdQuery, DbQueryData usrQuery) { if (stdQuery.FieldCount != usrQuery.FieldCount || stdQuery.Records.Count != usrQuery.Records.Count) return CompareResult.WrongAnswer; int filedCount = stdQuery.FieldCount; int recordCount = stdQuery.Records.Count; for (int i = 0; i < filedCount; i++) { if (!CmpString(stdQuery.FieldNames[i], usrQuery.FieldNames[i])) return CompareResult.WrongAnswer; } for (int i = 0; i < recordCount; i++) { for (int j = 0; j < filedCount; j++) { if (stdQuery.Records[i][j] != usrQuery.Records[i][j]) return CompareResult.WrongAnswer; } } return CompareResult.Accepted; } /// <summary> /// 对比文本是否相同(大小写敏感根据_caseSensitive) /// </summary> private bool CmpString(string a, string b) { if (_caseSensitive) return a == b; return string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase); } } }
33.493056
112
0.563757
[ "MIT" ]
Azure99/OpenJudger
src/Judger.Core/Database/Internal/SingleCaseJudger.cs
4,939
C#